pmcp 2.9.0

High-quality Rust SDK for Model Context Protocol (MCP) with full TypeScript SDK compatibility
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
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
//! Property-based tests for PMCP SDK
//!
//! These tests verify invariants and properties that should hold across
//! the entire PMCP protocol implementation using property-based testing.
//!
//! ALWAYS Requirement: Property tests for all new features

// Phase 73 list_all_* property tests share MockTransport + builders with
// tests/list_all_pagination.rs via this single `#[path]` declaration —
// `mod mock_paginated` MUST NOT be redeclared inside any nested module.
#[path = "common/mock_paginated.rs"]
mod mock_paginated;

use pmcp::types::*;
use proptest::prelude::*;

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

    proptest! {
        /// Property: JSON-RPC serialization round-trip should preserve data
        #[test]
        fn property_jsonrpc_roundtrip(
            id in prop::option::of(any::<i64>().prop_map(RequestId::Number)),
            method in "[a-zA-Z_][a-zA-Z0-9_/]*",
            params in prop::option::of(prop::collection::hash_map(
                "[a-zA-Z_][a-zA-Z0-9_]*",
                any::<i32>().prop_map(|i| serde_json::Value::Number(i.into())),
                0..10
            ))
        ) {
            let request = JSONRPCRequest {
                jsonrpc: "2.0".to_string(),
                id: id.unwrap_or(RequestId::Number(1)),
                method: method.clone(),
                params: params.clone().map(|p| serde_json::to_value(p).unwrap()),
            };

            // Serialize and deserialize
            let serialized = serde_json::to_string(&request).unwrap();
            let deserialized: JSONRPCRequest = serde_json::from_str(&serialized).unwrap();

            // Properties that must hold
            prop_assert_eq!(request.jsonrpc, deserialized.jsonrpc);
            prop_assert_eq!(request.id, deserialized.id);
            prop_assert_eq!(request.method, deserialized.method);
            prop_assert_eq!(request.params, deserialized.params);
        }

        /// Property: Error codes should round-trip correctly for non-server errors
        #[test]
        fn property_error_code_roundtrip(
            code in -32999i32..-32100i32
        ) {
            use pmcp::error::ErrorCode;

            let error_code = ErrorCode::other(code);
            let as_i32 = error_code.as_i32();
            let from_i32 = ErrorCode::other(as_i32);

            prop_assert_eq!(error_code.as_i32(), from_i32.as_i32());
        }

        /// Property: Request IDs should be unique and stable
        #[test]
        fn property_request_id_uniqueness(
            ids in prop::collection::vec(any::<i64>(), 1..100)
        ) {
            let request_ids: Vec<RequestId> = ids.into_iter()
                .map(RequestId::Number)
                .collect();

            // Each ID should serialize to a unique string
            let serialized: Vec<String> = request_ids.iter()
                .map(|id| serde_json::to_string(id).unwrap())
                .collect();

            let mut unique_serialized = serialized.clone();
            unique_serialized.sort();
            unique_serialized.dedup();

            prop_assert_eq!(serialized.len(), unique_serialized.len());
        }
    }
}

#[cfg(test)]
mod uri_template_properties {
    use super::*;
    use pmcp::shared::uri_template::UriTemplate;

