rmcp 1.5.0

Rust SDK for Model Context Protocol
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
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
#![cfg(not(feature = "local"))]
mod common;

use anyhow::Result;
use common::handlers::{TestClientHandler, TestServer};
use rmcp::{
    ServiceExt,
    model::*,
    service::{RequestContext, Service},
};

#[tokio::test]
async fn test_basic_sampling_message_creation() -> Result<()> {
    let message = SamplingMessage::user_text("What is the capital of France?");

    let json = serde_json::to_string(&message)?;
    let deserialized: SamplingMessage = serde_json::from_str(&json)?;
    assert_eq!(message, deserialized);
    assert_eq!(message.role, Role::User);

    Ok(())
}

#[tokio::test]
async fn test_sampling_request_params() -> Result<()> {
    let params =
        CreateMessageRequestParams::new(vec![SamplingMessage::user_text("Hello, world!")], 100)
            .with_model_preferences(
                ModelPreferences::new()
                    .with_hints(vec![ModelHint::new("claude")])
                    .with_cost_priority(0.5)
                    .with_speed_priority(0.8)
                    .with_intelligence_priority(0.7),
            )
            .with_system_prompt("You are a helpful assistant.")
            .with_temperature(0.7)
            .with_stop_sequences(vec!["STOP".to_string()])
            .with_include_context(ContextInclusion::None)
            .with_metadata(serde_json::json!({"test": "value"}));

    let json = serde_json::to_string(&params)?;
    let deserialized: CreateMessageRequestParams = serde_json::from_str(&json)?;
    assert_eq!(params, deserialized);

    assert_eq!(params.messages.len(), 1);
    assert_eq!(params.max_tokens, 100);
    assert_eq!(params.temperature, Some(0.7));

    Ok(())
}

#[tokio::test]
async fn test_sampling_result_structure() -> Result<()> {
    let result = CreateMessageResult::new(
        SamplingMessage::assistant_text("The capital of France is Paris."),
        "test-model".to_string(),
    )
    .with_stop_reason(CreateMessageResult::STOP_REASON_END_TURN);

    let json = serde_json::to_string(&result)?;
    let deserialized: CreateMessageResult = serde_json::from_str(&json)?;
    assert_eq!(result, deserialized);

    assert_eq!(result.message.role, Role::Assistant);
    assert_eq!(result.model, "test-model");
    assert_eq!(
        result.stop_reason,
        Some(CreateMessageResult::STOP_REASON_END_TURN.to_string())
    );

    Ok(())
}

#[tokio::test]
async fn test_sampling_context_inclusion_enum() -> Result<()> {
    let test_cases = vec![
        (ContextInclusion::None, "none"),
        (ContextInclusion::ThisServer, "thisServer"),
        (ContextInclusion::AllServers, "allServers"),
    ];

    for (context, expected_json) in test_cases {
        let json = serde_json::to_string(&context)?;
        assert_eq!(json, format!("\"{}\"", expected_json));

        let deserialized: ContextInclusion = serde_json::from_str(&json)?;
        assert_eq!(context, deserialized);
    }

    Ok(())
}

#[tokio::test]
async fn test_sampling_integration_with_test_handlers() -> Result<()> {
    let (server_transport, client_transport) = tokio::io::duplex(4096);

    let server_handle = tokio::spawn(async move {
        let server = TestServer::new().serve(server_transport).await?;
        server.waiting().await?;
        anyhow::Ok(())
    });

    let handler = TestClientHandler::new(true, true);
    let client = handler.clone().serve(client_transport).await?;

    tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;

    let request = ServerRequest::CreateMessageRequest(CreateMessageRequest::new(
        CreateMessageRequestParams::new(
            vec![SamplingMessage::user_text("What is the capital of France?")],
            100,
        )
        .with_include_context(ContextInclusion::ThisServer)
        .with_model_preferences(
            ModelPreferences::new()
                .with_hints(vec![ModelHint::new("test-model")])
                .with_cost_priority(0.5)
                .with_speed_priority(0.8)
                .with_intelligence_priority(0.7),
        )
        .with_system_prompt("You are a helpful assistant.")
        .with_temperature(0.7),
    ));

    let result = handler
        .handle_request(
            request.clone(),
            RequestContext::new(NumberOrString::Number(1), client.peer().clone()),
        )
        .await?;

    if let ClientResult::CreateMessageResult(result) = result {
        assert_eq!(result.message.role, Role::Assistant);
        assert_eq!(result.model, "test-model");
        assert_eq!(
            result.stop_reason,
            Some(CreateMessageResult::STOP_REASON_END_TURN.to_string())
        );

        let response_text = result
            .message
            .content
            .first()
            .unwrap()
            .as_text()
            .unwrap()
            .text
            .as_str();
        assert!(
            response_text.contains("test context"),
            "Response should include context for ThisServer inclusion"
        );
    } else {
        panic!("Expected CreateMessageResult");
    }

    client.cancel().await?;
    server_handle.await??;
    Ok(())
}

