mcpkit-core 0.6.0

Core types and traits for the Model Context Protocol (MCP)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
//! JSON-RPC 2.0 protocol types for the Model Context Protocol.
//!
//! This module provides the foundational JSON-RPC 2.0 types used for all
//! MCP communication. These types handle message framing, request/response
//! correlation, and notification delivery.
//!
//! # Protocol Overview
//!
//! MCP uses JSON-RPC 2.0 as its transport protocol. All messages are one of:
//!
//! - **Request**: A method call expecting a response
//! - **Response**: A reply to a request (success or error)
//! - **Notification**: A one-way message with no response
//!
//! # Example
//!
//! ```rust
//! use mcpkit_core::protocol::{Request, Response, RequestId};
//!
//! // Create a request
//! let request = Request::new("tools/list", RequestId::Number(1));
//!
//! // Parse a response
//! let json = r#"{"jsonrpc": "2.0", "id": 1, "result": {}}"#;
//! let response: Response = serde_json::from_str(json).unwrap();
//! ```

use crate::error::JsonRpcError;
use serde::{Deserialize, Serialize};
use std::borrow::Cow;

/// The JSON-RPC version string. Always "2.0".
pub const JSONRPC_VERSION: &str = "2.0";

/// A JSON-RPC request ID.
///
/// Request IDs are used to correlate requests with their responses.
/// They can be either numbers or strings per the JSON-RPC 2.0 specification.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(untagged)]
pub enum RequestId {
    /// Numeric request ID (most common).
    Number(u64),
    /// String request ID.
    String(String),
    /// A `null` request ID.
    ///
    /// JSON-RPC 2.0 requires error responses to a request that could not be
    /// parsed (so its id is unknown) to use `"id": null`.
    Null,
}

impl RequestId {
    /// Create a new numeric request ID.
    #[must_use]
    pub const fn number(id: u64) -> Self {
        Self::Number(id)
    }

    /// Create a new string request ID.
    #[must_use]
    pub fn string(id: impl Into<String>) -> Self {
        Self::String(id.into())
    }
}

impl From<u64> for RequestId {
    fn from(id: u64) -> Self {
        Self::Number(id)
    }
}

impl From<String> for RequestId {
    fn from(id: String) -> Self {
        Self::String(id)
    }
}

impl From<&str> for RequestId {
    fn from(id: &str) -> Self {
        Self::String(id.to_string())
    }
}

impl std::fmt::Display for RequestId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Number(n) => write!(f, "{n}"),
            Self::String(s) => write!(f, "{s}"),
            Self::Null => write!(f, "null"),
        }
    }
}

/// A JSON-RPC 2.0 request message.
///
/// Requests are method calls that expect a response. Each request has a unique
/// ID that is echoed in the corresponding response.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Request {
    /// The JSON-RPC version. Always "2.0".
    pub jsonrpc: Cow<'static, str>,
    /// The request ID for correlation.
    pub id: RequestId,
    /// The method to invoke.
    pub method: Cow<'static, str>,
    /// The method parameters, if any.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub params: Option<serde_json::Value>,
}

impl Request {
    /// Create a new request with no parameters.
    #[must_use]
    pub fn new(method: impl Into<Cow<'static, str>>, id: impl Into<RequestId>) -> Self {
        Self {
            jsonrpc: Cow::Borrowed(JSONRPC_VERSION),
            id: id.into(),
            method: method.into(),
            params: None,
        }
    }

    /// Create a new request with parameters.
    #[must_use]
    pub fn with_params(
        method: impl Into<Cow<'static, str>>,
        id: impl Into<RequestId>,
        params: serde_json::Value,
    ) -> Self {
        Self {
            jsonrpc: Cow::Borrowed(JSONRPC_VERSION),
            id: id.into(),
            method: method.into(),
            params: Some(params),
        }
    }

    /// Set the parameters for this request.
    #[must_use]
    pub fn params(mut self, params: serde_json::Value) -> Self {
        self.params = Some(params);
        self
    }

    /// Get the method name.
    #[must_use]
    pub fn method(&self) -> &str {
        &self.method
    }
}

/// A JSON-RPC 2.0 response message.
///
/// Responses are sent in reply to requests. They contain either a result
/// (on success) or an error (on failure), never both.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Response {
    /// The JSON-RPC version. Always "2.0".
    pub jsonrpc: Cow<'static, str>,
    /// The request ID this response corresponds to.
    pub id: RequestId,
    /// The result on success.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub result: Option<serde_json::Value>,
    /// The error on failure.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<JsonRpcError>,
}

impl Response {
    /// Create a successful response.
    #[must_use]
    pub fn success(id: impl Into<RequestId>, result: serde_json::Value) -> Self {
        Self {
            jsonrpc: Cow::Borrowed(JSONRPC_VERSION),
            id: id.into(),
            result: Some(result),
            error: None,
        }
    }