    proptest! {
        /// Property: URI template expansion should be deterministic
        #[test]
        fn property_uri_template_deterministic(
            template_str in "[a-zA-Z0-9_/{}-]*",
            params_vec in prop::collection::vec(
                ("[a-zA-Z_][a-zA-Z0-9_]*", "[a-zA-Z0-9_-]*"),
                0..5
            )
        ) {
            if let Ok(template) = UriTemplate::new(&template_str) {
                let expanded1 = template.expand(&params_vec);
                let expanded2 = template.expand(&params_vec);

                // Expansion should be deterministic
                prop_assert_eq!(expanded1.is_ok(), expanded2.is_ok());
                if let (Ok(exp1), Ok(exp2)) = (expanded1, expanded2) {
                    prop_assert_eq!(exp1, exp2);
                }
            }
        }

        /// Property: URI template matching should be consistent
        #[test]
        fn property_uri_template_match_consistency(
            segments in prop::collection::vec("[a-zA-Z0-9_-]+", 1..5)
        ) {
            let template_str = format!("/{}", segments.join("/"));
            let uri_str = format!("/{}", segments.join("/"));

            if let Ok(template) = UriTemplate::new(&template_str) {
                let matches1 = template.match_uri(&uri_str);
                let matches2 = template.match_uri(&uri_str);

                // Matching should be deterministic
                prop_assert_eq!(matches1.is_some(), matches2.is_some());
                if let (Some(m1), Some(m2)) = (matches1, matches2) {
                    prop_assert_eq!(m1, m2);
                }
            }
        }
    }
}

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

    proptest! {
        /// Property: Client capabilities should maintain logical consistency
        #[test]
        fn property_client_capabilities_consistency(
            roots_support in any::<bool>(),
            sampling_support in any::<bool>()
        ) {
            let mut capabilities = ClientCapabilities::minimal();

            if roots_support {
                capabilities.roots = Some(RootsCapabilities {
                    list_changed: true,
                });
            }

            if sampling_support {
                capabilities.sampling = Some(SamplingCapabilities::default());
            }

            // Test serialization round-trip
            let serialized = serde_json::to_string(&capabilities).unwrap();
            let deserialized: ClientCapabilities = serde_json::from_str(&serialized).unwrap();

            // Capability support methods should be consistent
            prop_assert_eq!(
                capabilities.sampling.is_some(),
                deserialized.sampling.is_some()
            );

            prop_assert_eq!(
                capabilities.roots.is_some(),
                deserialized.roots.is_some()
            );
        }

        /// Property: Server capabilities should be logically consistent
        #[test]
        fn property_server_capabilities_consistency(
            tools_count in 0usize..10,
            resources_count in 0usize..10,
            prompts_count in 0usize..10
        ) {
            let mut capabilities = ServerCapabilities::minimal();

            if tools_count > 0 {
                capabilities.tools = Some(ToolCapabilities {
                    list_changed: Some(true),
                });
            }

            if resources_count > 0 {
                capabilities.resources = Some(ResourceCapabilities {
                    subscribe: Some(true),
                    list_changed: Some(true),
                });
            }

            if prompts_count > 0 {
                capabilities.prompts = Some(PromptCapabilities {
                    list_changed: Some(true),
                });
            }

            // Logical consistency checks
            prop_assert_eq!(
                capabilities.tools.is_some(),
                tools_count > 0
            );

            prop_assert_eq!(
                capabilities.resources.is_some(),
                resources_count > 0
            );

            prop_assert_eq!(
                capabilities.prompts.is_some(),
                prompts_count > 0
            );
        }
    }
}

#[cfg(test)]
mod transport_properties {
    use super::*;
    use pmcp::shared::transport::*;

    proptest! {
        /// Property: Message priorities should be ordered correctly
        #[test]
        fn property_message_priority_ordering(
            priorities in prop::collection::vec(
                prop::strategy::Union::new([
                    Just(MessagePriority::High).boxed(),
                    Just(MessagePriority::Normal).boxed(),
                    Just(MessagePriority::Low).boxed(),
                ]),
                1..10
            )
        ) {
            let mut sorted_priorities = priorities.clone();
            sorted_priorities.sort();

            // High should be last, Low should be first
            if priorities.contains(&MessagePriority::High) {
                prop_assert_eq!(sorted_priorities[sorted_priorities.len() - 1], MessagePriority::High);
            }

            if priorities.contains(&MessagePriority::Low) {
                prop_assert_eq!(sorted_priorities[0], MessagePriority::Low);
            }
        }

        /// Property: Transport message metadata should maintain consistency
        #[test]
        fn property_transport_message_metadata(
            priority in prop::strategy::Union::new([
                Just(MessagePriority::High).boxed(),
                Just(MessagePriority::Normal).boxed(),
                Just(MessagePriority::Low).boxed(),
            ])
        ) {
            let metadata = MessageMetadata {
                content_type: None,
                priority: Some(priority),
                flush: false,
            };

            // Test that metadata maintains consistency
            prop_assert_eq!(metadata.priority, Some(priority));
        }
    }
}

#[cfg(test)]
mod error_properties {
    use super::*;
    use pmcp::error::*;

