From 42e7728b3a2a1b6b1dcbd558c995f8dc2cbe0e89 Mon Sep 17 00:00:00 2001 From: bsodfather Date: Thu, 12 Nov 2026 05:02:14 +0000 Subject: [PATCH] refactor(mcp): migrate catalog-change signals and listen to rmcp SDK --- .../src/app/dispatch_observer.rs | 31 ++ .../src/protocol/signals.rs | 143 ++++---- .../src/protocol/signals_sdk.rs | 178 ++++++++++ .../src/rmcp_signals_runtime_tests.rs | 312 ++++++++++++++++++ .../src/rmcp_signals_test_support.rs | 280 ++++++++++++++++ docs/development/rmcp-migration-plan.md | 2 + 6 files changed, 883 insertions(+), 63 deletions(-) create mode 100644 crates/crank-community-mcp/src/protocol/signals_sdk.rs create mode 100644 crates/crank-community-mcp/src/rmcp_signals_runtime_tests.rs create mode 100644 crates/crank-community-mcp/src/rmcp_signals_test_support.rs diff --git a/crates/crank-community-mcp/src/app/dispatch_observer.rs b/crates/crank-community-mcp/src/app/dispatch_observer.rs index 73203ad..2244024 100644 --- a/crates/crank-community-mcp/src/app/dispatch_observer.rs +++ b/crates/crank-community-mcp/src/app/dispatch_observer.rs @@ -68,9 +68,21 @@ pub(crate) struct CounterSet { sdk_logging_notification: AtomicUsize, sdk_progress_notification: AtomicUsize, sdk_cancelled_params: AtomicUsize, + sdk_subscriptions_listen: AtomicUsize, + sdk_subscriptions_acknowledged: AtomicUsize, + sdk_signal_notification: AtomicUsize, } impl CounterSet { + pub(crate) fn sdk_subscriptions_listen(&self) -> usize { + self.sdk_subscriptions_listen.load(Ordering::SeqCst) + } + pub(crate) fn sdk_subscriptions_acknowledged(&self) -> usize { + self.sdk_subscriptions_acknowledged.load(Ordering::SeqCst) + } + pub(crate) fn sdk_signal_notification(&self) -> usize { + self.sdk_signal_notification.load(Ordering::SeqCst) + } pub(crate) fn sdk_progress_notification(&self) -> usize { self.sdk_progress_notification.load(Ordering::SeqCst) } @@ -325,6 +337,25 @@ pub(crate) fn sdk_cancelled_params_decoded() { #[path = "../rmcp_progress_cancel_runtime_tests.rs"] mod rmcp_progress_cancel_runtime_tests; +pub(crate) fn installed_observer() -> Option> { + OBSERVER.try_with(Arc::clone).ok() +} + +pub(crate) fn sdk_subscriptions_listen_decoded() { + increment(|counters| &counters.sdk_subscriptions_listen); +} + +pub(crate) fn sdk_subscriptions_acknowledged_serialized() { + increment(|counters| &counters.sdk_subscriptions_acknowledged); +} + +pub(crate) fn sdk_signal_notification_serialized() { + increment(|counters| &counters.sdk_signal_notification); +} + +#[path = "../rmcp_signals_runtime_tests.rs"] +mod rmcp_signals_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/protocol/signals.rs b/crates/crank-community-mcp/src/protocol/signals.rs index 32b7428..bab64ad 100644 --- a/crates/crank-community-mcp/src/protocol/signals.rs +++ b/crates/crank-community-mcp/src/protocol/signals.rs @@ -42,8 +42,12 @@ use std::{ use axum::response::sse::Event; use crank_registry::PublishedAgentCatalog; use futures_util::stream; -use serde::Deserialize; -use serde_json::{Map, Value, json}; +use rmcp::model::{SubscriptionFilter, SubscriptionsListenRequestParams}; +use serde::{Deserialize, Deserializer, de::Error}; +use serde_json::{Value, json}; + +#[path = "signals_sdk.rs"] +mod sdk; use tokio::sync::mpsc; use tracing::warn; @@ -60,6 +64,7 @@ pub(crate) const PROMPT_LIST_CHANGED: &str = "notifications/prompts/list_changed /// `notifications/tools/list_changed` (both approved revisions, Story 3.5). pub(crate) const TOOL_LIST_CHANGED: &str = "notifications/tools/list_changed"; /// `notifications/subscriptions/acknowledged` (modern revision only). +#[cfg(test)] pub(crate) const SUBSCRIPTIONS_ACKNOWLEDGED: &str = "notifications/subscriptions/acknowledged"; /// Engineering default of the watcher tick. It is not a measured latency SLO: the story only needs @@ -113,32 +118,61 @@ impl Signals { } } -/// The pinned modern `SubscriptionFilter`, as far as this server reads it. -/// -/// Unknown members are ignored and a malformed shape is a deserialization error, so a client cannot -/// reach the watcher with anything but the reviewed field set. -#[derive(Debug, Default, Deserialize)] -#[serde(rename_all = "camelCase")] -pub(crate) struct ListenFilter { - #[serde(default)] - tools_list_changed: bool, - #[serde(default)] - prompts_list_changed: bool, - #[serde(default)] - resources_list_changed: bool, - #[serde(default)] - resource_subscriptions: Vec, +/// Compatibility bounds around the real SDK filter, not a second protocol field model. +#[derive(Debug, Default)] +pub(crate) struct ListenFilter(SubscriptionFilter); + +// SDK optional fields accept null; the existing public filter contract rejects explicit null. +fn validate_filter(value: &Value) -> Result<(), &'static str> { + let object = value.as_object().ok_or(INVALID_LISTEN_FILTER)?; + for key in [ + "toolsListChanged", + "promptsListChanged", + "resourcesListChanged", + "resourceSubscriptions", + ] { + if object.get(key).is_some_and(Value::is_null) { + return Err(INVALID_LISTEN_FILTER); + } + } + Ok(()) } -/// The pinned `SubscriptionsListenRequestParams`: the notification filter is a required member. -/// -/// Only the reviewed member is read; `_meta` and any other member of the request params is not part -/// of this contract. -#[derive(Debug, Deserialize)] +impl<'de> Deserialize<'de> for ListenFilter { + fn deserialize>(deserializer: D) -> Result { + let value = Value::deserialize(deserializer)?; + validate_filter(&value).map_err(D::Error::custom)?; + serde_json::from_value(value) + .map(Self) + .map_err(D::Error::custom) + } +} + +/// Decode only the reviewed notifications projection: HTTP admission already owns `_meta`. +#[derive(Debug)] pub(crate) struct ListenParams { pub(crate) notifications: ListenFilter, } +impl<'de> Deserialize<'de> for ListenParams { + fn deserialize>(deserializer: D) -> Result { + let value = Value::deserialize(deserializer)?; + let notifications = value + .as_object() + .and_then(|object| object.get("notifications")) + .ok_or_else(|| D::Error::custom(INVALID_LISTEN_FILTER))?; + validate_filter(notifications).map_err(D::Error::custom)?; + let params: SubscriptionsListenRequestParams = + serde_json::from_value(json!({"notifications": notifications})) + .map_err(D::Error::custom)?; + #[cfg(test)] + crate::app::dispatch_observer::sdk_subscriptions_listen_decoded(); + Ok(Self { + notifications: ListenFilter(params.notifications), + }) + } +} + /// The bounded input contract of a `subscriptions/listen` filter. pub(crate) enum FilterOutcome { /// The list-change subset this server honours for the stream. @@ -154,37 +188,18 @@ impl ListenFilter { /// acknowledgment reports: it is simply not honoured, and the pinned schema forbids the server /// from sending a type it did not agree to. pub(crate) fn accepted(&self) -> FilterOutcome { - if self.resource_subscriptions.len() > MAX_FILTER_URIS - || self - .resource_subscriptions - .iter() - .any(|uri| uri.len() > MAX_FILTER_URI_BYTES) - { + let uris = self.0.resource_subscriptions.as_deref().unwrap_or_default(); + if uris.len() > MAX_FILTER_URIS || uris.iter().any(|uri| uri.len() > MAX_FILTER_URI_BYTES) { return FilterOutcome::Invalid(INVALID_LISTEN_FILTER); } FilterOutcome::Accepted(Signals { - resources: self.resources_list_changed, - prompts: self.prompts_list_changed, - tools: self.tools_list_changed, + resources: self.0.resources_list_changed == Some(true), + prompts: self.0.prompts_list_changed == Some(true), + tools: self.0.tools_list_changed == Some(true), }) } } -/// The `notifications` object of the acknowledgment: exactly the subset that will be delivered. -fn acknowledged_filter_wire(accepted: Signals) -> Value { - let mut filter = Map::new(); - if accepted.prompts { - filter.insert("promptsListChanged".to_owned(), Value::Bool(true)); - } - if accepted.resources { - filter.insert("resourcesListChanged".to_owned(), Value::Bool(true)); - } - if accepted.tools { - filter.insert("toolsListChanged".to_owned(), Value::Bool(true)); - } - Value::Object(filter) -} - /// The exact bound Resource/Prompt/Tool projection of one published Agent catalog. /// /// The projection is derived from the same committed catalog read that already feeds @@ -268,15 +283,11 @@ impl Wire { if !changed { continue; } - let frame = match self { - Wire::Legacy => json!({ "jsonrpc": "2.0", "method": method }), - Wire::Modern(subscription_id) => json!({ - "jsonrpc": "2.0", - "method": method, - "params": { "_meta": { SUBSCRIPTION_ID_KEY: subscription_id } } - }), + let subscription_id = match self { + Wire::Legacy => None, + Wire::Modern(subscription_id) => Some(subscription_id), }; - frames.push(frame.to_string()); + frames.push(sdk::signal_frame(method, subscription_id)); } frames } @@ -284,15 +295,7 @@ impl Wire { /// The first modern frame: the accepted subset, before any list-change notification of the stream. pub(crate) fn acknowledged_frame(subscription_id: &Value, accepted: Signals) -> String { - json!({ - "jsonrpc": "2.0", - "method": SUBSCRIPTIONS_ACKNOWLEDGED, - "params": { - "_meta": { SUBSCRIPTION_ID_KEY: subscription_id }, - "notifications": acknowledged_filter_wire(accepted), - } - }) - .to_string() + sdk::acknowledged_frame(subscription_id, accepted) } /// The subscription id of a `subscriptions/listen` request, or `None` when its encoding is not a @@ -387,7 +390,21 @@ pub(crate) fn spawn(state: Arc, watch: Watch) -> mpsc::Receiver { + crate::app::dispatch_observer::observe(observer, run(watch, sender, reader)) + .await + } + None => run(watch, sender, reader).await, + } + }); + } receiver } diff --git a/crates/crank-community-mcp/src/protocol/signals_sdk.rs b/crates/crank-community-mcp/src/protocol/signals_sdk.rs new file mode 100644 index 0000000..11847bc --- /dev/null +++ b/crates/crank-community-mcp/src/protocol/signals_sdk.rs @@ -0,0 +1,178 @@ +//! SDK serialization for the stream-local list-change notifications. + +use rmcp::model::{ + JsonRpcNotification, JsonRpcVersion2_0, NotificationMetaObject, PromptListChangedNotification, + ResourceListChangedNotification, SubscriptionFilter, SubscriptionsAcknowledgedNotification, + SubscriptionsAcknowledgedNotificationParams, ToolListChangedNotification, +}; +use serde_json::{Map, Value}; + +use super::{PROMPT_LIST_CHANGED, RESOURCE_LIST_CHANGED, Signals, TOOL_LIST_CHANGED}; + +fn subscription_meta(subscription_id: &Value) -> NotificationMetaObject { + let mut meta = Map::new(); + // Keep the JSON identity: SDK RequestId narrows numbers to i64. + meta.insert( + super::SUBSCRIPTION_ID_KEY.to_owned(), + subscription_id.clone(), + ); + NotificationMetaObject::from(meta) +} + +pub(super) fn signal_frame(method: &str, subscription_id: Option<&Value>) -> String { + let meta = subscription_id.map(subscription_meta); + let frame = match method { + RESOURCE_LIST_CHANGED => { + let mut notification = ResourceListChangedNotification::default(); + if let Some(meta) = meta { + notification.extensions.insert(meta); + } + serde_json::to_string(&JsonRpcNotification { + jsonrpc: JsonRpcVersion2_0, + notification, + }) + } + PROMPT_LIST_CHANGED => { + let mut notification = PromptListChangedNotification::default(); + if let Some(meta) = meta { + notification.extensions.insert(meta); + } + serde_json::to_string(&JsonRpcNotification { + jsonrpc: JsonRpcVersion2_0, + notification, + }) + } + TOOL_LIST_CHANGED => { + let mut notification = ToolListChangedNotification::default(); + if let Some(meta) = meta { + notification.extensions.insert(meta); + } + serde_json::to_string(&JsonRpcNotification { + jsonrpc: JsonRpcVersion2_0, + notification, + }) + } + _ => unreachable!("list-change methods are a closed set"), + } + .expect("SDK list-change notification with JSON metadata is serializable"); + #[cfg(test)] + crate::app::dispatch_observer::sdk_signal_notification_serialized(); + frame +} + +pub(super) fn acknowledged_frame(subscription_id: &Value, accepted: Signals) -> String { + let mut notifications = SubscriptionFilter::new(); + notifications.resources_list_changed = accepted.resources.then_some(true); + notifications.prompts_list_changed = accepted.prompts.then_some(true); + notifications.tools_list_changed = accepted.tools.then_some(true); + let params = SubscriptionsAcknowledgedNotificationParams::new(notifications) + .with_meta(subscription_meta(subscription_id)); + let notification = SubscriptionsAcknowledgedNotification::new(params); + let frame = serde_json::to_string(&JsonRpcNotification { + jsonrpc: JsonRpcVersion2_0, + notification, + }) + .expect("SDK subscription acknowledgment with JSON metadata is serializable"); + #[cfg(test)] + crate::app::dispatch_observer::sdk_subscriptions_acknowledged_serialized(); + frame +} + +#[cfg(test)] +mod tests { + use serde_json::json; + + use super::*; + + const METHODS: [&str; 3] = [ + RESOURCE_LIST_CHANGED, + PROMPT_LIST_CHANGED, + TOOL_LIST_CHANGED, + ]; + + #[test] + fn legacy_signals_omit_params() { + for method in METHODS { + let frame: Value = serde_json::from_str(&signal_frame(method, None)).unwrap(); + assert_eq!(frame, json!({"jsonrpc": "2.0", "method": method})); + } + } + + #[test] + fn modern_signals_and_acknowledgments_preserve_json_identity() { + for encoded in [ + r#""subscription-\"quoted""#, + "-7", + "18446744073709551615", + "1.0", + "0.12345678901234567890123456789", + "1.234567890123456789e+25", + ] { + let id: Value = serde_json::from_str(encoded).unwrap(); + let mut frames = METHODS + .map(|method| (signal_frame(method, Some(&id)), method)) + .to_vec(); + frames.push(( + acknowledged_frame(&id, Signals::default()), + super::super::SUBSCRIPTIONS_ACKNOWLEDGED, + )); + for (encoded_frame, method) in frames { + let frame: Value = serde_json::from_str(&encoded_frame).unwrap(); + assert_eq!(frame["jsonrpc"], "2.0"); + assert_eq!(frame["method"], method); + assert_eq!( + frame["params"]["_meta"][super::super::SUBSCRIPTION_ID_KEY], + id + ); + assert_eq!( + frame["params"]["_meta"][super::super::SUBSCRIPTION_ID_KEY].to_string(), + id.to_string(), + ); + assert_eq!(frame["params"]["_meta"].as_object().unwrap().len(), 1); + assert!(frame.get("id").is_none()); + if method != super::super::SUBSCRIPTIONS_ACKNOWLEDGED { + assert_eq!(frame["params"].as_object().unwrap().len(), 1); + } + } + } + } + + #[test] + fn acknowledgment_reports_only_accepted_true_flags_and_never_uris() { + for resources in [false, true] { + for prompts in [false, true] { + for tools in [false, true] { + let accepted = Signals { + resources, + prompts, + tools, + }; + let frame: Value = + serde_json::from_str(&acknowledged_frame(&json!("listen"), accepted)) + .unwrap(); + let mut expected = Map::new(); + for (enabled, name) in [ + (resources, "resourcesListChanged"), + (prompts, "promptsListChanged"), + (tools, "toolsListChanged"), + ] { + if enabled { + expected.insert(name.to_owned(), Value::Bool(true)); + } + } + assert_eq!( + frame, + json!({ + "jsonrpc": "2.0", + "method": super::super::SUBSCRIPTIONS_ACKNOWLEDGED, + "params": { + "_meta": {super::super::SUBSCRIPTION_ID_KEY: "listen"}, + "notifications": expected, + }, + }), + ); + } + } + } + } +} diff --git a/crates/crank-community-mcp/src/rmcp_signals_runtime_tests.rs b/crates/crank-community-mcp/src/rmcp_signals_runtime_tests.rs new file mode 100644 index 0000000..bbfc9f0 --- /dev/null +++ b/crates/crank-community-mcp/src/rmcp_signals_runtime_tests.rs @@ -0,0 +1,312 @@ +//! #107: HTTP wire controls are independent of the SDK execution oracle. +//! A real committed Tool removal exercises the watcher; existing mcp_signals::scenarios covers +//! Resource/Prompt publications, isolation, coalescing, reconnect and authoritative recovery. +use super::{CounterSet, support::*}; +use serde_json::{Value, json}; +use std::{sync::Arc, time::Duration}; +#[path = "rmcp_signals_test_support.rs"] +mod fixtures; +use fixtures::{Endpoint, terminal}; + +const SUB_ID: &str = "io.modelcontextprotocol/subscriptionId"; +const ACK: &str = "notifications/subscriptions/acknowledged"; +const TOOLS: &str = "notifications/tools/list_changed"; +const INVALID_FILTER: &str = "invalid subscriptions/listen notification filter"; + +fn counts(c: &CounterSet) -> [usize; 3] { + [ + c.sdk_subscriptions_listen(), + c.sdk_subscriptions_acknowledged(), + c.sdk_signal_notification(), + ] +} +fn ack(id: &Value, notifications: Value) -> Value { + json!({"jsonrpc":"2.0", "method":ACK, + "params":{"_meta":{SUB_ID:id},"notifications":notifications}}) +} +fn listen_body(id: Value, params: Value) -> Value { + json!({"jsonrpc":"2.0","id":id,"method":"subscriptions/listen","params":params}) +} + +async fn catalog_control(revision: &str) -> [usize; 3] { + let h = Endpoint::started().await; + let session = if revision == LEGACY_REVISION { + Some(h.session().await) + } else { + None + }; + let admission_before = h.counters.snapshot().admission; + let before_list = h.tools(revision, session.as_deref()).await; + assert_eq!( + h.counters.snapshot().admission - admission_before, + 1, + "positive control: the HTTP request must carry this observer" + ); + assert_eq!(before_list["result"]["tools"].as_array().unwrap().len(), 1); + assert_eq!(before_list["result"]["tools"][0]["name"], TOOL_NAME); + let id = json!(u64::MAX); + let before = counts(&h.counters); + let mut stream = if revision == MODERN_REVISION { + let mut stream = h + .listen( + id.clone(), + json!({ + "toolsListChanged":true,"resourcesListChanged":true,"promptsListChanged":true, + "resourceSubscriptions":["crank://CANARY-URI"], "unknown":null + }), + ) + .await; + // Whole-frame equality proves ack first, exact id, no result/id/URI/payload leakage. + assert_eq!( + stream.frame().await, + ack( + &id, + json!({ + "toolsListChanged":true,"resourcesListChanged":true,"promptsListChanged":true + }) + ) + ); + stream + } else { + h.legacy_stream(session.as_deref().unwrap()).await + }; + // Enough for the existing one-second watcher to establish its initial committed fingerprint. + stream.silent().await; + h.draft_without_tools().await; + stream.silent().await; + assert_eq!( + h.tools(revision, session.as_deref()).await["result"]["tools"] + .as_array() + .unwrap() + .len(), + 1 + ); + h.publish_without_tools().await; + let expected = if revision == MODERN_REVISION { + json!({"jsonrpc":"2.0","method":TOOLS,"params":{"_meta":{SUB_ID:id}}}) + } else { + json!({"jsonrpc":"2.0","method":TOOLS}) + }; + assert_eq!( + stream.frame().await, + expected, + "exact committed signal, no catalog payload" + ); + stream.silent().await; + assert_eq!( + h.tools(revision, session.as_deref()).await["result"]["tools"], + json!([]) + ); + let after = counts(&h.counters); + std::array::from_fn(|i| after[i] - before[i]) +} + +#[tokio::test] +async fn modern_wire_control() { + catalog_control(MODERN_REVISION).await; +} +#[tokio::test] +async fn legacy_wire_control() { + catalog_control(LEGACY_REVISION).await; +} + +#[tokio::test] +async fn modern_sdk_runtime_oracle() { + // All real HTTP/commit assertions above must pass before missing SDK behavior can be RED. + assert_eq!( + catalog_control(MODERN_REVISION).await, + [1, 1, 1], + "real HTTP listen decode / ack serialization / watcher signal serialization SDK entries" + ); +} +#[tokio::test] +async fn legacy_sdk_runtime_oracle() { + assert_eq!( + catalog_control(LEGACY_REVISION).await, + [0, 0, 1], + "legacy GET must use SDK signal serialization but not modern listen/ack" + ); +} + +#[tokio::test] +async fn modern_false_absent_and_uri_only_do_not_opt_in() { + let h = Endpoint::started().await; + let mut absent = h.listen(json!("absent"), json!({})).await; + assert_eq!(absent.frame().await, ack(&json!("absent"), json!({}))); + let mut disabled = h + .listen( + json!("disabled"), + json!({ + "toolsListChanged":false,"resourcesListChanged":false,"promptsListChanged":false, + "resourceSubscriptions":["crank://CANARY-URI"] + }), + ) + .await; + assert_eq!(disabled.frame().await, ack(&json!("disabled"), json!({}))); + // A simultaneous positive stream proves the publication was visible to the running watchers. + let mut enabled = h + .listen(json!("enabled"), json!({"toolsListChanged":true})) + .await; + assert_eq!( + enabled.frame().await, + ack(&json!("enabled"), json!({"toolsListChanged":true})) + ); + enabled.silent().await; + h.draft_without_tools().await; + h.publish_without_tools().await; + assert_eq!( + enabled.frame().await, + json!({"jsonrpc":"2.0","method":TOOLS,"params":{"_meta":{SUB_ID:"enabled"}}}) + ); + absent.silent().await; + disabled.silent().await; + let body = terminal( + h.post( + MODERN_REVISION, + None, + json!({ + "jsonrpc":"2.0","id":4,"method":"resources/subscribe", + "params":{"_meta":modern_meta(),"uri":"crank://CANARY-URI"} + }), + ) + .await, + ) + .await; + assert_eq!(body["error"]["code"], -32601); + assert!(body.get("result").is_none()); + assert!(!body.to_string().contains("CANARY")); +} + +#[tokio::test] +async fn modern_http_filter_shape_and_bounds_stay_compatible() { + let h = Endpoint::started().await; + let mut invalid = vec![ + json!({}), + json!({"notifications":null}), + json!({"notifications":[]}), + json!({"notifications":{"toolsListChanged":"CANARY"}}), + json!({"notifications":{"resourceSubscriptions":[null]}}), + json!({"notifications":{"resourceSubscriptions":vec!["CANARY";33]}}), + json!({"notifications":{"resourceSubscriptions":["X".repeat(2049)]}}), + ]; + for key in [ + "toolsListChanged", + "resourcesListChanged", + "promptsListChanged", + "resourceSubscriptions", + ] { + let mut filter = json!({}); + filter[key] = Value::Null; + invalid.push(json!({"notifications":filter})); + } + for mut params in invalid { + params["_meta"] = modern_meta(); + let body = terminal( + h.post(MODERN_REVISION, None, listen_body(json!(7), params)) + .await, + ) + .await; + assert_eq!(body["id"], 7); + assert_eq!(body["error"]["code"], -32602); + assert_eq!(body["error"]["message"], INVALID_FILTER); + assert!(body.get("result").is_none()); + assert!(!body.to_string().contains("CANARY")); + assert!(body.to_string().len() < 4096); + } + // Inclusive bounds, unknown null extension and explicit false are accepted, never acknowledged + // as a URI-content subscription or an extra list-change type. + let mut stream = h + .listen( + json!(8), + json!({ + "resourceSubscriptions":vec!["é".repeat(1024);32], "toolsListChanged":false, + "unknown":null + }), + ) + .await; + assert_eq!(stream.frame().await, ack(&json!(8), json!({}))); +} + +#[tokio::test] +async fn modern_http_ids_are_lossless_and_bounded() { + let h = Endpoint::started().await; + for id in [ + json!("a".repeat(62)), + json!("é".repeat(31)), + json!(u64::MAX), + json!(9_007_199_254_740_993_u64), + json!(1.25), + json!(1.0), + ] { + let mut stream = h.listen(id.clone(), json!({})).await; + let frame = stream.frame().await; + assert_eq!(frame, ack(&id, json!({}))); + assert_eq!(frame["params"]["_meta"][SUB_ID].to_string(), id.to_string()); + } + for id in [json!("a".repeat(63)), json!("é".repeat(32))] { + let body = terminal( + h.post( + MODERN_REVISION, + None, + listen_body( + id.clone(), + json!({"_meta":modern_meta(),"notifications":{}}), + ), + ) + .await, + ) + .await; + assert_eq!(body["id"], id); + assert_eq!(body["error"]["code"], -32600); + assert!(body.get("result").is_none()); + } +} + +#[tokio::test] +async fn modern_http_meta_admission_precedes_sdk_decode() { + let h = Endpoint::started().await; + for meta in [ + Value::Null, + json!([]), + json!({META_PROTOCOL_VERSION:MODERN_REVISION, + META_CLIENT_CAPABILITIES:null}), + ] { + let before = counts(&h.counters); + let response = h + .post( + MODERN_REVISION, + None, + listen_body(json!(9), json!({"_meta":meta,"notifications":{}})), + ) + .await; + // Admission rejections are HTTP 400, not a successful SSE response. + assert_eq!(response.status(), 400); + let raw = tokio::time::timeout(Duration::from_secs(6), response.text()) + .await + .unwrap() + .unwrap(); + let body: Value = serde_json::from_str(&raw).unwrap(); + assert_eq!(body["error"]["code"], -32020); + assert!(body.get("result").is_none()); + assert_eq!( + counts(&h.counters), + before, + "admission must reject before any SDK entry" + ); + } + // clientInfo is optional at HTTP admission; SDK decoding must not newly require it. + let mut meta = modern_meta(); + meta.as_object_mut().unwrap().remove(META_CLIENT_INFO); + let response = h + .post( + MODERN_REVISION, + None, + listen_body( + json!(10), + json!({"_meta":meta,"notifications":{},"extension":null}), + ), + ) + .await; + let mut stream = fixtures::Events::open(response); + assert_eq!(stream.frame().await, ack(&json!(10), json!({}))); +} diff --git a/crates/crank-community-mcp/src/rmcp_signals_test_support.rs b/crates/crank-community-mcp/src/rmcp_signals_test_support.rs new file mode 100644 index 0000000..d378532 --- /dev/null +++ b/crates/crank-community-mcp/src/rmcp_signals_test_support.rs @@ -0,0 +1,280 @@ +//! Small real catalog fixture; broader Resource/Prompt mutations stay in mcp_signals::scenarios. +use super::*; +use crank_core::{AgentStatus, AgentVersion, ToolSelectionPolicy}; +use crank_registry::{CreateAgentDraftVersionRequest, PublishAgentRequest, PublishRequest}; +use crank_runtime::{ + InMemoryCoordinationStateStore, RequestRateLimitConfig, RequestRateLimiter, SecretCrypto, +}; + +pub(super) struct Endpoint { + pub registry: crank_registry::PostgresRegistry, + pub counters: Arc, + key: String, + url: String, + server: tokio::task::JoinHandle<()>, +} +impl Drop for Endpoint { + fn drop(&mut self) { + self.server.abort(); + } +} +impl Endpoint { + pub async fn started() -> Self { + // First caller labels the shared, exit-cleaned disposable PostgreSQL with this owner. + crank_test_support::postgres_schema_url_for_task("signals_owner", "t_7d5f77a6").await; + let registry = test_registry().await; + // This fixture only lists/removes a Tool; no upstream execution is needed. + let operation = test_operation("http://127.0.0.1:9"); + registry + .create_operation(&workspace_id(), &operation, Some("alice")) + .await + .unwrap(); + registry + .publish_operation(PublishRequest { + workspace_id: &workspace_id(), + operation_id: &operation.id, + version: 1, + published_at: &test_time(), + published_by: Some("alice"), + }) + .await + .unwrap(); + publish_agent(®istry, &operation).await; + let key = create_api_key(®istry).await; + let counters = Arc::new(CounterSet::default()); + let app = crate::build_app( + registry.clone(), + Duration::ZERO, + None, + SecretCrypto::new("test-master-key-00000000000000000000000000000000").unwrap(), + crank_runtime::community_with_outbound_policy( + crank_runtime::OutboundHttpPolicy::allowing_hosts(["127.0.0.1"]), + ) + .build(), + RequestRateLimiter::new(RequestRateLimitConfig::new(10_000, 10_000).unwrap()), + Arc::new(InMemoryCoordinationStateStore::default()), + Arc::new(crate::session::InMemorySessionStore::default()), + Arc::new(crate::auth::CommunityMachineCredentialVerifier), + ); + let app = observe_requests(app, counters.clone(), None); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!( + "http://{}/v1/{WORKSPACE_SLUG}/{AGENT_SLUG}", + listener.local_addr().unwrap() + ); + let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + Self { + registry, + counters, + key, + url, + server, + } + } + pub async fn post( + &self, + revision: &str, + session: Option<&str>, + body: Value, + ) -> reqwest::Response { + let mut request = reqwest::Client::new() + .post(&self.url) + .bearer_auth(&self.key) + .header("Accept", "application/json, text/event-stream") + .header("MCP-Protocol-Version", revision); + if revision == MODERN_REVISION { + request = request.header("Mcp-Method", body["method"].as_str().unwrap()); + } + if let Some(session) = session { + request = request.header("MCP-Session-Id", session); + } + tokio::time::timeout(Duration::from_secs(6), request.json(&body).send()) + .await + .unwrap() + .unwrap() + } + pub async fn listen(&self, id: Value, notifications: Value) -> Events { + Events::open( + self.post( + MODERN_REVISION, + None, + json!({ + "jsonrpc":"2.0", "id":id, "method":"subscriptions/listen", + "params":{"_meta":modern_meta(), "notifications":notifications} + }), + ) + .await, + ) + } + pub async fn session(&self) -> String { + let response = self.post(LEGACY_REVISION, None, legacy_initialize(1)).await; + assert_eq!(response.status(), 200); + let session = response.headers()["MCP-Session-Id"] + .to_str() + .unwrap() + .to_owned(); + let body = terminal(response).await; + assert_eq!(body["result"]["protocolVersion"], LEGACY_REVISION); + let response = self + .post(LEGACY_REVISION, Some(&session), initialized_notification()) + .await; + assert_eq!(response.status(), 202); + session + } + pub async fn legacy_stream(&self, session: &str) -> Events { + let response = tokio::time::timeout( + Duration::from_secs(6), + reqwest::Client::new() + .get(&self.url) + .bearer_auth(&self.key) + .header("Accept", "text/event-stream") + .header("MCP-Protocol-Version", LEGACY_REVISION) + .header("MCP-Session-Id", session) + .send(), + ) + .await + .unwrap() + .unwrap(); + Events::open(response) + } + pub async fn tools(&self, revision: &str, session: Option<&str>) -> Value { + let params = if revision == MODERN_REVISION { + json!({"_meta":modern_meta()}) + } else { + json!({}) + }; + terminal( + self.post( + revision, + session, + json!({"jsonrpc":"2.0","id":2,"method":"tools/list","params":params}), + ) + .await, + ) + .await + } + pub async fn draft_without_tools(&self) { + self.registry + .create_agent_draft_version(CreateAgentDraftVersionRequest { + workspace_id: &workspace_id(), + agent_id: &agent_id(), + version: &AgentVersion { + agent_id: agent_id(), + version: 2, + status: AgentStatus::Draft, + instructions: json!({}), + tool_selection_policy: ToolSelectionPolicy::default(), + created_at: test_time(), + }, + bindings: &[], + updated_at: &test_time(), + }) + .await + .unwrap(); + } + pub async fn publish_without_tools(&self) { + self.registry + .publish_agent(PublishAgentRequest { + workspace_id: &workspace_id(), + agent_id: &agent_id(), + version: 2, + published_at: &test_time(), + published_by: Some("alice"), + expected_state: None, + }) + .await + .unwrap(); + } +} + +pub(super) struct Events { + response: reqwest::Response, + buffer: Vec, +} +impl Events { + pub fn open(response: reqwest::Response) -> Self { + assert_eq!(response.status(), 200, "notification stream must open"); + assert!( + response.headers()["content-type"] + .to_str() + .unwrap() + .starts_with("text/event-stream") + ); + Self { + response, + buffer: Vec::new(), + } + } + // One absolute deadline: keepalive comments cannot extend a missing-frame assertion forever. + pub async fn next(&mut self, wait: Duration) -> Option { + let deadline = tokio::time::Instant::now() + wait; + loop { + if let Some(index) = self.buffer.windows(2).position(|w| w == b"\n\n") { + let frame: Vec = self.buffer.drain(..index + 2).collect(); + let frame = std::str::from_utf8(&frame).unwrap(); + if let Some(data) = frame.lines().find_map(|line| line.strip_prefix("data:")) { + return Some(serde_json::from_str(data.trim()).expect("SSE data must be JSON")); + } + continue; + } + match tokio::time::timeout_at(deadline, self.response.chunk()).await { + Err(_) => return None, + Ok(Err(error)) => panic!("SSE transport failure, not silence: {error}"), + Ok(Ok(None)) => panic!("SSE closed unexpectedly, not silence"), + Ok(Ok(Some(bytes))) => self.buffer.extend_from_slice(&bytes), + } + } + } + pub async fn frame(&mut self) -> Value { + self.next(Duration::from_secs(6)) + .await + .expect("notification must arrive before deadline") + } + pub async fn silent(&mut self) { + assert_eq!( + self.next(Duration::from_millis(2200)).await, + None, + "no duplicate/unrequested signal" + ); + } +} + +pub(super) async fn terminal(response: reqwest::Response) -> Value { + let status = response.status(); + assert!( + status == 200 || status == 404, + "unexpected terminal status {status}" + ); + let sse = response.headers()["content-type"] + .to_str() + .unwrap() + .starts_with("text/event-stream"); + 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(); + assert_eq!( + frames.len(), + 1, + "one terminal frame, no notification: {raw}" + ); + frames.into_iter().next().unwrap() + } else { + serde_json::from_str(&raw).unwrap() + }; + assert_eq!( + status.as_u16(), + if body["error"]["code"] == -32601 { + 404 + } else { + 200 + } + ); + body +} diff --git a/docs/development/rmcp-migration-plan.md b/docs/development/rmcp-migration-plan.md index 5115633..0fffd17 100644 --- a/docs/development/rmcp-migration-plan.md +++ b/docs/development/rmcp-migration-plan.md @@ -43,6 +43,8 @@ Logging-срез #107 на базе rc.22/rmcp3.9.0 использует сущ Progress/cancel-срез #107 на базе rc.23/rmcp3.9.0 подключает штатный SSE `lifecycle::progress_frame` обеих revisions к сериализации `ProgressNotificationParam`, а legacy `handle_cancelled_notification` — к декодированию `CancelledNotificationParam.request_id`. Локальная projection+restore сохраняет исходные JSON numbers токена/ID и целочисленный u64 progress, включая значения вне i64/exact-f64; message и omissions берутся из SDK. Decoder передаёт SDK только requestId, не валидируя reason/_meta/extensions. Session+credential ownership, bounded queues/slots, transport, auth и modern stream-close cancellation не меняются. Runtime ATDD подтверждает SDK seams отдельно от wire; unit regression проверяет точную числовую форму. Decoder ignore действует только после HTTP admission: `_meta:[]` сохраняет прежний HTTP400/-32020 до SDK decoder. Отдельная HTTP-регрессия проверяет отказ без отмены активного вызова, а допустимый `_meta:{}` с reason/extensions — успешную SDK-отмену. Это частичная миграция params, не завершение #107, feature qualification или production deployment. +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 этим срезом не завершены. + Проверяемый результат: - Через SDK проходят действующие Tools, Resources, Prompts, completion, уведомления и подписки в применимых revisions, а также progress/cancel и существующая logging policy.