turbomcp-server 4.0.0-alpha.2

TurboMCP v4 server: McpServerCore + capability traits, MethodRouter, ServerBuilder.
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
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
//! # turbomcp-server
//!
//! The server framework: the user-facing traits, the capability router, and the
//! `tower`-shaped dispatcher that connects them to a transport.
//!
//! - [`McpServerCore`] + capability traits ([`WithTools`], …) — what a user
//!   implements. Handlers speak `turbomcp_protocol::neutral` types, never wire
//!   types, so a server is portable across protocol versions.
//! - [`MethodRouter`] — registers the capabilities a server actually implements;
//!   advertised capabilities are *derived* from it, so they can't drift.
//! - [`VersionDispatcher`] — `Service<JsonRpcMessage>`: extracts the version,
//!   routes to the typed handler, and serializes the response. All per-version
//!   branching is concentrated here.
//!
//! Both protocol paths are live: the modern `2026-07-28` stateless path and
//! the legacy `2025-11-25` stateful path (`initialize` handshake +
//! [`SessionStore`]; see [`LegacySessionAdapter`] for byte-pipe transports).
#![forbid(unsafe_code)]
#![warn(missing_docs)]

mod adapter;
mod builder;
mod composite;
mod context;
mod dispatcher;
mod extension;
mod inflight;
mod logging;
mod mrtr;
mod progress;
mod response;
mod router;
mod session;
mod subscriptions;
pub mod tags;
mod tasks;
mod traits;
pub mod visibility;

pub use adapter::LegacySessionAdapter;
pub use builder::{IntoServerBuilder, ServerBuilder};
pub use composite::{Composite, CompositeServer};
pub use context::{
    CallToolContext, CompleteContext, GetPromptContext, ListPromptsContext,
    ListResourceTemplatesContext, ListResourcesContext, ListToolsContext, ReadResourceContext,
};
pub use dispatcher::{CachePolicies, DispatcherSessionTerminator, VersionDispatcher};
pub use extension::{
    CallAugmentRequest, CallRunner, Extension, ExtensionRequest, SubscribeOutcome, TaskInputBroker,
    TaskInputSlot,
};
pub use logging::LogSender;
pub use mrtr::ClientHandle;
pub use progress::ProgressReporter;
pub use response::{
    Audio, Image, IntoCallToolResult, IntoGetPromptResult, IntoReadResourceResult, Json,
};
pub use router::MethodRouter;
pub use session::{SessionBackend, SessionState, SessionStore};
pub use subscriptions::ServerNotifier;
pub use tasks::{TaskBackend, TaskError, TaskSnapshot, TaskStatus, TaskStore};
pub use traits::{McpServerCore, WithCompletions, WithPrompts, WithResources, WithTools};
pub use visibility::{ComponentKind, Visibility, VisibilityPolicy, VisibleComponent};

/// Support items called by `#[server]`-generated code. Not part of the stable
/// API — do not depend on it directly.
#[doc(hidden)]
pub mod __macro_support {
    use serde_json::Value;

    /// Strip the schemars `title` bookkeeping (the arg-struct's Rust name, which
    /// is noise on a tool input schema). The `$schema` dialect declaration is
    /// **kept** — the MCP spec (and the official conformance suite) expect a tool
    /// `inputSchema` to advertise its JSON Schema dialect
    /// (`https://json-schema.org/draft/2020-12/schema`).
    #[must_use]
    pub fn normalize_input_schema(mut v: Value) -> Value {
        if let Some(obj) = v.as_object_mut() {
            obj.remove("title");
        }
        v
    }

    /// Close a generated object schema to additional properties. A tool
    /// `inputSchema` forbids unknown arguments — the function-calling norm (it
    /// keeps models from inventing parameters) and what the official MCP
    /// conformance suite's json-schema-2020-12 scenario checks. Schema-only:
    /// deserialization stays lenient (unknown args are still ignored, not an
    /// error). No-op unless the root is an `object` that hasn't already set
    /// `additionalProperties`.
    #[must_use]
    pub fn close_object_schema(mut v: Value) -> Value {
        if let Some(obj) = v.as_object_mut()
            && obj.get("type").and_then(Value::as_str) == Some("object")
            && !obj.contains_key("additionalProperties")
        {
            obj.insert("additionalProperties".into(), Value::Bool(false));
        }
        v
    }