    proptest! {
        /// Property: Error creation should be consistent
        #[test]
        fn property_error_consistency(
            message in "[a-zA-Z0-9 _.-]{1,100}"
        ) {
            let parse_error = Error::parse(message.clone());
            let invalid_request = Error::validation(message.clone());
            let method_not_found = Error::method_not_found(message.clone());
            let invalid_params = Error::invalid_params(message.clone());
            let internal_error = Error::internal(message.clone());

            // Parse errors should have error codes
            prop_assert!(parse_error.error_code().is_some());

            // Other errors may or may not have error codes depending on the implementation
            // But we can test they handle properly
            let _has_code = invalid_request.error_code();
            let _has_code = method_not_found.error_code();
            let _has_code = invalid_params.error_code();
            let _has_code = internal_error.error_code();

            // Error codes should be in valid range
            if let Some(code) = parse_error.error_code() {
                let code_i32 = code.as_i32();
                prop_assert!((-32999..=-32000).contains(&code_i32));
            }
        }
    }
}

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

    proptest! {
        /// Property: JSON serialization should be stable
        #[test]
        fn property_json_stability(
            numbers in prop::collection::vec(any::<i64>(), 0..50),
            strings in prop::collection::vec("[a-zA-Z0-9 _.-]*", 0..20),
            booleans in prop::collection::vec(any::<bool>(), 0..10)
        ) {
            let mut json_obj = serde_json::Map::new();

            for (i, num) in numbers.iter().enumerate() {
                json_obj.insert(
                    format!("num_{}", i),
                    serde_json::Value::Number((*num).into())
                );
            }

            for (i, s) in strings.iter().enumerate() {
                json_obj.insert(
                    format!("str_{}", i),
                    serde_json::Value::String(s.clone())
                );
            }

            for (i, b) in booleans.iter().enumerate() {
                json_obj.insert(
                    format!("bool_{}", i),
                    serde_json::Value::Bool(*b)
                );
            }

            let json_value = serde_json::Value::Object(json_obj);

            // Serialize and deserialize
            let serialized1 = serde_json::to_string(&json_value).unwrap();
            let deserialized: serde_json::Value = serde_json::from_str(&serialized1).unwrap();
            let serialized2 = serde_json::to_string(&deserialized).unwrap();

            // Should be stable through round-trips
            let deser2: serde_json::Value = serde_json::from_str(&serialized2).unwrap();
            prop_assert_eq!(json_value, deser2);
        }
    }
}

// === Typed-helper delegation equivalence ===
//
// Property: `call_tool_typed(name, &args)` sends the same wire bytes as
// `call_tool(name, serde_json::to_value(&args).unwrap())`. Validated by
// capturing the outgoing JSON-RPC `tools/call` request on a pair of mock
// transports and asserting the recovered `params.arguments` field equals
// `serde_json::to_value(&args)`.
#[cfg(test)]
mod typed_helper_properties {
    use async_trait::async_trait;
    use pmcp::{
        shared::Transport,
        types::{ClientCapabilities, RequestId, TransportMessage},
        Client, Error as PmcpError, Result as PmcpResult,
    };
    use proptest::prelude::*;
    use serde::Serialize;
    use serde_json::json;
    use std::sync::{Arc, Mutex};

    #[derive(Clone, Debug, Serialize)]
    struct ProptestArgs {
        a: i64,
        b: String,
        c: Vec<u32>,
    }

    /// `MockTransport` variant that exposes captured outgoing messages.
    #[derive(Debug)]
    struct CaptureTransport {
        responses: Arc<Mutex<Vec<TransportMessage>>>,
        sent: Arc<Mutex<Vec<TransportMessage>>>,
    }

    #[async_trait]
    impl Transport for CaptureTransport {
        async fn send(&mut self, m: TransportMessage) -> PmcpResult<()> {
            self.sent.lock().unwrap().push(m);
            Ok(())
        }

        async fn receive(&mut self) -> PmcpResult<TransportMessage> {
            self.responses
                .lock()
                .unwrap()
                .pop()
                .ok_or_else(|| PmcpError::protocol_msg("no more responses"))
        }

        async fn close(&mut self) -> PmcpResult<()> {
            Ok(())
        }
    }

    fn init_response() -> TransportMessage {
        use pmcp::types::{jsonrpc::ResponsePayload, JSONRPCResponse};
        TransportMessage::Response(JSONRPCResponse {
            jsonrpc: "2.0".to_string(),
            id: RequestId::from(1i64),
            payload: ResponsePayload::Result(json!({
                "protocolVersion": "2025-06-18",
                "capabilities": { "tools": {} },
                "serverInfo": { "name": "t", "version": "0" }
            })),
        })
    }