#[tokio::test]
async fn test_sampling_no_context_inclusion() -> Result<()> {
    let (server_transport, client_transport) = tokio::io::duplex(4096);

    let server_handle = tokio::spawn(async move {
        let server = TestServer::new().serve(server_transport).await?;
        server.waiting().await?;
        anyhow::Ok(())
    });

    let handler = TestClientHandler::new(true, true);
    let client = handler.clone().serve(client_transport).await?;

    tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;

    let request = ServerRequest::CreateMessageRequest(CreateMessageRequest::new(
        CreateMessageRequestParams::new(vec![SamplingMessage::user_text("Hello")], 50)
            .with_include_context(ContextInclusion::None),
    ));

    let result = handler
        .handle_request(
            request.clone(),
            RequestContext::new(NumberOrString::Number(2), client.peer().clone()),
        )
        .await?;

    if let ClientResult::CreateMessageResult(result) = result {
        assert_eq!(result.message.role, Role::Assistant);
        assert_eq!(result.model, "test-model");

        let response_text = result
            .message
            .content
            .first()
            .unwrap()
            .as_text()
            .unwrap()
            .text
            .as_str();
        assert!(
            !response_text.contains("test context"),
            "Response should not include context for None inclusion"
        );
    } else {
        panic!("Expected CreateMessageResult");
    }

    client.cancel().await?;
    server_handle.await??;
    Ok(())
}

#[tokio::test]
async fn test_sampling_error_invalid_message_sequence() -> Result<()> {
    let (server_transport, client_transport) = tokio::io::duplex(4096);

    let server_handle = tokio::spawn(async move {
        let server = TestServer::new().serve(server_transport).await?;
        server.waiting().await?;
        anyhow::Ok(())
    });

    let handler = TestClientHandler::new(true, true);
    let client = handler.clone().serve(client_transport).await?;

    tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;

    let request = ServerRequest::CreateMessageRequest(CreateMessageRequest::new(
        CreateMessageRequestParams::new(
            vec![SamplingMessage::assistant_text(
                "I'm an assistant message without a user message",
            )],
            50,
        )
        .with_include_context(ContextInclusion::None),
    ));

    let result = handler
        .handle_request(
            request.clone(),
            RequestContext::new(NumberOrString::Number(3), client.peer().clone()),
        )
        .await;

    assert!(result.is_err());

    client.cancel().await?;
    server_handle.await??;
    Ok(())
}

#[tokio::test]
async fn test_tool_choice_serialization() -> Result<()> {
    let auto = ToolChoice::auto();
    let json = serde_json::to_string(&auto)?;
    assert!(json.contains("auto"));
    let deserialized: ToolChoice = serde_json::from_str(&json)?;
    assert_eq!(auto, deserialized);

    let required = ToolChoice::required();
    let json = serde_json::to_string(&required)?;
    assert!(json.contains("required"));
    let deserialized: ToolChoice = serde_json::from_str(&json)?;
    assert_eq!(required, deserialized);

    let none = ToolChoice::none();
    let json = serde_json::to_string(&none)?;
    assert!(json.contains("none"));
    let deserialized: ToolChoice = serde_json::from_str(&json)?;
    assert_eq!(none, deserialized);

    Ok(())
}

