From 1b51d441217f6a654cb48c141d4088d5ac9b7505 Mon Sep 17 00:00:00 2001 From: bsodfather Date: Thu, 12 Nov 2026 07:52:03 +0000 Subject: [PATCH] refactor(mcp): serialize success and error envelopes through SDK --- .../src/app/dispatch_observer.rs | 21 ++ crates/crank-community-mcp/src/jsonrpc.rs | 142 ++++++- .../src/rmcp_envelopes_runtime_tests.rs | 348 ++++++++++++++++++ docs/development/rmcp-migration-plan.md | 2 + 4 files changed, 496 insertions(+), 17 deletions(-) create mode 100644 crates/crank-community-mcp/src/rmcp_envelopes_runtime_tests.rs diff --git a/crates/crank-community-mcp/src/app/dispatch_observer.rs b/crates/crank-community-mcp/src/app/dispatch_observer.rs index 2244024..d8cb90c 100644 --- a/crates/crank-community-mcp/src/app/dispatch_observer.rs +++ b/crates/crank-community-mcp/src/app/dispatch_observer.rs @@ -71,9 +71,17 @@ pub(crate) struct CounterSet { sdk_subscriptions_listen: AtomicUsize, sdk_subscriptions_acknowledged: AtomicUsize, sdk_signal_notification: AtomicUsize, + sdk_jsonrpc_response: AtomicUsize, + sdk_jsonrpc_error: AtomicUsize, } impl CounterSet { + pub(crate) fn sdk_jsonrpc_response(&self) -> usize { + self.sdk_jsonrpc_response.load(Ordering::SeqCst) + } + pub(crate) fn sdk_jsonrpc_error(&self) -> usize { + self.sdk_jsonrpc_error.load(Ordering::SeqCst) + } pub(crate) fn sdk_subscriptions_listen(&self) -> usize { self.sdk_subscriptions_listen.load(Ordering::SeqCst) } @@ -356,6 +364,19 @@ pub(crate) fn sdk_signal_notification_serialized() { #[path = "../rmcp_signals_runtime_tests.rs"] mod rmcp_signals_runtime_tests; +/// Mark only immediately after successfully serializing a real SDK JsonRpcResponse. +pub(crate) fn sdk_jsonrpc_response_serialized() { + increment(|counters| &counters.sdk_jsonrpc_response); +} + +/// Mark only immediately after successfully serializing a real SDK JsonRpcError. +pub(crate) fn sdk_jsonrpc_error_serialized() { + increment(|counters| &counters.sdk_jsonrpc_error); +} + +#[path = "../rmcp_envelopes_runtime_tests.rs"] +mod rmcp_envelopes_runtime_tests; + fn increment(counter: impl Fn(&CounterSet) -> &AtomicUsize) { let _ = OBSERVER.try_with(|counters| { counter(counters).fetch_add(1, Ordering::SeqCst); diff --git a/crates/crank-community-mcp/src/jsonrpc.rs b/crates/crank-community-mcp/src/jsonrpc.rs index cdb3798..8681db3 100644 --- a/crates/crank-community-mcp/src/jsonrpc.rs +++ b/crates/crank-community-mcp/src/jsonrpc.rs @@ -1,3 +1,6 @@ +use rmcp::model::{ + ErrorCode, ErrorData, JsonRpcError, JsonRpcResponse, JsonRpcVersion2_0, RequestId, +}; use serde_json::{Value, json}; /// The two approved MCP revisions (`docs/`-approved window of 2026-10-11). @@ -60,28 +63,50 @@ pub fn is_response(message: &Value) -> bool { && (message.get("result").is_some() || message.get("error").is_some()) } +fn projected_sdk_id(id: &Value) -> RequestId { + match id { + Value::String(value) => RequestId::String(value.as_str().into()), + Value::Number(value) => RequestId::Number(value.as_i64().unwrap_or(0)), + _ => RequestId::Number(0), + } +} + pub fn jsonrpc_result(id: Value, result: Value) -> Value { - json!({ - "jsonrpc": "2.0", - "id": id, - "result": result - }) + let sdk = JsonRpcResponse:: { + jsonrpc: JsonRpcVersion2_0, + id: projected_sdk_id(&id), + result, + }; + let mut wire = serde_json::to_value(sdk).expect("SDK response contains only JSON values"); + #[cfg(test)] + crate::app::dispatch_observer::sdk_jsonrpc_response_serialized(); + // SDK RequestId cannot preserve the full Value domain or floating-point form. + wire["id"] = id; + wire } pub fn jsonrpc_error(id: Value, code: i64, message: impl Into) -> Value { - let mut error = json!({ - "code": code, - "message": message.into() - }); let (request_id, trace_id) = crank_observability::current_request_correlation(); - if request_id.is_some() && trace_id.is_some() { - error["data"] = correlated_error_data(json!({})); - } - json!({ - "jsonrpc": "2.0", - "id": id, - "error": error - }) + let data = if request_id.is_some() && trace_id.is_some() { + Some(correlated_error_data(json!({}))) + } else { + None + }; + let sdk = JsonRpcError::new( + Some(projected_sdk_id(&id)), + ErrorData::new( + ErrorCode(i32::try_from(code).unwrap_or(0)), + message.into(), + data, + ), + ); + let mut wire = serde_json::to_value(sdk).expect("SDK error contains only JSON values"); + #[cfg(test)] + crate::app::dispatch_observer::sdk_jsonrpc_error_serialized(); + // Restore the helper's wider id/code contract before exposing the SDK envelope. + wire["id"] = id; + wire["error"]["code"] = Value::from(code); + wire } pub fn correlated_error_data(mut data: Value) -> Value { @@ -104,3 +129,86 @@ pub fn negotiated_protocol_version(requested: &str) -> Option<&'static str> { .copied() .find(|version| *version == requested) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn jsonrpc_preserves_helper_values_and_numeric_forms() { + let values = [ + json!(""), + json!("Юникод"), + json!(i64::MIN), + json!(i64::MAX), + json!(9007199254740993_u64), + json!(u64::MAX), + json!(1.5), + json!(1.0), + json!(-0.0), + Value::Null, + json!(true), + json!([null, u64::MAX]), + json!({"extension": {"nested": null}}), + ]; + for id in &values { + for result in &values { + let actual = jsonrpc_result(id.clone(), result.clone()); + let expected = json!({"jsonrpc": "2.0", "id": id, "result": result}); + assert_eq!(actual, expected); + assert_eq!(actual.to_string(), expected.to_string()); + } + for code in [ + i64::MIN, + i64::from(i32::MIN) - 1, + i64::from(i32::MIN), + -32602, + 0, + i64::from(i32::MAX), + i64::from(i32::MAX) + 1, + i64::MAX, + ] { + for message in ["", "Ошибка Ю"] { + let actual = jsonrpc_error(id.clone(), code, message); + let expected = json!({"jsonrpc": "2.0", "id": id, + "error": {"code": code, "message": message}}); + assert_eq!(actual, expected); + assert_eq!(actual.to_string(), expected.to_string()); + } + } + } + } + + #[tokio::test] + async fn jsonrpc_error_requires_complete_valid_correlation() { + use crank_observability::{current_request_correlation, with_request_correlation}; + let request_id = "request-123"; + let trace_id = "1234567890abcdef1234567890abcdef"; + for (request, trace) in [("", ""), (request_id, ""), ("", trace_id)] { + with_request_correlation(request.into(), trace.into(), async { + assert_eq!(current_request_correlation(), (None, None)); + assert_eq!( + jsonrpc_error(Value::Null, -32602, "error"), + json!({"jsonrpc": "2.0", "id": null, + "error": {"code": -32602, "message": "error"}}) + ); + }) + .await; + } + with_request_correlation(request_id.into(), trace_id.into(), async { + assert_eq!( + jsonrpc_error(Value::Null, i64::MAX, "Ошибка"), + json!({"jsonrpc": "2.0", "id": null, "error": { + "code": i64::MAX, "message": "Ошибка", + "data": {"request_id": request_id, "trace_id": trace_id}}}) + ); + assert_eq!( + correlated_error_data(json!({"extension": [null, u64::MAX]})), + json!({"extension": [null, u64::MAX], + "request_id": request_id, "trace_id": trace_id}) + ); + }) + .await; + assert_eq!(current_request_correlation(), (None, None)); + } +} diff --git a/crates/crank-community-mcp/src/rmcp_envelopes_runtime_tests.rs b/crates/crank-community-mcp/src/rmcp_envelopes_runtime_tests.rs new file mode 100644 index 0000000..17c7df8 --- /dev/null +++ b/crates/crank-community-mcp/src/rmcp_envelopes_runtime_tests.rs @@ -0,0 +1,348 @@ +//! #107 envelope migration: independent real HTTP wire and SDK participation controls. +use super::{CounterSet, observe, support::*}; +use axum::{body::Body, response::Response}; +use futures_util::{StreamExt, stream}; +use serde_json::{Value, json}; +use std::{sync::Arc, time::Duration}; + +// Reuse the existing real build_app, published catalog, auth and loopback execution fixture. +#[path = "rmcp_progress_cancel_http_support.rs"] +#[allow(dead_code)] +mod fixtures; +use fixtures::Endpoint; + +fn observe_body(response: Response, counters: Arc) -> Response { + let (parts, body) = response.into_parts(); + let body = stream::unfold( + (body.into_data_stream(), counters), + |(mut body, counters)| async move { + observe(counters.clone(), body.next()) + .await + .map(|chunk| (chunk, (body, counters))) + }, + ); + Response::from_parts(parts, Body::from_stream(body)) +} + +fn counts(c: &CounterSet) -> [usize; 2] { + [c.sdk_jsonrpc_response(), c.sdk_jsonrpc_error()] +} + +async fn wire( + response: reqwest::Response, + revision: &str, + id: &Value, + sse: bool, + session: Option<&str>, +) -> Value { + assert_eq!( + response.status(), + 200, + "envelope id={id}, SSE={sse}, revision={revision}" + ); + assert_eq!(response.headers()["MCP-Protocol-Version"], revision); + assert_eq!( + response + .headers() + .get("MCP-Session-Id") + .map(|v| v.to_str().unwrap()), + if sse { session } else { None } + ); + let request_id = response.headers()["x-request-id"] + .to_str() + .unwrap() + .to_owned(); + let trace_id = response.headers()["x-trace-id"] + .to_str() + .unwrap() + .to_owned(); + let content_type = response.headers()["content-type"].to_str().unwrap(); + assert!(content_type.starts_with(if sse { + "text/event-stream" + } else { + "application/json" + })); + let raw = tokio::time::timeout(Duration::from_secs(6), response.text()) + .await + .unwrap() + .unwrap(); + let body: Value = if sse { + let frames: Vec = raw + .lines() + .filter_map(|line| line.strip_prefix("data:")) + .map(|data| serde_json::from_str(data.trim()).unwrap()) + .collect(); + let terminals: Vec<_> = frames.iter().filter(|f| f.get("id").is_some()).collect(); + assert_eq!(terminals.len(), 1, "one terminal envelope: {raw}"); + assert_eq!(frames.last(), Some(terminals[0]), "terminal must be last"); + for frame in &frames[..frames.len() - 1] { + assert_eq!(frame["method"], "notifications/progress"); + assert_eq!(frame["params"]["progressToken"], "envelope-stream"); + } + terminals[0].clone() + } else { + serde_json::from_str(&raw).unwrap() + }; + assert_eq!(body["jsonrpc"], "2.0"); + assert_eq!(body["id"], *id); + assert_eq!( + body["id"].to_string(), + id.to_string(), + "preserve numeric form" + ); + assert_eq!( + body.as_object().unwrap().len(), + 3, + "no envelope extensions: {body}" + ); + assert!(body.get("method").is_none()); + if let Some(error) = body.get("error") { + assert!( + body.get("result").is_none(), + "protocol error, not tool isError" + ); + assert_eq!(error["code"], -32602); + if sse { + // Existing stream polling has no request correlation scope; preserve omission. + assert!( + error.get("data").is_none(), + "existing SSE omission: {error}" + ); + assert_eq!(error.as_object().unwrap().len(), 2); + } else { + assert_eq!( + error["data"], + json!({"request_id":request_id,"trace_id":trace_id}) + ); + assert_eq!(error.as_object().unwrap().len(), 3); + } + } else { + assert!(body.get("result").is_some()); + } + body +} + +async fn control(revision: &str) -> Vec<[usize; 2]> { + // Own the process-wide disposable DB before the reused fixture's older ownership hint. + crank_test_support::postgres_schema_url_for_task("envelopes_owner", "t_b27f5c9d").await; + let h = Endpoint::started().await; + let session = h.session(revision).await; + let mut deltas = vec![]; + for id in [ + json!("opaque/Ю"), + json!(""), + json!(i64::MIN), + json!(i64::MAX), + json!(9007199254740993_u64), + json!(u64::MAX), + json!(1.5), + json!(1.0), + json!(-0.0), + ] { + for invalid in [false, true] { + let mut params = if invalid { + json!({"cursor":"not-a-cursor"}) + } else { + json!({"cursor":"1"}) + }; + if revision == MODERN_REVISION { + params["_meta"] = modern_meta(); + } + let before = counts(&h.counters); + let response = h + .request( + revision, + session.as_deref(), + &h.key, + "application/json", + json!({"jsonrpc":"2.0","id":id,"method":"tools/list","params":params}), + ) + .send() + .await + .unwrap(); + let body = wire(response, revision, &id, false, session.as_deref()).await; + if invalid { + assert_eq!(body["error"]["message"], "invalid tools/list cursor"); + } else { + let mut expected = json!({"tools":[]}); + if revision == MODERN_REVISION { + expected["resultType"] = json!("complete"); + expected["cacheScope"] = json!("private"); + expected["ttlMs"] = json!(0); + } + assert_eq!( + body["result"], expected, + "empty result and omission of nextCursor" + ); + } + let after = counts(&h.counters); + deltas.push([after[0] - before[0], after[1] - before[1]]); + } + } + // Both revisions support streamed calls with the combined Accept negotiation. + // Missing tool resolves inside the shared Tools command, after the stream opens. + for sse in [false, true] { + for invalid in [false, true] { + let id = if invalid { + json!(u64::MAX) + } else { + json!(-0.0) + }; + let mut params = + json!({"name":TOOL_NAME,"arguments":{"email":"envelopes@example.test"}}); + if revision == MODERN_REVISION { + params["_meta"] = modern_meta(); + } + if invalid { + params["name"] = json!("missing_tool"); + } else { + h.gate.add_permits(1); + } + if sse { + params["_meta"]["progressToken"] = json!("envelope-stream"); + } + let before = counts(&h.counters); + let mut request = h + .request( + revision, + session.as_deref(), + &h.key, + if sse { + "text/event-stream, application/json" + } else { + "application/json" + }, + json!({"jsonrpc":"2.0","id":id,"method":"tools/call","params":params}), + ) + .build() + .unwrap(); + if revision == MODERN_REVISION { + request.headers_mut().insert( + "Mcp-Name", + if invalid { "missing_tool" } else { TOOL_NAME } + .parse() + .unwrap(), + ); + } + let response = reqwest::Client::new().execute(request).await.unwrap(); + let body = wire(response, revision, &id, sse, session.as_deref()).await; + if invalid { + assert_eq!(body["error"]["message"], "tool missing_tool was not found"); + } else { + assert_eq!( + body["result"].as_object().unwrap().len(), + if revision == MODERN_REVISION { 4 } else { 3 } + ); + assert_eq!(body["result"]["isError"], false); + assert_eq!( + body["result"]["structuredContent"], + json!({"id":"lead_progress"}) + ); + assert_eq!( + body["result"]["content"], + json!([{"type":"text","text":serde_json::to_string_pretty(&json!({"id":"lead_progress"})).unwrap()}]) + ); + if revision == MODERN_REVISION { + assert_eq!(body["result"]["resultType"], "complete"); + } else { + assert!(body["result"].get("resultType").is_none()); + } + } + let after = counts(&h.counters); + deltas.push([after[0] - before[0], after[1] - before[1]]); + } + } + eprintln!( + "existing GREEN envelopes wire {revision}: exact id forms, JSON success/protocol error, terminal SSE success/protocol error; SDK deltas={deltas:?}" + ); + deltas +} + +#[tokio::test] +async fn rmcp_envelopes_wire_legacy() { + control(LEGACY_REVISION).await; +} +#[tokio::test] +async fn rmcp_envelopes_wire_modern() { + control(MODERN_REVISION).await; +} +#[tokio::test] +async fn rmcp_envelopes_sdk_legacy() { + let actual = control(LEGACY_REVISION).await; + let expected: Vec<_> = (0..actual.len()) + .map(|i| if i % 2 == 0 { [1, 0] } else { [0, 1] }) + .collect(); + assert_eq!( + actual, expected, + "real SDK envelope serialization after complete HTTP body" + ); +} +#[tokio::test] +async fn rmcp_envelopes_sdk_modern() { + let actual = control(MODERN_REVISION).await; + let expected: Vec<_> = (0..actual.len()) + .map(|i| if i % 2 == 0 { [1, 0] } else { [0, 1] }) + .collect(); + assert_eq!( + actual, expected, + "real SDK envelope serialization after complete HTTP body" + ); +} + +#[tokio::test] +async fn rmcp_envelopes_observer_positive_control() { + let c = Arc::new(CounterSet::default()); + observe(c.clone(), async { + super::sdk_jsonrpc_response_serialized(); + super::sdk_jsonrpc_error_serialized(); + }) + .await; + assert_eq!(counts(&c), [1, 1]); + super::sdk_jsonrpc_response_serialized(); + super::sdk_jsonrpc_error_serialized(); + assert_eq!(counts(&c), [1, 1], "out-of-scope markers are no-ops"); +} + +#[test] +fn rmcp_envelopes_helper_lossless_control() { + use crate::jsonrpc::{jsonrpc_error, jsonrpc_result}; + let values = [ + json!(null), + json!(""), + json!("Ю"), + json!(i64::MIN), + json!(i64::MAX), + json!(9007199254740993_u64), + json!(u64::MAX), + json!(1.5), + json!(1.0), + json!(-0.0), + json!([null, {"nested":u64::MAX}]), + json!({"x":null}), + ]; + for id in &values { + for result in &values { + let actual = jsonrpc_result(id.clone(), result.clone()); + let expected = json!({"jsonrpc":"2.0","id":id,"result":result}); + assert_eq!(actual, expected); + assert_eq!(actual.to_string(), expected.to_string()); + } + for code in [ + i64::MIN, + i32::MIN as i64 - 1, + i32::MIN as i64, + -32602, + i32::MAX as i64, + i32::MAX as i64 + 1, + i64::MAX, + ] { + for message in ["", "Ошибка Ю"] { + let actual = jsonrpc_error(id.clone(), code, message); + let expected = + json!({"jsonrpc":"2.0","id":id,"error":{"code":code,"message":message}}); + assert_eq!(actual, expected, "data absent outside correlation scope"); + assert_eq!(actual.to_string(), expected.to_string()); + } + } + } +} diff --git a/docs/development/rmcp-migration-plan.md b/docs/development/rmcp-migration-plan.md index 0fffd17..edfe756 100644 --- a/docs/development/rmcp-migration-plan.md +++ b/docs/development/rmcp-migration-plan.md @@ -45,6 +45,8 @@ Progress/cancel-срез #107 на базе rc.23/rmcp3.9.0 подключает Catalog-change signals/subscriptions-срез #107 на базе rc.24/rmcp3.9.0 использует прежний `protocol/signals.rs` watcher: штатный modern `subscriptions/listen` декодирует notifications через `SubscriptionsListenRequestParams`/`SubscriptionFilter`, а acknowledgment и три list-change notification сериализуются настоящими SDK notification types в `protocol/signals_sdk.rs`. Тонкая входная projection сохраняет прежний запрет explicit null известных filter fields и игнорирование extensions; `_meta` по-прежнему проверяется только HTTP admission до decoder. SDK `NotificationMetaObject` хранит исходный JSON subscriptionId без сужения через RequestId; legacy frames остаются без params, modern ack первым сообщает только true accepted subset. URI-content subscriptions остаются unsupported, bounds32/2048 и64-byte id bound сохранены. Ближайший потребитель уже подключён: действующий `build_app` modern listen SSE и legacy GET SSE после committed catalog changes. HTTP ATDD независимо проверяет SDK execution и wire обеих revisions; прежние signals integration сохраняют Resource/Prompt/Tool delivery, scope, coalescing/recovery. Handwritten filter field DTO и frame builders заменены; fingerprint, watcher timing/queue/drop, auth/session/ownership/TTL/capabilities и transport не меняются. Полный #107, external-client/feature qualification и production deployment этим срезом не завершены. +Envelopes-срез #107 на базе rc.25/rmcp3.9.0 заменяет handwritten `jsonrpc_result`/`jsonrpc_error` в `jsonrpc.rs` сериализацией настоящих `JsonRpcResponse` и `JsonRpcError`/`ErrorData`. Уже подключённые consumers — общий `build_app` HTTP JSON и lifecycle SSE terminal обеих revisions; новые dispatch/transport пути не добавляются. Локальная projection+restore сразу возвращает исходные JSON id (включая null, u64 и точную floating-point форму) и i64 error code, которые SDK-типы не представляют полностью; произвольный result и omission error.data сохраняются. Прежний guard correlation не меняется: JSON protocol errors содержат correlation data, lifecycle SSE terminal errors по-прежнему её опускают. Runtime wire controls и отдельный SDK oracle проверяют success/protocol error, а affected regressions — admission, revoked credentials, tool isError и cancellation. Входная валидация, safe response id, auth, статусы/headers, очереди/сессии и transport остаются прежними; это не завершение #107, feature qualification или production deployment. + Проверяемый результат: - Через SDK проходят действующие Tools, Resources, Prompts, completion, уведомления и подписки в применимых revisions, а также progress/cancel и существующая logging policy. -- 2.54.0