    fn call_response(id: i64) -> TransportMessage {
        use pmcp::types::{jsonrpc::ResponsePayload, JSONRPCResponse};
        TransportMessage::Response(JSONRPCResponse {
            jsonrpc: "2.0".to_string(),
            id: RequestId::from(id),
            payload: ResponsePayload::Result(json!({ "content": [] })),
        })
    }

    /// Extract the `params.arguments` JSON field from the captured outgoing
    /// `tools/call` request, if any.
    fn captured_arguments(sent: &[TransportMessage]) -> Option<serde_json::Value> {
        sent.iter().find_map(|m| {
            let TransportMessage::Request { request, .. } = m else {
                return None;
            };
            let v = serde_json::to_value(request).ok()?;
            // The wire format nests under method-name key "tools/call" which
            // maps to params via serde's internally-tagged enum. Try a few
            // traversal shapes to stay robust:
            // 1. { "method": "tools/call", "params": { "arguments": ... } }
            // 2. { "tools/call": { "arguments": ... } }
            // 3. { "params": { "arguments": ... } }
            if let Some(args) = v.get("params").and_then(|p| p.get("arguments")).cloned() {
                return Some(args);
            }
            if let Some(args) = v
                .get("tools/call")
                .and_then(|p| p.get("arguments"))
                .cloned()
            {
                return Some(args);
            }
            None
        })
    }

    proptest! {
        /// Delegation equivalence for `call_tool_typed` serialize path:
        /// for any ProptestArgs, the `arguments` field on the captured
        /// tools/call JSONRPC request equals `serde_json::to_value(&args)`.
        #[test]
        fn prop_call_tool_typed_sends_expected_value(
            a in any::<i64>(),
            b in "[a-z]{0,16}",
            c in prop::collection::vec(any::<u32>(), 0..8),
        ) {
            let args = ProptestArgs { a, b: b.clone(), c: c.clone() };
            let expected = serde_json::to_value(&args).unwrap();

            let sent = Arc::new(Mutex::new(Vec::<TransportMessage>::new()));
            let transport = CaptureTransport {
                responses: Arc::new(Mutex::new(vec![call_response(2), init_response()])),
                sent: Arc::clone(&sent),
            };

            let rt = tokio::runtime::Builder::new_current_thread()
                .enable_all()
                .build()
                .unwrap();
            rt.block_on(async move {
                let mut client = Client::new(transport);
                client.initialize(ClientCapabilities::minimal()).await.unwrap();
                let _ = client.call_tool_typed("prop", &args).await;
            });

            let sent_snapshot = sent.lock().unwrap().clone();
            let recovered = captured_arguments(&sent_snapshot);

            // If the wire-format traversal could not locate arguments, fall
            // back to the delegation-equivalence check: driving `call_tool`
            // with the same serialized value must produce the identical
            // `sent` vec. This establishes the same invariant (typed helper
            // serializes-and-delegates) without relying on internal wire
            // accessors.
            if recovered.is_none() {
                let sent_b = Arc::new(Mutex::new(Vec::<TransportMessage>::new()));
                let transport_b = CaptureTransport {
                    responses: Arc::new(Mutex::new(vec![call_response(2), init_response()])),
                    sent: Arc::clone(&sent_b),
                };
                let rt = tokio::runtime::Builder::new_current_thread()
                .enable_all()
                .build()
                .unwrap();
                rt.block_on(async move {
                    let mut client = Client::new(transport_b);
                    client.initialize(ClientCapabilities::minimal()).await.unwrap();
                    let _ = client.call_tool("prop".to_string(), expected.clone()).await;
                });
                let snap_a = sent_snapshot;
                let snap_b = sent_b.lock().unwrap().clone();
                // The two sent vecs must be byte-identical at the serde_json
                // level (RequestId strings will differ — strip them before
                // comparison).
                let strip = |msgs: &[TransportMessage]| -> Vec<serde_json::Value> {
                    msgs.iter()
                        .filter_map(|m| {
                            let TransportMessage::Request { request, .. } = m else { return None };
                            serde_json::to_value(request).ok()
                        })
                        .collect()
                };
                prop_assert_eq!(strip(&snap_a), strip(&snap_b));
            } else {
                prop_assert_eq!(recovered, Some(expected));
            }
        }
    }
}

