Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .changeset/mcp-text-content-fallback.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
---
---

fix(mcp): include text content for pre-2025-06-18 or undeclared protocol clients (#1324)
44 changes: 39 additions & 5 deletions crates/nostream-mcp/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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)
}
}

Expand Down Expand Up @@ -1372,19 +1382,26 @@ 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);
result.is_error = Some(false);
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)]
Expand Down Expand Up @@ -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
)));
}
}
24 changes: 21 additions & 3 deletions crates/nostream-mcp/tests/common/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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,
Expand Down
44 changes: 43 additions & 1 deletion crates/nostream-mcp/tests/tool_payloads.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand All @@ -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<String> {
Expand Down Expand Up @@ -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;
Expand Down
Loading