#[tokio::test]
async fn test_sampling_with_tools() -> Result<()> {
    use std::sync::Arc;

    let tool = Tool::new(
        "get_weather",
        "Get the current weather for a location",
        Arc::new(
            serde_json::json!({
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "The city and state, e.g. San Francisco, CA"
                    }
                },
                "required": ["location"]
            })
            .as_object()
            .unwrap()
            .clone(),
        ),
    );

    let params = CreateMessageRequestParams::new(
        vec![SamplingMessage::user_text(
            "What's the weather in San Francisco?",
        )],
        100,
    )
    .with_tools(vec![tool])
    .with_tool_choice(ToolChoice::auto());

    let json = serde_json::to_string(&params)?;
    let deserialized: CreateMessageRequestParams = serde_json::from_str(&json)?;

    assert!(deserialized.tools.is_some());
    assert_eq!(deserialized.tools.as_ref().unwrap().len(), 1);
    assert_eq!(deserialized.tools.as_ref().unwrap()[0].name, "get_weather");
    assert!(deserialized.tool_choice.is_some());

    Ok(())
}

#[tokio::test]
async fn test_tool_use_content_serialization() -> Result<()> {
    let tool_use = ToolUseContent::new(
        "call_123",
        "get_weather",
        serde_json::json!({
            "location": "San Francisco, CA"
        })
        .as_object()
        .unwrap()
        .clone(),
    );

    let json = serde_json::to_string(&tool_use)?;
    let deserialized: ToolUseContent = serde_json::from_str(&json)?;
    assert_eq!(tool_use, deserialized);
    assert_eq!(deserialized.id, "call_123");
    assert_eq!(deserialized.name, "get_weather");

    Ok(())
}

#[tokio::test]
async fn test_tool_result_content_serialization() -> Result<()> {
    let tool_result = ToolResultContent::new(
        "call_123",
        vec![Content::text(
            "The weather in San Francisco is 72°F and sunny.",
        )],
    );

    let json = serde_json::to_string(&tool_result)?;
    let deserialized: ToolResultContent = serde_json::from_str(&json)?;
    assert_eq!(tool_result, deserialized);
    assert_eq!(deserialized.tool_use_id, "call_123");
    assert!(!deserialized.content.is_empty());

    Ok(())
}

#[tokio::test]
async fn test_sampling_message_with_tool_use() -> Result<()> {
    let message = SamplingMessage::assistant_tool_use(
        "call_123",
        "get_weather",
        serde_json::json!({
            "location": "San Francisco, CA"
        })
        .as_object()
        .unwrap()
        .clone(),
    );

    let json = serde_json::to_string(&message)?;
    let deserialized: SamplingMessage = serde_json::from_str(&json)?;
    assert_eq!(message, deserialized);
    assert_eq!(deserialized.role, Role::Assistant);

    let tool_use = deserialized.content.first().unwrap().as_tool_use().unwrap();
    assert_eq!(tool_use.name, "get_weather");

    Ok(())
}

#[tokio::test]
async fn test_sampling_message_with_tool_result() -> Result<()> {
    let message =
        SamplingMessage::user_tool_result("call_123", vec![Content::text("72°F and sunny")]);

    let json = serde_json::to_string(&message)?;
    let deserialized: SamplingMessage = serde_json::from_str(&json)?;
    assert_eq!(message, deserialized);
    assert_eq!(deserialized.role, Role::User);

    let tool_result = deserialized
        .content
        .first()
        .unwrap()
        .as_tool_result()
        .unwrap();
    assert_eq!(tool_result.tool_use_id, "call_123");

    Ok(())
}

#[tokio::test]
async fn test_create_message_result_tool_use_stop_reason() -> Result<()> {
    let result = CreateMessageResult::new(
        SamplingMessage::assistant_tool_use(
            "call_123",
            "get_weather",
            serde_json::json!({
                "location": "San Francisco"
            })
            .as_object()
            .unwrap()
            .clone(),
        ),
        "test-model".to_string(),
    )
    .with_stop_reason(CreateMessageResult::STOP_REASON_TOOL_USE);

    let json = serde_json::to_string(&result)?;
    let deserialized: CreateMessageResult = serde_json::from_str(&json)?;
    assert_eq!(result, deserialized);
    assert_eq!(deserialized.stop_reason, Some("toolUse".to_string()));

    Ok(())
}

