Skip to main content

mcport/
lib.rs

1//! Blocking, dependency-light MCP stdio server runtime.
2//!
3//! MCP over stdio is a single ordered byte stream: the client writes one
4//! newline-delimited JSON-RPC message, the server answers on stdout. There is
5//! no need for an async executor: the inline adapter is a blocking bounded
6//! read loop, while the optional controlled adapter uses fixed standard-library
7//! worker threads and one ordered writer. The protocol path uses
8//! `blazingly-json` without Tokio, Hyper, or Axum.
9//!
10//! Ordinary Rust functions become tools without a Tokio runtime:
11//!
12//! ```no_run
13//! use mcport::{tool, tools, McpServer};
14//!
15//! /// Echoes the provided text.
16//! #[tool]
17//! fn echo(text: String) -> String {
18//!     text
19//! }
20//!
21//! fn main() -> std::io::Result<()> {
22//!     McpServer::new("echo", env!("CARGO_PKG_VERSION"))
23//!         .tools(tools![echo])
24//!         .serve()
25//! }
26//! ```
27//!
28//! The original [`typed_tool`](McpServer::typed_tool) and [`tool`](McpServer::tool)
29//! methods remain for handwritten schemas and raw JSON handlers.
30//!
31//! Implement [`ToolServer`] when dispatch needs a fully custom static surface:
32//!
33//! ```no_run
34//! use mcport::{json, ServerIdentity, ToolReply, ToolServer, Value};
35//!
36//! struct Echo;
37//!
38//! impl ToolServer for Echo {
39//!     fn identity(&self) -> ServerIdentity {
40//!         ServerIdentity::new("echo", "1.0.0", "Echoes tool arguments back.")
41//!     }
42//!
43//!     fn catalog(&mut self) -> Value {
44//!         json!([{
45//!             "name": "echo",
46//!             "description": "Echo the arguments.",
47//!             "inputSchema": {
48//!                 "type": "object",
49//!                 "description": "Any caller-defined object; every key is echoed.",
50//!                 "additionalProperties": true
51//!             }
52//!         }])
53//!     }
54//!
55//!     fn call(&mut self, name: &str, arguments: Value) -> ToolReply {
56//!         match name {
57//!             "echo" => ToolReply::structured(arguments),
58//!             _ => ToolReply::error(format!("unknown tool: {name}")),
59//!         }
60//!     }
61//! }
62//!
63//! fn main() -> std::io::Result<()> {
64//!     mcport::serve(&mut Echo)
65//! }
66//! ```
67//!
68//! Runtime guarantees:
69//!
70//! - `initialize`, `ping`, and `tools/list` are answered from the catalog
71//!   alone, so servers can defer expensive startup to the first `tools/call`;
72//! - a UTF-8 byte-order mark on any line is stripped before parsing, so
73//!   Windows shell pipelines cannot break the first request;
74//! - notifications (messages without an `id`) are consumed without replies;
75//! - malformed JSON, missing methods, and unknown methods produce JSON-RPC
76//!   errors without terminating the loop;
77//! - stream adapters bound request and response bytes and never emit a partial
78//!   JSON response when the output budget is exceeded;
79//! - both builders check every advertised tool schema at registration and
80//!   expose the defects; opting into `McpServer::strict_schemas` turns those
81//!   defects into a startup failure. See [`validate_tool_schema`].
82
83mod builder;
84mod controlled;
85mod fast;
86pub mod protocol;
87mod schema;
88mod tool;
89mod transport;
90
91pub use blazingly_json::{json, Map, RawJson, RawValue, Value};
92pub use builder::McpServer;
93pub use controlled::{
94    serve_controlled, serve_controlled_streams, CancellationToken, ConcurrentMcpServer,
95    ConcurrentToolServer, RequestContext, RuntimeConfig,
96};
97pub use schema::{validate_tool_schema, SchemaDefect, SchemaDefectKind};
98pub use tool::{
99    decorate_schema, object_schema, IntoToolReply, Json, PreparedTool, ToolAnnotations,
100    ToolDefinition, ToolError, ToolSchema,
101};
102pub use transport::{FlushPolicy, TransportConfig, TransportLimits};
103
104#[cfg(feature = "macros")]
105pub use mcport_macros::{tool, tools, ToolOutput, ToolSchema};
106
107/// Helpers used by generated `#[tool]` adapters. Not a public contract.
108#[doc(hidden)]
109pub mod __private {
110    pub use blazingly_json::{from_str, to_value};
111}
112
113use serde::Serialize;
114use std::io::{self, BufRead, Write};
115
116/// Latest legacy handshake revision implemented by the runtime.
117pub const DEFAULT_PROTOCOL_VERSION: &str = "2025-11-25";
118
119/// Stateless per-request protocol revision implemented by the runtime.
120pub const MODERN_PROTOCOL_VERSION: &str = "2026-07-28";
121
122/// Protocol revisions accepted by this runtime.
123pub const SUPPORTED_PROTOCOL_VERSIONS: &[&str] =
124    &[MODERN_PROTOCOL_VERSION, "2025-11-25", "2025-06-18"];
125
126const SUPPORTED_LEGACY_PROTOCOL_VERSIONS: &[&str] = &["2025-11-25", "2025-06-18"];
127
128/// Chooses a supported protocol revision for an initialize response.
129///
130/// A supported client revision is echoed. Unknown or missing revisions receive
131/// the latest stable revision so the client can decide whether to continue.
132#[must_use]
133pub fn negotiate_protocol_version(requested: Option<&str>) -> &'static str {
134    requested
135        .and_then(|requested| {
136            SUPPORTED_LEGACY_PROTOCOL_VERSIONS
137                .iter()
138                .copied()
139                .find(|supported| *supported == requested)
140        })
141        .unwrap_or(DEFAULT_PROTOCOL_VERSION)
142}
143
144/// Identity block reported from `initialize`.
145#[derive(Debug, Clone)]
146pub struct ServerIdentity {
147    /// Server name reported to the client.
148    pub name: String,
149    /// Server version reported to the client.
150    pub version: String,
151    /// One-line operating instructions shown to the model.
152    pub instructions: String,
153}
154
155impl ServerIdentity {
156    #[must_use]
157    pub fn new(
158        name: impl Into<String>,
159        version: impl Into<String>,
160        instructions: impl Into<String>,
161    ) -> Self {
162        Self {
163            name: name.into(),
164            version: version.into(),
165            instructions: instructions.into(),
166        }
167    }
168}
169
170/// Which representations of one successful result reach the client.
171///
172/// MCP recommends mirroring `structuredContent` into a text block so a client
173/// that reads only `content` still sees the result. That mirror is the entire
174/// payload a second time, and it is the pretty-printed copy, so it is the
175/// larger of the two blocks. A server whose client reads structured output can
176/// drop it and roughly halve every response.
177#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
178pub enum ToolPayload {
179    /// Compact text content only. No `structuredContent`.
180    Text,
181    /// `structuredContent` plus the text mirror the MCP revision recommends
182    /// for clients that read only `content`.
183    #[default]
184    Mirrored,
185    /// `structuredContent` only, with an empty content array.
186    ///
187    /// A deliberate departure from the backwards-compatibility recommendation:
188    /// a client that ignores `structuredContent` sees an empty result, so this
189    /// is only correct when the server knows what reads it.
190    Structured,
191}
192
193impl ToolPayload {
194    /// Whether this payload carries `structuredContent`.
195    #[must_use]
196    pub fn is_structured(self) -> bool {
197        matches!(self, Self::Mirrored | Self::Structured)
198    }
199
200    /// Whether this payload carries a text content block.
201    #[must_use]
202    pub fn has_text(self) -> bool {
203        matches!(self, Self::Text | Self::Mirrored)
204    }
205}
206
207/// Outcome of one `tools/call` dispatch.
208#[derive(Debug, Clone)]
209pub enum ToolReply {
210    /// Successful tool output.
211    Success {
212        /// Tool output value serialized into the text content block.
213        value: Value,
214        /// Which representations reach the client.
215        payload: ToolPayload,
216    },
217    /// Pre-serialized tool output used by the fast response path.
218    Serialized {
219        /// One complete validated JSON value.
220        value: Box<RawValue>,
221        /// Which representations reach the client.
222        payload: ToolPayload,
223    },
224    /// Pre-serialized non-object structured output for MCP 2026-07-28.
225    ///
226    /// Legacy revisions still expose this value through text content only.
227    StructuredAny {
228        /// One complete validated JSON scalar or array.
229        value: Box<RawValue>,
230    },
231    /// Tool failure reported as `isError: true` content, not a protocol error.
232    Error(String),
233    /// Literal text content. The string is the text block, not JSON-encoded again.
234    Literal {
235        /// Characters that appear in the MCP text content block.
236        text: String,
237    },
238}
239
240impl ToolReply {
241    /// Success carrying both text and `structuredContent`.
242    ///
243    /// Any serializable result is accepted; handlers do not need to build a
244    /// JSON [`Value`] first.
245    #[must_use]
246    pub fn structured(value: impl Serialize) -> Self {
247        Self::success_with(value, ToolPayload::Mirrored)
248    }
249
250    /// Success carrying compact text content only.
251    ///
252    /// Any serializable result is accepted. The value is serialized as JSON
253    /// first, so `ToolReply::text("hello")` puts the JSON string `"hello"` —
254    /// including its quotes — into the text block. Use
255    /// [`ToolReply::literal_text`] when the handler already has the characters
256    /// the client should read.
257    #[must_use]
258    pub fn text(value: impl Serialize) -> Self {
259        Self::success_with(value, ToolPayload::Text)
260    }
261
262    /// Success carrying a literal text block, without an extra JSON quote layer.
263    ///
264    /// `ToolReply::literal_text("hello")` produces a text content block whose
265    /// value is `hello`. This constructor is additive and does not change
266    /// [`ToolReply::text`].
267    #[must_use]
268    pub fn literal_text(text: impl Into<String>) -> Self {
269        Self::Literal { text: text.into() }
270    }
271
272    /// Success carrying `structuredContent` without the text mirror.
273    ///
274    /// Halves the response for a client that reads structured output, and
275    /// leaves nothing readable for a client that does not.
276    #[must_use]
277    pub fn structured_only(value: impl Serialize) -> Self {
278        Self::success_with(value, ToolPayload::Structured)
279    }
280
281    /// Serializes a successful tool result once, mirroring when `structured`.
282    #[must_use]
283    pub fn success(value: impl Serialize, structured: bool) -> Self {
284        Self::success_with(
285            value,
286            if structured {
287                ToolPayload::Mirrored
288            } else {
289                ToolPayload::Text
290            },
291        )
292    }
293
294    /// Serializes a successful tool result once.
295    ///
296    /// Object-shaped output is structured in every supported revision.
297    /// Arrays and scalars are structured in MCP 2026-07-28 and remain
298    /// text-only when serving a legacy revision, so a non-object value never
299    /// takes a structured-only payload: dropping the text block would leave
300    /// the legacy client with nothing at all.
301    #[must_use]
302    pub fn success_with(value: impl Serialize, payload: ToolPayload) -> Self {
303        match blazingly_json::to_raw_value(&value) {
304            Ok(value) if payload.is_structured() && !value.get().starts_with('{') => {
305                Self::StructuredAny { value }
306            }
307            Ok(value) => Self::Serialized { payload, value },
308            Err(error) => Self::Error(format!("tool result serialization failed: {error}")),
309        }
310    }
311
312    /// Tool failure with a human-readable message.
313    #[must_use]
314    pub fn error(message: impl Into<String>) -> Self {
315        Self::Error(message.into())
316    }
317}
318
319/// Outcome of a non-tool JSON-RPC method handled by a server extension.
320#[derive(Debug, Clone)]
321pub enum MethodReply {
322    /// Successful JSON-RPC result.
323    Success(Value),
324    /// JSON-RPC error with an optional structured data payload.
325    Error {
326        /// JSON-RPC error code.
327        code: i64,
328        /// Human-readable error message.
329        message: String,
330        /// Optional machine-readable error data.
331        data: Option<Value>,
332    },
333}
334
335impl MethodReply {
336    /// Creates a successful extension-method result.
337    #[must_use]
338    pub fn success(value: impl Serialize) -> Self {
339        match blazingly_json::to_value(value) {
340            Ok(value) => Self::Success(value),
341            Err(error) => Self::error(
342                -32_603,
343                format!("method result serialization failed: {error}"),
344            ),
345        }
346    }
347
348    /// Creates a JSON-RPC extension-method error.
349    #[must_use]
350    pub fn error(code: i64, message: impl Into<String>) -> Self {
351        Self::Error {
352            code,
353            message: message.into(),
354            data: None,
355        }
356    }
357
358    /// Creates a JSON-RPC extension-method error with structured data.
359    #[must_use]
360    pub fn error_with_data(code: i64, message: impl Into<String>, data: impl Serialize) -> Self {
361        Self::Error {
362            code,
363            message: message.into(),
364            data: blazingly_json::to_value(data).ok(),
365        }
366    }
367}
368
369/// One cursor-addressed page returned from `tools/list`.
370#[derive(Debug, Clone)]
371pub struct ToolPage {
372    /// Tool descriptors in this page.
373    pub tools: Value,
374    /// Opaque cursor for the next page.
375    pub next_cursor: Option<String>,
376}
377
378impl ToolPage {
379    /// Creates a complete, non-paginated tool list.
380    #[must_use]
381    pub const fn complete(tools: Value) -> Self {
382        Self {
383            tools,
384            next_cursor: None,
385        }
386    }
387}
388
389/// A read-only tool surface served over MCP stdio.
390pub trait ToolServer {
391    /// Identity reported from `initialize`.
392    fn identity(&self) -> ServerIdentity;
393
394    /// Borrows the identity when the implementation stores it.
395    ///
396    /// The default preserves source compatibility with existing
397    /// implementations. Returning a reference avoids three string clones
398    /// during initialization.
399    fn identity_ref(&self) -> Option<&ServerIdentity> {
400        None
401    }
402
403    /// Server capabilities reported by initialization and discovery.
404    fn capabilities(&self) -> Value {
405        json!({"tools": {"listChanged": false}})
406    }
407
408    /// Borrows stored server capabilities when available.
409    fn capabilities_ref(&self) -> Option<&Value> {
410        None
411    }
412
413    /// Tool catalog returned from `tools/list`, as a JSON array.
414    fn catalog(&mut self) -> Value;
415
416    /// Borrows the catalog when the implementation stores it.
417    ///
418    /// Returning a reference avoids cloning the complete schema list.
419    fn catalog_ref(&mut self) -> Option<&Value> {
420        None
421    }
422
423    /// Borrows a compact, validated serialization of the catalog.
424    ///
425    /// Builder-backed servers use this to splice immutable schemas directly
426    /// into `tools/list` responses instead of serializing the same catalog on
427    /// every request.
428    fn catalog_raw_ref(&mut self) -> Option<&RawValue> {
429        None
430    }
431
432    /// Fatal registration problems that must refuse startup.
433    ///
434    /// Used by the convenience facade for duplicate tool names. Handwritten
435    /// [`ToolServer`] implementations inherit an empty slice.
436    fn registration_errors(&self) -> &[String] {
437        &[]
438    }
439
440    /// Reports whether `tools/list` should use [`ToolServer::catalog_page`].
441    fn catalog_is_paginated(&self) -> bool {
442        false
443    }
444
445    /// Returns one cursor-addressed tool page.
446    fn catalog_page(&mut self, cursor: Option<&str>) -> Result<ToolPage, String> {
447        if cursor.is_some() {
448            return Err("invalid tools/list cursor".to_owned());
449        }
450        Ok(ToolPage::complete(self.catalog()))
451    }
452
453    /// Reports whether a tool name is registered when the server can know
454    /// without invoking it.
455    ///
456    /// Returning `Some(false)` lets mcport emit a protocol-level invalid
457    /// params error for an unknown tool, as required by MCP. The compatibility
458    /// default leaves custom dispatch implementations authoritative.
459    fn has_tool(&self, _name: &str) -> Option<bool> {
460        None
461    }
462
463    /// Dispatches one tool call.
464    fn call(&mut self, name: &str, arguments: Value) -> ToolReply;
465
466    /// Dispatches validated raw arguments without constructing a JSON DOM.
467    ///
468    /// Existing implementations inherit a compatible default that decodes a
469    /// [`Value`] and calls [`ToolServer::call`]. Typed builders override this
470    /// method and deserialize directly into the handler input.
471    fn call_raw(&mut self, name: &str, arguments: RawJson<'_>) -> ToolReply {
472        match arguments.deserialize::<Value>() {
473            Ok(arguments) => self.call(name, arguments),
474            Err(error) => ToolReply::error(format!("invalid arguments for {name}: {error}")),
475        }
476    }
477
478    /// Handles a JSON-RPC method outside the built-in MCP tool surface.
479    ///
480    /// Returning `None` keeps the standard `method not found` response.
481    fn call_method(&mut self, _method: &str, _params: Value) -> Option<MethodReply> {
482        None
483    }
484
485    /// Advertised schemas that do not describe what their tool accepts.
486    ///
487    /// The stream adapters refuse to start when this is non-empty, so an
488    /// incomplete schema fails at startup instead of being discovered by a
489    /// client one rejected call at a time. Implementations that build their
490    /// catalog by hand inherit an empty slice and are unaffected; they can
491    /// check their schemas with [`validate_tool_schema`] in their own tests.
492    /// Both builders fill this in once [`McpServer::strict_schemas`] is set.
493    fn strict_schema_defects(&self) -> &[SchemaDefect] {
494        &[]
495    }
496}
497
498/// Serves a [`ToolServer`] over process stdin/stdout until EOF.
499///
500/// # Errors
501///
502/// Returns only stdio failures. Invalid requests are answered with JSON-RPC
503/// errors and do not terminate the server.
504pub fn serve(server: &mut impl ToolServer) -> io::Result<()> {
505    serve_with_limits(server, TransportLimits::default())
506}
507
508/// Serves a [`ToolServer`] over process stdin/stdout with explicit byte budgets.
509///
510/// # Errors
511///
512/// Returns stream failures or an invalid limits configuration.
513pub fn serve_with_limits(server: &mut impl ToolServer, limits: TransportLimits) -> io::Result<()> {
514    let stdin = io::stdin();
515    let stdout = io::stdout();
516    serve_streams_with_limits(server, stdin.lock(), stdout.lock(), limits)
517}
518
519/// Serves a [`ToolServer`] over process stdin/stdout with complete transport
520/// policy, including opt-in response batching.
521///
522/// # Errors
523///
524/// Returns stream failures or an invalid transport configuration.
525pub fn serve_with_config(server: &mut impl ToolServer, config: TransportConfig) -> io::Result<()> {
526    let stdin = io::stdin();
527    let stdout = io::stdout();
528    match config.flush_policy {
529        FlushPolicy::PerMessage => {
530            serve_streams_with_config(server, stdin.lock(), stdout.lock(), config)
531        }
532        FlushPolicy::Batch { .. } => serve_streams_with_config(
533            server,
534            stdin.lock(),
535            io::BufWriter::new(stdout.lock()),
536            config,
537        ),
538    }
539}
540
541/// Serves a [`ToolServer`] over arbitrary streams until EOF.
542///
543/// This is [`serve`] with injectable transport, which makes the full loop
544/// testable without spawning processes.
545///
546/// # Errors
547///
548/// Returns only stream I/O failures.
549pub fn serve_streams(
550    server: &mut impl ToolServer,
551    reader: impl BufRead,
552    writer: impl Write,
553) -> io::Result<()> {
554    serve_streams_with_limits(server, reader, writer, TransportLimits::default())
555}
556
557/// Serves a [`ToolServer`] over arbitrary streams with explicit byte budgets.
558///
559/// Responses are assembled in a reusable bounded buffer before they become
560/// visible on the output stream, so a response budget failure never emits a
561/// truncated JSON document.
562///
563/// # Errors
564///
565/// Returns stream failures or an invalid limits configuration.
566pub fn serve_streams_with_limits(
567    server: &mut impl ToolServer,
568    reader: impl BufRead,
569    writer: impl Write,
570    limits: TransportLimits,
571) -> io::Result<()> {
572    transport::serve_streams_bounded(server, reader, writer, limits)
573}
574
575/// Serves a [`ToolServer`] over arbitrary streams with byte and flush policy.
576///
577/// # Errors
578///
579/// Returns stream failures or an invalid transport configuration.
580pub fn serve_streams_with_config(
581    server: &mut impl ToolServer,
582    reader: impl BufRead,
583    writer: impl Write,
584    config: TransportConfig,
585) -> io::Result<()> {
586    transport::serve_streams_configured(server, reader, writer, config)
587}
588
589/// Processes one newline-free JSON-RPC message.
590///
591/// Returns `true` when a response was written and `false` for an empty line or
592/// notification. This is useful for embedding mcport in an existing blocking
593/// transport without giving the runtime ownership of its read loop.
594///
595/// # Errors
596///
597/// Returns only writer failures.
598pub fn serve_message(
599    server: &mut impl ToolServer,
600    line: &str,
601    writer: &mut impl Write,
602) -> io::Result<bool> {
603    let line = line.trim_start_matches('\u{feff}');
604    if line.trim().is_empty() {
605        return Ok(false);
606    }
607    fast::dispatch_line(server, line, writer)
608}
609
610/// Dispatches one parsed JSON-RPC request.
611///
612/// Returns `None` for notifications (requests without an `id`), which must
613/// not be answered.
614pub fn dispatch(server: &mut impl ToolServer, request: &Value) -> Option<Value> {
615    if !request.is_object() {
616        return Some(protocol::error(
617            &Value::Null,
618            -32_600,
619            "invalid JSON-RPC request",
620        ));
621    }
622    let id = request.get("id").cloned();
623    if request.get("jsonrpc").and_then(Value::as_str) != Some("2.0") {
624        return Some(protocol::error(
625            id.as_ref().unwrap_or(&Value::Null),
626            -32_600,
627            "invalid JSON-RPC version",
628        ));
629    }
630    let Some(method) = request.get("method").and_then(Value::as_str) else {
631        return Some(protocol::error(
632            id.as_ref().unwrap_or(&Value::Null),
633            -32_600,
634            "missing JSON-RPC method",
635        ));
636    };
637    let modern = match request_uses_modern_protocol(request, id.as_ref().unwrap_or(&Value::Null)) {
638        Ok(modern) => modern,
639        Err(response) => return Some(response),
640    };
641    let id = id?;
642    Some(match method {
643        "initialize" => initialize_response(server, request, &id),
644        "server/discover" if modern => discover_response(server, &id),
645        "ping" if modern => protocol::error(&id, -32_601, "method not found: ping"),
646        "ping" => protocol::success(&id, &json!({})),
647        "tools/list" => tools_list_response(server, request, &id, modern),
648        "tools/call" => tool_call_response(server, request, &id, modern),
649        _ => extension_method_response(server, method, request, &id),
650    })
651}
652
653fn extension_method_response(
654    server: &mut impl ToolServer,
655    method: &str,
656    request: &Value,
657    id: &Value,
658) -> Value {
659    let params = request.get("params").cloned().unwrap_or_else(|| json!({}));
660    match server.call_method(method, params) {
661        Some(MethodReply::Success(result)) => protocol::success(id, &result),
662        Some(MethodReply::Error {
663            code,
664            message,
665            data: Some(data),
666        }) => protocol::error_with_data(id, code, message, data),
667        Some(MethodReply::Error {
668            code,
669            message,
670            data: None,
671        }) => protocol::error(id, code, message),
672        None => protocol::error(id, -32_601, format!("method not found: {method}")),
673    }
674}
675
676fn request_uses_modern_protocol(request: &Value, id: &Value) -> Result<bool, Value> {
677    let requested_version = request
678        .pointer("/params/_meta/io.modelcontextprotocol~1protocolVersion")
679        .and_then(Value::as_str);
680    let Some(requested_version) = requested_version else {
681        return Ok(false);
682    };
683    if !SUPPORTED_PROTOCOL_VERSIONS.contains(&requested_version) {
684        return Err(protocol::error_with_data(
685            id,
686            -32_022,
687            "Unsupported protocol version",
688            json!({
689                "supported": SUPPORTED_PROTOCOL_VERSIONS,
690                "requested": requested_version
691            }),
692        ));
693    }
694    if requested_version != MODERN_PROTOCOL_VERSION {
695        return Err(protocol::error(
696            id,
697            -32_600,
698            "legacy protocol versions require the initialize lifecycle",
699        ));
700    }
701    if request
702        .pointer("/params/_meta/io.modelcontextprotocol~1clientCapabilities")
703        .is_none()
704    {
705        return Err(protocol::error(
706            id,
707            -32_602,
708            "missing io.modelcontextprotocol/clientCapabilities",
709        ));
710    }
711    Ok(true)
712}
713
714fn initialize_response(server: &impl ToolServer, request: &Value, id: &Value) -> Value {
715    let requested_version = request
716        .pointer("/params/protocolVersion")
717        .and_then(Value::as_str);
718    let version = negotiate_protocol_version(requested_version);
719    let identity = server.identity();
720    let capabilities = server
721        .capabilities_ref()
722        .cloned()
723        .unwrap_or_else(|| server.capabilities());
724    protocol::success(
725        id,
726        &json!({
727            "protocolVersion": version,
728            "capabilities": capabilities,
729            "serverInfo": {
730                "name": identity.name,
731                "version": identity.version
732            },
733            "instructions": identity.instructions
734        }),
735    )
736}
737
738fn discover_response(server: &impl ToolServer, id: &Value) -> Value {
739    let identity = server.identity();
740    let capabilities = server
741        .capabilities_ref()
742        .cloned()
743        .unwrap_or_else(|| server.capabilities());
744    protocol::success(
745        id,
746        &json!({
747            "resultType": "complete",
748            "supportedVersions": SUPPORTED_PROTOCOL_VERSIONS,
749            "capabilities": capabilities,
750            "_meta": {
751                "io.modelcontextprotocol/serverInfo": {
752                    "name": identity.name,
753                    "version": identity.version
754                }
755            },
756            "instructions": identity.instructions
757        }),
758    )
759}
760
761fn tool_call_response(
762    server: &mut impl ToolServer,
763    request: &Value,
764    id: &Value,
765    modern: bool,
766) -> Value {
767    let Some(name) = request.pointer("/params/name").and_then(Value::as_str) else {
768        return protocol::error(id, -32_602, "tools/call requires params.name");
769    };
770    if server.has_tool(name) == Some(false) {
771        return protocol::error(id, -32_602, format!("unknown tool: {name}"));
772    }
773    let arguments = request
774        .pointer("/params/arguments")
775        .cloned()
776        .unwrap_or_else(|| json!({}));
777    let mut response = match server.call(name, arguments) {
778        ToolReply::Success { value, payload } => protocol::tool_success(id, &value, payload),
779        ToolReply::Serialized { value, payload } => protocol::tool_success_raw(id, &value, payload),
780        ToolReply::StructuredAny { value } if modern => protocol::tool_success_raw_any(id, &value),
781        ToolReply::StructuredAny { value } => {
782            protocol::tool_success_raw(id, &value, ToolPayload::Text)
783        }
784        ToolReply::Literal { text } => protocol::tool_literal_text(id, text),
785        ToolReply::Error(message) => protocol::tool_error(id, message),
786    };
787    if modern {
788        protocol::mark_complete(&mut response);
789    }
790    response
791}
792
793fn tools_list_response(
794    server: &mut impl ToolServer,
795    request: &Value,
796    id: &Value,
797    modern: bool,
798) -> Value {
799    let cursor = request.pointer("/params/cursor").and_then(Value::as_str);
800    let page = if server.catalog_is_paginated() || cursor.is_some() {
801        match server.catalog_page(cursor) {
802            Ok(page) => page,
803            Err(message) => return protocol::error(id, -32_602, message),
804        }
805    } else {
806        ToolPage::complete(server.catalog())
807    };
808    let mut result = json!({"tools": page.tools});
809    if let (Some(result), Some(next_cursor)) = (result.as_object_mut(), page.next_cursor) {
810        result.insert("nextCursor".to_owned(), Value::String(next_cursor));
811    }
812    let mut response = protocol::success(id, &result);
813    if modern {
814        protocol::mark_complete(&mut response);
815    }
816    response
817}
818
819#[cfg(test)]
820mod tests {
821    use super::{
822        dispatch, json, serve_message, serve_streams, MethodReply, ServerIdentity, ToolReply,
823        ToolServer, Value,
824    };
825
826    struct Echo {
827        calls: usize,
828    }
829
830    impl ToolServer for Echo {
831        fn identity(&self) -> ServerIdentity {
832            ServerIdentity::new("echo", "1.2.3", "Echoes tool arguments back.")
833        }
834
835        fn catalog(&mut self) -> Value {
836            json!([{
837                "name": "echo",
838                "description": "Echo the arguments.",
839                "inputSchema": {"type": "object", "additionalProperties": true}
840            }])
841        }
842
843        fn call(&mut self, name: &str, arguments: Value) -> ToolReply {
844            self.calls += 1;
845            match name {
846                "echo" => ToolReply::structured(arguments),
847                "flat" => ToolReply::text(arguments),
848                "scalar" => ToolReply::structured(5),
849                _ => ToolReply::error(format!("unknown tool: {name}")),
850            }
851        }
852    }
853
854    struct Resources;
855
856    impl ToolServer for Resources {
857        fn identity(&self) -> ServerIdentity {
858            ServerIdentity::new("resources", "1.0.0", "Resource test server.")
859        }
860
861        fn capabilities(&self) -> Value {
862            json!({
863                "tools": {"listChanged": false},
864                "resources": {"subscribe": false, "listChanged": false}
865            })
866        }
867
868        fn catalog(&mut self) -> Value {
869            json!([])
870        }
871
872        fn call(&mut self, name: &str, _arguments: Value) -> ToolReply {
873            ToolReply::error(format!("unknown tool: {name}"))
874        }
875
876        fn call_method(&mut self, method: &str, params: Value) -> Option<MethodReply> {
877            match method {
878                "resources/list" => Some(MethodReply::success(json!({
879                    "resources": [{
880                        "uri": "test://resource",
881                        "name": "test"
882                    }]
883                }))),
884                "resources/read" => {
885                    if params.get("uri").and_then(Value::as_str) == Some("test://resource") {
886                        Some(MethodReply::success(json!({
887                            "contents": [{
888                                "uri": "test://resource",
889                                "text": "ok"
890                            }]
891                        })))
892                    } else {
893                        Some(MethodReply::error(-32_602, "unknown resource URI"))
894                    }
895                }
896                _ => None,
897            }
898        }
899    }
900
901    #[test]
902    fn composes_capabilities_and_extension_methods() {
903        let mut server = Resources;
904        let initialized = dispatch(
905            &mut server,
906            &json!({
907                "jsonrpc": "2.0",
908                "id": 1,
909                "method": "initialize",
910                "params": {"protocolVersion": "2025-11-25"}
911            }),
912        )
913        .unwrap();
914        assert_eq!(
915            initialized["result"]["capabilities"]["resources"]["subscribe"],
916            false
917        );
918
919        let listed = dispatch(
920            &mut server,
921            &json!({
922                "jsonrpc": "2.0",
923                "id": 2,
924                "method": "resources/list"
925            }),
926        )
927        .unwrap();
928        assert_eq!(listed["result"]["resources"][0]["uri"], "test://resource");
929
930        let mut output = Vec::new();
931        assert!(serve_message(
932            &mut server,
933            r#"{"jsonrpc":"2.0","id":3,"method":"resources/read","params":{"uri":"missing"}}"#,
934            &mut output,
935        )
936        .unwrap());
937        let response: Value = blazingly_json::from_slice(&output).expect("valid JSON response");
938        assert_eq!(response["error"]["code"], -32_602);
939    }
940
941    #[test]
942    fn negotiates_lists_and_calls() {
943        let mut server = Echo { calls: 0 };
944        let initialized = dispatch(
945            &mut server,
946            &json!({
947                "jsonrpc": "2.0",
948                "id": 1,
949                "method": "initialize",
950                "params": {"protocolVersion": "2025-06-18"}
951            }),
952        )
953        .unwrap();
954        assert_eq!(initialized["result"]["protocolVersion"], "2025-06-18");
955        assert_eq!(initialized["result"]["serverInfo"]["name"], "echo");
956        assert_eq!(server.calls, 0, "initialize must not call tools");
957
958        let fallback = dispatch(
959            &mut server,
960            &json!({"jsonrpc": "2.0", "id": 2, "method": "initialize"}),
961        )
962        .unwrap();
963        assert_eq!(
964            fallback["result"]["protocolVersion"],
965            super::DEFAULT_PROTOCOL_VERSION
966        );
967
968        let unknown_version = dispatch(
969            &mut server,
970            &json!({
971                "jsonrpc": "2.0",
972                "id": 3,
973                "method": "initialize",
974                "params": {"protocolVersion": "2099-01-01"}
975            }),
976        )
977        .unwrap();
978        assert_eq!(
979            unknown_version["result"]["protocolVersion"],
980            super::DEFAULT_PROTOCOL_VERSION
981        );
982
983        let listed = dispatch(
984            &mut server,
985            &json!({"jsonrpc": "2.0", "id": 4, "method": "tools/list"}),
986        )
987        .unwrap();
988        assert_eq!(listed["result"]["tools"].as_array().map(Vec::len), Some(1));
989
990        let called = dispatch(
991            &mut server,
992            &json!({
993                "jsonrpc": "2.0",
994                "id": 5,
995                "method": "tools/call",
996                "params": {"name": "echo", "arguments": {"value": 7}}
997            }),
998        )
999        .unwrap();
1000        assert_eq!(called["result"]["isError"], false);
1001        assert_eq!(called["result"]["structuredContent"]["value"], 7);
1002
1003        let flat = dispatch(
1004            &mut server,
1005            &json!({
1006                "jsonrpc": "2.0",
1007                "id": 6,
1008                "method": "tools/call",
1009                "params": {"name": "flat", "arguments": {"value": 7}}
1010            }),
1011        )
1012        .unwrap();
1013        assert!(flat["result"].get("structuredContent").is_none());
1014
1015        let failed = dispatch(
1016            &mut server,
1017            &json!({
1018                "jsonrpc": "2.0",
1019                "id": 7,
1020                "method": "tools/call",
1021                "params": {"name": "missing"}
1022            }),
1023        )
1024        .unwrap();
1025        assert_eq!(failed["result"]["isError"], true);
1026    }
1027
1028    #[test]
1029    fn rejects_invalid_requests_without_stopping() {
1030        let mut server = Echo { calls: 0 };
1031        let no_method = dispatch(&mut server, &json!({"jsonrpc": "2.0", "id": 1})).unwrap();
1032        assert_eq!(no_method["error"]["code"], -32_600);
1033
1034        let wrong_version = dispatch(
1035            &mut server,
1036            &json!({"jsonrpc": "1.0", "id": 2, "method": "ping"}),
1037        )
1038        .unwrap();
1039        assert_eq!(wrong_version["error"]["code"], -32_600);
1040
1041        let non_object = dispatch(&mut server, &json!([])).unwrap();
1042        assert_eq!(non_object["error"]["code"], -32_600);
1043
1044        let unknown = dispatch(
1045            &mut server,
1046            &json!({"jsonrpc": "2.0", "id": 3, "method": "resources/list"}),
1047        )
1048        .unwrap();
1049        assert_eq!(unknown["error"]["code"], -32_601);
1050
1051        let unnamed = dispatch(
1052            &mut server,
1053            &json!({"jsonrpc": "2.0", "id": 4, "method": "tools/call"}),
1054        )
1055        .unwrap();
1056        assert_eq!(unnamed["error"]["code"], -32_602);
1057
1058        let notification = dispatch(
1059            &mut server,
1060            &json!({"jsonrpc": "2.0", "method": "notifications/initialized"}),
1061        );
1062        assert!(notification.is_none(), "notifications are not answered");
1063
1064        let malformed_notification =
1065            dispatch(&mut server, &json!({"jsonrpc": "1.0", "method": "ping"})).unwrap();
1066        assert_eq!(malformed_notification["id"], Value::Null);
1067        assert_eq!(malformed_notification["error"]["code"], -32_600);
1068    }
1069
1070    #[test]
1071    fn supports_modern_discovery_and_versioned_tool_results() {
1072        let modern_meta = json!({
1073            "io.modelcontextprotocol/protocolVersion": super::MODERN_PROTOCOL_VERSION,
1074            "io.modelcontextprotocol/clientInfo": {"name": "test", "version": "1"},
1075            "io.modelcontextprotocol/clientCapabilities": {}
1076        });
1077        let mut server = Echo { calls: 0 };
1078        let discovered = dispatch(
1079            &mut server,
1080            &json!({
1081                "jsonrpc": "2.0",
1082                "id": "discover",
1083                "method": "server/discover",
1084                "params": {"_meta": modern_meta.clone()}
1085            }),
1086        )
1087        .unwrap();
1088        assert_eq!(discovered["result"]["resultType"], "complete");
1089        assert_eq!(
1090            discovered["result"]["supportedVersions"][0],
1091            super::MODERN_PROTOCOL_VERSION
1092        );
1093        assert_eq!(
1094            discovered["result"]["_meta"]["io.modelcontextprotocol/serverInfo"]["name"],
1095            "echo"
1096        );
1097
1098        let listed = dispatch(
1099            &mut server,
1100            &json!({
1101                "jsonrpc": "2.0",
1102                "id": 1,
1103                "method": "tools/list",
1104                "params": {"_meta": modern_meta.clone()}
1105            }),
1106        )
1107        .unwrap();
1108        assert_eq!(listed["result"]["resultType"], "complete");
1109
1110        let called = dispatch(
1111            &mut server,
1112            &json!({
1113                "jsonrpc": "2.0",
1114                "id": 2,
1115                "method": "tools/call",
1116                "params": {
1117                    "_meta": modern_meta.clone(),
1118                    "name": "echo",
1119                    "arguments": {"modern": true}
1120                }
1121            }),
1122        )
1123        .unwrap();
1124        assert_eq!(called["result"]["resultType"], "complete");
1125        assert_eq!(called["result"]["structuredContent"]["modern"], true);
1126
1127        let scalar = dispatch(
1128            &mut server,
1129            &json!({
1130                "jsonrpc": "2.0",
1131                "id": "scalar",
1132                "method": "tools/call",
1133                "params": {
1134                    "_meta": modern_meta,
1135                    "name": "scalar",
1136                    "arguments": {}
1137                }
1138            }),
1139        )
1140        .unwrap();
1141        assert_eq!(scalar["result"]["structuredContent"], 5);
1142
1143        let unsupported = dispatch(
1144            &mut server,
1145            &json!({
1146                "jsonrpc": "2.0",
1147                "id": 3,
1148                "method": "tools/list",
1149                "params": {"_meta": {
1150                    "io.modelcontextprotocol/protocolVersion": "1900-01-01",
1151                    "io.modelcontextprotocol/clientCapabilities": {}
1152                }}
1153            }),
1154        )
1155        .unwrap();
1156        assert_eq!(unsupported["error"]["code"], -32_022);
1157        assert_eq!(unsupported["error"]["data"]["requested"], "1900-01-01");
1158    }
1159
1160    #[test]
1161    fn serves_a_full_session_over_streams() {
1162        let mut server = Echo { calls: 0 };
1163        let input = concat!(
1164            "\u{feff}{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"ping\"}\n",
1165            "\n",
1166            "not json\n",
1167            "{\"jsonrpc\":\"2.0\",\"method\":\"notifications/initialized\"}\n",
1168            "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/call\",",
1169            "\"params\":{\"name\":\"echo\",\"arguments\":{\"ok\":true}}}\n",
1170        );
1171        let mut output = Vec::new();
1172        serve_streams(&mut server, input.as_bytes(), &mut output).unwrap();
1173        let lines = String::from_utf8(output).unwrap();
1174        let lines = lines.lines().collect::<Vec<_>>();
1175        assert_eq!(lines.len(), 3, "ping, parse error, tool call");
1176
1177        let ping = blazingly_json::from_str::<Value>(lines[0]).unwrap();
1178        assert_eq!(ping["id"], 1, "BOM-prefixed first request still parses");
1179
1180        let parse_error = blazingly_json::from_str::<Value>(lines[1]).unwrap();
1181        assert_eq!(parse_error["error"]["code"], -32_700);
1182
1183        let called = blazingly_json::from_str::<Value>(lines[2]).unwrap();
1184        assert_eq!(called["result"]["structuredContent"]["ok"], true);
1185        assert_eq!(server.calls, 1);
1186    }
1187
1188    #[test]
1189    fn fast_message_path_preserves_public_dispatch_semantics() {
1190        let fixtures = [
1191            r#"{"jsonrpc":"2.0","id":null,"method":"ping"}"#,
1192            r#"{"jsonrpc":"2.0","id":"init","method":"initialize","params":{"protocolVersion":"2025-06-18"}}"#,
1193            r#"{"jsonrpc":"2.0","id":"future","method":"initialize","params":{"protocolVersion":"2099-01-01"}}"#,
1194            r#"{"method":"initialize","id":-2,"jsonrpc":"2.0"}"#,
1195            r#"{"jsonrpc":"2.0","id":2,"method":"tools/list"}"#,
1196            r#"{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"echo","arguments":{"ok":true}}}"#,
1197            r#"{"jsonrpc":"2.0","id":"modern-list","method":"tools/list","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}"#,
1198            r#"{"jsonrpc":"2.0","id":"modern-call","method":"tools/call","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}},"name":"echo","arguments":{"modern":true}}}"#,
1199            r#"{"jsonrpc":"2.0","id":"modern-scalar","method":"tools/call","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}},"name":"scalar","arguments":{}}}"#,
1200            r#"{"jsonrpc":"2.0","id":"modern-bad","method":"tools/list","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"1900-01-01","io.modelcontextprotocol/clientCapabilities":{}}}}"#,
1201            r#"{"params":{"arguments":[1,2],"name":"fl\u0061t"},"method":"tools/call","id":4,"jsonrpc":"2.0"}"#,
1202            r#"{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"missing"}}"#,
1203            r#"{"jsonrpc":"2.0","id":6}"#,
1204            r#"{"jsonrpc":"2.0","id":7,"method":"resources/list"}"#,
1205            r#"{"jsonrpc":"2.0","id":8,"method":"tools/call"}"#,
1206            r#"{"jsonrpc":"2.0","id":9,"method":"tools/call","params":null}"#,
1207            r#"{"jsonrpc":"2.0","id":10,"method":false}"#,
1208            r#"{"jsonrpc":"2.0","id":11,"method":"tools/call","params":{"name":"echo","arguments":{"text":"quote: \" slash: \\ newline: \n snowman: ☃"}}}"#,
1209            r#"{"jsonrpc":"2.0","id":1.5,"method":"ping"}"#,
1210            r#"{"jsonrpc":"2.0","id":{"legacy":true},"method":"ping"}"#,
1211            r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#,
1212            r#"{"jsonrpc":"1.0","method":"ping"}"#,
1213            r#"{"jsonrpc":"2.0","method":false}"#,
1214            r"[]",
1215        ];
1216
1217        for fixture in fixtures {
1218            let request = blazingly_json::from_str::<Value>(fixture).unwrap();
1219            let mut expected_server = Echo { calls: 0 };
1220            let expected = dispatch(&mut expected_server, &request);
1221
1222            let mut actual_server = Echo { calls: 0 };
1223            let mut output = Vec::new();
1224            let wrote = serve_message(&mut actual_server, fixture, &mut output).unwrap();
1225            let actual = if output.is_empty() {
1226                None
1227            } else {
1228                Some(blazingly_json::from_slice::<Value>(&output).unwrap())
1229            };
1230
1231            assert_eq!(wrote, actual.is_some(), "fixture: {fixture}");
1232            assert_eq!(actual, expected, "fixture: {fixture}");
1233            assert_eq!(actual_server.calls, expected_server.calls);
1234        }
1235    }
1236}