-
Notifications
You must be signed in to change notification settings - Fork 580
Expand file tree
/
Copy pathserver.rs
More file actions
1780 lines (1682 loc) · 69.9 KB
/
Copy pathserver.rs
File metadata and controls
1780 lines (1682 loc) · 69.9 KB
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
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#![allow(deprecated)]
use std::{
collections::{HashMap, HashSet},
sync::{
Arc,
atomic::{AtomicU64, Ordering},
},
};
use rmcp::{
ErrorData, RoleServer, ServerHandler,
model::*,
service::{RequestContext, SubscriptionContext, SubscriptionSink},
task_manager::{TaskExit, TaskManager, TaskOptions},
transport::{
StreamableHttpServerConfig, StreamableHttpService,
streamable_http_server::session::local::LocalSessionManager,
},
};
use serde_json::{Value, json};
use tokio::sync::Mutex;
use tracing_subscriber::EnvFilter;
// Small base64-encoded 1x1 red PNG
const TEST_IMAGE_DATA: &str = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==";
// Small base64-encoded WAV (silence)
const TEST_AUDIO_DATA: &str = "UklGRiQAAABXQVZFZm10IBAAAAABAAEARKwAAIhYAQACABAAZGF0YQAAAAA=";
const CACHE_TTL_MS: u64 = 60_000;
/// Helper to convert a serde_json::Value (must be an object) into a JsonObject
fn json_object(v: Value) -> JsonObject {
match v {
Value::Object(map) => map,
_ => panic!("Expected JSON object"),
}
}
fn custom_header_tool() -> Tool {
Tool::new(
"test_custom_header",
"Validates SEP-2243 custom parameter headers",
json_object(json!({
"type": "object",
"properties": {
"value": { "type": "string", "x-mcp-header": "Value" }
},
"required": ["value"]
})),
)
}
/// Signing key for SEP-2322 `requestState` sealing. A fixed key is fine for a
/// conformance harness; real servers must load a secret out of clients' reach.
const REQUEST_STATE_KEY: &[u8] = b"rust-sdk-conformance-request-state-key!!";
#[derive(Clone)]
struct ConformanceServer {
legacy_resource_subscriptions: Arc<Mutex<HashSet<String>>>,
subscriptions: Arc<Mutex<HashMap<u64, SubscriptionSink>>>,
next_subscription: Arc<AtomicU64>,
log_level: Arc<Mutex<LoggingLevel>>,
request_state_codec: RequestStateCodec,
tasks: TaskManager,
}
impl ConformanceServer {
fn new() -> Self {
Self {
legacy_resource_subscriptions: Arc::new(Mutex::new(HashSet::new())),
subscriptions: Arc::new(Mutex::new(HashMap::new())),
next_subscription: Arc::new(AtomicU64::new(0)),
log_level: Arc::new(Mutex::new(LoggingLevel::Debug)),
request_state_codec: RequestStateCodec::new(REQUEST_STATE_KEY),
tasks: TaskManager::new(),
}
}
}
// ─── SEP-2663 Tasks extension fixtures ──────────────────────────────────────
/// Fixture tools required by the Tasks extension conformance scenarios.
const TASK_FIXTURE_TOOLS: &[&str] = &[
"greet",
"slow_compute",
"failing_job",
"protocol_error_job",
"confirm_delete",
"multi_input",
"test_tool_with_task",
];
/// Tools that are registered as task-supporting. `greet` is deliberately
/// sync-only.
const TASK_SUPPORTING_TOOLS: &[&str] = &[
"slow_compute",
"failing_job",
"protocol_error_job",
"confirm_delete",
"multi_input",
"test_tool_with_task",
];
/// Tools that cannot be serviced without returning a `CreateTaskResult`:
/// calling them from a client that did not declare the tasks extension is
/// rejected with -32021 before the tool body runs (SEP-2663 §Required
/// Capabilities). `failing_job` and `test_tool_with_task` are registered
/// this way for the required-task-error and MRTR-composition scenarios;
/// `confirm_delete` and `multi_input` must park on in-task elicitation, so
/// they have no synchronous fallback either.
const TASK_REQUIRED_TOOLS: &[&str] = &[
"failing_job",
"test_tool_with_task",
"confirm_delete",
"multi_input",
];
fn task_fixture_tool(name: &str) -> Tool {
let (description, schema) = match name {
"greet" => (
"Sync-only greeting fixture (SEP-2663)",
json!({
"type": "object",
"properties": { "name": { "type": "string" } },
"required": ["name"]
}),
),
"slow_compute" => (
"Task-supporting fixture: sleeps `seconds` then returns a result (SEP-2663)",
json!({
"type": "object",
"properties": {
"seconds": { "type": "number" },
"label": { "type": "string" }
}
}),
),
"failing_job" => (
"Task-supporting fixture (task support: required): returns a tool execution error (SEP-2663)",
json!({ "type": "object", "properties": {} }),
),
"protocol_error_job" => (
"Task-supporting fixture: fails with a protocol-level error (SEP-2663)",
json!({ "type": "object", "properties": {} }),
),
"confirm_delete" => (
"Task-supporting fixture: parks on a single elicitation inputRequest (SEP-2663)",
json!({
"type": "object",
"properties": { "filename": { "type": "string" } }
}),
),
"multi_input" => (
"Task-supporting fixture: parks on two parallel elicitation inputRequests (SEP-2663)",
json!({ "type": "object", "properties": {} }),
),
"test_tool_with_task" => (
"MRTR round 1 gathers user_name, round 2 escalates to a task (SEP-2663 composition)",
json!({ "type": "object", "properties": {} }),
),
other => panic!("unknown task fixture tool: {other}"),
};
Tool::new(name.to_string(), description, json_object(schema))
}
// ─── SEP-2322 MRTR (InputRequiredResult) helpers ────────────────────────────
fn mrtr_elicitation_request(message: &str, properties: Value, required: Value) -> InputRequest {
InputRequest::Elicitation(ElicitRequest::new(
ElicitRequestParams::FormElicitationParams {
meta: None,
message: message.into(),
requested_schema: serde_json::from_value(json!({
"type": "object",
"properties": properties,
"required": required,
}))
.expect("valid elicitation schema"),
},
))
}
fn mrtr_sampling_request(prompt: &str) -> InputRequest {
InputRequest::CreateMessage(CreateMessageRequest::new(CreateMessageRequestParams::new(
vec![SamplingMessage::user_text(prompt)],
100,
)))
}
fn mrtr_list_roots_request() -> InputRequest {
InputRequest::ListRoots(ListRootsRequest::default())
}
/// An input response is usable when it is a JSON object (an `ElicitResult`,
/// `CreateMessageResult`, or `ListRootsResult` shape). Anything else (e.g. a
/// bare number) is treated as missing so the server re-requests it.
fn mrtr_response<'a>(
responses: Option<&'a InputResponses>,
key: &str,
) -> Option<&'a serde_json::Map<String, Value>> {
responses
.and_then(|r| r.get(key))
.and_then(Value::as_object)
}
impl ConformanceServer {
fn mrtr_tampered_state_error() -> ErrorData {
ErrorData::invalid_params("requestState failed integrity verification", None)
}
/// SEP-2663 task fixture tools. The server decides per request whether to
/// materialize a task: task-supporting tools create one when the client
/// declared the tasks extension capability; otherwise they fall through to
/// synchronous execution (except task-*required* tools, which reject with
/// -32021).
async fn call_task_fixture_tool(
&self,
request: CallToolRequestParams,
cx: &RequestContext<RoleServer>,
) -> Result<CallToolResponse, ErrorData> {
let client_supports_tasks = cx
.client_capabilities()
.is_some_and(|caps| caps.supports_tasks());
let name = request.name.as_ref();
let args = request.arguments.clone().unwrap_or_default();
if TASK_REQUIRED_TOOLS.contains(&name) && !client_supports_tasks {
// SEP-2663 §Required Capabilities: this tool cannot be serviced
// without returning CreateTaskResult.
return Err(ErrorData::missing_required_client_capability(
ClientCapabilities::builder().enable_tasks().build(),
));
}
let create_task = client_supports_tasks && TASK_SUPPORTING_TOOLS.contains(&name);
match name {
"greet" => {
let who = args.get("name").and_then(Value::as_str).unwrap_or("friend");
Ok(
CallToolResult::success(vec![ContentBlock::text(format!("Hello, {who}!"))])
.into(),
)
}
"slow_compute" => {
let seconds = args.get("seconds").and_then(Value::as_f64).unwrap_or(1.0);
let label = args
.get("label")
.and_then(Value::as_str)
.unwrap_or("compute")
.to_string();
if create_task {
// The lifecycle scenario requires slow_compute to settle
// to `cancelled` when tasks/cancel arrives while running;
// cancellation is cooperative, so honor it explicitly.
let task = self.tasks.spawn(TaskOptions::default(), move |ctx| {
Box::pin(async move {
tokio::select! {
_ = ctx.cancelled() => Err(TaskExit::Cancelled),
_ = tokio::time::sleep(
std::time::Duration::from_secs_f64(seconds),
) => Ok(CallToolResult::success(vec![ContentBlock::text(
format!("slow_compute({label}) done after {seconds}s"),
)])),
}
})
});
Ok(CreateTaskResult::new(task).into())
} else {
tokio::time::sleep(std::time::Duration::from_secs_f64(seconds)).await;
Ok(CallToolResult::success(vec![ContentBlock::text(format!(
"slow_compute({label}) done after {seconds}s"
))])
.into())
}
}
"failing_job" => {
// Tool execution error: surfaces as status "completed" with
// result.isError = true when run as a task.
let work = || async {
tokio::time::sleep(std::time::Duration::from_millis(1000)).await;
Ok(CallToolResult::error(vec![ContentBlock::text(
"failing_job: intentional tool execution error",
)]))
};
if create_task {
let task = self.tasks.spawn(TaskOptions::default(), move |_ctx| {
Box::pin(async move { work().await.map_err(TaskExit::Error) })
});
Ok(CreateTaskResult::new(task).into())
} else {
Ok(work().await?.into())
}
}
"protocol_error_job" => {
// Protocol-level failure: surfaces as status "failed" with an
// inlined `error` object when run as a task.
let work = || async {
tokio::time::sleep(std::time::Duration::from_millis(200)).await;
Err(ErrorData::internal_error(
"protocol_error_job: intentional protocol-level failure",
None,
))
};
if create_task {
let task = self.tasks.spawn(TaskOptions::default(), move |_ctx| {
Box::pin(async move { work().await.map_err(TaskExit::Error) })
});
Ok(CreateTaskResult::new(task).into())
} else {
work().await.map(CallToolResponse::from)
}
}
"confirm_delete" => {
let filename = args
.get("filename")
.and_then(Value::as_str)
.unwrap_or("file.txt")
.to_string();
let task = self.tasks.spawn(TaskOptions::default(), move |ctx| {
Box::pin(async move {
let response = ctx
.request_input(
"confirm",
mrtr_elicitation_request(
&format!("Delete {filename}?"),
json!({ "confirm": { "type": "boolean" } }),
json!(["confirm"]),
),
)
.await?;
let confirmed = response
.get("content")
.and_then(|c| c.get("confirm"))
.and_then(Value::as_bool)
.unwrap_or(false);
Ok(CallToolResult::success(vec![ContentBlock::text(format!(
"confirm_delete({filename}): confirmed = {confirmed}"
))]))
})
});
Ok(CreateTaskResult::new(task).into())
}
"multi_input" => {
let task = self.tasks.spawn(TaskOptions::default(), move |ctx| {
Box::pin(async move {
// Fan out two elicitation requests in parallel so two
// keys are pending at once (partial fulfillment check).
let first = ctx.request_input(
"input-a",
mrtr_elicitation_request(
"Provide value A",
json!({ "value": { "type": "string" } }),
json!(["value"]),
),
);
let second = ctx.request_input(
"input-b",
mrtr_elicitation_request(
"Provide value B",
json!({ "value": { "type": "string" } }),
json!(["value"]),
),
);
let (a, b) = tokio::join!(first, second);
let (a, b) = (a?, b?);
let get = |v: &Value| {
v.get("content")
.and_then(|c| c.get("value"))
.and_then(Value::as_str)
.unwrap_or("(none)")
.to_string()
};
Ok(CallToolResult::success(vec![ContentBlock::text(format!(
"multi_input: a = {}, b = {}",
get(&a),
get(&b)
))]))
})
});
Ok(CreateTaskResult::new(task).into())
}
"test_tool_with_task" => {
// SEP-2663 MRTR → Tasks composition. Round 1 (no inputResponses)
// is a plain MRTR InputRequiredResult; round 2 escalates to a
// task whose result reflects the gathered user_name.
match mrtr_response(request.input_responses.as_ref(), "user_name") {
None => {
let mut requests = InputRequests::new();
requests.insert(
"user_name".into(),
mrtr_elicitation_request(
"What is your name?",
json!({ "name": { "type": "string" } }),
json!(["name"]),
),
);
Ok(InputRequiredResult::from_input_requests(requests).into())
}
Some(response) => {
let user_name = response
.get("content")
.and_then(|c| c.get("name"))
.and_then(Value::as_str)
.unwrap_or("friend")
.to_string();
let task = self.tasks.spawn(TaskOptions::default(), move |_ctx| {
Box::pin(async move {
tokio::time::sleep(std::time::Duration::from_millis(200)).await;
Ok(CallToolResult::success(vec![ContentBlock::text(format!(
"Hello, {user_name}! (async)"
))]))
})
});
Ok(CreateTaskResult::new(task).into())
}
}
}
other => Err(ErrorData::invalid_params(
format!("Unknown task fixture tool: {other}"),
None,
)),
}
}
/// SEP-2322 test tools. Each returns an `InputRequiredResult` until the
/// client retries with the expected `inputResponses` (and, where used, the
/// echoed `requestState`).
///
/// `meta` is the request's `_meta`, which the service loop moves out of the
/// params and into the `RequestContext`.
async fn call_mrtr_tool(
&self,
request: CallToolRequestParams,
meta: &RequestMetaObject,
) -> Result<CallToolResponse, ErrorData> {
let responses = request.input_responses.as_ref();
match request.name.as_ref() {
"test_input_required_result_elicitation" => {
match mrtr_response(responses, "user_name") {
Some(response) => {
let name = response
.get("content")
.and_then(|c| c.get("name"))
.and_then(Value::as_str)
.unwrap_or("friend");
Ok(CallToolResult::success(vec![ContentBlock::text(format!(
"Hello, {name}!"
))])
.into())
}
// Initial call, or a retry with missing/invalid responses:
// (re-)request the input per the SEP's recommendation.
None => {
let mut requests = InputRequests::new();
requests.insert(
"user_name".into(),
mrtr_elicitation_request(
"What is your name?",
json!({ "name": { "type": "string" } }),
json!(["name"]),
),
);
Ok(InputRequiredResult::from_input_requests(requests).into())
}
}
}
"test_input_required_result_sampling" => {
match mrtr_response(responses, "capital_question") {
Some(response) => {
let text = response
.get("content")
.and_then(|c| c.get("text"))
.and_then(Value::as_str)
.unwrap_or("(no sampling text)");
Ok(CallToolResult::success(vec![ContentBlock::text(format!(
"Sampling response: {text}"
))])
.into())
}
None => {
let mut requests = InputRequests::new();
requests.insert(
"capital_question".into(),
mrtr_sampling_request("What is the capital of France?"),
);
Ok(InputRequiredResult::from_input_requests(requests).into())
}
}
}
"test_input_required_result_list_roots" => {
match mrtr_response(responses, "client_roots") {
Some(response) => {
let roots = response
.get("roots")
.and_then(Value::as_array)
.map(|roots| {
roots
.iter()
.filter_map(|r| r.get("uri").and_then(Value::as_str))
.collect::<Vec<_>>()
.join(", ")
})
.unwrap_or_default();
Ok(CallToolResult::success(vec![ContentBlock::text(format!(
"Client roots: [{roots}]"
))])
.into())
}
None => {
let mut requests = InputRequests::new();
requests.insert("client_roots".into(), mrtr_list_roots_request());
Ok(InputRequiredResult::from_input_requests(requests).into())
}
}
}
"test_input_required_result_request_state"
| "test_input_required_result_tampered_state" => {
match request.request_state.as_deref() {
// Initial call: request confirmation and seal our progress.
None => {
let sealed = self
.request_state_codec
.seal_json(&json!({ "stage": "confirm" }))
.map_err(|e| ErrorData::internal_error(e.to_string(), None))?;
let mut requests = InputRequests::new();
requests.insert(
"confirm".into(),
mrtr_elicitation_request(
"Please confirm",
json!({ "ok": { "type": "boolean" } }),
json!(["ok"]),
),
);
Ok(InputRequiredResult::new(Some(requests), Some(sealed)).into())
}
// Retry: the echoed state is untrusted input and MUST pass
// integrity verification before we act on it.
Some(sealed) => {
self.request_state_codec
.open(sealed)
.map_err(|_| Self::mrtr_tampered_state_error())?;
Ok(
CallToolResult::success(vec![ContentBlock::text(
"Confirmed: state-ok",
)])
.into(),
)
}
}
}
"test_input_required_result_multiple_inputs" => {
if let Some(sealed) = request.request_state.as_deref() {
self.request_state_codec
.open(sealed)
.map_err(|_| Self::mrtr_tampered_state_error())?;
}
let all_present = mrtr_response(responses, "user_name").is_some()
&& mrtr_response(responses, "greeting").is_some()
&& mrtr_response(responses, "client_roots").is_some();
if all_present && request.request_state.is_some() {
Ok(
CallToolResult::success(vec![ContentBlock::text("All inputs received")])
.into(),
)
} else {
let sealed = self
.request_state_codec
.seal_json(&json!({ "stage": "gather" }))
.map_err(|e| ErrorData::internal_error(e.to_string(), None))?;
let mut requests = InputRequests::new();
requests.insert(
"user_name".into(),
mrtr_elicitation_request(
"What is your name?",
json!({ "name": { "type": "string" } }),
json!(["name"]),
),
);
requests.insert(
"greeting".into(),
mrtr_sampling_request("Generate a greeting"),
);
requests.insert("client_roots".into(), mrtr_list_roots_request());
Ok(InputRequiredResult::new(Some(requests), Some(sealed)).into())
}
}
"test_input_required_result_multi_round" => {
let round = match request.request_state.as_deref() {
None => 0,
Some(sealed) => {
let state: Value = self
.request_state_codec
.open_json(sealed)
.map_err(|_| Self::mrtr_tampered_state_error())?;
state.get("round").and_then(Value::as_i64).unwrap_or(0)
}
};
match round {
0 => {
let sealed = self
.request_state_codec
.seal_json(&json!({ "round": 1 }))
.map_err(|e| ErrorData::internal_error(e.to_string(), None))?;
let mut requests = InputRequests::new();
requests.insert(
"step1".into(),
mrtr_elicitation_request(
"Step 1: What is your name?",
json!({ "name": { "type": "string" } }),
json!(["name"]),
),
);
Ok(InputRequiredResult::new(Some(requests), Some(sealed)).into())
}
1 => {
let sealed = self
.request_state_codec
.seal_json(&json!({ "round": 2 }))
.map_err(|e| ErrorData::internal_error(e.to_string(), None))?;
let mut requests = InputRequests::new();
requests.insert(
"step2".into(),
mrtr_elicitation_request(
"Step 2: What is your favorite color?",
json!({ "color": { "type": "string" } }),
json!(["color"]),
),
);
Ok(InputRequiredResult::new(Some(requests), Some(sealed)).into())
}
_ => Ok(CallToolResult::success(vec![ContentBlock::text(
"Multi-round flow complete",
)])
.into()),
}
}
"test_input_required_result_capabilities" => {
if responses.is_some() {
return Ok(CallToolResult::success(vec![ContentBlock::text(
"Capability-aware flow complete",
)])
.into());
}
// Per SEP-2322, only request inputs the client declared support
// for in `_meta['io.modelcontextprotocol/clientCapabilities']`.
let capabilities = meta.client_capabilities().unwrap_or_default();
let mut requests = InputRequests::new();
if capabilities.elicitation.is_some() {
requests.insert(
"user_name".into(),
mrtr_elicitation_request(
"What is your name?",
json!({ "name": { "type": "string" } }),
json!(["name"]),
),
);
}
if capabilities.sampling.is_some() {
requests.insert(
"greeting".into(),
mrtr_sampling_request("Generate a greeting"),
);
}
if capabilities.roots.is_some() {
requests.insert("client_roots".into(), mrtr_list_roots_request());
}
if requests.is_empty() {
Ok(CallToolResult::success(vec![ContentBlock::text(
"Client declared no MRTR-capable capabilities",
)])
.into())
} else {
Ok(InputRequiredResult::from_input_requests(requests).into())
}
}
_ => Err(ErrorData::invalid_params(
format!("Unknown tool: {}", request.name),
None,
)),
}
}
}
impl ServerHandler for ConformanceServer {
fn get_tool(&self, name: &str) -> Option<Tool> {
(name == "test_custom_header").then(custom_header_tool)
}
fn get_info(&self) -> ServerInfo {
ServerInfo::new(
ServerCapabilities::builder()
.enable_prompts()
.enable_prompts_list_changed()
.enable_resources()
.enable_resources_subscribe()
.enable_resources_list_changed()
.enable_tools()
.enable_tool_list_changed()
.enable_logging()
.enable_tasks()
.build(),
)
.with_server_info(Implementation::new("rust-conformance-server", "0.1.0"))
.with_instructions("Rust MCP conformance test server")
}
async fn initialize(
&self,
request: InitializeRequestParams,
_cx: RequestContext<RoleServer>,
) -> Result<InitializeResult, ErrorData> {
let info = self.get_info();
Ok(InitializeResult::new(info.capabilities)
.with_protocol_version(request.protocol_version)
.with_server_info(info.server_info)
.with_instructions(info.instructions.unwrap_or_default()))
}
fn accepted_subscription_filter(
&self,
requested: &SubscriptionFilter,
) -> Option<SubscriptionFilter> {
Some(requested.supported_by(&self.get_info().capabilities))
}
async fn listen(&self, context: SubscriptionContext) -> Result<(), ErrorData> {
let key = self.next_subscription.fetch_add(1, Ordering::Relaxed);
self.subscriptions
.lock()
.await
.insert(key, context.sink().clone());
context.cancelled().await;
self.subscriptions.lock().await.remove(&key);
Ok(())
}
async fn ping(&self, _cx: RequestContext<RoleServer>) -> Result<(), ErrorData> {
Ok(())
}
async fn get_task(
&self,
request: GetTaskParams,
_cx: RequestContext<RoleServer>,
) -> Result<GetTaskResult, ErrorData> {
Ok(GetTaskResult::new(self.tasks.get_task(&request.task_id)?))
}
async fn update_task(
&self,
request: UpdateTaskParams,
_cx: RequestContext<RoleServer>,
) -> Result<(), ErrorData> {
self.tasks
.update_task(&request.task_id, request.input_responses)
}
async fn cancel_task(
&self,
request: CancelTaskParams,
_cx: RequestContext<RoleServer>,
) -> Result<(), ErrorData> {
self.tasks.cancel_task(&request.task_id)
}
async fn list_tools(
&self,
_request: Option<PaginatedRequestParams>,
_cx: RequestContext<RoleServer>,
) -> Result<ListToolsResult, ErrorData> {
let tools = vec![
Tool::new(
"test_simple_text",
"Returns simple text content",
json_object(json!({
"type": "object",
"properties": {}
})),
),
Tool::new(
"test_image_content",
"Returns image content",
json_object(json!({
"type": "object",
"properties": {}
})),
),
Tool::new(
"test_audio_content",
"Returns audio content",
json_object(json!({
"type": "object",
"properties": {}
})),
),
Tool::new(
"test_embedded_resource",
"Returns embedded resource content",
json_object(json!({
"type": "object",
"properties": {}
})),
),
Tool::new(
"test_multiple_content_types",
"Returns multiple content types",
json_object(json!({
"type": "object",
"properties": {}
})),
),
Tool::new(
"test_tool_with_logging",
"Sends logging notifications during execution",
json_object(json!({
"type": "object",
"properties": {}
})),
),
Tool::new(
"test_error_handling",
"Always returns an error",
json_object(json!({
"type": "object",
"properties": {}
})),
),
Tool::new(
"test_tool_with_progress",
"Reports progress notifications",
json_object(json!({
"type": "object",
"properties": {}
})),
),
Tool::new(
"test_sampling",
"Requests LLM sampling from client",
json_object(json!({
"type": "object",
"properties": {
"prompt": { "type": "string", "description": "The prompt to send" }
},
"required": ["prompt"]
})),
),
Tool::new(
"test_elicitation",
"Requests user input from client",
json_object(json!({
"type": "object",
"properties": {
"message": { "type": "string", "description": "The message to show" }
},
"required": ["message"]
})),
),
Tool::new(
"test_elicitation_sep1034_defaults",
"Tests elicitation with default values (SEP-1034)",
json_object(json!({
"type": "object",
"properties": {}
})),
),
Tool::new(
"test_elicitation_sep1330_enums",
"Tests enum schema improvements (SEP-1330)",
json_object(json!({
"type": "object",
"properties": {}
})),
),
Tool::new(
"json_schema_2020_12_tool",
"Tool with JSON Schema 2020-12 features",
json_object(json!({
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"$defs": {
"address": {
"$anchor": "address",
"type": "object",
"properties": {
"street": { "type": "string" },
"city": { "type": "string" }
}
}
},
"properties": {
"name": { "type": "string" },
"address": { "$ref": "#/$defs/address" }
},
"allOf": [{
"anyOf": [
{ "required": ["name"] },
{ "required": ["address"] }
]
}],
"if": { "required": ["address"] },
"then": {
"properties": {
"address": { "required": ["street"] }
}
},
"else": { "required": ["name"] },
"additionalProperties": false
})),
),
Tool::new(
"test_reconnection",
"Tests SSE reconnection behavior",
json_object(json!({
"type": "object",
"properties": {}
})),
),
custom_header_tool(),
Tool::new(
"test_trigger_tool_change",
"Triggers a tools/list_changed notification on matching subscriptions",
json_object(json!({
"type": "object",
"properties": {}
})),
),
Tool::new(
"test_trigger_prompt_change",
"Triggers a prompts/list_changed notification on matching subscriptions",
json_object(json!({
"type": "object",
"properties": {}
})),
),
Tool::new(
"test_missing_capability",
"Requires the sampling client capability",
json_object(json!({
"type": "object",
"properties": {}
})),
),
Tool::new(
"test_streaming_elicitation",
"Returns an input_required result containing an elicitation request",
json_object(json!({
"type": "object",
"properties": {}
})),
),
Tool::new(
"test_logging_tool",
"Emits notifications/message only when logLevel is requested",
json_object(json!({
"type": "object",
"properties": {}
})),
),
];
// SEP-2322 MRTR test tools; all take no arguments.
let mrtr_tools = [
(
"test_input_required_result_elicitation",
"Requires an elicitation input via InputRequiredResult (SEP-2322)",
),
(
"test_input_required_result_sampling",
"Requires a sampling input via InputRequiredResult (SEP-2322)",
),
(
"test_input_required_result_list_roots",
"Requires a roots/list input via InputRequiredResult (SEP-2322)",
),
(
"test_input_required_result_request_state",
"Round-trips integrity-protected requestState (SEP-2322)",
),
(
"test_input_required_result_multiple_inputs",
"Requires elicitation + sampling + roots inputs in one round (SEP-2322)",
),
(
"test_input_required_result_multi_round",
"Drives multiple input_required rounds with evolving requestState (SEP-2322)",
),
(