    /// Create an error response.
    #[must_use]
    pub fn error(id: impl Into<RequestId>, error: JsonRpcError) -> Self {
        Self {
            jsonrpc: Cow::Borrowed(JSONRPC_VERSION),
            id: id.into(),
            result: None,
            error: Some(error),
        }
    }

    /// Check if this response indicates success.
    #[must_use]
    pub const fn is_success(&self) -> bool {
        self.result.is_some() && self.error.is_none()
    }

    /// Check if this response indicates an error.
    #[must_use]
    pub const fn is_error(&self) -> bool {
        self.error.is_some()
    }

    /// Get the result, consuming self.
    ///
    /// Returns `Err` if this was an error response.
    pub fn into_result(self) -> Result<serde_json::Value, JsonRpcError> {
        if let Some(error) = self.error {
            Err(error)
        } else {
            self.result.ok_or_else(|| JsonRpcError {
                code: -32603,
                message: "Response contained neither result nor error".to_string(),
                data: None,
            })
        }
    }
}

/// A JSON-RPC 2.0 notification message.
///
/// Notifications are one-way messages that do not expect a response.
/// They have no ID field.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Notification {
    /// The JSON-RPC version. Always "2.0".
    pub jsonrpc: Cow<'static, str>,
    /// The notification method.
    pub method: Cow<'static, str>,
    /// The notification parameters, if any.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub params: Option<serde_json::Value>,
}

impl Notification {
    /// Create a new notification with no parameters.
    #[must_use]
    pub fn new(method: impl Into<Cow<'static, str>>) -> Self {
        Self {
            jsonrpc: Cow::Borrowed(JSONRPC_VERSION),
            method: method.into(),
            params: None,
        }
    }

    /// Create a new notification with parameters.
    #[must_use]
    pub fn with_params(method: impl Into<Cow<'static, str>>, params: serde_json::Value) -> Self {
        Self {
            jsonrpc: Cow::Borrowed(JSONRPC_VERSION),
            method: method.into(),
            params: Some(params),
        }
    }

    /// Set the parameters for this notification.
    #[must_use]
    pub fn params(mut self, params: serde_json::Value) -> Self {
        self.params = Some(params);
        self
    }

    /// Get the method name.
    #[must_use]
    pub fn method(&self) -> &str {
        &self.method
    }
}

/// A JSON-RPC 2.0 message (request, response, or notification).
///
/// This enum allows handling all message types uniformly during
/// parsing and routing.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum Message {
    /// A request message.
    Request(Request),
    /// A response message.
    Response(Response),
    /// A notification message.
    Notification(Notification),
}

impl Message {
    /// Get the method name if this is a request or notification.
    #[must_use]
    pub fn method(&self) -> Option<&str> {
        match self {
            Self::Request(r) => Some(&r.method),
            Self::Notification(n) => Some(&n.method),
            Self::Response(_) => None,
        }
    }

    /// Get the request ID if this is a request or response.
    #[must_use]
    pub const fn id(&self) -> Option<&RequestId> {
        match self {
            Self::Request(r) => Some(&r.id),
            Self::Response(r) => Some(&r.id),
            Self::Notification(_) => None,
        }
    }

    /// Check if this is a request.
    #[must_use]
    pub const fn is_request(&self) -> bool {
        matches!(self, Self::Request(_))
    }

    /// Check if this is a response.
    #[must_use]
    pub const fn is_response(&self) -> bool {
        matches!(self, Self::Response(_))
    }

    /// Check if this is a notification.
    #[must_use]
    pub const fn is_notification(&self) -> bool {
        matches!(self, Self::Notification(_))
    }

    /// Try to get this as a request.
    #[must_use]
    pub const fn as_request(&self) -> Option<&Request> {
        match self {
            Self::Request(r) => Some(r),
            _ => None,
        }
    }

    /// Try to get this as a response.
    #[must_use]
    pub const fn as_response(&self) -> Option<&Response> {
        match self {
            Self::Response(r) => Some(r),
            _ => None,
        }
    }

    /// Try to get this as a notification.
    #[must_use]
    pub const fn as_notification(&self) -> Option<&Notification> {
        match self {
            Self::Notification(n) => Some(n),
            _ => None,
        }
    }
}

impl From<Request> for Message {
    fn from(r: Request) -> Self {
        Self::Request(r)
    }
}

impl From<Response> for Message {
    fn from(r: Response) -> Self {
        Self::Response(r)
    }
}

impl From<Notification> for Message {
    fn from(n: Notification) -> Self {
        Self::Notification(n)
    }
}

/// A progress token for tracking long-running operations.
///
/// Progress tokens are included in requests that may take a long time,
/// allowing the server to send progress updates.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ProgressToken {
    /// Numeric progress token.
    Number(u64),
    /// String progress token.
    String(String),
}

