From a438c1df423b8651875e0149093ecbc8aad8bdba Mon Sep 17 00:00:00 2001 From: bsodfather Date: Sun, 25 Oct 2026 12:50:00 +0000 Subject: [PATCH] =?UTF-8?q?feat(epic3):=20=D0=B1=D0=B5=D0=B7=D0=BE=D0=BF?= =?UTF-8?q?=D0=B0=D1=81=D0=BD=D0=BE=D0=B5=20structured=20logging=20MCP=20(?= =?UTF-8?q?Story=203.18)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Story 3.18 (#25) surface: клиент получает только закрытые structured `notifications/message` выбранного уровня, без запросов, секретов и internal causes. - `logging` capability advertising в обеих поддерживаемых revisions; `logging/setLevel` — legacy-only dispatch (modern — `_meta` per request); - закрытый словарь LoggingLevel (RFC 5424), malformed → -32602 с одним safe detail; закрытый набор safe events, task-local request scope; bounded in-memory opt-in, без миграций; - `notifications/message` идут перед ответом в SSE; JSON-режим их не несёт; - ATDD в `scripts/ci-story-checks.sh`: mcp_logging (10), inventory projection (3), protocol::logging unit (12); - проекция capability inventory/frozen oracle переведена на `logging`. Story ATDD и affected проверки пройдены на этом дереве (fmt, clippy, python oracle 56 OK, capability inventory valid). Полный `just verify` — NOT_RUN на story по validation-policy, остаётся на собранной фиче. --- apps/mcp-server/tests/integration.rs | 1 + .../tests/integration/inventory_projection.rs | 7 +- .../tests/integration/mcp_logging.rs | 856 ++++++++++++++++++ crates/crank-community-mcp/src/app.rs | 4 + .../crank-community-mcp/src/app/dispatch.rs | 6 + .../crank-community-mcp/src/app/endpoint.rs | 98 +- crates/crank-community-mcp/src/app/metrics.rs | 50 + crates/crank-community-mcp/src/jsonrpc.rs | 3 + .../src/protocol/logging.rs | 338 +++++++ .../src/protocol/logging_tests.rs | 316 +++++++ .../crank-community-mcp/src/protocol/mod.rs | 6 + .../src/protocol/registry.rs | 50 + .../src/protocol/registry_tests.rs | 57 ++ crates/crank-community-mcp/src/transport.rs | 60 +- docs/capability-baseline/manifest.json | 2 +- docs/capability-inventory.json | 22 +- scripts/ci-story-checks.sh | 6 + ...-11-25-advertised-capabilities.frozen.json | 2 +- ...25-advertised-capabilities.provenance.json | 7 +- ...-07-28-advertised-capabilities.frozen.json | 2 +- ...28-advertised-capabilities.provenance.json | 7 +- .../expected-advertised-capabilities.json | 6 +- .../test_project_advertised_capabilities.py | 11 +- .../test_story31_foundation_boundaries.py | 4 +- 24 files changed, 1883 insertions(+), 38 deletions(-) create mode 100644 apps/mcp-server/tests/integration/mcp_logging.rs create mode 100644 crates/crank-community-mcp/src/protocol/logging.rs create mode 100644 crates/crank-community-mcp/src/protocol/logging_tests.rs diff --git a/apps/mcp-server/tests/integration.rs b/apps/mcp-server/tests/integration.rs index 53210ea..2da2a43 100644 --- a/apps/mcp-server/tests/integration.rs +++ b/apps/mcp-server/tests/integration.rs @@ -7,6 +7,7 @@ mod integration { mod inventory_projection; mod jsonrpc_correlation; mod mcp_completion; + mod mcp_logging; mod mcp_prompts; mod request_context; mod revision_matrix; diff --git a/apps/mcp-server/tests/integration/inventory_projection.rs b/apps/mcp-server/tests/integration/inventory_projection.rs index 5eb0e9a..220f8eb 100644 --- a/apps/mcp-server/tests/integration/inventory_projection.rs +++ b/apps/mcp-server/tests/integration/inventory_projection.rs @@ -241,6 +241,11 @@ async fn inventory_projection_sidecar_is_provenance_only_and_names_the_projectio assert_eq!( triples, vec![ + ( + "server".to_owned(), + "capability".to_owned(), + "logging".to_owned() + ), ( "server".to_owned(), "capability".to_owned(), @@ -262,7 +267,7 @@ async fn inventory_projection_sidecar_is_provenance_only_and_names_the_projectio "tools".to_owned() ) ], - "the advertised server capabilities of the current scope are `completions`, `prompts`, `resources` and `tools`" + "the advertised server capabilities of the current scope are `logging`, `completions`, `prompts`, `resources` and `tools`" ); // The sidecar is not the payload: byte comparison is against the frozen file only. diff --git a/apps/mcp-server/tests/integration/mcp_logging.rs b/apps/mcp-server/tests/integration/mcp_logging.rs new file mode 100644 index 0000000..93d5b01 --- /dev/null +++ b/apps/mcp-server/tests/integration/mcp_logging.rs @@ -0,0 +1,856 @@ +//! Story 3.18 acceptance tests: safe MCP server logging (AT-3.18-01..03, FR-19). +//! +//! Oracles: `docs/acceptance-test-plan.md` AT-3.18-01..03, `epics.md` Story 3.18 and the pinned +//! `logging`/`notifications/message`/`LoggingLevel` schemas of both supported revisions +//! (`2026-07-28` carries the level per request in `_meta`; `2025-11-25` serves `logging/setLevel`). +//! Every request travels through the real HTTP endpoint built by `build_test_app` over a real +//! PostgreSQL registry; the level is set through the production request path. +//! +//! The delivered events are observed on the SSE response stream, which is the only carrier the +//! pinned transport gives a server notification: a JSON body has no place for one. Where a pending +//! notification exists and the client offered `text/event-stream`, the negotiated mode is the stream. +//! +//! No external MCP client is exercised here: these are local harness results against the pinned wire +//! shapes, and the story handoff states that honestly. + +use std::time::Duration; + +use crank_core::PlatformApiKeyScope; +use crank_registry::PostgresRegistry; +use serde_json::{Value, json}; + +use super::common::{ + agent_mcp_url, build_test_app, create_platform_api_key, initialize_session, + publish_agent_with_bindings, spawn_mcp_server, test_registry, +}; + +const MODERN_REVISION: &str = "2026-07-28"; +const LEGACY_REVISION: &str = "2025-11-25"; +const META_PROTOCOL_VERSION: &str = "io.modelcontextprotocol/protocolVersion"; +const META_LOG_LEVEL: &str = "io.modelcontextprotocol/logLevel"; +const META_CLIENT_CAPABILITIES: &str = "io.modelcontextprotocol/clientCapabilities"; +const META_CLIENT_INFO: &str = "io.modelcontextprotocol/clientInfo"; + +const AGENT_SLUG: &str = "logging-agent"; +const OTHER_AGENT_SLUG: &str = "logging-other"; + +/// The one safe wire detail of a malformed logging level. +const INVALID_LEVEL: &str = "invalid logging level"; +/// The fixed logger name of a delivered notification. +const LOGGER_NAME: &str = "crank-mcp-server"; +/// A value that must never appear in a delivered notification. It is distinctive on purpose. +const CANARY: &str = "crank-canary-9f7620e5-aa41-4b0d"; + +struct LoggingEndpoint { + client: reqwest::Client, + base_url: String, + api_key: String, + other_api_key: String, + registry: PostgresRegistry, +} + +impl LoggingEndpoint { + fn url(&self, agent_slug: &str) -> String { + agent_mcp_url(&self.base_url, agent_slug) + } + + /// One request whose response is negotiated as the SSE stream, so a pending notification really + /// has a carrier. The body is split into its notifications and the final JSON-RPC response. + async fn post_stream( + &self, + agent_slug: &str, + api_key: &str, + headers: &[(&str, &str)], + payload: Value, + ) -> StreamReply { + let mut request = self + .client + .post(self.url(agent_slug)) + .header(reqwest::header::ACCEPT, "text/event-stream") + .header(reqwest::header::AUTHORIZATION, format!("Bearer {api_key}")); + for (name, value) in headers { + request = request.header(*name, *value); + } + let response = request + .json(&payload) + .send() + .await + .expect("the MCP endpoint answers"); + let status = response.status(); + let content_type = response + .headers() + .get(reqwest::header::CONTENT_TYPE) + .and_then(|value| value.to_str().ok()) + .unwrap_or_default() + .to_owned(); + let body = response.text().await.expect("the stream body is readable"); + StreamReply::parse(status, content_type, body) + } + + /// One legacy request inside the initialized session of `agent_slug`. + async fn legacy_post( + &self, + agent_slug: &str, + api_key: &str, + session_id: &str, + payload: Value, + ) -> StreamReply { + self.post_stream( + agent_slug, + api_key, + &[ + ("MCP-Protocol-Version", LEGACY_REVISION), + ("MCP-Session-Id", session_id), + ], + payload, + ) + .await + } + + /// One `logging/setLevel` request of the legacy era. + async fn set_level(&self, session_id: &str, level: Value) -> StreamReply { + self.legacy_post( + AGENT_SLUG, + &self.api_key, + session_id, + json!({ + "jsonrpc": "2.0", + "id": 41, + "method": "logging/setLevel", + "params": {"level": level} + }), + ) + .await + } + + /// One modern request of an arbitrary method with the required per-request identity. + async fn modern_stream(&self, method: &str, params: Value) -> StreamReply { + let mut params = params; + params["_meta"] = json!({ + META_PROTOCOL_VERSION: MODERN_REVISION, + META_CLIENT_CAPABILITIES: {}, + META_CLIENT_INFO: {"name": "crank-logging-atdd", "version": "0.1.0"} + }); + self.modern_stream_with_params(method, params).await + } + + /// The same, with the caller's `params` (including a chosen `_meta`). + async fn modern_stream_with_params(&self, method: &str, params: Value) -> StreamReply { + self.post_stream( + AGENT_SLUG, + &self.api_key, + &[ + ("MCP-Protocol-Version", MODERN_REVISION), + ("Mcp-Method", method), + ], + json!({"jsonrpc": "2.0", "id": 51, "method": method, "params": params}), + ) + .await + } + + async fn legacy_session(&self, agent_slug: &str, api_key: &str) -> String { + initialize_session(&self.client, &self.url(agent_slug), api_key).await + } +} + +struct StreamReply { + status: reqwest::StatusCode, + content_type: String, + /// The JSON-RPC response, which is the last event of the stream. + response: Value, + /// The `notifications/message` bodies delivered before it. + notifications: Vec, + /// The raw body, so a test can search it for a canary value. + raw: String, +} + +impl StreamReply { + /// Parse a reply that may arrive either as an SSE stream (a pending notification needs the + /// stream) or as the plain JSON body of a method this era does not serve. + fn parse(status: reqwest::StatusCode, content_type: String, body: String) -> Self { + let mut messages = Vec::new(); + for block in body.split("\n\n") { + for line in block.lines() { + let Some(data) = line.strip_prefix("data:") else { + continue; + }; + let data = data.trim_start(); + if data.is_empty() { + continue; + } + let value: Value = serde_json::from_str(data) + .unwrap_or_else(|error| panic!("every stream event is JSON: {data:?} {error}")); + messages.push(value); + } + } + if messages.is_empty() { + // An era-correct rejection of an unserved method is answered as a plain JSON body: it + // never carries a notification, so there is nothing to stream. + let response: Value = serde_json::from_str(&body) + .unwrap_or_else(|error| panic!("expected a JSON-RPC body, got {body:?}: {error}")); + return Self { + status, + content_type, + response, + notifications: Vec::new(), + raw: body, + }; + } + let response = messages + .pop() + .unwrap_or_else(|| panic!("the stream must end with the JSON-RPC response: {body:?}")); + Self { + status, + content_type, + response, + notifications: messages, + raw: body, + } + } + + fn result(&self) -> &Value { + self.response + .get("result") + .unwrap_or_else(|| panic!("expected a JSON-RPC result, got {}", self.response)) + } + + fn error(&self) -> (i64, String) { + let code = self + .response + .pointer("/error/code") + .and_then(Value::as_i64) + .unwrap_or_else(|| panic!("expected a JSON-RPC error, got {}", self.response)); + let message = self + .response + .pointer("/error/message") + .and_then(Value::as_str) + .unwrap_or_default() + .to_owned(); + (code, message) + } + + fn assert_stream(&self) { + assert_eq!(self.status, reqwest::StatusCode::OK); + assert!( + self.content_type.starts_with("text/event-stream"), + "a streamed answer must carry the SSE content type, got {:?}", + self.content_type + ); + } +} + +/// The exact closed body of one delivered event. Nothing else is allowed to be carried. +fn expected_notification(level: &str, event: &str, outcome: &str) -> Value { + json!({ + "jsonrpc": "2.0", + "method": "notifications/message", + "params": { + "level": level, + "logger": LOGGER_NAME, + "data": {"event": event, "outcome": outcome} + } + }) +} + +async fn logging_endpoint() -> LoggingEndpoint { + let registry = test_registry().await; + publish_agent_with_bindings(®istry, AGENT_SLUG, Vec::new()).await; + publish_agent_with_bindings(®istry, OTHER_AGENT_SLUG, Vec::new()).await; + + let api_key = create_platform_api_key( + ®istry, + AGENT_SLUG, + "mcp-logging", + &[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write], + ) + .await; + let other_api_key = create_platform_api_key( + ®istry, + OTHER_AGENT_SLUG, + "mcp-logging-other", + &[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write], + ) + .await; + let base_url = spawn_mcp_server(build_test_app( + registry.clone(), + Duration::from_millis(0), + Some("https://crank.example.com".to_owned()), + )) + .await; + + LoggingEndpoint { + client: reqwest::Client::new(), + base_url, + api_key, + other_api_key, + registry, + } +} + +/// AT-3.18-01/03: the advertisement equals the implemented surface on both revisions. +#[tokio::test] +async fn advertisement_declares_the_logging_capability_on_both_revisions() { + let endpoint = logging_endpoint().await; + + let discover = endpoint + .client + .post(endpoint.url(AGENT_SLUG)) + .header( + reqwest::header::ACCEPT, + "application/json, text/event-stream", + ) + .header( + reqwest::header::AUTHORIZATION, + format!("Bearer {}", endpoint.api_key), + ) + .header("MCP-Protocol-Version", MODERN_REVISION) + .header("Mcp-Method", "server/discover") + .json(&json!({ + "jsonrpc": "2.0", + "id": 1, + "method": "server/discover", + "params": {"_meta": { + META_PROTOCOL_VERSION: MODERN_REVISION, + META_CLIENT_CAPABILITIES: {}, + META_CLIENT_INFO: {"name": "crank-logging-atdd", "version": "0.1.0"} + }} + })) + .send() + .await + .expect("the endpoint answers"); + let discover: Value = discover.json().await.expect("a JSON body"); + assert_eq!( + discover["result"]["capabilities"]["logging"], + json!({}), + "the modern advertisement must declare the implemented logging capability: {discover}" + ); + + let initialize = endpoint + .client + .post(endpoint.url(AGENT_SLUG)) + .header( + reqwest::header::ACCEPT, + "application/json, text/event-stream", + ) + .header( + reqwest::header::AUTHORIZATION, + format!("Bearer {}", endpoint.api_key), + ) + .json(&json!({ + "jsonrpc": "2.0", + "id": 2, + "method": "initialize", + "params": {"protocolVersion": LEGACY_REVISION, "capabilities": {}} + })) + .send() + .await + .expect("the endpoint answers"); + let initialize: Value = initialize.json().await.expect("a JSON body"); + assert_eq!( + initialize["result"]["capabilities"]["logging"], + json!({}), + "the legacy advertisement must declare the implemented logging capability: {initialize}" + ); + // Control: a capability this story does not implement is still absent, so the assertion above is + // not a blanket "advertise everything" change. + assert!( + initialize["result"]["capabilities"] + .get("io.modelcontextprotocol/tasks") + .is_none(), + "an unimplemented extension must not appear: {initialize}" + ); + endpoint.registry.ping().await.expect("the registry is up"); +} + +/// AT-3.18-01: setting a valid legacy level is acknowledged with one safe structured event. +#[tokio::test] +async fn legacy_set_level_acknowledges_with_a_closed_safe_event() { + let endpoint = logging_endpoint().await; + let session = endpoint.legacy_session(AGENT_SLUG, &endpoint.api_key).await; + + let reply = endpoint.set_level(&session, json!("debug")).await; + reply.assert_stream(); + assert_eq!( + reply.result(), + &json!({}), + "the pinned `logging/setLevel` result is empty: {}", + reply.response + ); + assert_eq!( + reply.notifications, + vec![ + expected_notification("notice", "mcp.logging.level_applied", "applied"), + expected_notification("info", "mcp.request.served", "ok"), + ], + "the acknowledgment carries the applied level and the served outcome, nothing else" + ); + assert!( + reply.raw.len() < 4_096, + "one notification is a few hundred bytes, never a payload echo" + ); +} + +/// AT-3.18-01: after the opt-in, a served request delivers its own safe event only. +#[tokio::test] +async fn legacy_served_request_delivers_only_the_closed_safe_event() { + let endpoint = logging_endpoint().await; + let session = endpoint.legacy_session(AGENT_SLUG, &endpoint.api_key).await; + endpoint.set_level(&session, json!("debug")).await; + + let reply = endpoint + .legacy_post( + AGENT_SLUG, + &endpoint.api_key, + &session, + json!({"jsonrpc": "2.0", "id": 61, "method": "tools/list", "params": {}}), + ) + .await; + reply.assert_stream(); + assert!( + reply.result().get("tools").is_some(), + "the business result is unchanged: {}", + reply.response + ); + assert_eq!( + reply.notifications, + vec![expected_notification("info", "mcp.request.served", "ok")], + "a served request reports its outcome and nothing about the request" + ); +} + +/// AT-3.18-01 (redaction): a value the request carries can never reach a notification, while the +/// positive control proves the same search does find a reflected value elsewhere in the body. +#[tokio::test] +async fn a_request_value_can_never_reach_a_notification() { + let endpoint = logging_endpoint().await; + let session = endpoint.legacy_session(AGENT_SLUG, &endpoint.api_key).await; + endpoint.set_level(&session, json!("debug")).await; + + let reply = endpoint + .legacy_post( + AGENT_SLUG, + &endpoint.api_key, + &session, + json!({ + "jsonrpc": "2.0", + "id": 62, + "method": "tools/call", + "params": { + "name": CANARY, + "arguments": {"secret": CANARY}, + "_meta": {"progressToken": CANARY} + } + }), + ) + .await; + reply.assert_stream(); + + // Positive control: the existing product answer echoes the unknown tool name verbatim, so the + // canary is provably present in this very body — a "not found" search here would be meaningless. + let (code, message) = reply.error(); + assert_eq!(code, -32602, "an unknown tool is a safe client error"); + assert!( + message.contains(CANARY), + "the positive control must reflect the canary in the error message, got {message:?}" + ); + + // Positive control on delivery: the event is really delivered and its body is exactly the + // closed one for a rejected request, so the canary assertions below cannot pass vacuously. + assert_eq!( + reply.notifications, + vec![expected_notification( + "warning", + "mcp.request.rejected", + "invalid_params" + )], + "a rejected request must deliver exactly one safe warning event" + ); + + // The delivered notification is exactly the closed safe body: no canary, no argument value. + for notification in &reply.notifications { + assert_eq!( + notification["params"]["data"] + .as_object() + .map(|data| { + let mut keys: Vec<&str> = data.keys().map(String::as_str).collect(); + keys.sort_unstable(); + keys + }) + .unwrap_or_default(), + vec!["event", "outcome"], + "a notification data object carries exactly the two closed members: {notification}" + ); + assert!( + !notification.to_string().contains(CANARY), + "a request value must never reach a notification: {notification}" + ); + assert!( + notification["params"].get("id").is_none(), + "a notification is not a response: {notification}" + ); + } +} + +/// AT-3.18-02/03: the modern era opts in per request, and only from the pinned `_meta` key. +#[tokio::test] +async fn modern_level_is_per_request_and_requires_an_explicit_opt_in() { + let endpoint = logging_endpoint().await; + + let opted_in = endpoint + .modern_stream_with_params( + "tools/list", + json!({"_meta": { + META_PROTOCOL_VERSION: MODERN_REVISION, + META_CLIENT_CAPABILITIES: {}, + META_CLIENT_INFO: {"name": "crank-logging-atdd", "version": "0.1.0"}, + META_LOG_LEVEL: "debug" + }}), + ) + .await; + opted_in.assert_stream(); + assert!(opted_in.result().get("tools").is_some()); + assert_eq!( + opted_in.notifications, + vec![expected_notification("info", "mcp.request.served", "ok")], + "a request that opted in receives its safe event" + ); + + // The pinned modern schema: without the key the server MUST NOT send any notification. + let not_opted_in = endpoint.modern_stream("tools/list", json!({})).await; + assert_eq!(not_opted_in.status, reqwest::StatusCode::OK); + assert!( + not_opted_in.result().get("tools").is_some(), + "the business answer is unchanged without an opt-in: {}", + not_opted_in.response + ); + assert!( + not_opted_in.notifications.is_empty(), + "no notification without an explicit opt-in, got {:?}", + not_opted_in.notifications + ); + + // An unknown level is treated as "not opted in" rather than as an error of the business request, + // and it never widens the accepted vocabulary. + let unknown = endpoint + .modern_stream_with_params( + "tools/list", + json!({"_meta": { + META_PROTOCOL_VERSION: MODERN_REVISION, + META_CLIENT_CAPABILITIES: {}, + META_CLIENT_INFO: {"name": "crank-logging-atdd", "version": "0.1.0"}, + META_LOG_LEVEL: "verbose" + }}), + ) + .await; + assert!(unknown.result().get("tools").is_some()); + assert!( + unknown.notifications.is_empty(), + "an unpinned level must not opt in, got {:?}", + unknown.notifications + ); +} + +/// AT-3.18-03: the delivered severities follow the ranged level of the legacy session. +#[tokio::test] +async fn legacy_severity_filter_is_honoured() { + let endpoint = logging_endpoint().await; + let session = endpoint.legacy_session(AGENT_SLUG, &endpoint.api_key).await; + + // `error` is more severe than both a served request and a rejected one: neither is delivered. + endpoint.set_level(&session, json!("error")).await; + let served = endpoint + .legacy_post( + AGENT_SLUG, + &endpoint.api_key, + &session, + json!({"jsonrpc": "2.0", "id": 71, "method": "tools/list", "params": {}}), + ) + .await; + assert!( + served.notifications.is_empty(), + "a served event is below the `error` level, got {:?}", + served.notifications + ); + let rejected = endpoint + .legacy_post( + AGENT_SLUG, + &endpoint.api_key, + &session, + json!({"jsonrpc": "2.0", "id": 72, "method": "prompts/get", "params": {}}), + ) + .await; + assert_eq!( + rejected.error().0, + -32602, + "a malformed request is a client error" + ); + assert!( + rejected.notifications.is_empty(), + "a warning event is below the `error` level, got {:?}", + rejected.notifications + ); + + // `warning` admits the rejected event, and still not the served one. + endpoint.set_level(&session, json!("warning")).await; + let rejected = endpoint + .legacy_post( + AGENT_SLUG, + &endpoint.api_key, + &session, + json!({"jsonrpc": "2.0", "id": 73, "method": "prompts/get", "params": {}}), + ) + .await; + assert_eq!( + rejected.notifications, + vec![expected_notification( + "warning", + "mcp.request.rejected", + "invalid_params" + )], + "the rejection is delivered at the `warning` level" + ); + let served = endpoint + .legacy_post( + AGENT_SLUG, + &endpoint.api_key, + &session, + json!({"jsonrpc": "2.0", "id": 74, "method": "tools/list", "params": {}}), + ) + .await; + assert!( + served.notifications.is_empty(), + "an info event is still below the `warning` level, got {:?}", + served.notifications + ); +} + +/// AT-3.18-02: a malformed level is a revision-correct safe error with bounded work, and it never +/// changes the level of the client or of anybody else. +#[tokio::test] +async fn a_malformed_level_is_a_safe_error_without_state_change() { + let endpoint = logging_endpoint().await; + let session = endpoint.legacy_session(AGENT_SLUG, &endpoint.api_key).await; + endpoint.set_level(&session, json!("error")).await; + + // A value outside the pinned union, a non-string shape, a missing member and an oversized value + // all share one safe detail: the client cannot tell them apart and nothing is echoed back. + for level in [ + json!("verbose"), + json!("INFO"), + json!(7), + json!(null), + json!({}), + json!("i".repeat(64)), + ] { + let reply = endpoint.set_level(&session, level.clone()).await; + assert_eq!( + reply.error(), + (-32602, INVALID_LEVEL.to_owned()), + "a malformed level is one safe invalid-params detail for {level}" + ); + if let Some(text) = level.as_str() { + assert!( + !reply.raw.contains(text), + "the offending value must never be echoed back" + ); + } + assert!( + reply.notifications.is_empty(), + "a rejected level is not an opt-in, got {:?}", + reply.notifications + ); + } + + // An oversized value is refused by the fixed bound: the answer stays a short safe detail and the + // value is not reflected, which is the observable half of "bounded work". + let oversized = "i".repeat(65_536); + let reply = endpoint.set_level(&session, json!(oversized)).await; + assert_eq!(reply.error(), (-32602, INVALID_LEVEL.to_owned())); + assert!( + !reply.raw.contains(&oversized), + "an oversized level must not be reflected" + ); + assert!( + reply.raw.len() < 4_096, + "the answer to an oversized level is bounded, got {} bytes", + reply.raw.len() + ); + let missing = endpoint + .legacy_post( + AGENT_SLUG, + &endpoint.api_key, + &session, + json!({"jsonrpc": "2.0", "id": 81, "method": "logging/setLevel", "params": {}}), + ) + .await; + assert_eq!(missing.error(), (-32602, INVALID_LEVEL.to_owned())); + + // The level of the session is unchanged (`error` was set before the malformed attempts), so a + // served request still delivers nothing... + let served = endpoint + .legacy_post( + AGENT_SLUG, + &endpoint.api_key, + &session, + json!({"jsonrpc": "2.0", "id": 82, "method": "tools/list", "params": {}}), + ) + .await; + assert!( + served.notifications.is_empty(), + "a malformed level must not change the active level, got {:?}", + served.notifications + ); + // ...and a valid level still works, which proves the assertions above are not vacuous. + endpoint.set_level(&session, json!("debug")).await; + let served = endpoint + .legacy_post( + AGENT_SLUG, + &endpoint.api_key, + &session, + json!({"jsonrpc": "2.0", "id": 83, "method": "tools/list", "params": {}}), + ) + .await; + assert_eq!(served.notifications.len(), 1); +} + +/// AT-3.18-02 (era matrix): the modern schema declares no `logging/setLevel`, so the same wire name +/// is a method-not-found there and never reaches the legacy service. +#[tokio::test] +async fn the_modern_era_has_no_set_level_method() { + let endpoint = logging_endpoint().await; + let reply = endpoint + .modern_stream("logging/setLevel", json!({"level": "debug"})) + .await; + let (code, message) = reply.error(); + assert_eq!( + code, -32601, + "the modern revision has no logging/setLevel: {}", + reply.response + ); + assert!( + !message.contains("debug"), + "the rejection must not echo the level: {message:?}" + ); + // And the level was not applied through a wrong-era route: a modern request stays silent. + let after = endpoint.modern_stream("tools/list", json!({})).await; + assert!(after.notifications.is_empty()); +} + +/// AT-3.18-01/03: a method this era does not implement is a pinned client error, so the safe event +/// of an opted-in client describes a client-side rejection, never an internal server failure. +#[tokio::test] +async fn an_unknown_method_is_a_rejection_not_an_internal_failure() { + let endpoint = logging_endpoint().await; + let session = endpoint.legacy_session(AGENT_SLUG, &endpoint.api_key).await; + endpoint.set_level(&session, json!("info")).await; + + // `server/discover` is a modern-era method, so the legacy adapter answers it with -32601. + let reply = endpoint + .legacy_post( + AGENT_SLUG, + &endpoint.api_key, + &session, + json!({ + "jsonrpc": "2.0", + "id": 71, + "method": "server/discover", + "params": {} + }), + ) + .await; + assert_eq!( + reply.error().0, + -32601, + "an unimplemented method is a pinned client error: {}", + reply.response + ); + assert_eq!( + reply.notifications, + vec![expected_notification( + "warning", + "mcp.request.rejected", + "invalid_params" + )], + "a pinned client error must not be reported as an internal failure" + ); +} + +/// AT-3.18-01/03 (independence): a level belongs to one client context, so a second session and a +/// second Agent keep their own (or no) level. +#[tokio::test] +async fn a_level_never_leaks_to_another_client() { + let endpoint = logging_endpoint().await; + let session = endpoint.legacy_session(AGENT_SLUG, &endpoint.api_key).await; + endpoint.set_level(&session, json!("debug")).await; + + // Another initialized session of the same Agent never opted in. + let other_session = endpoint.legacy_session(AGENT_SLUG, &endpoint.api_key).await; + assert_ne!( + session, other_session, + "each initialize mints its own session" + ); + let other = endpoint + .legacy_post( + AGENT_SLUG, + &endpoint.api_key, + &other_session, + json!({"jsonrpc": "2.0", "id": 91, "method": "tools/list", "params": {}}), + ) + .await; + assert!( + other.notifications.is_empty(), + "a session that never opted in must stay silent, got {:?}", + other.notifications + ); + assert!(other.result().get("tools").is_some()); + + // The opted-in session still receives its own events... + let opted_in = endpoint + .legacy_post( + AGENT_SLUG, + &endpoint.api_key, + &session, + json!({"jsonrpc": "2.0", "id": 92, "method": "tools/list", "params": {}}), + ) + .await; + assert_eq!(opted_in.notifications.len(), 1); + + // ...and another Agent's session is unaffected by this Agent's level, both before and after it + // sets its own. + let other_agent_session = endpoint + .legacy_session(OTHER_AGENT_SLUG, &endpoint.other_api_key) + .await; + let other_agent = endpoint + .legacy_post( + OTHER_AGENT_SLUG, + &endpoint.other_api_key, + &other_agent_session, + json!({"jsonrpc": "2.0", "id": 93, "method": "tools/list", "params": {}}), + ) + .await; + assert!( + other_agent.notifications.is_empty(), + "another Agent must not inherit a level, got {:?}", + other_agent.notifications + ); + endpoint + .legacy_post( + OTHER_AGENT_SLUG, + &endpoint.other_api_key, + &other_agent_session, + json!({"jsonrpc": "2.0", "id": 94, "method": "logging/setLevel", "params": {"level": "error"}}), + ) + .await; + let other_agent_error = endpoint + .legacy_post( + OTHER_AGENT_SLUG, + &endpoint.other_api_key, + &other_agent_session, + json!({"jsonrpc": "2.0", "id": 95, "method": "tools/list", "params": {}}), + ) + .await; + assert!( + other_agent_error.notifications.is_empty(), + "the other Agent's own `error` level admits no served event" + ); +} diff --git a/crates/crank-community-mcp/src/app.rs b/crates/crank-community-mcp/src/app.rs index 5c23164..43efa94 100644 --- a/crates/crank-community-mcp/src/app.rs +++ b/crates/crank-community-mcp/src/app.rs @@ -82,6 +82,9 @@ pub(super) struct AppState { session_slots: Arc, pub(super) credential_verifier: SharedMachineCredentialVerifier, allowed_origins: AllowedOrigins, + /// Story 3.18: the bounded in-memory `logging/setLevel` opt-in of the legacy sessions. It is a + /// client-scoped level, never a process-global one, and it needs no schema migration. + pub(super) logging_levels: Arc, } #[derive(Clone)] @@ -248,6 +251,7 @@ fn build_app_inner( session_slots: Arc::new(Semaphore::new(max_concurrent_sessions)), credential_verifier, allowed_origins: AllowedOrigins::new(public_base_url), + logging_levels: Arc::new(crate::protocol::LogLevelStore::new()), }); if start_background_workers { spawn_approval_recovery(Arc::clone(&state)); diff --git a/crates/crank-community-mcp/src/app/dispatch.rs b/crates/crank-community-mcp/src/app/dispatch.rs index 9c2e5fb..4d4b8c0 100644 --- a/crates/crank-community-mcp/src/app/dispatch.rs +++ b/crates/crank-community-mcp/src/app/dispatch.rs @@ -67,6 +67,12 @@ pub(super) async fn handle_modern_request( .as_deref() .unwrap_or(crate::jsonrpc::MODERN_PROTOCOL_VERSION); + // Story 3.18: the modern revision carries the log level of this request in + // `_meta["io.modelcontextprotocol/logLevel"]` (SEP-2577); the former `logging/setLevel` request + // does not exist here. Absent, non-string or unknown values mean "not opted in", so no + // `notifications/message` is emitted for this request. + crate::protocol::set_active_level(crate::protocol::modern_request_level(message)); + // A notification carries no `id`. It is acknowledged before the request-only header rules: the // mandatory `Mcp-Method`/`Mcp-Name` pair applies to requests, not to notifications (protocol era // matrix row 18). The envelope, identity and mixed-carrier checks — and authentication — have diff --git a/crates/crank-community-mcp/src/app/endpoint.rs b/crates/crank-community-mcp/src/app/endpoint.rs index 321903e..ed51852 100644 --- a/crates/crank-community-mcp/src/app/endpoint.rs +++ b/crates/crank-community-mcp/src/app/endpoint.rs @@ -14,20 +14,22 @@ use crate::{ method_name, params, request_id, }, protocol::{ - CompletionCommand, CompletionOutcome, ContinuationSupport, DispatchDecision, EnvelopeKind, - Kind, MethodHandler, PromptGetCommand, PromptsCommand, PromptsListCommand, PromptsOutcome, - RequestEra, ResourceReadCommand, ResourcesCommand, ResourcesListCommand, ResourcesOutcome, - ServiceContext, ToolCallCommand, ToolsCommand, ToolsListCommand, ToolsOutcome, - ambiguous_session_carrier_response, handle_completion_command, handle_prompts_command, - handle_resources_command, handle_tools_command, resolve_request_identity, + CompletionCommand, CompletionOutcome, ContinuationSupport, DispatchDecision, + EVENT_LEVEL_APPLIED, EnvelopeKind, INVALID_LEVEL, Kind, LoggingOutcome, MethodHandler, + PromptGetCommand, PromptsCommand, PromptsListCommand, PromptsOutcome, RequestEra, + ResourceReadCommand, ResourcesCommand, ResourcesListCommand, ResourcesOutcome, + ServiceContext, SetLevelCommand, ToolCallCommand, ToolsCommand, ToolsListCommand, + ToolsOutcome, ambiguous_session_carrier_response, handle_completion_command, + handle_logging_command, handle_prompts_command, handle_resources_command, + handle_tools_command, resolve_request_identity, }, rate_limit::{rate_limited_jsonrpc_response, rate_limited_status_response}, request_context::RequestContext, tool_error::execution_locale, transport::{ - 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, + 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, }, }; use axum::{ @@ -224,8 +226,14 @@ pub(super) async fn mcp_post( "mcp request received" ); - let response = - mcp_post_response(&path, state, &headers, &message, &transport_correlation).await; + let response = crate::protocol::logging_scope(mcp_post_response( + &path, + state, + &headers, + &message, + &transport_correlation, + )) + .await; request_metrics.complete(&response); with_request_id_header(response, &transport_request_id) } @@ -250,6 +258,13 @@ async fn mcp_post_response( Ok(mode) => mode, Err(status) => return status.into_response(), }; + // Story 3.18: a server notification is delivered only on the SSE stream, so the logging + // projection records whether this request offered it. This is an admission fact of the same + // `Accept` header the mode above was negotiated from. + if accepts_event_stream(headers) { + crate::protocol::set_sse_acceptable(); + } + // A conflicting duplicate session carrier is an ambiguous identity: it must not be resolved to // one of its values. The carrier itself cannot tell which era the request belongs to, so the // diagnostic is read from the non-ambiguous part of the request (matrix row 17) — a consumer of @@ -327,6 +342,17 @@ async fn mcp_post_response( } } + // Story 3.18: the legacy logging opt-in belongs to this session, so it is read before dispatch. + // A session that never sent `logging/setLevel` has no level, which is what the pinned schema + // describes as "not opted in" (no notification is delivered). + if matches!(identity.era, RequestEra::Legacy) { + crate::protocol::set_active_level( + request_session_id + .as_deref() + .and_then(|session_id| state.logging_levels.get(session_id)), + ); + } + let required_scope = match method_name(message) { Some("tools/call") => PlatformApiKeyScope::Write, _ => PlatformApiKeyScope::Read, @@ -953,6 +979,56 @@ async fn mcp_post_response( } } } + // Story 3.18: the pinned legacy `logging/setLevel`. The level belongs to the initialized + // session of this request, so setting it can never change another client's level. The request + // answers an empty result; the acknowledgment event is filtered by the level it just set. + DispatchDecision::Allowed { + handler: MethodHandler::LoggingSetLevel, + .. + } if is_request(message) => { + let session = match require_initialized_session(&state, path, headers, message).await { + Ok(session) => session, + Err(response) => return response, + }; + let command: SetLevelCommand = match serde_json::from_value(params(message)) { + Ok(command) => command, + // A non-string, missing or otherwise unparsable level shares the one safe detail of a + // value outside the pinned union: nothing the client sent is echoed back. + Err(_) => { + return transport_response( + StatusCode::OK, + jsonrpc_error(request_id(message), -32602, INVALID_LEVEL), + response_mode, + None, + Some(&session.protocol_version), + ); + } + }; + match handle_logging_command(&state.logging_levels, &session.id, command) { + LoggingOutcome::Applied(level) => { + crate::protocol::set_active_level(Some(level)); + crate::protocol::note( + crate::protocol::LogLevel::Notice, + EVENT_LEVEL_APPLIED, + "applied", + ); + transport_response( + StatusCode::OK, + jsonrpc_result(request_id(message), json!({})), + response_mode, + None, + Some(&session.protocol_version), + ) + } + LoggingOutcome::InvalidParams(detail) => transport_response( + StatusCode::OK, + jsonrpc_error(request_id(message), -32602, detail), + response_mode, + None, + Some(&session.protocol_version), + ), + } + } // 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(), diff --git a/crates/crank-community-mcp/src/app/metrics.rs b/crates/crank-community-mcp/src/app/metrics.rs index 649d73b..3624d1b 100644 --- a/crates/crank-community-mcp/src/app/metrics.rs +++ b/crates/crank-community-mcp/src/app/metrics.rs @@ -121,3 +121,53 @@ impl ActiveStreamGuard { }) } } + +#[cfg(test)] +mod tests { + use crank_metrics::McpMethod; + use serde_json::json; + + use super::normalized_mcp_method; + + /// AT-3.18-02: the metric label of the logging request is a member of the closed label enum, so + /// neither the level nor any other client-supplied identifier can reach the label space. There is + /// no mapping from a request value to a label anywhere in this file. + #[test] + fn a_logging_request_can_only_produce_a_fixed_metric_label() { + for level in [ + json!("debug"), + json!("verbose"), + json!("crank-canary-9f7620e5-aa41-4b0d"), + json!(7), + json!(null), + ] { + let message = json!({ + "jsonrpc": "2.0", + "id": 1, + "method": "logging/setLevel", + "params": {"level": level} + }); + assert_eq!( + normalized_mcp_method(&message), + McpMethod::Unsupported, + "the method label is a fixed enum member, never the request value" + ); + } + assert_eq!(McpMethod::Unsupported.as_str(), "unsupported"); + // Every label value of the enum is a pinned literal, so the label domain cannot be widened by + // a request at all. + assert!( + McpMethod::VALUES.iter().all(|value| value + .chars() + .all(|character| character.is_ascii_lowercase() || character == '_')), + "every method label is a fixed lowercase literal: {:?}", + McpMethod::VALUES + ); + + // A malformed envelope has its own fixed label as well. + assert_eq!( + normalized_mcp_method(&json!({"level": "debug"})), + McpMethod::Invalid + ); + } +} diff --git a/crates/crank-community-mcp/src/jsonrpc.rs b/crates/crank-community-mcp/src/jsonrpc.rs index e4140fe..cdb3798 100644 --- a/crates/crank-community-mcp/src/jsonrpc.rs +++ b/crates/crank-community-mcp/src/jsonrpc.rs @@ -18,6 +18,9 @@ pub const CURRENT_PROTOCOL_VERSION: &str = LEGACY_PROTOCOL_VERSION; pub const META_PROTOCOL_VERSION_KEY: &str = "io.modelcontextprotocol/protocolVersion"; pub const META_CLIENT_CAPABILITIES_KEY: &str = "io.modelcontextprotocol/clientCapabilities"; pub const META_CLIENT_INFO_KEY: &str = "io.modelcontextprotocol/clientInfo"; +/// `_meta` key of the per-request log level (Story 3.18). SEP-2577 replaces the former +/// `logging/setLevel` request of the legacy era with this per-request opt-in. +pub const META_LOG_LEVEL_KEY: &str = "io.modelcontextprotocol/logLevel"; /// Result `_meta` key carrying the self-reported server identity (pinned `DiscoverResult`). pub const META_SERVER_INFO_KEY: &str = "io.modelcontextprotocol/serverInfo"; diff --git a/crates/crank-community-mcp/src/protocol/logging.rs b/crates/crank-community-mcp/src/protocol/logging.rs new file mode 100644 index 0000000..25928e4 --- /dev/null +++ b/crates/crank-community-mcp/src/protocol/logging.rs @@ -0,0 +1,338 @@ +//! Story 3.18: safe MCP server logging (FR-19). +//! +//! Scope of this module is the server side of the pinned `logging` capability of the two approved +//! revisions, and nothing else: +//! +//! * `2025-11-25` (legacy session era) declares `logging/setLevel` as a client request with one +//! `level` of the pinned `LoggingLevel` union, and `logging?: object` in `ServerCapabilities`. +//! The request sets the severity a client wants to receive for its own session. +//! * `2026-07-28` (modern stateless era) has no `logging/setLevel` method at all: SEP-2577 replaces +//! it with the per-request `_meta["io.modelcontextprotocol/logLevel"]`, and the schema says that +//! when that key is absent "the server MUST NOT send any notifications/message notifications for +//! this request". The `logging` capability and `notifications/message` themselves stay in the +//! pinned schema as deprecated for at least twelve months. +//! +//! The answer of this story is therefore the narrow one the contract offers: an opt-in level that +//! belongs to the current negotiated client context (one legacy session, or one modern request — +//! never a process-global level shared by every agent), and `notifications/message` events that are +//! built **only** from the closed safe vocabulary below. +//! +//! Redaction is structural, not a filter: no request payload, credential, internal error cause, +//! Prompt/Resource/Tool name, URI, argument value or any other user-supplied value is ever accepted +//! by this module, so none of them can reach the wire. A `notifications/message` body is exactly +//! `{"level": , "logger": "crank-mcp-server", "data": {"event": , +//! "outcome": }}` — every member of it is a `&'static str` from this file. +//! +//! Bounds (issue requirement: bounded frequency/queues/bytes, logging never blocks execution and +//! never replaces the audit trail): +//! * at most one event per response is recorded, and at most [`MAX_PENDING_NOTIFICATIONS`] are +//! drained into one response — a fixed, per-response frequency bound; +//! * every event has a fixed size and no variable input, so the byte bound follows from the count +//! bound without a separate accounting path; +//! * recording is a bounded in-memory push that drops the event when the buffer is full, the active +//! level is unset, or the task has no request scope. No I/O, no lock acquisition that can wait, and +//! no error path: logging can never fail or slow down the request it describes. +//! * the legacy opt-in table is a bounded in-memory map read/written with `try_lock` only. + +use std::{ + cell::RefCell, + collections::HashMap, + future::Future, + sync::{Mutex, MutexGuard}, +}; + +use serde::Deserialize; +use serde_json::{Value, json}; +use tokio::task_local; + +/// The pinned `LoggingLevel` union: RFC 5424 severities, ordered from the most verbose to the most +/// severe. The ordering is the filtering contract — a client is sent the events at or above its +/// level. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub(crate) enum LogLevel { + Debug, + Info, + Notice, + Warning, + Error, + Critical, + Alert, + Emergency, +} + +impl LogLevel { + /// The exact wire literal of this level. + pub(crate) const fn as_str(self) -> &'static str { + match self { + Self::Debug => "debug", + Self::Info => "info", + Self::Notice => "notice", + Self::Warning => "warning", + Self::Error => "error", + Self::Critical => "critical", + Self::Alert => "alert", + Self::Emergency => "emergency", + } + } + + /// Exact parse of the eight pinned literals. + /// + /// Nothing is coerced: no case folding, no aliases (`warn`), no numeric severities. A value that + /// is not one of the pinned strings is malformed, which is what the pinned `LoggingLevel` type + /// says and what `InvalidParamsError` is for. + pub(crate) fn parse(value: &str) -> Option { + match value { + "debug" => Some(Self::Debug), + "info" => Some(Self::Info), + "notice" => Some(Self::Notice), + "warning" => Some(Self::Warning), + "error" => Some(Self::Error), + "critical" => Some(Self::Critical), + "alert" => Some(Self::Alert), + "emergency" => Some(Self::Emergency), + _ => None, + } + } +} + +/// Bound of `params.level` before it is compared: the longest pinned literal is nine bytes, so a +/// value beyond this cannot be a level and must not be scanned further. +pub(crate) const MAX_LEVEL_BYTES: usize = 16; + +/// The one safe detail of a malformed `logging/setLevel`: it never echoes the offending value, so an +/// oversized or hostile value cannot be reflected back or widened into an error payload. +pub(crate) const INVALID_LEVEL: &str = "invalid logging level"; + +/// Notifications drained into one response (frequency bound). +pub(crate) const MAX_PENDING_NOTIFICATIONS: usize = 4; + +/// Bound of the in-memory legacy opt-in table (memory bound; see [`LogLevelStore`]). +pub(crate) const MAX_TRACKED_SESSIONS: usize = 1_024; + +/// The fixed logger name carried by every notification. It is a server constant, never a +/// client-supplied or catalog-supplied value. +const LOGGER_NAME: &str = "crank-mcp-server"; + +/// Closed safe vocabulary: the server served the request. +pub(crate) const EVENT_SERVED: &str = "mcp.request.served"; +/// Closed safe vocabulary: the request was rejected as invalid before any service work. +pub(crate) const EVENT_REJECTED: &str = "mcp.request.rejected"; +/// Closed safe vocabulary: the request failed on the server side. +pub(crate) const EVENT_FAILED: &str = "mcp.request.failed"; +/// Closed safe vocabulary: this client set its logging level. +pub(crate) const EVENT_LEVEL_APPLIED: &str = "mcp.logging.level_applied"; + +/// The `params` of one `logging/setLevel` request as the legacy adapter parses it from the wire form. +/// +/// Only the single pinned member exists here: an unknown member is ignored by serde, and a `level` +/// that is not a string is a deserialization error, which the adapter answers with the same safe +/// [`INVALID_LEVEL`] detail instead of a serde diagnostic. +#[derive(Debug, Deserialize)] +pub(crate) struct SetLevelCommand { + pub(crate) level: String, +} + +impl SetLevelCommand { + /// The bounded input contract of AC2: the level is length-bounded and compared exactly, so a + /// malformed or oversized value is refused with bounded work and one safe detail. + pub(crate) fn validate(&self) -> Result { + if self.level.is_empty() || self.level.len() > MAX_LEVEL_BYTES { + return Err(INVALID_LEVEL); + } + LogLevel::parse(&self.level).ok_or(INVALID_LEVEL) + } +} + +/// A neutral outcome of the shared `logging/setLevel` service. +pub(crate) enum LoggingOutcome { + /// The level of this client context was accepted. + Applied(LogLevel), + /// Malformed or oversized level: one safe detail, no echoed input. + InvalidParams(&'static str), +} + +/// One recorded event of the closed vocabulary. +#[derive(Debug, Clone, Copy)] +struct SafeEvent { + level: LogLevel, + event: &'static str, + outcome: &'static str, +} + +/// The request-scoped logging state: the level this client opted in to, whether the client offered +/// the SSE response mode that is the only carrier of a server notification, and the bounded events +/// this response will carry. +#[derive(Default)] +struct RequestLog { + active: Option, + sse_acceptable: bool, + pending: Vec, +} + +task_local! { + /// Per-request logging scope. Installed by the HTTP entry point of the MCP endpoint, so two + /// concurrently served requests never share a level or a buffer. Code outside such a scope + /// (unit tests, background workers) sees a no-op. + static REQUEST_LOG: RefCell; +} + +/// Run one request inside its own logging scope. +pub(crate) async fn scoped(future: F) -> F::Output { + REQUEST_LOG + .scope(RefCell::new(RequestLog::default()), future) + .await +} + +/// Activate (or clear) the level of the current client context. Outside a scope this is a no-op. +pub(crate) fn set_active_level(level: Option) { + let _ = REQUEST_LOG.try_with(|log| { + if let Ok(mut log) = log.try_borrow_mut() { + log.active = level; + } + }); +} + +/// Remember that this request offered `text/event-stream`, the only carrier of a notification. +pub(crate) fn set_sse_acceptable() { + let _ = REQUEST_LOG.try_with(|log| { + if let Ok(mut log) = log.try_borrow_mut() { + log.sse_acceptable = true; + } + }); +} + +/// Record one event of the closed vocabulary for the level this client opted in to. +/// +/// Everything below the active level, every event without an active level (the client did not opt +/// in), and every event beyond the fixed buffer bound is dropped silently: the caller never branches +/// on logging. +pub(crate) fn note(level: LogLevel, event: &'static str, outcome: &'static str) { + let _ = REQUEST_LOG.try_with(|log| { + let Ok(mut log) = log.try_borrow_mut() else { + return; + }; + let Some(active) = log.active else { + return; + }; + if level < active || log.pending.len() >= MAX_PENDING_NOTIFICATIONS { + return; + } + log.pending.push(SafeEvent { + level, + event, + outcome, + }); + }); +} + +/// The pending events as wire `notifications/message` bodies, and whether this request can carry +/// them at all. Draining is the last step of the response projection, so a notification can never be +/// delivered twice or survive into another request. +pub(crate) fn take_notifications() -> Vec { + REQUEST_LOG + .try_with(|log| { + let Ok(mut log) = log.try_borrow_mut() else { + return Vec::new(); + }; + if !log.sse_acceptable { + // A JSON body has no place for a server notification: the event is not delivered + // instead of being smuggled into the result object. + log.pending.clear(); + return Vec::new(); + } + std::mem::take(&mut log.pending) + .into_iter() + .map(|event| { + json!({ + "jsonrpc": "2.0", + "method": "notifications/message", + "params": { + "level": event.level.as_str(), + "logger": LOGGER_NAME, + "data": { + "event": event.event, + "outcome": event.outcome, + } + } + }) + }) + .collect() + }) + .unwrap_or_default() +} + +/// The per-session opt-in of the legacy era. +/// +/// The login belongs to the session the client negotiated, so a level set by one agent's client can +/// never apply to another. It is deliberately **in-memory only**: persisting it would need a schema +/// migration of the transport session store, and the deprecated capability does not justify that. +/// +/// shortcut: the table is per process — a level set on one replica is not seen by another replica +/// serving the same session, and a restart clears it; upgrade to the session store if a durable or +/// cross-replica level is ever required. +#[derive(Default)] +pub(crate) struct LogLevelStore { + levels: Mutex>, +} + +impl LogLevelStore { + pub(crate) fn new() -> Self { + Self::default() + } + + /// Store the level of one session. Never waits and never fails: on lock contention the update is + /// skipped rather than blocking the request. + pub(crate) fn set(&self, session_id: &str, level: LogLevel) { + let Some(mut levels) = self.lock() else { + return; + }; + if levels.len() >= MAX_TRACKED_SESSIONS && !levels.contains_key(session_id) { + // Bounded table: the oldest opt-ins are dropped instead of growing without a limit. A + // dropped client simply stops receiving notifications until it sets its level again. + levels.clear(); + } + levels.insert(session_id.to_owned(), level); + } + + /// The level of one session, if this process still remembers it. + pub(crate) fn get(&self, session_id: &str) -> Option { + self.lock()?.get(session_id).copied() + } + + fn lock(&self) -> Option>> { + self.levels.try_lock().ok() + } +} + +/// Serve one `logging/setLevel` request of the legacy era (AC1/AC2). +/// +/// The command has already been parsed from the wire form, so this function only validates and +/// records; it never reads the registry, the catalog or any stored value. +pub(crate) fn handle_logging_command( + store: &LogLevelStore, + session_id: &str, + command: SetLevelCommand, +) -> LoggingOutcome { + match command.validate() { + Ok(level) => { + store.set(session_id, level); + LoggingOutcome::Applied(level) + } + Err(detail) => LoggingOutcome::InvalidParams(detail), + } +} + +/// The level a modern request asked for in `_meta`. +/// +/// The pinned schema says the server must not send `notifications/message` for a request that does +/// not carry the key, so an absent, non-string or unknown value is simply "not opted in": it is not +/// an error of the business request and never widens the accepted vocabulary. +pub(crate) fn modern_request_level(message: &Value) -> Option { + let meta = crate::jsonrpc::params(message).get("_meta")?.clone(); + let value = meta.get(crate::jsonrpc::META_LOG_LEVEL_KEY)?.as_str()?; + LogLevel::parse(value) +} + +#[cfg(test)] +#[path = "logging_tests.rs"] +mod tests; diff --git a/crates/crank-community-mcp/src/protocol/logging_tests.rs b/crates/crank-community-mcp/src/protocol/logging_tests.rs new file mode 100644 index 0000000..d80344f --- /dev/null +++ b/crates/crank-community-mcp/src/protocol/logging_tests.rs @@ -0,0 +1,316 @@ +//! Unit contract of Story 3.18: the pinned level vocabulary, the bounded input contract of +//! `logging/setLevel`, the request-scoped bounded event buffer and the closed safe notification +//! shape. + +use serde_json::json; + +use super::*; + +/// Parse one `logging/setLevel` params object and validate its level, or `None` when the shape itself +/// is malformed (which the adapter answers with the same safe detail). +fn validate(level: &str) -> Option> { + let command: SetLevelCommand = serde_json::from_value(json!({ "level": level })).ok()?; + Some(command.validate()) +} + +#[test] +fn every_pinned_level_is_accepted_exactly_once_and_in_severity_order() { + // The pinned `LoggingLevel` union of both revisions, most verbose first. + let pinned = [ + ("debug", LogLevel::Debug), + ("info", LogLevel::Info), + ("notice", LogLevel::Notice), + ("warning", LogLevel::Warning), + ("error", LogLevel::Error), + ("critical", LogLevel::Critical), + ("alert", LogLevel::Alert), + ("emergency", LogLevel::Emergency), + ]; + for (index, (literal, expected)) in pinned.iter().enumerate() { + assert_eq!( + LogLevel::parse(literal), + Some(*expected), + "{literal} is a pinned level" + ); + assert_eq!( + expected.as_str(), + *literal, + "the wire literal of a level is exactly the pinned string" + ); + assert_eq!( + *expected as usize, index, + "the severity ordering of {literal} must follow the RFC 5424 order" + ); + assert_eq!( + validate(literal), + Some(Ok(*expected)), + "{literal} must be accepted through the wire shape too" + ); + } + assert!( + pinned.windows(2).all(|pair| pair[0].1 < pair[1].1), + "severity must be strictly increasing so the filter is `event >= level`" + ); +} + +#[test] +fn nothing_outside_the_pinned_union_is_a_level() { + for value in [ + "", + "warn", + "WARN", + "Info", + "information", + " debug", + "debug ", + "0", + "7", + "emergency!", + "debug\u{0}", + "информация", + ] { + assert_eq!( + LogLevel::parse(value), + None, + "{value:?} is not one of the pinned literals and must never be coerced into one" + ); + assert_eq!( + validate(value), + Some(Err(INVALID_LEVEL)), + "a value outside the union is a bounded invalid-params detail, got {value:?}" + ); + } +} + +#[test] +fn malformed_level_shapes_share_one_safe_detail() { + // A `level` the schema types as a string, sent as something else: a deserialization error that the + // adapter answers with the same safe detail. It never echoes what the client sent. + for value in [json!(7), json!(1.5), json!(0)] { + assert!( + serde_json::from_value::(json!({ "level": value })).is_err(), + "a numeric level is not a pinned LoggingLevel" + ); + } + for value in [json!(null), json!({}), json!(["info"]), json!(true)] { + assert!( + serde_json::from_value::(json!({ "level": value })).is_err(), + "a non-string level is not a pinned LoggingLevel" + ); + } + assert!( + serde_json::from_value::(json!({})).is_err(), + "the pinned request requires `level`" + ); + // Control: the same safe detail is what an unknown string produces, so both malformed shapes are + // indistinguishable on the wire and neither discloses what was sent. + assert_eq!(validate("verbose"), Some(Err(INVALID_LEVEL))); + assert!( + INVALID_LEVEL.len() < 64, + "the detail stays a fixed short text" + ); +} + +#[test] +fn an_oversized_level_is_refused_before_any_comparison() { + let oversized = "i".repeat(MAX_LEVEL_BYTES + 1); + assert_eq!(validate(&oversized), Some(Err(INVALID_LEVEL))); + // Positive control: the bound is not so tight that a pinned literal is refused. + assert_eq!(validate("emergency"), Some(Ok(LogLevel::Emergency))); +} + +#[test] +fn the_session_opt_in_is_per_session_and_bounded() { + let store = LogLevelStore::new(); + store.set("session-a", LogLevel::Error); + store.set("session-b", LogLevel::Debug); + assert_eq!(store.get("session-a"), Some(LogLevel::Error)); + assert_eq!(store.get("session-b"), Some(LogLevel::Debug)); + assert_eq!( + store.get("session-c"), + None, + "a session that never opted in must not inherit another session's level" + ); + + // The table stays bounded: filling it past the cap drops the previous opt-ins instead of growing. + for index in 0..MAX_TRACKED_SESSIONS { + store.set(&format!("filler-{index}"), LogLevel::Info); + } + store.set("session-after-cap", LogLevel::Alert); + assert_eq!(store.get("session-after-cap"), Some(LogLevel::Alert)); +} + +#[tokio::test] +async fn an_event_is_delivered_only_at_or_above_the_opted_in_level() { + // One closed-vocabulary event per severity, recorded inside a request scope that offered SSE. + for (active, expected) in [ + (LogLevel::Debug, 4usize), + (LogLevel::Info, 4), + (LogLevel::Notice, 3), + (LogLevel::Warning, 2), + (LogLevel::Error, 1), + (LogLevel::Critical, 0), + (LogLevel::Alert, 0), + (LogLevel::Emergency, 0), + ] { + let delivered = scoped(async move { + set_active_level(Some(active)); + set_sse_acceptable(); + note(LogLevel::Info, EVENT_SERVED, "ok"); + note(LogLevel::Notice, EVENT_LEVEL_APPLIED, "applied"); + note(LogLevel::Warning, EVENT_REJECTED, "invalid_params"); + note(LogLevel::Error, EVENT_FAILED, "internal"); + take_notifications() + }) + .await; + assert_eq!( + delivered.len(), + expected, + "level {} must deliver exactly the events at or above it", + active.as_str() + ); + } +} + +#[tokio::test] +async fn without_an_opt_in_nothing_is_even_recorded() { + // Outside a scope (no request, e.g. a background worker): a no-op. + note(LogLevel::Info, EVENT_SERVED, "ok"); + assert!(take_notifications().is_empty()); + + // Inside a scope without an opted-in level. + let no_level = scoped(async { + set_sse_acceptable(); + note(LogLevel::Error, EVENT_FAILED, "internal"); + take_notifications() + }) + .await; + assert!( + no_level.is_empty(), + "the pinned modern schema forbids notifications for a client that did not opt in" + ); +} + +#[tokio::test] +async fn a_level_is_present_but_the_client_offered_no_stream() { + let delivered = scoped(async { + set_active_level(Some(LogLevel::Debug)); + note(LogLevel::Error, EVENT_FAILED, "internal"); + take_notifications() + }) + .await; + assert!( + delivered.is_empty(), + "a JSON body has no carrier for notifications/message; the event is dropped, not smuggled in" + ); +} + +#[tokio::test] +async fn the_buffer_is_bounded_and_drains_once() { + let (first, second) = scoped(async { + set_active_level(Some(LogLevel::Debug)); + set_sse_acceptable(); + for _ in 0..(MAX_PENDING_NOTIFICATIONS * 4) { + note(LogLevel::Info, EVENT_SERVED, "ok"); + } + let first = take_notifications(); + let second = take_notifications(); + (first, second) + }) + .await; + assert_eq!( + first.len(), + MAX_PENDING_NOTIFICATIONS, + "the per-response frequency bound" + ); + assert!( + second.is_empty(), + "a delivered event must not survive into a later response" + ); +} + +#[tokio::test] +async fn the_notification_body_is_exactly_the_closed_safe_shape() { + let delivered = scoped(async { + set_active_level(Some(LogLevel::Debug)); + set_sse_acceptable(); + note(LogLevel::Warning, EVENT_REJECTED, "invalid_params"); + take_notifications() + }) + .await; + assert_eq!( + delivered, + vec![json!({ + "jsonrpc": "2.0", + "method": "notifications/message", + "params": { + "level": "warning", + "logger": "crank-mcp-server", + "data": {"event": "mcp.request.rejected", "outcome": "invalid_params"} + } + })], + "`params` carries only the severity, the fixed logger name and the closed data object" + ); + // A notification has no `id`, so it can never be mistaken for a response. + assert!(delivered[0].get("id").is_none()); +} + +#[test] +fn the_modern_level_is_read_from_the_pinned_meta_key_only() { + let modern = |meta: Value| json!({"jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {"_meta": meta}}); + assert_eq!( + modern_request_level(&modern( + json!({ "io.modelcontextprotocol/logLevel": "error" }) + )), + Some(LogLevel::Error) + ); + // Not opted in: an absent key, a non-string value and an unknown literal are all "no level". + assert_eq!(modern_request_level(&modern(json!({}))), None); + assert_eq!( + modern_request_level(&modern(json!({ "io.modelcontextprotocol/logLevel": 7 }))), + None + ); + assert_eq!( + modern_request_level(&modern( + json!({ "io.modelcontextprotocol/logLevel": "verbose" }) + )), + None + ); + // A level under another key is not the pinned carrier. + assert_eq!( + modern_request_level(&modern(json!({ "logLevel": "error" }))), + None + ); + assert_eq!( + modern_request_level(&json!({"jsonrpc": "2.0", "id": 1, "method": "tools/list"})), + None + ); +} + +#[test] +fn the_command_records_the_level_of_its_own_session_only() { + let store = LogLevelStore::new(); + store.set("other-session", LogLevel::Debug); + let command: SetLevelCommand = + serde_json::from_value(json!({ "level": "critical" })).expect("a pinned level parses"); + let outcome = handle_logging_command(&store, "this-session", command); + assert!(matches!( + outcome, + LoggingOutcome::Applied(LogLevel::Critical) + )); + assert_eq!(store.get("this-session"), Some(LogLevel::Critical)); + assert_eq!( + store.get("other-session"), + Some(LogLevel::Debug), + "setting one session's level must never change another client's level" + ); + + // A malformed level changes nothing. + let malformed: SetLevelCommand = + serde_json::from_value(json!({ "level": "verbose" })).expect("the shape parses"); + assert!(matches!( + handle_logging_command(&store, "this-session", malformed), + LoggingOutcome::InvalidParams(INVALID_LEVEL) + )); + assert_eq!(store.get("this-session"), Some(LogLevel::Critical)); +} diff --git a/crates/crank-community-mcp/src/protocol/mod.rs b/crates/crank-community-mcp/src/protocol/mod.rs index 25610e5..147488f 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 logging; mod prompts; mod registry; mod resources; @@ -35,6 +36,11 @@ pub(crate) use command::{ ToolsListCommand, ToolsOutcome, handle_tools_command, }; pub(crate) use completion::{CompletionCommand, CompletionOutcome, handle_completion_command}; +pub(crate) use logging::{ + EVENT_FAILED, EVENT_LEVEL_APPLIED, EVENT_REJECTED, EVENT_SERVED, INVALID_LEVEL, LogLevel, + LogLevelStore, LoggingOutcome, SetLevelCommand, handle_logging_command, modern_request_level, + note, scoped as logging_scope, set_active_level, set_sse_acceptable, take_notifications, +}; pub(crate) use prompts::{ PromptGetCommand, PromptsCommand, PromptsListCommand, PromptsOutcome, handle_prompts_command, }; diff --git a/crates/crank-community-mcp/src/protocol/registry.rs b/crates/crank-community-mcp/src/protocol/registry.rs index 198be78..8dd9d4b 100644 --- a/crates/crank-community-mcp/src/protocol/registry.rs +++ b/crates/crank-community-mcp/src/protocol/registry.rs @@ -22,6 +22,15 @@ pub(crate) enum CapabilityId { Prompts, /// Bounded argument completion for bound Published Prompts and Resource templates (Story 3.17). Completions, + /// `logging` server capability: safe structured `notifications/message` events of the negotiated + /// client context (Story 3.18). Advertised in both revisions; the pinned modern revision carries + /// the level per request in `_meta` and marks the capability deprecated (SEP-2577). + Logging, + /// `logging/setLevel` as the *legacy* client request that sets a session level. It is a + /// dispatch-only registration without an advertisement fragment because the pinned modern + /// revision has no such method: there the per-request `_meta` key replaces it, so the same wire + /// name is a wrong-era request and must never be served. + LoggingSetLevel, Ping, Discovery, LegacyLifecycle, @@ -81,6 +90,10 @@ pub(crate) enum MethodHandler { /// `completion/complete`: bounded suggestions from the typed schema of one exact bound Prompt /// argument or one exact bound Resource template parameter (Story 3.17). Completion, + /// `logging/setLevel`: validate the pinned level and record it for this legacy session, so the + /// adapter can deliver safe structured `notifications/message` events of that context + /// (Story 3.18). The handler never widens the accepted vocabulary and never echoes the input. + LoggingSetLevel, Ping, Discover, Lifecycle, @@ -382,6 +395,33 @@ pub(crate) const CAPABILITY_DESCRIPTORS: &[CapabilityIdDescriptor] = &[ advertised: Some(("completions", &[])), revisions: MODERN_AND_LEGACY, }, + CapabilityIdDescriptor { + // Story 3.18: the standard `logging` declaration of both approved revisions. The pinned + // modern revision marks it deprecated (SEP-2577) but keeps it in the schema for at least + // twelve months, and `notifications/message` remains the only log channel there; the legacy + // revision additionally serves `logging/setLevel`. + id: CapabilityId::Logging, + roster: Roster::Server, + kind: Kind::Capability, + extension: None, + deprecated: None, + // The pinned schema declares `logging` as an open object with no named sub-features. + sub_features: FeatureSet(&[]), + advertised: Some(("logging", &[])), + revisions: MODERN_AND_LEGACY, + }, + CapabilityIdDescriptor { + // Dispatch-only registration of the legacy `logging/setLevel` request: it is a client + // request, not an advertised server capability, and it does not exist in the modern schema. + id: CapabilityId::LoggingSetLevel, + roster: Roster::Server, + kind: Kind::Method, + extension: None, + deprecated: None, + sub_features: FeatureSet(&[]), + advertised: None, + revisions: LEGACY_ONLY, + }, CapabilityIdDescriptor { id: CapabilityId::Ping, roster: Roster::Server, @@ -486,6 +526,16 @@ pub(crate) const METHOD_DESCRIPTORS: &[MethodDescriptor] = &[ required_headers: HEADERS_METHOD_ONLY, handler: MethodHandler::Completion, }, + MethodDescriptor { + // Story 3.18: the legacy client request that sets the log level of its session. It declares + // the level, not a server-side name, so only the method header applies; the pinned modern + // revision has no such method at all (per-request `_meta` replaces it). + name: "logging/setLevel", + capability: CapabilityId::LoggingSetLevel, + kind: Kind::Method, + required_headers: HEADERS_METHOD_ONLY, + handler: MethodHandler::LoggingSetLevel, + }, MethodDescriptor { name: "ping", capability: CapabilityId::Ping, diff --git a/crates/crank-community-mcp/src/protocol/registry_tests.rs b/crates/crank-community-mcp/src/protocol/registry_tests.rs index 4fc7071..6534ee5 100644 --- a/crates/crank-community-mcp/src/protocol/registry_tests.rs +++ b/crates/crank-community-mcp/src/protocol/registry_tests.rs @@ -36,6 +36,7 @@ fn static_registration_is_unique_and_advertises_only_the_registered_capability() registry.advertised_capabilities(revision), json!({ "completions": {}, + "logging": {}, "prompts": {"listChanged": false}, "resources": {"listChanged": false, "subscribe": false}, "tools": {"listChanged": false} @@ -46,6 +47,7 @@ fn static_registration_is_unique_and_advertises_only_the_registered_capability() advertised_server_capabilities(revision), json!({ "completions": {}, + "logging": {}, "prompts": {"listChanged": false}, "resources": {"listChanged": false, "subscribe": false}, "tools": {"listChanged": false} @@ -259,6 +261,7 @@ fn an_inert_test_descriptor_changes_both_projections_and_is_never_registered_in_ without.advertised_capabilities(MODERN_PROTOCOL_VERSION), json!({ "completions": {}, + "logging": {}, "prompts": {"listChanged": false}, "resources": {"listChanged": false, "subscribe": false}, "tools": {"listChanged": false} @@ -269,6 +272,7 @@ fn an_inert_test_descriptor_changes_both_projections_and_is_never_registered_in_ json!({ "inert_test_capability": {"enabled": true}, "completions": {}, + "logging": {}, "prompts": {"listChanged": false}, "resources": {"listChanged": false, "subscribe": false}, "tools": {"listChanged": false} @@ -279,6 +283,7 @@ fn an_inert_test_descriptor_changes_both_projections_and_is_never_registered_in_ json!({ "inert_test_capability": {"enabled": true}, "completions": {}, + "logging": {}, "prompts": {"listChanged": false}, "resources": {"listChanged": false, "subscribe": false}, "tools": {"listChanged": false} @@ -462,6 +467,7 @@ fn a_single_era_descriptor_never_leaks_into_the_other_era_advertisement() { other_era_advertisement, json!({ "completions": {}, + "logging": {}, "prompts": {"listChanged": false}, "resources": {"listChanged": false, "subscribe": false}, "tools": {"listChanged": false} @@ -654,6 +660,56 @@ fn story317_completion_is_advertised_and_dispatchable_in_both_revisions() { ); } +#[test] +fn story318_logging_is_advertised_on_both_revisions_and_set_level_is_legacy_only() { + let registry = production_registry(); + for revision in [MODERN_PROTOCOL_VERSION, LEGACY_PROTOCOL_VERSION] { + assert!( + registry.advertise_for(CapabilityId::Logging, revision), + "the implemented logging surface must be advertised in {revision}" + ); + assert_eq!( + registry.advertised_capabilities(revision)["logging"], + json!({}), + "the pinned advertisement is an empty `logging` object in {revision}" + ); + } + + // `logging/setLevel` is a legacy request only: the pinned modern revision replaces it with the + // per-request `_meta` log level, so the modern era must never serve it. + assert_eq!( + registry.dispatch_decision("logging/setLevel", LEGACY_PROTOCOL_VERSION), + DispatchDecision::Allowed { + handler: MethodHandler::LoggingSetLevel, + kind: Kind::Method, + } + ); + assert_eq!( + registry.dispatch_decision("logging/setLevel", MODERN_PROTOCOL_VERSION), + DispatchDecision::WrongEra { + handler: MethodHandler::LoggingSetLevel, + kind: Kind::Method, + }, + "a method the modern schema does not declare must never reach a handler there" + ); + let descriptor = METHOD_DESCRIPTORS + .iter() + .find(|descriptor| descriptor.name == "logging/setLevel") + .expect("logging/setLevel is a registered method"); + assert_eq!( + descriptor.required_headers.0, + &["Mcp-Method"], + "the request declares a level, not a server-side name" + ); + assert!( + CAPABILITY_DESCRIPTORS + .iter() + .filter(|descriptor| descriptor.id == CapabilityId::LoggingSetLevel) + .all(|descriptor| descriptor.advertised.is_none()), + "the client request must never be advertised as a server capability" + ); +} + #[test] fn adding_and_removing_a_method_descriptor_changes_the_dispatch_decision() { // The inert capability owns one inert method. With the method descriptor registered the @@ -702,6 +758,7 @@ fn adding_and_removing_a_method_descriptor_changes_the_dispatch_decision() { json!({ "inert_test_capability": {"enabled": true}, "completions": {}, + "logging": {}, "prompts": {"listChanged": false}, "resources": {"listChanged": false, "subscribe": false}, "tools": {"listChanged": false} diff --git a/crates/crank-community-mcp/src/transport.rs b/crates/crank-community-mcp/src/transport.rs index 7b938f0..d20c41a 100644 --- a/crates/crank-community-mcp/src/transport.rs +++ b/crates/crank-community-mcp/src/transport.rs @@ -116,6 +116,19 @@ fn accepted_media_types(headers: &HeaderMap) -> Option> { ) } +/// Whether this request offered `text/event-stream`. +/// +/// Story 3.18: the SSE response stream is the only carrier of a server `notifications/message`, so +/// the logging projection asks this before it promises a notification. It is the same admission rule +/// the response-mode negotiation already applies, not a second interpretation of the header. +pub(super) fn accepts_event_stream(headers: &HeaderMap) -> bool { + accepted_media_types(headers).is_some_and(|media_types| { + media_types + .iter() + .any(|media_type| media_type == "text/event-stream") + }) +} + pub(super) fn negotiate_post_response_mode( headers: &HeaderMap, ) -> Result { @@ -266,8 +279,26 @@ pub(super) fn transport_response( protocol_version: Option<&str>, ) -> Response { let outcome = payload_outcome(&payload); + // Story 3.18: this is the single projection point of the adapter's own safe structured event. + // The severity is derived from the already-decided outcome of the payload, so no request payload, + // credential, error cause or user value is read here. + note_logging_outcome(&payload); + let notifications = crate::protocol::take_notifications(); + // A pending `notifications/message` has no carrier in a JSON body. When the client offered both + // media types and opted in to logging, the negotiated mode is the SSE stream, so the notification + // precedes the response instead of being silently dropped. + let response_mode = if notifications.is_empty() { + response_mode + } else { + ResponseMode::Sse + }; if status == StatusCode::OK && matches!(response_mode, ResponseMode::Sse) { - let stream = stream::iter([Ok(Event::default().data(payload.to_string()))]); + let mut messages = Vec::with_capacity(notifications.len() + 1); + for notification in notifications { + messages.push(Ok(Event::default().data(notification.to_string()))); + } + messages.push(Ok(Event::default().data(payload.to_string()))); + let stream = stream::iter(messages); let mut response = sse_response(status, stream, session_id, protocol_version); if let Some(outcome) = outcome { @@ -279,6 +310,33 @@ pub(super) fn transport_response( json_response(status, payload, session_id, protocol_version) } +/// Record the closed safe event of one response: served, rejected as invalid, failed, or a tool-level +/// error. Every label is a fixed string of the closed vocabulary; nothing from the payload or the +/// request is copied into it. +fn note_logging_outcome(payload: &Value) { + use crate::protocol::{EVENT_FAILED, EVENT_REJECTED, EVENT_SERVED, LogLevel, note}; + if payload.get("error").is_some() { + match payload.pointer("/error/code").and_then(Value::as_i64) { + // The pinned client-error codes: a malformed request, a method that this era does not + // implement, and invalid params. The client can correct all three, so they are a + // rejection rather than a server failure; the closed label stays the one client-error + // label of the vocabulary instead of growing a new one. + Some(-32602..=-32600) => note(LogLevel::Warning, EVENT_REJECTED, "invalid_params"), + _ => note(LogLevel::Error, EVENT_FAILED, "internal"), + } + return; + } + if payload + .pointer("/result/isError") + .and_then(Value::as_bool) + .unwrap_or(false) + { + note(LogLevel::Warning, EVENT_REJECTED, "tool_error"); + return; + } + note(LogLevel::Info, EVENT_SERVED, "ok"); +} + fn payload_outcome(payload: &Value) -> Option { if payload.get("error").is_some() { return Some(McpOutcome::JsonRpcError); diff --git a/docs/capability-baseline/manifest.json b/docs/capability-baseline/manifest.json index 78fab21..cbcf2dc 100644 --- a/docs/capability-baseline/manifest.json +++ b/docs/capability-baseline/manifest.json @@ -3,7 +3,7 @@ { "kind": "inventory", "path": "docs/capability-inventory.json", - "sha256": "96589e25b7a3247f633fba2b031910e2ed4355d9ce8d29c7641638217800de0d" + "sha256": "85970569edd1b658a6cea4444c796efabe166a6833787c7e98249f20a1eaf29d" }, { "kind": "required_surfaces", diff --git a/docs/capability-inventory.json b/docs/capability-inventory.json index ad2efdf..e06c41b 100644 --- a/docs/capability-inventory.json +++ b/docs/capability-inventory.json @@ -884,26 +884,28 @@ "surface": "experimental" }, { - "advertised": null, + "advertised": { + "logging": {} + }, "applicability": "stable", "evidence_target": "logging", "fallback": "capability not advertised, request not dispatched", "kind": "capability", "open_subfeatures": false, - "owner": "story 3.18", + "owner": "community-release", "per_revision": { "2026-07-28": { "applicability": "deprecated" } }, - "reason": "safe MCP server logging is owned by story 3.18 (FR-19); the capability is deprecated in the pinned 2026-07-28 revision and remains present in the legacy revision", + "reason": "safe MCP server logging is implemented (Story 3.18, FR-19); the capability is deprecated in the pinned 2026-07-28 revision, where the per-request `_meta` log level replaces logging/setLevel, and present in the legacy revision, where logging/setLevel is served", "requirement": "FR-19", "revisions": [ "2026-07-28", "2025-11-25" ], "role": "server", - "status": "deferred", + "status": "supported", "subfeatures": [], "surface": "logging" }, @@ -1366,14 +1368,14 @@ "fallback": "capability not advertised, request not dispatched", "kind": "method", "open_subfeatures": false, - "owner": "story 3.18", - "reason": "safe MCP server logging is owned by story 3.18 (FR-19); the pinned modern revision replaces this method with a per-request log level", + "owner": "community-release", + "reason": "served in the legacy revision by Story 3.18 (FR-19): the level is validated against the pinned LoggingLevel union and recorded for the client session; the pinned modern revision replaces this method with the per-request `_meta` log level, so the same wire name is a wrong-era request there", "requirement": "FR-19", "revisions": [ "2025-11-25" ], "role": "client", - "status": "deferred", + "status": "supported", "subfeatures": [], "surface": "logging/setLevel" }, @@ -1692,20 +1694,20 @@ "fallback": "capability not advertised, request not dispatched", "kind": "notification", "open_subfeatures": false, - "owner": "story 3.18", + "owner": "community-release", "per_revision": { "2026-07-28": { "applicability": "deprecated" } }, - "reason": "safe MCP server logging is owned by story 3.18 (FR-19); the notification is deprecated in the pinned 2026-07-28 revision, where a request opts in per request", + "reason": "emitted by the adapter since Story 3.18 (FR-19) from a closed safe vocabulary only; still declared (deprecated) in the pinned 2026-07-28 revision, where a request opts in through `_meta`", "requirement": "FR-19", "revisions": [ "2026-07-28", "2025-11-25" ], "role": "server", - "status": "deferred", + "status": "supported", "subfeatures": [], "surface": "notifications/message" }, diff --git a/scripts/ci-story-checks.sh b/scripts/ci-story-checks.sh index 8db715d..7ecc8d0 100755 --- a/scripts/ci-story-checks.sh +++ b/scripts/ci-story-checks.sh @@ -33,3 +33,9 @@ run_atdd() { run_atdd "MCP prompt composition" -p mcp-server --test integration mcp_prompts::composition -- --test-threads=1 run_atdd "MCP completion" -p mcp-server --test integration mcp_completion -- --test-threads=1 run_atdd "bound template resources/list regression" -p mcp-server --test integration static_resources::list::list_stays_available_when_a_published_template_is_bound -- --test-threads=1 + +# Story 3.18: safe structured logging — the closed level vocabulary, the endpoint ATDD, and the +# capability projection the `logging` surface changes. +run_atdd "MCP log level vocabulary" -p crank-community-mcp --lib protocol::logging -- --test-threads=1 +run_atdd "MCP safe logging" -p mcp-server --test integration mcp_logging -- --test-threads=1 +run_atdd "capability inventory projection" -p mcp-server --test integration inventory_projection -- --test-threads=1 diff --git a/tests/fixtures/mcp-revisions/2025-11-25-advertised-capabilities.frozen.json b/tests/fixtures/mcp-revisions/2025-11-25-advertised-capabilities.frozen.json index 7159eb8..43455ef 100644 --- a/tests/fixtures/mcp-revisions/2025-11-25-advertised-capabilities.frozen.json +++ b/tests/fixtures/mcp-revisions/2025-11-25-advertised-capabilities.frozen.json @@ -1 +1 @@ -{"completions":{},"prompts":{"listChanged":false},"resources":{"listChanged":false,"subscribe":false},"tools":{"listChanged":false}} \ No newline at end of file +{"completions":{},"logging":{},"prompts":{"listChanged":false},"resources":{"listChanged":false,"subscribe":false},"tools":{"listChanged":false}} \ No newline at end of file diff --git a/tests/fixtures/mcp-revisions/2025-11-25-advertised-capabilities.provenance.json b/tests/fixtures/mcp-revisions/2025-11-25-advertised-capabilities.provenance.json index 04b5913..a8f60ba 100644 --- a/tests/fixtures/mcp-revisions/2025-11-25-advertised-capabilities.provenance.json +++ b/tests/fixtures/mcp-revisions/2025-11-25-advertised-capabilities.provenance.json @@ -1,9 +1,14 @@ { "revision": "2025-11-25", "inventory_path": "docs/capability-inventory.json", - "inventory_sha256": "96589e25b7a3247f633fba2b031910e2ed4355d9ce8d29c7641638217800de0d", + "inventory_sha256": "85970569edd1b658a6cea4444c796efabe166a6833787c7e98249f20a1eaf29d", "rule": "remaining-ac-spec.md#5-server-only-projection-rules-1-4", "projection_inputs": [ + { + "role": "server", + "kind": "capability", + "surface": "logging" + }, { "role": "server", "kind": "capability", diff --git a/tests/fixtures/mcp-revisions/2026-07-28-advertised-capabilities.frozen.json b/tests/fixtures/mcp-revisions/2026-07-28-advertised-capabilities.frozen.json index 7159eb8..43455ef 100644 --- a/tests/fixtures/mcp-revisions/2026-07-28-advertised-capabilities.frozen.json +++ b/tests/fixtures/mcp-revisions/2026-07-28-advertised-capabilities.frozen.json @@ -1 +1 @@ -{"completions":{},"prompts":{"listChanged":false},"resources":{"listChanged":false,"subscribe":false},"tools":{"listChanged":false}} \ No newline at end of file +{"completions":{},"logging":{},"prompts":{"listChanged":false},"resources":{"listChanged":false,"subscribe":false},"tools":{"listChanged":false}} \ No newline at end of file diff --git a/tests/fixtures/mcp-revisions/2026-07-28-advertised-capabilities.provenance.json b/tests/fixtures/mcp-revisions/2026-07-28-advertised-capabilities.provenance.json index 0486934..eaa125f 100644 --- a/tests/fixtures/mcp-revisions/2026-07-28-advertised-capabilities.provenance.json +++ b/tests/fixtures/mcp-revisions/2026-07-28-advertised-capabilities.provenance.json @@ -1,9 +1,14 @@ { "revision": "2026-07-28", "inventory_path": "docs/capability-inventory.json", - "inventory_sha256": "96589e25b7a3247f633fba2b031910e2ed4355d9ce8d29c7641638217800de0d", + "inventory_sha256": "85970569edd1b658a6cea4444c796efabe166a6833787c7e98249f20a1eaf29d", "rule": "remaining-ac-spec.md#5-server-only-projection-rules-1-4", "projection_inputs": [ + { + "role": "server", + "kind": "capability", + "surface": "logging" + }, { "role": "server", "kind": "capability", diff --git a/tests/fixtures/mcp-revisions/expected-advertised-capabilities.json b/tests/fixtures/mcp-revisions/expected-advertised-capabilities.json index aaf76bf..e2fc569 100644 --- a/tests/fixtures/mcp-revisions/expected-advertised-capabilities.json +++ b/tests/fixtures/mcp-revisions/expected-advertised-capabilities.json @@ -1,9 +1,10 @@ { "oracle": "crank-current-scope-advertised-capabilities", "note": "Independent expected projection of the capability descriptor the CURRENT scope is allowed to advertise: advertisement equals what is implemented. Later capabilities are deferred and must not appear until their owning story implements them. This is a scoped projection, not the official MCP capability list.", - "expected_keys": ["completions", "prompts", "resources", "tools"], + "expected_keys": ["completions", "logging", "prompts", "resources", "tools"], "expected_descriptor": { "completions": {}, + "logging": {}, "prompts": { "listChanged": false }, @@ -18,7 +19,6 @@ "must_not_be_advertised": ["experimental", "extensions"], "deferred_with_owner": { "change_signals": "story 3.19 (FR-19)", - "io.modelcontextprotocol/tasks": "story 4.7", - "logging": "story 3.18 (FR-19)" + "io.modelcontextprotocol/tasks": "story 4.7" } } diff --git a/tests/unit/test_project_advertised_capabilities.py b/tests/unit/test_project_advertised_capabilities.py index 66bea33..af50b61 100644 --- a/tests/unit/test_project_advertised_capabilities.py +++ b/tests/unit/test_project_advertised_capabilities.py @@ -47,13 +47,12 @@ EXPECTED_FROZEN = ( b'{"resources":{"listChanged":false,"subscribe":false},"tools":{"listChanged":false}}' ) EXPECTED_SHA256 = "e38c795fc28fee74168cb045427df55d882f8f7ace206af5c9a3ca4df5892c9a" -# The canonical inventory implements the completions/prompts/resources/tools surfaces, so the committed -# oracle and the canonical projection carry exactly those four; the logging surface is still deferred -# to its owning story and must not appear in the advertisement. +# The canonical inventory also implements the logging surface (Story 3.18, FR-19), so the committed +# oracle and the canonical projection carry `logging` next to `completions`/`prompts`/`resources`/`tools`. COMMITTED_FROZEN = ( - b'{"completions":{},"prompts":{"listChanged":false},"resources":{"listChanged":false,"subscribe":false},"tools":{"listChanged":false}}' + b'{"completions":{},"logging":{},"prompts":{"listChanged":false},"resources":{"listChanged":false,"subscribe":false},"tools":{"listChanged":false}}' ) -COMMITTED_SHA256 = "08c29e3df2bd8ffc58c1ec172714cc06031c5b279ef042940a8591940aca91fe" +COMMITTED_SHA256 = "f806e750402d418b8a3784eff200338cd8fd91b69c2f99e9d564cb08217b84d2" class AdvertisedCapabilitiesProjectionTests(unittest.TestCase): @@ -294,6 +293,7 @@ class AdvertisedCapabilitiesProjectionTests(unittest.TestCase): ), [ ("server", "capability", "completions"), + ("server", "capability", "logging"), ("server", "capability", "prompts"), ("server", "capability", "resources"), ("server", "capability", "tools"), @@ -332,6 +332,7 @@ class CommittedFrozenOracleTests(unittest.TestCase): ), [ ("server", "capability", "completions"), + ("server", "capability", "logging"), ("server", "capability", "prompts"), ("server", "capability", "resources"), ("server", "capability", "tools"), diff --git a/tests/unit/test_story31_foundation_boundaries.py b/tests/unit/test_story31_foundation_boundaries.py index c173815..e6a4431 100644 --- a/tests/unit/test_story31_foundation_boundaries.py +++ b/tests/unit/test_story31_foundation_boundaries.py @@ -1276,9 +1276,9 @@ class Story31FoundationProjectionBoundaryTests(unittest.TestCase): """ EXPECTED_FROZEN = ( - b'{"completions":{},"prompts":{"listChanged":false},"resources":{"listChanged":false,"subscribe":false},"tools":{"listChanged":false}}' + b'{"completions":{},"logging":{},"prompts":{"listChanged":false},"resources":{"listChanged":false,"subscribe":false},"tools":{"listChanged":false}}' ) - EXPECTED_FROZEN_SHA256 = "08c29e3df2bd8ffc58c1ec172714cc06031c5b279ef042940a8591940aca91fe" + EXPECTED_FROZEN_SHA256 = "f806e750402d418b8a3784eff200338cd8fd91b69c2f99e9d564cb08217b84d2" def test_control_committed_frozen_oracle_is_the_canonical_projection(self) -> None: """Positive control (existing GREEN, AT-13): the committed frozen bytes are canonical."""