mcpr-core 0.4.70

Core types, traits, protocol, and proxy engine for mcpr crates
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
//! MCP message taxonomy (spec v2025-11-25).
//!
//! See `PIPELINE.md` §Types. Method identity
//! is a cheap enum — one string match per message. Grouping by feature
//! area (`Tools`, `Resources`, …) matches the spec table and lets
//! middlewares pattern-match at the granularity they need.
//!
//! Every method enum has an `Unknown(String)` tail variant so non-spec
//! methods forward unchanged instead of failing classification.

use super::jsonrpc::JsonRpcEnvelope;

/// Shallow envelope paired with its classification. Used inside
/// `McpRequest` (client direction) and `Response::McpBuffered` (server
/// direction).
#[derive(Debug, Clone)]
pub struct McpMessage {
    pub envelope: JsonRpcEnvelope,
    pub kind: MessageKind,
}

/// Direction discriminator for an `McpMessage`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MessageKind {
    Client(ClientKind),
    Server(ServerKind),
}

// ── Client → Server ──────────────────────────────────────────

/// Kind of message the client is sending. Computed at intake from
/// `method` + `id` + `result`/`error` presence.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ClientKind {
    Request(ClientMethod),
    Notification(ClientNotifMethod),
    Result,
    Error,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ClientMethod {
    Ping,
    Lifecycle(LifecycleMethod),
    Tools(ToolsMethod),
    Resources(ResourcesMethod),
    Prompts(PromptsMethod),
    Completion(CompletionMethod),
    Logging(LoggingMethod),
    Tasks(TasksMethod),
    Unknown(String),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LifecycleMethod {
    Initialize,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ToolsMethod {
    List,
    Call,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ResourcesMethod {
    List,
    TemplatesList,
    Read,
    Subscribe,
    Unsubscribe,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PromptsMethod {
    List,
    Get,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CompletionMethod {
    Complete,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LoggingMethod {
    SetLevel,
}

/// Task lifecycle methods. Used by both directions (client asks the
/// server about tasks; server can also request task state from the
/// client).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TasksMethod {
    List,
    Get,
    Result,
    Cancel,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ClientNotifMethod {
    Initialized,
    Cancelled,
    Progress,
    RootsListChanged,
    TaskStatus,
    Unknown(String),
}

// ── Server → Client ──────────────────────────────────────────

/// Kind of message the server is sending. Appears in response bodies
/// (streamable-HTTP chunks or legacy SSE frames).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ServerKind {
    Request(ServerMethod),
    Notification(ServerNotifMethod),
    Result,
    Error,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ServerMethod {
    Ping,
    Sampling,
    Elicitation,
    Roots,
    Tasks(TasksMethod),
    Unknown(String),
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ServerNotifMethod {
    Cancelled,
    Progress,
    LogMessage,
    ResourcesListChanged,
    ResourceUpdated,
    ToolsListChanged,
    PromptsListChanged,
    ElicitationComplete,
    TaskStatus,
    Unknown(String),
}

// ── Method parsing ────────────────────────────────────────────

impl ClientMethod {
    pub fn parse(method: &str) -> Self {
        match method {
            "ping" => Self::Ping,
            "initialize" => Self::Lifecycle(LifecycleMethod::Initialize),
            "tools/list" => Self::Tools(ToolsMethod::List),
            "tools/call" => Self::Tools(ToolsMethod::Call),
            "resources/list" => Self::Resources(ResourcesMethod::List),
            "resources/templates/list" => Self::Resources(ResourcesMethod::TemplatesList),
            "resources/read" => Self::Resources(ResourcesMethod::Read),
            "resources/subscribe" => Self::Resources(ResourcesMethod::Subscribe),
            "resources/unsubscribe" => Self::Resources(ResourcesMethod::Unsubscribe),
            "prompts/list" => Self::Prompts(PromptsMethod::List),
            "prompts/get" => Self::Prompts(PromptsMethod::Get),
            "completion/complete" => Self::Completion(CompletionMethod::Complete),
            "logging/setLevel" => Self::Logging(LoggingMethod::SetLevel),
            "tasks/list" => Self::Tasks(TasksMethod::List),
            "tasks/get" => Self::Tasks(TasksMethod::Get),
            "tasks/result" => Self::Tasks(TasksMethod::Result),
            "tasks/cancel" => Self::Tasks(TasksMethod::Cancel),
            other => Self::Unknown(other.to_owned()),
        }
    }

    /// Inverse of [`ClientMethod::parse`]. Returns `None` for
    /// `Self::Unknown(_)` — unknown methods don't have a canonical
    /// spec string.
    pub fn as_str(&self) -> Option<&'static str> {
        Some(match self {
            Self::Ping => "ping",
            Self::Lifecycle(LifecycleMethod::Initialize) => "initialize",
            Self::Tools(ToolsMethod::List) => "tools/list",
            Self::Tools(ToolsMethod::Call) => "tools/call",
            Self::Resources(ResourcesMethod::List) => "resources/list",
            Self::Resources(ResourcesMethod::TemplatesList) => "resources/templates/list",
            Self::Resources(ResourcesMethod::Read) => "resources/read",
            Self::Resources(ResourcesMethod::Subscribe) => "resources/subscribe",
            Self::Resources(ResourcesMethod::Unsubscribe) => "resources/unsubscribe",
            Self::Prompts(PromptsMethod::List) => "prompts/list",
            Self::Prompts(PromptsMethod::Get) => "prompts/get",
            Self::Completion(CompletionMethod::Complete) => "completion/complete",
            Self::Logging(LoggingMethod::SetLevel) => "logging/setLevel",
            Self::Tasks(TasksMethod::List) => "tasks/list",
            Self::Tasks(TasksMethod::Get) => "tasks/get",
            Self::Tasks(TasksMethod::Result) => "tasks/result",
            Self::Tasks(TasksMethod::Cancel) => "tasks/cancel",
            Self::Unknown(_) => return None,
        })
    }
}

impl ClientNotifMethod {
    pub fn parse(method: &str) -> Self {
        match method {
            "notifications/initialized" => Self::Initialized,
            "notifications/cancelled" => Self::Cancelled,
            "notifications/progress" => Self::Progress,
            "notifications/roots/list_changed" => Self::RootsListChanged,
            "notifications/tasks/status" => Self::TaskStatus,
            other => Self::Unknown(other.to_owned()),
        }
    }
}

impl ServerMethod {
    pub fn parse(method: &str) -> Self {
        match method {
            "ping" => Self::Ping,
            "sampling/createMessage" => Self::Sampling,
            "elicitation/create" => Self::Elicitation,
            "roots/list" => Self::Roots,
            "tasks/list" => Self::Tasks(TasksMethod::List),
            "tasks/get" => Self::Tasks(TasksMethod::Get),
            "tasks/result" => Self::Tasks(TasksMethod::Result),
            "tasks/cancel" => Self::Tasks(TasksMethod::Cancel),
            other => Self::Unknown(other.to_owned()),
        }
    }
}

impl ServerNotifMethod {
    pub fn parse(method: &str) -> Self {
        match method {
            "notifications/cancelled" => Self::Cancelled,
            "notifications/progress" => Self::Progress,
            "notifications/message" => Self::LogMessage,
            "notifications/resources/list_changed" => Self::ResourcesListChanged,
            "notifications/resources/updated" => Self::ResourceUpdated,
            "notifications/tools/list_changed" => Self::ToolsListChanged,
            "notifications/prompts/list_changed" => Self::PromptsListChanged,
            "notifications/elicitation/complete" => Self::ElicitationComplete,
            "notifications/tasks/status" => Self::TaskStatus,
            other => Self::Unknown(other.to_owned()),
        }
    }
}

// ── Classification ────────────────────────────────────────────

/// Classify a client→server envelope. Assumes the envelope came from
/// [`JsonRpcEnvelope::parse`], which already rejected malformed shapes.
pub fn classify_client(env: &JsonRpcEnvelope) -> ClientKind {
    match (
        env.method.as_deref(),
        env.id.is_some(),
        env.result.is_some(),
        env.error.is_some(),
    ) {
        (Some(m), true, false, false) => ClientKind::Request(ClientMethod::parse(m)),
        (Some(m), false, false, false) => ClientKind::Notification(ClientNotifMethod::parse(m)),
        (None, true, true, false) => ClientKind::Result,
        (None, true, false, true) => ClientKind::Error,
        _ => {
            debug_assert!(
                false,
                "classify_client: envelope shape should have been rejected by parse",
            );
            ClientKind::Error
        }
    }
}

/// Classify a server→client envelope.
pub fn classify_server(env: &JsonRpcEnvelope) -> ServerKind {
    match (
        env.method.as_deref(),
        env.id.is_some(),
        env.result.is_some(),
        env.error.is_some(),
    ) {
        (Some(m), true, false, false) => ServerKind::Request(ServerMethod::parse(m)),
        (Some(m), false, false, false) => ServerKind::Notification(ServerNotifMethod::parse(m)),
        (None, true, true, false) => ServerKind::Result,
        (None, true, false, true) => ServerKind::Error,
        _ => {
            debug_assert!(
                false,
                "classify_server: envelope shape should have been rejected by parse",
            );
            ServerKind::Error
        }
    }
}

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

    fn parsed(bytes: &[u8]) -> JsonRpcEnvelope {
        JsonRpcEnvelope::parse(bytes).unwrap()
    }

    // ── ClientMethod::parse coverage ─────────────────────────

    #[test]
    fn client_method__spec_coverage() {
        let cases: &[(&str, ClientMethod)] = &[
            ("ping", ClientMethod::Ping),
            (
                "initialize",
                ClientMethod::Lifecycle(LifecycleMethod::Initialize),
            ),
            ("tools/list", ClientMethod::Tools(ToolsMethod::List)),
            ("tools/call", ClientMethod::Tools(ToolsMethod::Call)),
            (
                "resources/list",
                ClientMethod::Resources(ResourcesMethod::List),
            ),
            (
                "resources/templates/list",
                ClientMethod::Resources(ResourcesMethod::TemplatesList),
            ),
            (
                "resources/read",
                ClientMethod::Resources(ResourcesMethod::Read),
            ),
            (
                "resources/subscribe",
                ClientMethod::Resources(ResourcesMethod::Subscribe),
            ),
            (
                "resources/unsubscribe",
                ClientMethod::Resources(ResourcesMethod::Unsubscribe),
            ),
            ("prompts/list", ClientMethod::Prompts(PromptsMethod::List)),
            ("prompts/get", ClientMethod::Prompts(PromptsMethod::Get)),
            (
                "completion/complete",
                ClientMethod::Completion(CompletionMethod::Complete),
            ),
            (
                "logging/setLevel",
                ClientMethod::Logging(LoggingMethod::SetLevel),
            ),
            ("tasks/list", ClientMethod::Tasks(TasksMethod::List)),
            ("tasks/get", ClientMethod::Tasks(TasksMethod::Get)),
            ("tasks/result", ClientMethod::Tasks(TasksMethod::Result)),
            ("tasks/cancel", ClientMethod::Tasks(TasksMethod::Cancel)),
        ];
        for (m, expected) in cases {
            assert_eq!(ClientMethod::parse(m), *expected, "method = {m}");
        }
    }

    #[test]
    fn client_method__unknown_preserves_string() {
        assert_eq!(
            ClientMethod::parse("tools/future-method"),
            ClientMethod::Unknown("tools/future-method".into()),
        );
    }

    // ── ClientNotifMethod::parse coverage ────────────────────

    #[test]
    fn client_notif_method__spec_coverage() {
        let cases: &[(&str, ClientNotifMethod)] = &[
            ("notifications/initialized", ClientNotifMethod::Initialized),
            ("notifications/cancelled", ClientNotifMethod::Cancelled),
            ("notifications/progress", ClientNotifMethod::Progress),
            (
                "notifications/roots/list_changed",
                ClientNotifMethod::RootsListChanged,
            ),
            ("notifications/tasks/status", ClientNotifMethod::TaskStatus),
        ];
        for (m, expected) in cases {
            assert_eq!(ClientNotifMethod::parse(m), *expected, "method = {m}");
        }
    }

    #[test]
    fn client_notif_method__unknown_preserves_string() {
        assert_eq!(
            ClientNotifMethod::parse("notifications/something"),
            ClientNotifMethod::Unknown("notifications/something".into()),
        );
    }

    // ── ServerMethod::parse coverage ─────────────────────────

    #[test]
    fn server_method__spec_coverage() {
        let cases: &[(&str, ServerMethod)] = &[
            ("ping", ServerMethod::Ping),
            ("sampling/createMessage", ServerMethod::Sampling),
            ("elicitation/create", ServerMethod::Elicitation),
            ("roots/list", ServerMethod::Roots),
            ("tasks/list", ServerMethod::Tasks(TasksMethod::List)),
            ("tasks/get", ServerMethod::Tasks(TasksMethod::Get)),
            ("tasks/result", ServerMethod::Tasks(TasksMethod::Result)),
            ("tasks/cancel", ServerMethod::Tasks(TasksMethod::Cancel)),
        ];
        for (m, expected) in cases {
            assert_eq!(ServerMethod::parse(m), *expected, "method = {m}");
        }
    }

    #[test]
    fn server_method__unknown_preserves_string() {
        assert_eq!(
            ServerMethod::parse("custom/method"),
            ServerMethod::Unknown("custom/method".into()),
        );
    }

    // ── ServerNotifMethod::parse coverage ────────────────────

    #[test]
    fn server_notif_method__spec_coverage() {
        let cases: &[(&str, ServerNotifMethod)] = &[
            ("notifications/cancelled", ServerNotifMethod::Cancelled),
            ("notifications/progress", ServerNotifMethod::Progress),
            ("notifications/message", ServerNotifMethod::LogMessage),
            (
                "notifications/resources/list_changed",
                ServerNotifMethod::ResourcesListChanged,
            ),
            (
                "notifications/resources/updated",
                ServerNotifMethod::ResourceUpdated,
            ),
            (
                "notifications/tools/list_changed",
                ServerNotifMethod::ToolsListChanged,
            ),
            (
                "notifications/prompts/list_changed",
                ServerNotifMethod::PromptsListChanged,
            ),
            (
                "notifications/elicitation/complete",
                ServerNotifMethod::ElicitationComplete,
            ),
            ("notifications/tasks/status", ServerNotifMethod::TaskStatus),
        ];
        for (m, expected) in cases {
            assert_eq!(ServerNotifMethod::parse(m), *expected, "method = {m}");
        }
    }

    #[test]
    fn server_notif_method__unknown_preserves_string() {
        assert_eq!(
            ServerNotifMethod::parse("notifications/future"),
            ServerNotifMethod::Unknown("notifications/future".into()),
        );
    }

    // ── classify_client ──────────────────────────────────────

    #[test]
    fn classify_client__request() {
        let e = parsed(br#"{"jsonrpc":"2.0","id":1,"method":"tools/list"}"#);
        assert_eq!(
            classify_client(&e),
            ClientKind::Request(ClientMethod::Tools(ToolsMethod::List)),
        );
    }

    #[test]
    fn classify_client__notification() {
        let e = parsed(br#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#);
        assert_eq!(
            classify_client(&e),
            ClientKind::Notification(ClientNotifMethod::Initialized),
        );
    }

    #[test]
    fn classify_client__result() {
        let e = parsed(br#"{"jsonrpc":"2.0","id":1,"result":{}}"#);
        assert_eq!(classify_client(&e), ClientKind::Result);
    }

    #[test]
    fn classify_client__error() {
        let e = parsed(br#"{"jsonrpc":"2.0","id":1,"error":{"code":-1,"message":"x"}}"#);
        assert_eq!(classify_client(&e), ClientKind::Error);
    }

    #[test]
    fn classify_client__unknown_method() {
        let e = parsed(br#"{"jsonrpc":"2.0","id":1,"method":"custom/method"}"#);
        assert_eq!(
            classify_client(&e),
            ClientKind::Request(ClientMethod::Unknown("custom/method".into())),
        );
    }

    // ── classify_server ──────────────────────────────────────

    #[test]
    fn classify_server__request() {
        let e = parsed(br#"{"jsonrpc":"2.0","id":1,"method":"sampling/createMessage"}"#);
        assert_eq!(
            classify_server(&e),
            ServerKind::Request(ServerMethod::Sampling),
        );
    }

    #[test]
    fn classify_server__notification() {
        let e = parsed(br#"{"jsonrpc":"2.0","method":"notifications/tools/list_changed"}"#);
        assert_eq!(
            classify_server(&e),
            ServerKind::Notification(ServerNotifMethod::ToolsListChanged),
        );
    }

    #[test]
    fn classify_server__result() {
        let e = parsed(br#"{"jsonrpc":"2.0","id":1,"result":{}}"#);
        assert_eq!(classify_server(&e), ServerKind::Result);
    }

    #[test]
    fn classify_server__error() {
        let e = parsed(br#"{"jsonrpc":"2.0","id":1,"error":{"code":-1,"message":"x"}}"#);
        assert_eq!(classify_server(&e), ServerKind::Error);
    }
}