//! 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; } }); } /// The request's logging context, carried into a streamed response body (Story 3.4). /// /// A streamed `tools/call` response is assembled after the request handler returned, so its terminal /// event would be projected outside the task-local scope of the request. This snapshot carries the /// only two facts the projection needs — the level the client opted in to and whether the request /// offered the SSE carrier — and never a request value. #[derive(Clone, Copy, Default)] pub(crate) struct CarriedScope { active: Option, sse_acceptable: bool, } /// Snapshot the scope of the request that is being served now. Outside a scope the snapshot is /// "not opted in", which delivers nothing. pub(crate) fn carry_scope() -> CarriedScope { REQUEST_LOG .try_with(|log| { let log = log.borrow(); CarriedScope { active: log.active, sse_acceptable: log.sse_acceptable, } }) .unwrap_or_default() } /// Run one step of the streamed response inside a scope carrying the request's logging context. pub(crate) async fn in_carried_scope(scope: CarriedScope, future: F) -> F::Output { REQUEST_LOG .scope( RefCell::new(RequestLog { active: scope.active, sse_acceptable: scope.sse_acceptable, pending: Vec::new(), }), future, ) .await } /// 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;