impl std::fmt::Display for ProgressToken {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Number(n) => write!(f, "{n}"),
            Self::String(s) => write!(f, "{s}"),
        }
    }
}

/// A cursor for paginated results.
///
/// Cursors are opaque strings that represent a position in a paginated
/// result set. Pass the cursor from a previous response to get the next page.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct Cursor(pub String);

impl Cursor {
    /// Create a new cursor.
    #[must_use]
    pub fn new(cursor: impl Into<String>) -> Self {
        Self(cursor.into())
    }
}

impl std::fmt::Display for Cursor {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl From<String> for Cursor {
    fn from(s: String) -> Self {
        Self(s)
    }
}

impl From<&str> for Cursor {
    fn from(s: &str) -> Self {
        Self(s.to_string())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn request_id_null_round_trips() {
        // #17: JSON-RPC error responses to unparsable requests use `"id": null`.
        assert_eq!(serde_json::to_string(&RequestId::Null).unwrap(), "null");
        assert_eq!(
            serde_json::from_str::<RequestId>("null").unwrap(),
            RequestId::Null
        );
        // Numbers and strings still take precedence over null.
        assert_eq!(
            serde_json::from_str::<RequestId>("7").unwrap(),
            RequestId::Number(7)
        );
        assert_eq!(
            serde_json::from_str::<RequestId>("\"abc\"").unwrap(),
            RequestId::String("abc".to_string())
        );
    }

    #[test]
    fn test_request_serialization() -> Result<(), Box<dyn std::error::Error>> {
        let request = Request::new("tools/list", 1u64);
        let json = serde_json::to_string(&request)?;
        assert!(json.contains("\"jsonrpc\":\"2.0\""));
        assert!(json.contains("\"method\":\"tools/list\""));
        assert!(json.contains("\"id\":1"));
        Ok(())
    }

    #[test]
    fn test_request_with_params() -> Result<(), Box<dyn std::error::Error>> {
        let request = Request::with_params(
            "tools/call",
            1u64,
            serde_json::json!({"name": "search", "arguments": {"query": "test"}}),
        );
        let json = serde_json::to_string(&request)?;
        assert!(json.contains("\"params\""));
        assert!(json.contains("\"name\":\"search\""));
        Ok(())
    }

    #[test]
    fn test_response_success() -> Result<(), Box<dyn std::error::Error>> {
        let response = Response::success(1u64, serde_json::json!({"tools": []}));
        assert!(response.is_success());
        assert!(!response.is_error());

        let result = response
            .into_result()
            .map_err(|e| format!("Error: {}", e.message))?;
        assert!(result.get("tools").is_some());
        Ok(())
    }

    #[test]
    fn test_response_error() {
        let error = JsonRpcError {
            code: -32601,
            message: "Method not found".to_string(),
            data: None,
        };
        let response = Response::error(1u64, error);
        assert!(!response.is_success());
        assert!(response.is_error());

        // unwrap_err is intentional - we're testing the error path
        let err = response.into_result().unwrap_err();
        assert_eq!(err.code, -32601);
    }

    #[test]
    fn test_notification() -> Result<(), Box<dyn std::error::Error>> {
        let notification = Notification::with_params(
            "notifications/progress",
            serde_json::json!({"progress": 50, "total": 100}),
        );
        let json = serde_json::to_string(&notification)?;
        assert!(json.contains("\"method\":\"notifications/progress\""));
        assert!(!json.contains("\"id\"")); // Notifications have no ID
        Ok(())
    }

    #[test]
    fn test_message_parsing() -> Result<(), Box<dyn std::error::Error>> {
        // Request
        let json = r#"{"jsonrpc":"2.0","id":1,"method":"test"}"#;
        let msg: Message = serde_json::from_str(json)?;
        assert!(msg.is_request());
        assert_eq!(msg.method(), Some("test"));

        // Response
        let json = r#"{"jsonrpc":"2.0","id":1,"result":{}}"#;
        let msg: Message = serde_json::from_str(json)?;
        assert!(msg.is_response());

        // Notification
        let json = r#"{"jsonrpc":"2.0","method":"notify"}"#;
        let msg: Message = serde_json::from_str(json)?;
        assert!(msg.is_notification());
        Ok(())
    }

    #[test]
    fn test_request_id_types() -> Result<(), Box<dyn std::error::Error>> {
        // Number ID
        let request = Request::new("test", 42u64);
        let json = serde_json::to_string(&request)?;
        assert!(json.contains("\"id\":42"));

        // String ID
        let request = Request::new("test", "req-001");
        let json = serde_json::to_string(&request)?;
        assert!(json.contains("\"id\":\"req-001\""));
        Ok(())
    }
}