// === list_all_* pagination properties ===
//
// The `#[path = "common/mock_paginated.rs"] mod mock_paginated;` declaration
// lives ONCE at the top of this file — do NOT redeclare it here.
#[cfg(test)]
mod list_all_pagination_properties {
    use super::mock_paginated::{
        build_paginated_responses, init_response, MockTransport, PaginationCapability,
    };
    use pmcp::{types::ClientCapabilities, Client, ClientOptions, Error};
    use proptest::prelude::*;
    use serde_json::{json, Value};

    proptest! {
        #![proptest_config(ProptestConfig { cases: 64, .. ProptestConfig::default() })]

        /// Flat-concatenation invariant: for any N-page sequence (N in 1..=7),
        /// `list_all_tools` returns the in-order concatenation of tool names
        /// across all pages.
        #[test]
        fn prop_list_all_tools_flat_concatenation(
            pages in prop::collection::vec(
                prop::collection::vec("[a-z]{1,6}", 0..4),
                1..8,
            ),
        ) {
            let page_payloads: Vec<Vec<Value>> = pages
                .iter()
                .map(|names| {
                    names
                        .iter()
                        .map(|n| json!({"name": n, "description": "", "inputSchema": {}}))
                        .collect()
                })
                .collect();
            let responses = build_paginated_responses(
                init_response(),
                page_payloads,
                PaginationCapability::Tools,
            );
            let expected: Vec<String> = pages.into_iter().flatten().collect();

            let rt = tokio::runtime::Builder::new_current_thread()
                .enable_all()
                .build()
                .unwrap();
            let observed = rt.block_on(async move {
                let mut client = Client::new(MockTransport::with_responses(responses));
                client
                    .initialize(ClientCapabilities::minimal())
                    .await
                    .unwrap();
                client.list_all_tools().await.unwrap()
            });
            let observed_names: Vec<String> = observed.into_iter().map(|t| t.name).collect();
            prop_assert_eq!(observed_names, expected);
        }

        /// Cap-enforcement invariant: `max_iterations = cap` + `cap + 2` scripted
        /// pages forces the cap-exceeded branch to fire with `Error::Validation`.
        ///
        /// `build_paginated_responses` assigns `next_cursor: None` to the final
        /// scripted page. With `cap + 1` pages, the `cap`-th iteration would see
        /// that terminal `None` and exit with `Ok(_)`, so the cap branch would be
        /// unreachable and the property would pass vacuously. `cap + 2` pages
        /// guarantees every page inside the budget carries `Some(_)`, so the
        /// `cap`-th iteration observes a non-terminal cursor and the for-loop's
        /// cap branch fires. `Ok(_)` is a counter-example under this property.
        #[test]
        fn prop_list_all_tools_cap_enforced(cap in 1usize..20) {
            let page_count = cap + 2;
            let page_payloads: Vec<Vec<Value>> = (0..page_count)
                .map(|i| {
                    vec![json!({
                        "name": format!("t{i}"),
                        "description": "",
                        "inputSchema": {}
                    })]
                })
                .collect();
            let responses = build_paginated_responses(
                init_response(),
                page_payloads,
                PaginationCapability::Tools,
            );

            let opts = ClientOptions::default().with_max_iterations(cap);
            let rt = tokio::runtime::Builder::new_current_thread()
                .enable_all()
                .build()
                .unwrap();
            let result = rt.block_on(async move {
                let mut client = Client::with_client_options(
                    MockTransport::with_responses(responses),
                    opts,
                );
                client
                    .initialize(ClientCapabilities::minimal())
                    .await
                    .unwrap();
                client.list_all_tools().await
            });

            prop_assert!(
                result.is_err(),
                "cap-enforced property violated: helper returned Ok(_) when it should have errored with Error::Validation after {cap} iterations"
            );
            let e = result.unwrap_err();
            prop_assert!(
                matches!(e, Error::Validation(_)),
                "expected Error::Validation, got a different error variant: {e}"
            );
            let msg = format!("{e}");
            prop_assert!(
                msg.contains("list_all_tools"),
                "method name missing from validation error: {msg}"
            );
        }
    }
}