    /// Merge the `#[tool(schema_extend = "…")]` keywords into a generated
    /// `inputSchema`.
    ///
    /// Top-level keys only, and the caller's keys win — the point is to state
    /// what a Rust signature can't (cross-field rules like `allOf` / `anyOf` /
    /// `if` / `then` / `else`, or an `$anchor`), which SEP-2106 requires a
    /// server to carry through untouched. The macro already parsed `extra` at
    /// compile time, so a parse failure here is unreachable and leaves the
    /// schema as-is rather than panicking in a handler's list path.
    #[must_use]
    pub fn extend_object_schema(mut v: Value, extra: &str) -> Value {
        let (Some(obj), Ok(Value::Object(add))) =
            (v.as_object_mut(), serde_json::from_str::<Value>(extra))
        else {
            return v;
        };
        for (key, value) in add {
            obj.insert(key, value);
        }
        v
    }

    /// Mark a property as an MCP header parameter (SEP-2243). The annotation
    /// value is the **name portion** of the mirrored `Mcp-Param-{name}` header
    /// (the transports spec made `x-mcp-header` a string; the earlier boolean
    /// form is obsolete) — we use the property name itself, which satisfies
    /// the spec's constraints (RFC 9110 tchar, case-insensitively unique
    /// within one schema) for any valid Rust identifier.
    pub fn mark_mcp_header(schema: &mut Value, property: &str) {
        if let Some(prop) = schema
            .get_mut("properties")
            .and_then(|p| p.get_mut(property))
            .and_then(Value::as_object_mut)
        {
            prop.insert("x-mcp-header".into(), Value::String(property.to_owned()));
        }
    }

    /// Match a concrete `uri` against an RFC 6570 URI template, returning the
    /// captured variables (in template order) on a match.
    ///
    /// RFC 6570 defines expansion, not matching, so — like the reference SDKs —
    /// we compile the template to an anchored regex: literal spans are escaped,
    /// `{var}` captures one path segment (`[^/]+`), and `{+var}` (reserved
    /// expansion) captures across segments (`.+`). Other operators aren't
    /// modeled. Returns `None` if the template is malformed or doesn't match.
    #[must_use]
    pub fn match_uri_template(template: &str, uri: &str) -> Option<Vec<(String, String)>> {
        let mut pattern = String::from("^");
        let mut names = Vec::new();
        let mut rest = template;
        while let Some(open) = rest.find('{') {
            pattern.push_str(&regex::escape(&rest[..open]));
            let close = rest[open..].find('}')? + open;
            let mut var = &rest[open + 1..close];
            let greedy = var.starts_with('+');
            if greedy {
                var = &var[1..];
            }
            if var.is_empty() || !var.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
                return None;
            }
            names.push(var.to_string());
            pattern.push_str(if greedy { "(.+)" } else { "([^/]+)" });
            rest = &rest[close + 1..];
        }
        pattern.push_str(&regex::escape(rest));
        pattern.push('$');