#[tokio::test]
async fn test_sampling_capability() -> Result<()> {
    let cap = SamplingCapability {
        tools: Some(JsonObject::default()),
        context: None,
    };

    let json = serde_json::to_string(&cap)?;
    let deserialized: SamplingCapability = serde_json::from_str(&json)?;
    assert_eq!(cap, deserialized);
    assert!(deserialized.tools.is_some());
    assert!(deserialized.context.is_none());

    let client_cap = ClientCapabilities::builder()
        .enable_sampling()
        .enable_sampling_tools()
        .build();

    assert!(client_cap.sampling.is_some());
    assert!(client_cap.sampling.as_ref().unwrap().tools.is_some());

    Ok(())
}

#[tokio::test]
async fn test_backward_compat_sampling_message_deserialization() -> Result<()> {
    let old_format_json = r#"{
        "role": "user",
        "content": {
            "type": "text",
            "text": "Hello, world!"
        }
    }"#;

    let message: SamplingMessage = serde_json::from_str(old_format_json)?;
    assert_eq!(message.role, Role::User);
    let text = message.content.first().unwrap().as_text().unwrap();
    assert_eq!(text.text, "Hello, world!");

    Ok(())
}

#[tokio::test]
async fn test_backward_compat_sampling_message_with_image() -> Result<()> {
    let old_format_json = r#"{
        "role": "user",
        "content": {
            "type": "image",
            "data": "base64data",
            "mimeType": "image/png"
        }
    }"#;

    let message: SamplingMessage = serde_json::from_str(old_format_json)?;
    assert_eq!(message.role, Role::User);
    assert_eq!(message.content.len(), 1);

    Ok(())
}

#[tokio::test]
async fn test_backward_compat_sampling_capability_empty_object() -> Result<()> {
    let empty_json = "{}";
    let cap: SamplingCapability = serde_json::from_str(empty_json)?;
    assert!(cap.tools.is_none());
    assert!(cap.context.is_none());

    let client_cap_json = r#"{"sampling": {}}"#;
    let client_cap: ClientCapabilities = serde_json::from_str(client_cap_json)?;
    assert!(client_cap.sampling.is_some());

    Ok(())
}

#[tokio::test]
async fn test_content_to_sampling_message_content_conversion() -> Result<()> {
    use std::convert::TryInto;

    let content = Content::text("Hello");
    let sampling_content: SamplingMessageContent =
        content.try_into().map_err(|e: &str| anyhow::anyhow!(e))?;
    assert!(sampling_content.as_text().is_some());
    assert_eq!(sampling_content.as_text().unwrap().text, "Hello");

    let content = Content::image("base64data", "image/png");
    let sampling_content: SamplingMessageContent =
        content.try_into().map_err(|e: &str| anyhow::anyhow!(e))?;
    assert!(matches!(sampling_content, SamplingMessageContent::Image(_)));

    Ok(())
}

#[tokio::test]
async fn test_content_to_sampling_content_conversion() -> Result<()> {
    use std::convert::TryInto;

    let content = Content::text("Hello");
    let sampling_content: SamplingContent<SamplingMessageContent> =
        content.try_into().map_err(|e: &str| anyhow::anyhow!(e))?;
    assert_eq!(sampling_content.len(), 1);
    assert!(sampling_content.first().unwrap().as_text().is_some());

    Ok(())
}

#[tokio::test]
async fn test_content_conversion_unsupported_variants() {
    use std::convert::TryInto;

    use rmcp::model::ResourceContents;

    let resource_content = Content::resource(ResourceContents::TextResourceContents {
        uri: "file:///test.txt".to_string(),
        mime_type: Some("text/plain".to_string()),
        text: "test".to_string(),
        meta: None,
    });

    let result: Result<SamplingMessageContent, _> = resource_content.try_into();
    assert!(result.is_err());
    assert_eq!(
        result.unwrap_err(),
        "Resource content is not supported in sampling messages"
    );
}

