From 0de1e94df483d11cc085edb859e18689086c5019 Mon Sep 17 00:00:00 2001 From: bsodfather Date: Thu, 12 Nov 2026 21:53:24 +0000 Subject: [PATCH] MCP: dispatch incoming requests and notifications through SDK envelopes --- .../crank-community-mcp/src/app/dispatch.rs | 27 +- .../src/app/dispatch_observer.rs | 21 ++ .../src/app/legacy_dispatch.rs | 58 +-- .../src/protocol/dispatch_sdk.rs | 151 ++++++++ .../crank-community-mcp/src/protocol/mod.rs | 3 + .../src/rmcp_dispatch_runtime_tests.rs | 330 ++++++++++++++++++ .../src/rmcp_dispatch_test_support.rs | 103 ++++++ docs/development/rmcp-migration-plan.md | 2 + 8 files changed, 662 insertions(+), 33 deletions(-) create mode 100644 crates/crank-community-mcp/src/protocol/dispatch_sdk.rs create mode 100644 crates/crank-community-mcp/src/rmcp_dispatch_runtime_tests.rs create mode 100644 crates/crank-community-mcp/src/rmcp_dispatch_test_support.rs diff --git a/crates/crank-community-mcp/src/app/dispatch.rs b/crates/crank-community-mcp/src/app/dispatch.rs index c45a219..4c747d3 100644 --- a/crates/crank-community-mcp/src/app/dispatch.rs +++ b/crates/crank-community-mcp/src/app/dispatch.rs @@ -12,10 +12,7 @@ use super::rmcp_dispatch::{ }; use crate::{ auth::VerifiedMachineCredential, - jsonrpc::{ - is_notification, jsonrpc_error, jsonrpc_result, method_name, negotiated_protocol_version, - params, request_id, - }, + jsonrpc::{jsonrpc_error, jsonrpc_result, negotiated_protocol_version, params, request_id}, protocol::{ CompletionCommand, CompletionOutcome, ContinuationSupport, DispatchDecision, MethodHandler, PromptGetCommand, PromptsCommand, PromptsListCommand, PromptsOutcome, RequestIdentity, @@ -81,7 +78,20 @@ pub(super) async fn handle_modern_request( // matrix row 18). The envelope, identity and mixed-carrier checks — and authentication — have // already run at this point, so this early return cannot admit a malformed identity or a session // conflict, and the notification is never dispatched. - if is_notification(message) { + let envelope = match crate::protocol::decode_dispatch_envelope(message) { + Ok(Some(envelope)) => envelope, + _ => { + return internal_jsonrpc_error( + message, + "admitted dispatch envelope could not be decoded", + ); + } + }; + let method = envelope.method(); + let notification = envelope.is_notification(); + #[cfg(test)] + super::dispatch_observer::sdk_dispatch_envelope_consumed(); + if notification { return crate::protocol::modern_notification_response(); } @@ -89,15 +99,14 @@ pub(super) async fn handle_modern_request( Ok(declared_method) => declared_method, Err(response) => return *response, }; - if declared_method != method_name(message) { + if declared_method != method { return crate::protocol::modern_header_mismatch_response(message); } // R5/F5: the same registration-backed dispatch as the legacy adapter. The handler is decided by // the owning registration (not by a literal method list inside this adapter), and a method whose // capability is not eligible in this revision is never served here. - let dispatch = - crate::protocol::dispatch_decision(method_name(message).unwrap_or_default(), version); + let dispatch = crate::protocol::dispatch_decision(method.unwrap_or_default(), version); match dispatch { DispatchDecision::Allowed { handler: MethodHandler::Discover, @@ -121,7 +130,7 @@ pub(super) async fn handle_modern_request( request_id(message), crate::protocol::project_modern_result( version, - crate::protocol::ping_result(message, version), + crate::protocol::ping_result(&json!({"method": "ping"}), version), ), ), response_mode, diff --git a/crates/crank-community-mcp/src/app/dispatch_observer.rs b/crates/crank-community-mcp/src/app/dispatch_observer.rs index 9ad4259..8026036 100644 --- a/crates/crank-community-mcp/src/app/dispatch_observer.rs +++ b/crates/crank-community-mcp/src/app/dispatch_observer.rs @@ -75,6 +75,8 @@ pub(crate) struct CounterSet { sdk_jsonrpc_error: AtomicUsize, sdk_ping_request: AtomicUsize, sdk_ping_result: AtomicUsize, + sdk_dispatch_decoded: AtomicUsize, + sdk_dispatch_consumed: AtomicUsize, sdk_initialized_decoded: AtomicUsize, sdk_initialized_consumed: AtomicUsize, sdk_initialize_input: AtomicUsize, @@ -83,6 +85,12 @@ pub(crate) struct CounterSet { } impl CounterSet { + pub(crate) fn sdk_dispatch_decoded(&self) -> usize { + self.sdk_dispatch_decoded.load(Ordering::SeqCst) + } + pub(crate) fn sdk_dispatch_consumed(&self) -> usize { + self.sdk_dispatch_consumed.load(Ordering::SeqCst) + } pub(crate) fn sdk_initialized_decoded(&self) -> usize { self.sdk_initialized_decoded.load(Ordering::SeqCst) } @@ -456,6 +464,19 @@ pub(crate) fn sdk_initialized_notification_consumed( #[path = "../rmcp_initialized_runtime_tests.rs"] mod rmcp_initialized_runtime_tests; +/// Mark after successful SDK envelope decode, independently of routing consumption. +pub(crate) fn sdk_dispatch_envelope_decoded() { + increment(|counters| &counters.sdk_dispatch_decoded); +} + +/// Mark only when decoded method/kind selects the existing registry-backed route. +pub(crate) fn sdk_dispatch_envelope_consumed() { + increment(|counters| &counters.sdk_dispatch_consumed); +} + +#[path = "../rmcp_dispatch_runtime_tests.rs"] +mod rmcp_dispatch_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/app/legacy_dispatch.rs b/crates/crank-community-mcp/src/app/legacy_dispatch.rs index bf57a4e..32f7ac8 100644 --- a/crates/crank-community-mcp/src/app/legacy_dispatch.rs +++ b/crates/crank-community-mcp/src/app/legacy_dispatch.rs @@ -30,10 +30,7 @@ use super::rmcp_dispatch::{ use super::{AgentRoutePath, AppState}; use crate::{ auth::VerifiedMachineCredential, - jsonrpc::{ - LEGACY_PROTOCOL_VERSION, is_notification, is_request, jsonrpc_error, jsonrpc_result, - method_name, params, request_id, - }, + jsonrpc::{LEGACY_PROTOCOL_VERSION, jsonrpc_error, jsonrpc_result, params, request_id}, protocol::{ CompletionCommand, CompletionOutcome, ContinuationSupport, DispatchDecision, EVENT_LEVEL_APPLIED, INVALID_LEVEL, Kind, LoggingOutcome, MethodHandler, PromptGetCommand, @@ -65,10 +62,20 @@ pub(super) async fn handle_legacy_request( // `protocol::registry` and is read through `dispatch_decision`, so a newly registered method // really reaches its handler and removing a descriptor removes the dispatch. let registration_revision = protocol_version.unwrap_or(LEGACY_PROTOCOL_VERSION); - let dispatch = crate::protocol::dispatch_decision( - method_name(message).unwrap_or_default(), - registration_revision, - ); + let envelope = match crate::protocol::decode_dispatch_envelope(message) { + Ok(Some(envelope)) => envelope, + _ => { + return internal_jsonrpc_error( + message, + "admitted dispatch envelope could not be decoded", + ); + } + }; + let method = envelope.method(); + let dispatch = + crate::protocol::dispatch_decision(method.unwrap_or_default(), registration_revision); + #[cfg(test)] + super::dispatch_observer::sdk_dispatch_envelope_consumed(); match dispatch { // G2: the *registered kind* of the matched method, not the envelope shape, decides which // legacy lifecycle action runs. `initialize` is a request and `notifications/initialized` is a @@ -78,11 +85,11 @@ pub(super) async fn handle_legacy_request( DispatchDecision::Allowed { handler: MethodHandler::Lifecycle, kind: Kind::Method, - } if is_request(message) => handle_initialize(state, path, message, response_mode).await, + } if envelope.is_request() => handle_initialize(state, path, message, response_mode).await, DispatchDecision::Allowed { handler: MethodHandler::Lifecycle, kind: Kind::Notification, - } if is_notification(message) => { + } if envelope.is_notification() => { handle_initialized_notification( state, path, @@ -94,7 +101,7 @@ pub(super) async fn handle_legacy_request( DispatchDecision::Allowed { handler: MethodHandler::Ping, .. - } if is_request(message) => { + } if envelope.is_request() => { let session = match require_initialized_session(&state, path, headers, message).await { Ok(session) => session, Err(response) => return response, @@ -104,7 +111,10 @@ pub(super) async fn handle_legacy_request( StatusCode::OK, jsonrpc_result( request_id(message), - crate::protocol::ping_result(message, &session.protocol_version), + crate::protocol::ping_result( + &json!({"method": "ping"}), + &session.protocol_version, + ), ), response_mode, None, @@ -114,7 +124,7 @@ pub(super) async fn handle_legacy_request( DispatchDecision::Allowed { handler: MethodHandler::ToolList, .. - } if is_request(message) => { + } if envelope.is_request() => { let session = match require_initialized_session(&state, path, headers, message).await { Ok(session) => session, Err(response) => return response, @@ -183,7 +193,7 @@ pub(super) async fn handle_legacy_request( DispatchDecision::Allowed { handler: MethodHandler::ToolCall, .. - } if is_request(message) => { + } if envelope.is_request() => { let session = match require_initialized_session(&state, path, headers, message).await { Ok(session) => session, Err(response) => return response, @@ -241,13 +251,13 @@ pub(super) async fn handle_legacy_request( DispatchDecision::Allowed { handler: MethodHandler::Cancelled, kind: Kind::Notification, - } if is_notification(message) => { + } if envelope.is_notification() => { handle_cancelled_notification(&state, path, headers, message, credential).await } DispatchDecision::Allowed { handler: MethodHandler::ResourceList, .. - } if is_request(message) => { + } if envelope.is_request() => { let session = match require_initialized_session(&state, path, headers, message).await { Ok(session) => session, Err(response) => return response, @@ -316,7 +326,7 @@ pub(super) async fn handle_legacy_request( DispatchDecision::Allowed { handler: MethodHandler::ResourceRead, .. - } if is_request(message) => { + } if envelope.is_request() => { let session = match require_initialized_session(&state, path, headers, message).await { Ok(session) => session, Err(response) => return response, @@ -397,7 +407,7 @@ pub(super) async fn handle_legacy_request( DispatchDecision::Allowed { handler: MethodHandler::ResourceTemplateList, .. - } if is_request(message) => { + } if envelope.is_request() => { let session = match require_initialized_session(&state, path, headers, message).await { Ok(session) => session, Err(response) => return response, @@ -469,7 +479,7 @@ pub(super) async fn handle_legacy_request( DispatchDecision::Allowed { handler: MethodHandler::PromptList, .. - } if is_request(message) => { + } if envelope.is_request() => { let session = match require_initialized_session(&state, path, headers, message).await { Ok(session) => session, Err(response) => return response, @@ -534,7 +544,7 @@ pub(super) async fn handle_legacy_request( DispatchDecision::Allowed { handler: MethodHandler::PromptGet, .. - } if is_request(message) => { + } if envelope.is_request() => { let session = match require_initialized_session(&state, path, headers, message).await { Ok(session) => session, Err(response) => return response, @@ -632,7 +642,7 @@ pub(super) async fn handle_legacy_request( DispatchDecision::Allowed { handler: MethodHandler::Completion, .. - } if is_request(message) => { + } if envelope.is_request() => { let session = match require_initialized_session(&state, path, headers, message).await { Ok(session) => session, Err(response) => return response, @@ -711,7 +721,7 @@ pub(super) async fn handle_legacy_request( DispatchDecision::Allowed { handler: MethodHandler::LoggingSetLevel, .. - } if is_request(message) => { + } if envelope.is_request() => { let session = match require_initialized_session(&state, path, headers, message).await { Ok(session) => session, Err(response) => return response, @@ -757,10 +767,10 @@ pub(super) async fn handle_legacy_request( } // A notification whose method the registration does not map to this adapter's handlers is // acknowledged without being dispatched, exactly as before. - _ if is_notification(message) => StatusCode::ACCEPTED.into_response(), + _ if envelope.is_notification() => StatusCode::ACCEPTED.into_response(), // Every remaining decision (unregistered, wrong era, or a handler this adapter does not // serve) is a method-level rejection: no handler, no service entry, no outbound call. - _ => match method_name(message) { + _ => match method { Some(method) => transport_response( StatusCode::OK, jsonrpc_error( diff --git a/crates/crank-community-mcp/src/protocol/dispatch_sdk.rs b/crates/crank-community-mcp/src/protocol/dispatch_sdk.rs new file mode 100644 index 0000000..0dac574 --- /dev/null +++ b/crates/crank-community-mcp/src/protocol/dispatch_sdk.rs @@ -0,0 +1,151 @@ +//! Generic SDK envelopes for routing after the authoritative Crank admission guard. + +use rmcp::model::{JsonRpcNotification, JsonRpcRequest}; +use serde_json::{Value, json}; + +#[derive(Debug)] +pub(crate) enum DispatchEnvelope { + Request(JsonRpcRequest), + Notification(JsonRpcNotification), +} + +impl DispatchEnvelope { + pub(crate) fn method(&self) -> Option<&str> { + let payload = match self { + Self::Request(envelope) => &envelope.request, + Self::Notification(envelope) => &envelope.notification, + }; + payload.get("method").and_then(Value::as_str) + } + + pub(crate) fn is_request(&self) -> bool { + matches!(self, Self::Request(_)) + } + + pub(crate) fn is_notification(&self) -> bool { + matches!(self, Self::Notification(_)) + } +} + +/// Call only after `validate_jsonrpc_envelope`; responses keep their existing non-SDK path. +/// Params and extensions stay in the raw message, not in this routing-only projection. +pub(crate) fn decode_dispatch_envelope( + message: &Value, +) -> Result, serde_json::Error> { + let Some(method) = message.get("method") else { + return Ok(None); + }; + let mut projection = json!({"jsonrpc": message.get("jsonrpc"), "method": method}); + let envelope = if let Some(id) = message.get("id") { + // SDK ids are string/i64; the surrogate must never leave this routing-only envelope. + projection["id"] = if id.is_number() && id.as_i64().is_none() { + json!(0) + } else { + id.clone() + }; + DispatchEnvelope::Request(serde_json::from_value(projection)?) + } else { + DispatchEnvelope::Notification(serde_json::from_value(projection)?) + }; + #[cfg(test)] + crate::app::dispatch_observer::sdk_dispatch_envelope_decoded(); + Ok(Some(envelope)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn arbitrary_method_ignores_params_and_mixed_extra_fields() { + for params in [ + None, + Some(json!({})), + Some(json!({ + "_meta": {"clientInfo": false}, "extension": [null, 3] + })), + ] { + let mut message = json!({ + "jsonrpc": "2.0", "id": "request", "method": "private/arbitrary", + "result": false, "error": [1], "extension": {"anything": true} + }); + if let Some(params) = params { + message["params"] = params; + } + let original = message.clone(); + let envelope = decode_dispatch_envelope(&message) + .expect("admitted request decodes") + .expect("request envelope"); + assert_eq!(envelope.method(), Some("private/arbitrary")); + assert!(envelope.is_request()); + assert!(!envelope.is_notification()); + let DispatchEnvelope::Request(request) = envelope else { + panic!("request must retain its SDK variant"); + }; + assert_eq!(request.request, json!({"method": "private/arbitrary"})); + assert_eq!(message, original); + } + } + + #[test] + fn request_ids_preserve_raw_value_and_only_surrogate_sdk_incompatible_numbers() { + for (id, sdk_id) in [ + (json!("string-id"), json!("string-id")), + (json!(i64::MIN), json!(i64::MIN)), + (json!(i64::MAX), json!(i64::MAX)), + (json!(u64::MAX), json!(0)), + (json!(1.25), json!(0)), + (json!(1.0), json!(0)), + ] { + let message = json!({"jsonrpc": "2.0", "id": id, "method": "arbitrary"}); + let original = message.clone(); + let DispatchEnvelope::Request(request) = decode_dispatch_envelope(&message) + .expect("admitted id decodes") + .expect("request envelope") + else { + panic!("id-bearing method must be a request"); + }; + assert_eq!(serde_json::to_value(request.id).expect("SDK id"), sdk_id); + assert_eq!(message, original); + assert_eq!(message.to_string(), original.to_string()); + } + } + + #[test] + fn notification_kind_is_independent_of_method_and_ignored_fields() { + let message = json!({ + "jsonrpc": "2.0", "method": "private/arbitrary", "params": {}, + "result": {}, "error": {}, "extension": 42 + }); + let original = message.clone(); + let envelope = decode_dispatch_envelope(&message) + .expect("notification decodes") + .expect("notification envelope"); + assert_eq!(envelope.method(), Some("private/arbitrary")); + assert!(!envelope.is_request()); + assert!(envelope.is_notification()); + let DispatchEnvelope::Notification(notification) = envelope else { + panic!("notification must retain its SDK variant"); + }; + assert_eq!( + notification.notification, + json!({"method": "private/arbitrary"}) + ); + assert_eq!(message, original); + } + + #[test] + fn incoming_success_and_error_responses_are_not_migrated() { + for message in [ + json!({"jsonrpc": "2.0", "id": 1, "result": {}}), + json!({"jsonrpc": "2.0", "id": "id", "error": {"code": -1, "message": "error"}}), + json!({"jsonrpc": "2.0", "error": {"code": -1, "message": "error"}}), + ] { + assert!( + decode_dispatch_envelope(&message) + .expect("response bypass") + .is_none() + ); + } + } +} diff --git a/crates/crank-community-mcp/src/protocol/mod.rs b/crates/crank-community-mcp/src/protocol/mod.rs index 3dca0f5..2550c16 100644 --- a/crates/crank-community-mcp/src/protocol/mod.rs +++ b/crates/crank-community-mcp/src/protocol/mod.rs @@ -26,6 +26,7 @@ use crate::transport::{json_response, protocol_version_from_headers, singleton_h mod command; mod completion; +mod dispatch_sdk; mod lifecycle_sdk; mod logging; mod prompts; @@ -33,6 +34,8 @@ mod registry; mod resources; mod signals; +pub(crate) use dispatch_sdk::decode_dispatch_envelope; + pub(crate) use command::{ ContinuationSupport, ServiceContext, ToolCallCommand, ToolCallOutcome, ToolsCommand, ToolsListCommand, ToolsOutcome, handle_tools_command, diff --git a/crates/crank-community-mcp/src/rmcp_dispatch_runtime_tests.rs b/crates/crank-community-mcp/src/rmcp_dispatch_runtime_tests.rs new file mode 100644 index 0000000..d140ec5 --- /dev/null +++ b/crates/crank-community-mcp/src/rmcp_dispatch_runtime_tests.rs @@ -0,0 +1,330 @@ +//! #107 generic dispatch: existing wire GREEN precedes independent SDK RED assertions. +use super::rmcp_progress_cancel_runtime_tests::fixtures::Endpoint; +use super::{CounterSet, Snapshot, observe, support::*}; +use serde_json::{Value, json}; +use std::sync::{Arc, atomic::Ordering}; +#[path = "rmcp_dispatch_test_support.rs"] +mod fixtures; +use fixtures::*; + +async fn success_control() -> Vec<[usize; 2]> { + let h = endpoint().await; + let mut deltas = vec![]; + for revision in [LEGACY_REVISION, MODERN_REVISION] { + let session = prepared(&h, revision).await; + for accept in ["application/json", "text/event-stream, application/json"] { + for id in [ + json!("dispatch/Ю"), + json!(18446744073709551615u64), + json!(3.25), + ] { + for method in ["tools/list", "ping"] { + let mut message = payload(revision, method, id.clone()); + // Legacy params remain absent; modern identity metadata remains mandatory. + message["extension"] = json!({"future":[null,true]}); + message["result"] = json!({"ignored":true}); + message["error"] = json!({"ignored":"not an error envelope"}); + let before = sdk(&h.counters); + let ops = h.sessions.snapshot(); + let entries = h.counters.snapshot(); + let response = request(&h, revision, session.as_deref(), accept, message) + .send() + .await + .unwrap(); + assert_eq!(response.status(), 200); + assert_eq!(response.headers()["MCP-Protocol-Version"], revision); + assert!(response.headers().get("MCP-Session-Id").is_none()); + let wire = body(response, accept.starts_with("text/event-stream")).await; + assert_eq!(wire["jsonrpc"], "2.0"); + assert_eq!(wire["id"], id, "lossless response correlation"); + assert!(wire.get("error").is_none(), "{wire}"); + if method == "tools/list" { + assert_eq!(wire["result"]["tools"][0]["name"], TOOL_NAME); + assert_eq!(wire["result"]["tools"].as_array().unwrap().len(), 1); + } else { + let result = if revision == MODERN_REVISION { + json!({"protocolVersion":revision,"resultType":"complete"}) + } else { + json!({"protocolVersion":revision}) + }; + assert_eq!(wire, json!({"jsonrpc":"2.0","id":id,"result":result})); + } + if revision == MODERN_REVISION { + assert_eq!(wire["result"]["resultType"], "complete"); + assert_eq!(h.sessions.snapshot(), ops, "no modern session access"); + } + assert_deltas( + method, + entries, + h.counters.snapshot(), + Snapshot::new( + 1, + usize::from(revision == MODERN_REVISION), + usize::from(revision == LEGACY_REVISION), + usize::from(method == "tools/list"), + ), + ); + assert_eq!(h.started.load(Ordering::SeqCst), 0); + let after = sdk(&h.counters); + deltas.push([after[0] - before[0], after[1] - before[1]]); + } + } + } + } + eprintln!( + "existing GREEN 24 HTTP requests after legacy handshake / modern discovery; SDK deltas={deltas:?}" + ); + deltas +} + +#[tokio::test] +async fn wire_positive_control_json_sse_ids_tolerance_and_routes() { + success_control().await; +} + +#[tokio::test] +async fn sdk_envelope_decoded_on_successful_http() { + let deltas = success_control().await; + assert_eq!( + deltas.iter().map(|d| d[0]).collect::>(), + vec![1; 24], + "successful HTTP must decode a real SDK request envelope" + ); +} + +#[tokio::test] +async fn sdk_envelope_consumed_for_registry_routing_on_successful_http() { + let deltas = success_control().await; + assert_eq!( + deltas.iter().map(|d| d[1]).collect::>(), + vec![1; 24], + "decoded SDK method/kind must drive registry routing, not decode-and-discard" + ); +} + +async fn notification_control() -> Vec<[usize; 2]> { + let h = endpoint().await; + let response = request( + &h, + LEGACY_REVISION, + None, + "application/json", + legacy_initialize(1), + ) + .send() + .await + .unwrap(); + assert_eq!(response.status(), 200); + let session = response.headers()["MCP-Session-Id"] + .to_str() + .unwrap() + .to_owned(); + let _ = body(response, false).await; + for method in ["notifications/initialized", "unknown/notification"] { + let mut wrong_kind = json!({"jsonrpc":"2.0","id":"wrong-kind","method":method}); + let ops = h.sessions.snapshot(); + let response = request( + &h, + LEGACY_REVISION, + Some(&session), + "application/json", + wrong_kind.clone(), + ) + .send() + .await + .unwrap(); + assert_eq!(response.status(), 200); + assert_eq!(body(response, false).await["error"]["code"], -32601); + assert_eq!(h.sessions.snapshot().mark_initialized, ops.mark_initialized); + assert!(!h.sessions.retained(&session).await.unwrap().initialized); + wrong_kind.as_object_mut().unwrap().remove("id"); + if method.starts_with("unknown") { + ack(request( + &h, + LEGACY_REVISION, + Some(&session), + "application/json", + wrong_kind, + ) + .send() + .await + .unwrap()) + .await; + assert!(!h.sessions.retained(&session).await.unwrap().initialized); + } + } + let before = sdk(&h.counters); + ack(request( + &h, + LEGACY_REVISION, + Some(&session), + "application/json", + initialized_notification(), + ) + .send() + .await + .unwrap()) + .await; + assert!(h.sessions.retained(&session).await.unwrap().initialized); + let after = sdk(&h.counters); + let mut deltas = vec![[after[0] - before[0], after[1] - before[1]]]; + let ops = h.sessions.snapshot(); + let entries = h.counters.snapshot(); + for method in [ + "notifications/initialized", + "unknown/notification", + "tools/call", + ] { + let mut message = payload(MODERN_REVISION, method, json!(1)); + message.as_object_mut().unwrap().remove("id"); + let mut req = request(&h, MODERN_REVISION, None, "application/json", message) + .build() + .unwrap(); + req.headers_mut().remove("Mcp-Method"); + req.headers_mut().remove("Mcp-Name"); + let before = sdk(&h.counters); + ack(reqwest::Client::new().execute(req).await.unwrap()).await; + let after = sdk(&h.counters); + deltas.push([after[0] - before[0], after[1] - before[1]]); + } + assert_eq!(h.sessions.snapshot(), ops); + assert_eq!(h.counters.snapshot().tools_service, entries.tools_service); + assert_eq!(h.started.load(Ordering::SeqCst), 0); + eprintln!("existing GREEN notification kind/state/early ACK; SDK deltas={deltas:?}"); + deltas +} + +#[tokio::test] +async fn notification_order_and_legacy_registered_kind_wire_control() { + notification_control().await; +} + +#[tokio::test] +async fn sdk_notification_kind_consumed_on_successful_http() { + assert_eq!( + notification_control().await, + vec![[1, 1]; 4], + "SDK notification variant must drive legacy handshake / modern early ACK" + ); +} + +#[tokio::test] +async fn rejection_controls_never_enter_service_or_outbound() { + let h = endpoint().await; + for revision in [LEGACY_REVISION, MODERN_REVISION] { + let session = prepared(&h, revision).await; + let base = payload(revision, "tools/list", json!("reject")); + let mut malformed = base.clone(); + malformed["jsonrpc"] = json!("1.0"); + let mut bad_params = base.clone(); + bad_params["params"] = json!([]); + let mut bad_meta = base.clone(); + bad_meta["params"] = json!({"_meta":false}); + let unknown = payload(revision, "unknown/request", json!("reject")); + let wrong_era = payload( + revision, + if revision == MODERN_REVISION { + "initialize" + } else { + "server/discover" + }, + json!("reject"), + ); + for (message, status, code) in [ + (malformed, 400, -32600), + (bad_params, 400, -32600), + (bad_meta, 400, -32020), + ( + unknown, + if revision == MODERN_REVISION { + 404 + } else { + 200 + }, + -32601, + ), + ( + wrong_era, + if revision == MODERN_REVISION { + 404 + } else { + 200 + }, + -32601, + ), + ] { + let entries = h.counters.snapshot(); + let ops = h.sessions.snapshot(); + let response = request( + &h, + revision, + session.as_deref(), + "application/json", + message.clone(), + ) + .send() + .await + .unwrap(); + assert_eq!(response.status().as_u16(), status, "{revision} {message}"); + let wire = body(response, false).await; + assert_eq!(wire["error"]["code"], code, "{revision} {message}: {wire}"); + assert!(wire.get("result").is_none()); + assert_eq!(h.counters.snapshot().tools_service, entries.tools_service); + assert_eq!(h.started.load(Ordering::SeqCst), 0); + if revision == MODERN_REVISION { + assert_eq!(h.sessions.snapshot(), ops); + } + } + } + for (header, value) in [("Mcp-Method", "ping"), ("Mcp-Name", "wrong-tool")] { + let ops = h.sessions.snapshot(); + let entries = h.counters.snapshot(); + let message = json!({"jsonrpc":"2.0","id":"headers","method":"tools/call","params":{"name":TOOL_NAME,"arguments":{"email":"dispatch@example.com"},"_meta":modern_meta()}}); + let response = request(&h, MODERN_REVISION, None, "application/json", message) + .header(header, value) + .send() + .await + .unwrap(); + assert_eq!(response.status(), 400); + assert!(body(response, false).await.get("error").is_some()); + assert_eq!(h.sessions.snapshot(), ops); + assert_eq!(h.counters.snapshot().tools_service, entries.tools_service); + assert_eq!(h.started.load(Ordering::SeqCst), 0); + } + let ops = h.sessions.snapshot(); + let response = request( + &h, + "2099-01-01", + None, + "application/json", + payload(LEGACY_REVISION, "tools/list", json!(1)), + ) + .send() + .await + .unwrap(); + assert_eq!(response.status(), 400); + assert!(body(response, false).await.get("error").is_some()); + assert_eq!(h.sessions.snapshot(), ops); + assert_eq!(h.started.load(Ordering::SeqCst), 0); +} + +#[tokio::test] +async fn observer_independent_positive_control() { + let a = Arc::new(CounterSet::default()); + let b = Arc::new(CounterSet::default()); + super::sdk_dispatch_envelope_decoded(); + super::sdk_dispatch_envelope_consumed(); + assert_eq!(sdk(&a), [0, 0]); + tokio::join!( + observe(a.clone(), async { + super::sdk_dispatch_envelope_decoded(); + }), + observe(b.clone(), async { + super::sdk_dispatch_envelope_consumed(); + }) + ); + assert_eq!(sdk(&a), [1, 0]); + assert_eq!(sdk(&b), [0, 1]); + assert_eq!(a.snapshot(), Snapshot::new(0, 0, 0, 0)); + assert_eq!(b.snapshot(), Snapshot::new(0, 0, 0, 0)); +} diff --git a/crates/crank-community-mcp/src/rmcp_dispatch_test_support.rs b/crates/crank-community-mcp/src/rmcp_dispatch_test_support.rs new file mode 100644 index 0000000..636addf --- /dev/null +++ b/crates/crank-community-mcp/src/rmcp_dispatch_test_support.rs @@ -0,0 +1,103 @@ +//! Narrow HTTP helpers; all app/auth/catalog/upstream fixtures remain shared. +use super::*; + +pub(super) async fn endpoint() -> Endpoint { + crank_test_support::postgres_schema_url_for_task("dispatch_owner", "t_e862066c").await; + Endpoint::started().await +} + +pub(super) fn sdk(c: &CounterSet) -> [usize; 2] { + [c.sdk_dispatch_decoded(), c.sdk_dispatch_consumed()] +} + +pub(super) fn payload(revision: &str, method: &str, id: Value) -> Value { + let mut message = json!({"jsonrpc":"2.0","id":id,"method":method}); + if revision == MODERN_REVISION { + message["params"] = json!({"_meta":modern_meta()}); + } + message +} + +pub(super) fn request( + h: &Endpoint, + revision: &str, + session: Option<&str>, + accept: &str, + message: Value, +) -> reqwest::RequestBuilder { + h.request(revision, session, &h.key, accept, message) + .header("x-request-id", "dispatch-atdd") + .header( + "traceparent", + "00-11111111111111111111111111111111-2222222222222222-01", + ) +} + +pub(super) async fn body(response: reqwest::Response, sse: bool) -> Value { + assert_eq!(response.headers()["x-request-id"], "dispatch-atdd"); + assert_eq!( + response.headers()["x-trace-id"], + "11111111111111111111111111111111" + ); + assert!( + response.headers()["content-type"] + .to_str() + .unwrap() + .starts_with(if sse { + "text/event-stream" + } else { + "application/json" + }) + ); + let raw = tokio::time::timeout(std::time::Duration::from_secs(6), response.text()) + .await + .unwrap() + .unwrap(); + if sse { + let frames: Vec = raw + .lines() + .filter_map(|l| l.strip_prefix("data:")) + .map(|l| serde_json::from_str(l.trim()).unwrap()) + .collect(); + assert_eq!(frames.len(), 1, "one terminal SSE frame: {raw}"); + frames.into_iter().next().unwrap() + } else { + serde_json::from_str(&raw).unwrap() + } +} + +pub(super) async fn ack(response: reqwest::Response) { + assert_eq!(response.status(), 202); + assert!(response.headers().get("content-type").is_none()); + assert!(response.headers().get("MCP-Session-Id").is_none()); + assert!(response.bytes().await.unwrap().is_empty()); +} + +pub(super) async fn prepared(h: &Endpoint, revision: &str) -> Option { + if revision == LEGACY_REVISION { + return h.session(revision).await; + } + let ops = h.sessions.snapshot(); + let response = request( + h, + revision, + None, + "application/json", + payload(revision, "server/discover", json!(1)), + ) + .send() + .await + .unwrap(); + assert_eq!(response.status(), 200); + assert_eq!(response.headers()["MCP-Protocol-Version"], revision); + assert!(response.headers().get("MCP-Session-Id").is_none()); + let wire = body(response, false).await; + assert_eq!( + wire["result"]["supportedVersions"], + json!([MODERN_REVISION, LEGACY_REVISION]) + ); + assert_eq!(wire["result"]["resultType"], "complete"); + assert!(wire.get("error").is_none(), "{wire}"); + assert_eq!(h.sessions.snapshot(), ops); + None +} diff --git a/docs/development/rmcp-migration-plan.md b/docs/development/rmcp-migration-plan.md index ffd4d38..499df1c 100644 --- a/docs/development/rmcp-migration-plan.md +++ b/docs/development/rmcp-migration-plan.md @@ -53,6 +53,8 @@ Ping-срез #107 на базе rc.28/rmcp3.9.0 подключает обе ш Initialized-срез #107 на базе rc.29/rmcp3.9.0 подключает штатный legacy HTTP handshake к `InitializedNotification` и `ClientNotification`: после registry/admission проекция метода декодируется SDK, а matched initialized variant после прежних session/scope guards разрешает существующий durable `mark_initialized`. Игнорируемые params/extensions, 202 с пустым телом, JSON/SSE и modern no-session поведение сохранены; SDK SessionManager не используется. Runtime-тесты отдельно наблюдают decoding и consumption, проверяют PostgreSQL reconnect и отказ store на чтении/записи. Это только lifecycle-срез, не завершение #107. +Envelope-dispatch-срез #107 на базе rc.30/rmcp3.9.0 подключает обе действующие HTTP ветки `app/dispatch.rs` и `app/legacy_dispatch.rs` к общему `protocol/dispatch_sdk.rs`: после прежних admission/auth guards минимальная проекция декодируется в настоящие `JsonRpcRequest`/`JsonRpcNotification`. SDK payload method выбирает прежний `registry::dispatch_decision`, SDK variant определяет request/notification routing вместо повторных raw-JSON predicates. Второй таблицы методов нет; registry остаётся policy gate revisions/capabilities/registered kind. Modern notification ACK по-прежнему предшествует request-only Mcp-Method/Mcp-Name checks и не обращается к sessions/domain. Params и ignored extensions/result/error остаются вне routing projection; SDK-incompatible числовые ID получают только внутренний surrogate, исходные ID/числовая форма остаются в raw message для wire/correlation/cancellation ownership. Для выбранного registry Ping handler typed projection использует canonical ping, сохраняя registered alias semantics. Runtime HTTP ATDD отдельно проверяет SDK decode/consumption и прежний JSON/SSE wire; affected registry/admission, durable initialized/reconnect, progress/cancel и auth guards проверяются без замены storage/transport. Это перенос только generic request/notification envelope routing: domain/generic handler execution, inbound response/error envelopes и их shape validation, session storage/TTL/reconnect, transport и feature qualification остаются вне среза. Полный #107 остаётся open; #108/4.7 и production switch не запускаются. + Проверяемый результат: - Через SDK проходят действующие Tools, Resources, Prompts, completion, уведомления и подписки в применимых revisions, а также progress/cancel и существующая logging policy. -- 2.54.0