        let re = regex::Regex::new(&pattern).ok()?;
        let caps = re.captures(uri)?;
        Some(
            names
                .into_iter()
                .enumerate()
                .map(|(i, name)| (name, caps[i + 1].to_string()))
                .collect(),
        )
    }

    #[cfg(test)]
    mod template_tests {
        use super::match_uri_template;

        #[test]
        fn single_segment_var() {
            let m = match_uri_template("file://{name}", "file://notes").unwrap();
            assert_eq!(m, vec![("name".to_string(), "notes".to_string())]);
        }

        #[test]
        fn segment_var_stops_at_slash() {
            // `{name}` is one segment, so a slashed remainder doesn't match.
            assert!(match_uri_template("file://{name}", "file://a/b").is_none());
        }

        #[test]
        fn reserved_var_spans_slashes() {
            let m = match_uri_template("file://{+path}", "file:///etc/hosts").unwrap();
            assert_eq!(m, vec![("path".to_string(), "/etc/hosts".to_string())]);
        }

        #[test]
        fn multiple_vars() {
            let m = match_uri_template("db://{table}/{id}", "db://users/42").unwrap();
            assert_eq!(
                m,
                vec![
                    ("table".to_string(), "users".to_string()),
                    ("id".to_string(), "42".to_string()),
                ]
            );
        }

        #[test]
        fn literal_mismatch_is_none() {
            assert!(match_uri_template("file://{name}", "http://notes").is_none());
        }

        #[test]
        fn regex_metachars_in_literal_are_escaped() {
            let m = match_uri_template("x.y://{v}", "x.y://z").unwrap();
            assert_eq!(m, vec![("v".to_string(), "z".to_string())]);
            // The `.` is a literal, not "any char".
            assert!(match_uri_template("x.y://{v}", "xqy://z").is_none());
        }
    }
}

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

    use serde_json::json;
    use tower::{Service, ServiceExt};
    use turbomcp_core::{Implementation, JsonRpcMessage, JsonRpcRequest, McpResult};
    use turbomcp_protocol::neutral;

    #[derive(Clone)]
    struct Calculator;

    impl McpServerCore for Calculator {
        fn server_info(&self) -> Implementation {
            Implementation::new("calculator", "0.1.0")
        }
        fn instructions(&self) -> Option<String> {
            Some("A demo calculator server.".into())
        }
    }

    impl WithTools for Calculator {
        async fn list_tools(
            &self,
            _ctx: &ListToolsContext,
            _params: neutral::ListParams,
        ) -> McpResult<neutral::ListToolsResult> {
            Ok(neutral::ListToolsResult::new(vec![neutral::Tool::new(
                "add",
                json!({"type": "object", "properties": {"a": {"type": "number"}, "b": {"type": "number"}}}),
            )
            .with_description("Add two numbers")]))
        }

        async fn call_tool(
            &self,
            _ctx: &CallToolContext,
            params: neutral::CallToolParams,
        ) -> McpResult<neutral::CallToolResult> {
            if params.name != "add" {
                return Ok(neutral::CallToolResult::error(format!(
                    "unknown tool: {}",
                    params.name
                )));
            }
            let a = params
                .arguments
                .get("a")
                .and_then(|v| v.as_f64())
                .unwrap_or(0.0);
            let b = params
                .arguments
                .get("b")
                .and_then(|v| v.as_f64())
                .unwrap_or(0.0);
            Ok(neutral::CallToolResult::text(format!("{}", a + b)))
        }
    }

    fn dispatcher() -> VersionDispatcher<Calculator> {
        VersionDispatcher::new(Calculator, MethodRouter::new().with_tools())
    }

    /// Build draft `_meta` carrying the per-request protocol version.
    fn draft_meta() -> serde_json::Value {
        json!({
            "io.modelcontextprotocol/protocolVersion": "2026-07-28",
            "io.modelcontextprotocol/clientCapabilities": {},
        })
    }

    async fn call(svc: &mut VersionDispatcher<Calculator>, req: JsonRpcRequest) -> JsonRpcMessage {
        svc.ready()
            .await
            .unwrap()
            .call(req.into())
            .await
            .unwrap()
            .expect("request should produce a response")
    }

    #[tokio::test]
    async fn discover_advertises_tools_and_versions() {
        let mut svc = dispatcher();
        let resp = call(
            &mut svc,
            JsonRpcRequest::new(1, "server/discover", Some(json!({ "_meta": draft_meta() }))),
        )
        .await;
        let JsonRpcMessage::Response(r) = resp else {
            panic!("expected response")
        };
        let result = r.result.expect("discover result");
        // Identity rides in `_meta` on the frozen `2026-07-28` (the RC had
        // briefly made it a first-class `serverInfo` field).
        assert_eq!(
            result["_meta"]["io.modelcontextprotocol/serverInfo"]["name"],
            "calculator"
        );
        assert_eq!(result["capabilities"]["tools"]["listChanged"], true);
        assert_eq!(result["resultType"], "complete");
        let versions = result["supportedVersions"].as_array().unwrap();
        assert!(versions.iter().any(|v| v == "2026-07-28"));
        assert!(versions.iter().any(|v| v == "2025-11-25"));
        assert_eq!(result["instructions"], "A demo calculator server.");
    }

    #[tokio::test]
    async fn tools_list_returns_registered_tools() {
        let mut svc = dispatcher();
        let req = JsonRpcRequest::new(2, "tools/list", Some(json!({ "_meta": draft_meta() })));
        let JsonRpcMessage::Response(r) = call(&mut svc, req).await else {
            panic!()
        };
        let result = r.result.unwrap();
        assert_eq!(result["tools"][0]["name"], "add");
        assert_eq!(result["tools"][0]["description"], "Add two numbers");
        assert_eq!(result["resultType"], "complete");
        // The RC dropped the per-result `_meta` server-identity convention:
        // only `server/discover` carries `serverInfo`.
        assert!(result.get("_meta").is_none());
    }

    #[tokio::test]
    async fn tools_call_invokes_handler() {
        let mut svc = dispatcher();
        let req = JsonRpcRequest::new(
            3,
            "tools/call",
            Some(json!({ "name": "add", "arguments": {"a": 2, "b": 3}, "_meta": draft_meta() })),
        );
        let JsonRpcMessage::Response(r) = call(&mut svc, req).await else {
            panic!()
        };
        let result = r.result.unwrap();
        assert_eq!(result["content"][0]["text"], "5");
        assert_eq!(result["isError"], false);
    }

    /// A request with no `_meta` is a malformed envelope, not a rejected
    /// version: SEP-2575 marks the fields required, so their absence is
    /// invalid params. The supported list still rides in `data`, so a client
    /// that simply forgot can re-issue.
    #[tokio::test]
    async fn missing_envelope_is_invalid_params_naming_the_field() {
        let mut svc = dispatcher();
        // tools/list without `_meta.protocolVersion`.
        let req = JsonRpcRequest::new(4, "tools/list", Some(json!({})));
        let JsonRpcMessage::Response(r) = call(&mut svc, req).await else {
            panic!()
        };
        let err = r.error.expect("should be an error");
        assert_eq!(err.code, -32602);
        let data = err.data.expect("names the missing field");
        assert_eq!(
            data["missingField"],
            "io.modelcontextprotocol/protocolVersion"
        );
        assert!(data["supported"].is_array(), "{data}");
    }

    /// The version is *named* but not served: that is negotiation, not a
    /// malformed request, and keeps the dedicated code.
    #[tokio::test]
    async fn unsupported_version_yields_its_own_code_with_the_list() {
        let mut svc = dispatcher();
        let meta = json!({
            "io.modelcontextprotocol/protocolVersion": "1999-01-01",
            "io.modelcontextprotocol/clientCapabilities": {},
        });
        let req = JsonRpcRequest::new(4, "tools/list", Some(json!({ "_meta": meta })));
        let JsonRpcMessage::Response(r) = call(&mut svc, req).await else {
            panic!()
        };
        let err = r.error.expect("should be an error");
        assert_eq!(err.code, turbomcp_core::codes::UNSUPPORTED_PROTOCOL_VERSION);
    }

    #[tokio::test]
    async fn legacy_version_without_session_is_not_initialized() {
        let mut svc = dispatcher();
        let meta = json!({ "io.modelcontextprotocol/protocolVersion": "2025-11-25" });
        let req = JsonRpcRequest::new(5, "tools/list", Some(json!({ "_meta": meta })));
        let JsonRpcMessage::Response(r) = call(&mut svc, req).await else {
            panic!()
        };
        let err = r.error.expect("legacy request without a session must fail");
        assert_eq!(err.code, -32002);
        assert!(err.message.contains("initialize"));
    }

    #[tokio::test]
    async fn unknown_method_is_method_not_found() {
        let mut svc = dispatcher();
        let req = JsonRpcRequest::new(
            6,
            "tools/nonexistent",
            Some(json!({ "_meta": draft_meta() })),
        );
        let JsonRpcMessage::Response(r) = call(&mut svc, req).await else {
            panic!()
        };
        assert_eq!(r.error.unwrap().code, -32601);
    }

    #[tokio::test]
    async fn notification_produces_no_response() {
        let mut svc = dispatcher();
        let msg: JsonRpcMessage =
            turbomcp_core::JsonRpcNotification::new("notifications/initialized", None).into();
        let out = svc.ready().await.unwrap().call(msg).await.unwrap();
        assert!(out.is_none());
    }

    /// A server without `WithTools` must not advertise tools.
    #[tokio::test]
    async fn server_without_tools_omits_capability() {
        #[derive(Clone)]
        struct Bare;
        impl McpServerCore for Bare {
            fn server_info(&self) -> Implementation {
                Implementation::new("bare", "0.0.0")
            }
        }
        let mut svc = VersionDispatcher::new(Bare, MethodRouter::<Bare>::new());
        // Reuse the dispatch path directly.
        let resp = svc
            .ready()
            .await
            .unwrap()
            .call(
                JsonRpcRequest::new(1, "server/discover", Some(json!({ "_meta": draft_meta() })))
                    .into(),
            )
            .await
            .unwrap()
            .unwrap();
        let JsonRpcMessage::Response(r) = resp else {
            panic!()
        };
        assert!(
            r.result
                .unwrap()
                .get("capabilities")
                .unwrap()
                .get("tools")
                .is_none()
        );
    }

    fn _is_send<T: Send>() {}
    #[test]
    fn dispatcher_is_send() {
        _is_send::<VersionDispatcher<Calculator>>();
    }

    #[tokio::test]
    async fn builder_registers_capabilities() {
        // `into_server()` (blanket) starts empty; `with_tools()` registers.
        let mut svc = Calculator.into_server().with_tools().build();
        let JsonRpcMessage::Response(r) = svc
            .ready()
            .await
            .unwrap()
            .call(
                JsonRpcRequest::new(1, "server/discover", Some(json!({ "_meta": draft_meta() })))
                    .into(),
            )
            .await
            .unwrap()
            .unwrap()
        else {
            panic!()
        };
        assert_eq!(
            r.result.unwrap()["capabilities"]["tools"]["listChanged"],
            true
        );
    }

    #[test]
    fn builder_without_registration_has_no_capabilities() {
        let dispatcher = ServerBuilder::new(Calculator).build();
        _is_send::<VersionDispatcher<Calculator>>();
        let _ = dispatcher; // built successfully with an empty router
    }

    // ---- resources / prompts / completions ----------------------------------

    /// A server implementing every capability trait, used to prove discover
    /// advertises each one and the dispatcher routes all method families.
    #[derive(Clone)]
    struct Everything;

    impl McpServerCore for Everything {
        fn server_info(&self) -> Implementation {
            Implementation::new("everything", "0.1.0")
        }
    }

    impl WithResources for Everything {
        async fn list_resources(
            &self,
            _ctx: &ListResourcesContext,
            _params: neutral::ListParams,
        ) -> McpResult<neutral::ListResourcesResult> {
            Ok(neutral::ListResourcesResult::new(vec![
                neutral::Resource::new("file://readme", "readme").with_mime_type("text/plain"),
            ]))
        }

        async fn read_resource(
            &self,
            _ctx: &ReadResourceContext,
            params: neutral::ReadResourceParams,
        ) -> McpResult<neutral::ReadResourceResult> {
            Ok(neutral::ReadResourceResult::text(
                params.uri,
                "file contents",
            ))
        }
    }

    impl WithPrompts for Everything {
        async fn list_prompts(
            &self,
            _ctx: &ListPromptsContext,
            _params: neutral::ListParams,
        ) -> McpResult<neutral::ListPromptsResult> {
            Ok(neutral::ListPromptsResult::new(vec![
                neutral::Prompt::new("greet")
                    .with_argument(neutral::PromptArgument::new("name").required(true)),
            ]))
        }

        async fn get_prompt(
            &self,
            _ctx: &GetPromptContext,
            params: neutral::GetPromptParams,
        ) -> McpResult<neutral::GetPromptResult> {
            let name = params.arguments.get("name").cloned().unwrap_or_default();
            Ok(neutral::GetPromptResult::new(vec![
                neutral::PromptMessage::user_text(format!("Greet {name}")),
            ]))
        }
    }

    impl WithCompletions for Everything {
        async fn complete(
            &self,
            _ctx: &CompleteContext,
            params: neutral::CompleteParams,
        ) -> McpResult<neutral::CompleteResult> {
            // Echo the partial value back as the single suggestion.
            Ok(neutral::CompleteResult::new(vec![params.argument.value]))
        }
    }

    fn everything() -> VersionDispatcher<Everything> {
        VersionDispatcher::new(
            Everything,
            MethodRouter::new()
                .with_resources()
                .with_prompts()
                .with_completions(),
        )
    }

    async fn call_everything(
        svc: &mut VersionDispatcher<Everything>,
        req: JsonRpcRequest,
    ) -> serde_json::Value {
        let JsonRpcMessage::Response(r) = svc
            .ready()
            .await
            .unwrap()
            .call(req.into())
            .await
            .unwrap()
            .expect("response")
        else {
            panic!("expected response")
        };
        r.result.expect("result")
    }

    #[tokio::test]
    async fn discover_advertises_all_capabilities() {
        let mut svc = everything();
        let result = call_everything(
            &mut svc,
            JsonRpcRequest::new(1, "server/discover", Some(json!({ "_meta": draft_meta() }))),
        )
        .await;
        let caps = &result["capabilities"];
        assert_eq!(caps["resources"]["listChanged"], true);
        assert_eq!(caps["resources"]["subscribe"], true);
        assert_eq!(caps["prompts"]["listChanged"], true);
        assert!(caps["completions"].is_object());
        // No tools were registered → no tools capability.
        assert!(caps.get("tools").is_none());
    }

    #[tokio::test]
    async fn resources_list_read_and_templates_route() {
        let mut svc = everything();
        let meta = json!({ "_meta": draft_meta() });

        let list = call_everything(
            &mut svc,
            JsonRpcRequest::new(2, "resources/list", Some(meta.clone())),
        )
        .await;
        assert_eq!(list["resources"][0]["uri"], "file://readme");
        assert_eq!(list["resources"][0]["mimeType"], "text/plain");

        let read = call_everything(
            &mut svc,
            JsonRpcRequest::new(
                3,
                "resources/read",
                Some(json!({ "uri": "file://readme", "_meta": draft_meta() })),
            ),
        )
        .await;
        assert_eq!(read["contents"][0]["uri"], "file://readme");
        assert_eq!(read["contents"][0]["text"], "file contents");

        // The default `list_resource_templates` answers with an empty list.
        let templates = call_everything(
            &mut svc,
            JsonRpcRequest::new(4, "resources/templates/list", Some(meta)),
        )
        .await;
        assert_eq!(templates["resourceTemplates"].as_array().unwrap().len(), 0);
        assert_eq!(templates["resultType"], "complete");
    }

    #[tokio::test]
    async fn prompts_list_and_get_route() {
        let mut svc = everything();
        let list = call_everything(
            &mut svc,
            JsonRpcRequest::new(5, "prompts/list", Some(json!({ "_meta": draft_meta() }))),
        )
        .await;
        assert_eq!(list["prompts"][0]["name"], "greet");
        assert_eq!(list["prompts"][0]["arguments"][0]["required"], true);

        let got = call_everything(
            &mut svc,
            JsonRpcRequest::new(
                6,
                "prompts/get",
                Some(
                    json!({ "name": "greet", "arguments": {"name": "Ada"}, "_meta": draft_meta() }),
                ),
            ),
        )
        .await;
        assert_eq!(got["messages"][0]["role"], "user");
        assert_eq!(got["messages"][0]["content"]["text"], "Greet Ada");
    }

    #[tokio::test]
    async fn completion_complete_routes_with_ref_union() {
        let mut svc = everything();
        let result = call_everything(
            &mut svc,
            JsonRpcRequest::new(
                7,
                "completion/complete",
                Some(json!({
                    "ref": { "type": "ref/prompt", "name": "greet" },
                    "argument": { "name": "name", "value": "Ad" },
                    "_meta": draft_meta(),
                })),
            ),
        )
        .await;
        assert_eq!(result["completion"]["values"][0], "Ad");
        assert_eq!(result["resultType"], "complete");
    }

    #[tokio::test]
    async fn unregistered_capability_is_method_not_found() {
        // `Everything` doesn't register tools; calling a tools method 404s.
        let mut svc = everything();
        let JsonRpcMessage::Response(r) = svc
            .ready()
            .await
            .unwrap()
            .call(
                JsonRpcRequest::new(8, "tools/list", Some(json!({ "_meta": draft_meta() }))).into(),
            )
            .await
            .unwrap()
            .unwrap()
        else {
            panic!()
        };
        assert_eq!(r.error.unwrap().code, -32601);
    }

    #[tokio::test]
    async fn malformed_completion_ref_is_invalid_params() {
        let mut svc = everything();
        let JsonRpcMessage::Response(r) = svc
            .ready()
            .await
            .unwrap()
            .call(
                JsonRpcRequest::new(
                    9,
                    "completion/complete",
                    Some(json!({
                        "ref": { "type": "ref/prompt" },
                        "argument": { "name": "x", "value": "" },
                        "_meta": draft_meta(),
                    })),
                )
                .into(),
            )
            .await
            .unwrap()
            .unwrap()
        else {
            panic!()
        };
        assert_eq!(r.error.unwrap().code, -32602);
    }
}