From 2499016dc7a691f240b51f180cea06a87930b6be Mon Sep 17 00:00:00 2001 From: bsodfather Date: Mon, 26 Oct 2026 16:03:48 +0000 Subject: [PATCH] =?UTF-8?q?fix(epic3):=20=D0=BF=D1=80=D0=B8=D0=BD=D0=B8?= =?UTF-8?q?=D0=BC=D0=B0=D1=82=D1=8C=20=D0=BF=D0=BE=D1=82=D0=BE=D0=BA=20pro?= =?UTF-8?q?gress=20=D0=BF=D1=80=D0=B8=20JSON-first=20Accept=20=D0=BE=D1=84?= =?UTF-8?q?=D0=B8=D1=86=D0=B8=D0=B0=D0=BB=D1=8C=D0=BD=D0=BE=D0=B3=D0=BE=20?= =?UTF-8?q?SDK=20(Story=203.4,=20FR-14)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Официальный MCP SDK перечисляет медиатипы в `Accept` JSON-first (`application/json, text/event-stream`). Прежняя реализация выбирала negotiated JSON-тело, и клиент, которому нужен progress, не получал ни одного кадра. Коррекция переиспользует уже провалидированные шаги: для `tools/call` с допустимым progress token и предложенным event-stream режим ответа переключается на SSE. Admission/авторизация не двигались; другой метод, отсутствующий или непригодный token и JSON-only `Accept` сохраняют negotiated режим. ATDD: тот же JSON-first `Accept` даёт строго монотонные progress 1/2/3 и прежний result в обеих supported revisions, а негативные контроли (без token и с непригодным token) остаются на JSON-теле. --- .../tests/integration/tools_lifecycle.rs | 91 +++++++++++++++++++ .../crank-community-mcp/src/app/endpoint.rs | 19 +++- 2 files changed, 107 insertions(+), 3 deletions(-) diff --git a/apps/mcp-server/tests/integration/tools_lifecycle.rs b/apps/mcp-server/tests/integration/tools_lifecycle.rs index b5b4b95..245e74a 100644 --- a/apps/mcp-server/tests/integration/tools_lifecycle.rs +++ b/apps/mcp-server/tests/integration/tools_lifecycle.rs @@ -536,6 +536,97 @@ async fn at_3_4_01_modern_progress_stream_is_monotonic_and_ends_with_the_real_re ); } +// --------------------------------------------------------------------------------------------- +// AT-3.4-01 (TL correction): the official SDK sends the dual `Accept` JSON-first. A `tools/call` +// that carries a validated token and offers `text/event-stream` in that same header must still be +// answered on its own stream, wherever the media types are ordered. +// --------------------------------------------------------------------------------------------- +#[tokio::test] +async fn at_3_4_01_json_first_dual_accept_keeps_progress_for_a_valid_token() { + /// Exactly what the official MCP SDK sends when it can read a stream. + const SDK_ACCEPT: &str = "application/json, text/event-stream"; + let fixture = fixture("lifecycle-json-first", HOLD_MS, 5_000).await; + let session = initialize_session(&fixture.client, &fixture.mcp_url, &fixture.api_key).await; + + for revision in [Revision::Legacy, Revision::Modern] { + let carrier = match revision { + Revision::Legacy => Some(session.as_str()), + Revision::Modern => None, + }; + let token = json!("tok-json-first"); + let reply = fixture + .send( + SDK_ACCEPT, + &fixture.api_key, + revision, + 550, + fixture.call_params(Some(token.clone()), revision), + carrier, + Some("req-json-first"), + ) + .await; + reply.assert_stream(); + + let progress = reply.progress_frames(); + assert!( + !progress.is_empty(), + "{revision:?}: a valid token with an acceptable stream must produce progress, got {}", + reply.raw + ); + for frame in &progress { + assert_eq!(frame["params"]["progressToken"], token, "{frame}"); + assert!( + frame["params"].get("total").is_none(), + "this server knows no total: {frame}" + ); + } + let values = progress_values(&progress); + assert!( + values.windows(2).all(|pair| pair[0] < pair[1]), + "{revision:?}: progress must be strictly monotonic, got {values:?}" + ); + assert_eq!(values, vec![1, 2, 3], "{revision:?}: got {values:?}"); + + let terminal = reply.terminal(); + assert_eq!(terminal["id"], json!(550), "{revision:?}"); + assert_eq!(terminal["result"]["isError"], json!(false), "{revision:?}"); + assert_eq!( + terminal["result"]["structuredContent"], + json!({ "id": "lead_123" }), + "{revision:?}" + ); + } + + // The correction is scoped to a call that can actually carry progress: the same JSON-first + // header without a token, and with an unusable token, keeps the negotiated single JSON body. + for token in [None, Some(json!("x".repeat(4096)))] { + let reply = fixture + .send( + SDK_ACCEPT, + &fixture.api_key, + Revision::Legacy, + 551, + fixture.call_params(token.clone(), Revision::Legacy), + Some(&session), + None, + ) + .await; + assert_eq!(reply.status, reqwest::StatusCode::OK); + assert!( + reply.content_type.starts_with("application/json"), + "token {token:?} must keep the negotiated JSON body, got {:?}: {}", + reply.content_type, + reply.raw + ); + assert!(reply.progress_frames().is_empty(), "{token:?}"); + assert_eq!( + reply.terminal()["result"]["structuredContent"], + json!({ "id": "lead_123" }), + "token {token:?}" + ); + } +} + #[tokio::test] async fn at_3_4_01_no_token_and_no_carrier_keep_the_result_identical() { let fixture = fixture("lifecycle-no-token", HOLD_MS, 5_000).await; diff --git a/crates/crank-community-mcp/src/app/endpoint.rs b/crates/crank-community-mcp/src/app/endpoint.rs index a0b794e..af5fa79 100644 --- a/crates/crank-community-mcp/src/app/endpoint.rs +++ b/crates/crank-community-mcp/src/app/endpoint.rs @@ -17,8 +17,8 @@ use crate::{ rate_limit::{rate_limited_jsonrpc_response, rate_limited_status_response}, request_context::RequestContext, transport::{ - accepts_event_stream, negotiate_post_response_mode, session_id_from_headers, sse_response, - transport_response, validate_get_accept_header, validate_origin, + ResponseMode, accepts_event_stream, negotiate_post_response_mode, session_id_from_headers, + sse_response, transport_response, validate_get_accept_header, validate_origin, validate_session_protocol_version, with_request_id_header, }, }; @@ -256,7 +256,7 @@ async fn mcp_post_response( return status.into_response(); } - let response_mode = match negotiate_post_response_mode(headers) { + let mut response_mode = match negotiate_post_response_mode(headers) { Ok(mode) => mode, Err(status) => return status.into_response(), }; @@ -365,6 +365,19 @@ async fn mcp_post_response( Err(error) => return error.into_response(), }; + // Story 3.4 correction: the official SDK lists the media types JSON-first. For a `tools/call` + // that carries a validated progress token and offered `text/event-stream`, the stream is the only + // carrier that can deliver the progress the client asked for, so the media-type order is not a + // preference for the JSON body here. Every other request — another method, no token, an unusable + // token, a JSON-only `Accept` — keeps the negotiated mode, and no admission check moved. + if matches!(response_mode, ResponseMode::Json) + && method_name(message) == Some("tools/call") + && accepts_event_stream(headers) + && crate::app::lifecycle::token_from_meta(message.pointer("/params/_meta")).is_some() + { + response_mode = ResponseMode::Sse; + } + if matches!(identity.era, RequestEra::Modern) { // ERA_MODERN_ENTER (spec section 7.2): this request entered the modern era-adapter. #[cfg(test)]