#[tokio::test]
async fn test_validate_rejects_tool_use_in_user_message() {
    let params = CreateMessageRequestParams::new(
        vec![SamplingMessage::new(
            Role::User,
            SamplingMessageContent::tool_use("call_1", "some_tool", Default::default()),
        )],
        100,
    );

    let err = params.validate().unwrap_err();
    assert!(
        err.contains("ToolUse content is only allowed in assistant messages"),
        "unexpected error: {err}"
    );
}

#[tokio::test]
async fn test_validate_rejects_tool_result_in_assistant_message() {
    let params = CreateMessageRequestParams::new(
        vec![SamplingMessage::new(
            Role::Assistant,
            SamplingMessageContent::tool_result("call_1", vec![Content::text("result")]),
        )],
        100,
    );

    let err = params.validate().unwrap_err();
    assert!(
        err.contains("ToolResult content is only allowed in user messages"),
        "unexpected error: {err}"
    );
}

#[tokio::test]
async fn test_validate_rejects_mixed_content_with_tool_result() {
    let params = CreateMessageRequestParams::new(
        vec![SamplingMessage::new_multiple(
            Role::User,
            vec![
                SamplingMessageContent::tool_result("call_1", vec![Content::text("result")]),
                SamplingMessageContent::text("some extra text"),
            ],
        )],
        100,
    );

    let err = params.validate().unwrap_err();
    assert!(
        err.contains("MUST NOT contain other content types"),
        "unexpected error: {err}"
    );
}

#[tokio::test]
async fn test_validate_rejects_unbalanced_tool_use_result() {
    let params = CreateMessageRequestParams::new(
        vec![
            SamplingMessage::user_text("Hello"),
            SamplingMessage::assistant_tool_use("call_1", "some_tool", Default::default()),
        ],
        100,
    );

    let err = params.validate().unwrap_err();
    assert!(
        err.contains("not balanced with ToolResult"),
        "unexpected error: {err}"
    );
}

#[tokio::test]
async fn test_validate_rejects_tool_result_without_matching_use() {
    let params = CreateMessageRequestParams::new(
        vec![
            SamplingMessage::user_text("Hello"),
            SamplingMessage::user_tool_result("nonexistent_call", vec![Content::text("result")]),
        ],
        100,
    );

    let err = params.validate().unwrap_err();
    assert!(
        err.contains("has no matching ToolUse"),
        "unexpected error: {err}"
    );
}

#[tokio::test]
async fn test_validate_accepts_valid_tool_conversation() {
    let params = CreateMessageRequestParams::new(
        vec![
            SamplingMessage::user_text("What's the weather?"),
            SamplingMessage::assistant_tool_use(
                "call_1",
                "get_weather",
                serde_json::json!({"location": "SF"})
                    .as_object()
                    .unwrap()
                    .clone(),
            ),
            SamplingMessage::user_tool_result("call_1", vec![Content::text("72°F and sunny")]),
            SamplingMessage::assistant_text("It's 72°F and sunny in SF."),
        ],
        100,
    );

    assert!(params.validate().is_ok());
}

#[tokio::test]
async fn test_create_message_result_validate_rejects_user_role() {
    let result = CreateMessageResult::new(
        SamplingMessage::user_text("This should not be a user message"),
        "test-model".to_string(),
    )
    .with_stop_reason(CreateMessageResult::STOP_REASON_END_TURN);

    let err = result.validate().unwrap_err();
    assert!(
        err.contains("role must be 'assistant'"),
        "unexpected error: {err}"
    );
}

#[tokio::test]
async fn test_create_message_result_validate_accepts_assistant_role() {
    let result = CreateMessageResult::new(
        SamplingMessage::assistant_text("Hello!"),
        "test-model".to_string(),
    )
    .with_stop_reason(CreateMessageResult::STOP_REASON_END_TURN);

    assert!(result.validate().is_ok());
}