fix(epic3): принимать поток progress при JSON-first Accept официального SDK (Story 3.4, FR-14)
CI / UI Checks (pull_request) Successful in 10s
CI / Rust Checks (pull_request) Successful in 9m12s
CI / Rust Feature Validation (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Required Checks (pull_request) Successful in 1s
CI / Deploy (pull_request) Skipped
Community Release / release (push) Successful in 24m39s

Официальный 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-теле.
This commit is contained in:
bsodfather committed 2026-10-26 16:03:48 +00:00
1 parent f613250fd3
commit 2499016dc7
2 files changed
+107 -3

No files matched your search

@@ -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;
+16 -3
View File
@@ -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)]