From 47463c37a435e8adb4d2f50dd8258d3ae689a1f3 Mon Sep 17 00:00:00 2001 From: Tirthraj Chavan Date: Fri, 4 Dec 2026 21:29:08 +0530 Subject: [PATCH] fix(mcp): gate text payload omission on negotiated protocol version --- .changeset/mcp-text-content-fallback.md | 4 ++ crates/nostream-mcp/src/server.rs | 44 +++++++++++++++++++--- crates/nostream-mcp/tests/common/mod.rs | 24 ++++++++++-- crates/nostream-mcp/tests/tool_payloads.rs | 44 +++++++++++++++++++++- 4 files changed, 107 insertions(+), 9 deletions(-) create mode 100644 .changeset/mcp-text-content-fallback.md diff --git a/.changeset/mcp-text-content-fallback.md b/.changeset/mcp-text-content-fallback.md new file mode 100644 index 000000000..b1877e504 --- /dev/null +++ b/.changeset/mcp-text-content-fallback.md @@ -0,0 +1,4 @@ +--- +--- + +fix(mcp): include text content for pre-2025-06-18 or undeclared protocol clients (#1324) diff --git a/crates/nostream-mcp/src/server.rs b/crates/nostream-mcp/src/server.rs index fa4006fe5..fe43e3018 100644 --- a/crates/nostream-mcp/src/server.rs +++ b/crates/nostream-mcp/src/server.rs @@ -25,7 +25,7 @@ use rmcp::handler::server::tool::ToolCallContext; use rmcp::handler::server::wrapper::Parameters; use rmcp::model::{ CallToolRequestParams, CallToolResponse, CallToolResult, ContentBlock, Implementation, - ServerCapabilities, ServerConfig, + ProtocolVersion, ServerCapabilities, ServerConfig, }; use rmcp::schemars::{self, JsonSchema, Schema, SchemaGenerator, json_schema}; use rmcp::service::RequestContext; @@ -1319,8 +1319,18 @@ impl ServerHandler for AdminMcp { if (entry.parses)(request.arguments.as_ref()) { self.record_dispatch(entry.name, request.arguments.as_ref()); } + let structured_only = supports_structured_only(context.protocol_version().as_ref()); let call = ToolCallContext::new(self, request, context); - self.tool_router.call(call).await + let mut response = self.tool_router.call(call).await?; + if !structured_only + && let CallToolResponse::Complete(result) = &mut response + && result.is_error != Some(true) + && result.content.is_empty() + && let Some(payload) = result.structured_content.as_ref() + { + result.content.push(ContentBlock::text(payload.to_string())); + } + Ok(response) } } @@ -1372,12 +1382,13 @@ fn tool_error_body(body: &Value) -> CallToolResult { CallToolResult::error(vec![ContentBlock::text(body.to_string())]) } -/// A success: the payload in `structuredContent`, and no copy of it in `content`. +/// A success: the payload in `structuredContent`, with `content` left empty by default. /// /// `CallToolResult::structured` fills `content` with `value.to_string()` *and* sets /// `structured_content`, so every page crossed the wire twice — 48.3% of a 5,000-row response -/// was a text copy nothing read. A client reads `structuredContent`; the protocol allows an -/// empty `content` array, which is what this sends. +/// was a text copy modern clients did not read. [`ServerHandler::call_tool`] keeps this omission +/// when the client negotiated protocol version `2025-06-18` or newer and fills `content` with +/// the serialized JSON for pre-`structuredContent` or undeclared clients. fn tool_ok(payload: Value) -> CallToolResult { let mut result = CallToolResult::default(); result.structured_content = Some(payload); @@ -1385,6 +1396,12 @@ fn tool_ok(payload: Value) -> CallToolResult { result } +/// Whether `version` is `2025-06-18` or later (the MCP revision that introduced +/// `structuredContent`), allowing successful tool results to omit the duplicate `content` text. +fn supports_structured_only(version: Option<&ProtocolVersion>) -> bool { + version.is_some_and(|version| version.as_str() >= ProtocolVersion::V_2025_06_18.as_str()) +} + #[cfg(test)] mod tests { #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] @@ -1424,4 +1441,21 @@ mod tests { ); assert_eq!(logged_name(TOOL_SETTINGS_GET), TOOL_SETTINGS_GET); } + + #[test] + fn structured_only_requires_2025_06_18_or_newer() { + assert!(!supports_structured_only(None)); + assert!(!supports_structured_only(Some( + &ProtocolVersion::V_2024_11_05 + ))); + assert!(!supports_structured_only(Some( + &ProtocolVersion::V_2025_03_26 + ))); + assert!(supports_structured_only(Some( + &ProtocolVersion::V_2025_06_18 + ))); + assert!(supports_structured_only(Some( + &ProtocolVersion::V_2025_11_25 + ))); + } } diff --git a/crates/nostream-mcp/tests/common/mod.rs b/crates/nostream-mcp/tests/common/mod.rs index 0013b5c72..590da271a 100644 --- a/crates/nostream-mcp/tests/common/mod.rs +++ b/crates/nostream-mcp/tests/common/mod.rs @@ -302,7 +302,27 @@ impl TestMcp { .await } + /// Connects a client declaring a specific MCP protocol version during `initialize`. + pub async fn client_with_protocol(&self, protocol_version: ProtocolVersion) -> Mcp { + self.client_with( + env!("CARGO_PKG_VERSION"), + self.credential.clone(), + protocol_version, + ) + .await + } + async fn client_with_version_and(&self, version: &str, credential: Credential) -> Mcp { + self.client_with(version, credential, ProtocolVersion::V_2025_06_18) + .await + } + + async fn client_with( + &self, + version: &str, + credential: Credential, + protocol_version: ProtocolVersion, + ) -> Mcp { let server = AdminMcp::new( Arc::clone(&self.state), credential, @@ -313,13 +333,11 @@ impl TestMcp { let service = server.serve(server_io).await.unwrap(); service.waiting().await.unwrap(); }); - // Pinned to a version with the `initialize` handshake, so the dialogue is the session - // model the console's credential belongs to. let config = ClientConfig::new( ClientCapabilities::default(), Implementation::new("nostream-mcp-tests", "0.1.0"), ) - .with_protocol_version(ProtocolVersion::V_2025_06_18); + .with_protocol_version(protocol_version); let client = config.serve(client_io).await.unwrap(); Mcp { client, diff --git a/crates/nostream-mcp/tests/tool_payloads.rs b/crates/nostream-mcp/tests/tool_payloads.rs index 046400450..514beee77 100644 --- a/crates/nostream-mcp/tests/tool_payloads.rs +++ b/crates/nostream-mcp/tests/tool_payloads.rs @@ -24,7 +24,8 @@ //! | `a_refused_criterion_never_reaches_the_store` | the refusal comes before the store: over the unwired store the argument error and offset ceiling answer, not `NotImplemented` | //! | `a_page_is_the_first_rows_oldest_first` | the payload is one order, and `limit` is its first N, with `truncated` marking a full page | //! | `a_full_default_page_is_marked_truncated` | a page the store's own bound cut says so | -//! | `a_success_carries_one_copy_of_the_payload` | a success is in `structuredContent` only, never also as a text block | +//! | `a_success_carries_one_copy_of_the_payload` | on `2025-06-18`+, a success is in `structuredContent` only, never also as a text block | +//! | `a_pre_structured_client_receives_the_payload_as_text` | on pre-`2025-06-18` revisions (`2024-11-05`, `2025-03-26`), a success also carries the serialized JSON in `content` | //! | `the_settings_schema_forbids_what_the_handler_refuses` | the published schema and the handler agree on the two accepted shapes | #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] @@ -39,6 +40,7 @@ use nostream_mcp::{ TOOL_SETTINGS_SET, }; use nostream_storage::repositories::EventRepository; +use rmcp::model::ProtocolVersion; use serde_json::{Value, json}; fn ids(events: &[Value]) -> BTreeSet { @@ -697,6 +699,46 @@ async fn a_success_carries_one_copy_of_the_payload() { } } +#[tokio::test] +async fn a_pre_structured_client_receives_the_payload_as_text() { + let fixture = TestMcp::start().await; + fixture + .seed(&[event(15, 1, 1_699_999_954), event(16, 1, 1_699_999_955)]) + .await; + + for version in [ProtocolVersion::V_2024_11_05, ProtocolVersion::V_2025_03_26] { + let client = fixture.client_with_protocol(version.clone()).await; + + for (tool, arguments) in [ + (TOOL_SETTINGS_GET, json!({})), + (TOOL_LIST_EVENTS, json!({})), + (TOOL_GET_EVENT, json!({ "id": "abcd" })), + ( + TOOL_SETTINGS_SET, + json!({ "path": "wot.enabled", "value": false }), + ), + ] { + let answer = client.call(tool, arguments).await; + assert_eq!(answer.is_error, Some(false), "{version} {tool}"); + assert_eq!( + answer.content.len(), + 1, + "{version} {tool} sends one text block alongside structured content: {:?}", + answer.content + ); + let raw = text(&answer); + let parsed: Value = serde_json::from_str(&raw).unwrap_or_else(|error| { + panic!("{version} {tool} text is not JSON ({error}): {raw}") + }); + assert_eq!( + Some(parsed), + answer.structured_content, + "{version} {tool} text block matches structuredContent" + ); + } + } +} + #[tokio::test] async fn the_settings_schema_forbids_what_the_handler_refuses() { let fixture = TestMcp::start().await;