//! The MCP transport endpoint: `GET`/`DELETE`/`POST` on the agent route, the session and //! response-mode negotiation at the HTTP level and the entry into the modern dispatch. //! //! Moved verbatim out of `app.rs` (Story 3.6, kanban t_987bf309); `mcp_post_response` is reached from //! `build_app_inner` via `mcp_post`, hence `pub(super)`. No behaviour changed. //! //! The legacy-era dispatch itself lives in `super::legacy_dispatch` (Story 3.18 code-health, kanban //! t_d1b45ddc) to keep this transport entry file inside the 1000-line limit. use super::metrics::{ActiveStreamGuard, McpRequestMetrics}; use super::stages::{enforce_traced_rate_limit, require_traced_machine_access}; use crate::{ jsonrpc::{jsonrpc_error, method_name, request_id}, protocol::{ EnvelopeKind, RequestEra, ambiguous_session_carrier_response, resolve_request_identity, }, rate_limit::{rate_limited_jsonrpc_response, rate_limited_status_response}, request_context::RequestContext, transport::{ ResponseMode, 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::{ Json, extract::{Extension, Path, State, rejection::JsonRejection}, http::{HeaderMap, StatusCode}, response::{IntoResponse, Response}, }; use crank_core::{CorrelationContext, PlatformApiKeyScope}; use serde_json::Value; use std::{sync::Arc, time::Duration, time::Instant}; use tracing::info; use super::dispatch::handle_modern_request; use super::{AgentRoutePath, AppState, TRANSPORT_SESSION_TTL_MS}; pub(super) async fn mcp_get( Path(path): Path, State(state): State>, headers: HeaderMap, ) -> Response { if let Err(status) = validate_origin(&state.allowed_origins, &headers) { return status.into_response(); } if let Err(status) = validate_get_accept_header(&headers) { return status.into_response(); } if let Err(status) = require_traced_machine_access(&state, &path, &headers, PlatformApiKeyScope::Read).await { return status.into_response(); } // Identity admission runs before the session-keyed rate accounting: an explicit modern identity has // no session to stream (matrix row 20 answers `405`), and an unknown, withdrawn or ambiguous // revision — including a conflicting duplicate session carrier — is a safe admission error. A // rejected request must not consume the legitimate legacy bucket or reach the session store. if let Err(response) = crate::protocol::session_lifecycle_admission(&headers) { return *response; } let session_id = match session_id_from_headers(&headers) { Ok(Some(session_id)) => session_id, Ok(None) => return StatusCode::BAD_REQUEST.into_response(), Err(status) => return status.into_response(), }; if let Err(rejection) = enforce_traced_rate_limit(&state, &path, &headers).await { return rate_limited_status_response(rejection); } let Some(session) = (match state.sessions.get(&session_id).await { Ok(session) => session, Err(_) => return StatusCode::INTERNAL_SERVER_ERROR.into_response(), }) else { return StatusCode::NOT_FOUND.into_response(); }; if session.workspace_slug != path.workspace_slug || session.agent_slug != path.agent_slug { return StatusCode::NOT_FOUND.into_response(); } // A persisted session whose negotiated revision is no longer supported is never served, even when // the request carries no version header (protocol era matrix row 15: safe error, `405` belongs to // the modern identity of row 20). The session state stays intact. if let Err(status) = crate::protocol::validate_session_revision(&session) { return status.into_response(); } if !session.initialized { return StatusCode::BAD_REQUEST.into_response(); } if let Err(status) = validate_session_protocol_version(&headers, &session.protocol_version) { return status.into_response(); } let Ok(permit) = ActiveStreamGuard::try_acquire(&state.session_slots) else { return StatusCode::TOO_MANY_REQUESTS.into_response(); }; // Story 3.19: the pinned legacy transport forbids broadcasting one JSON-RPC message across the // SSE streams of a session, so exactly one admitted `GET` receives the Resource/Prompt/Tool // list-change signals. A newer `GET` takes them over and the older stream simply ends; a // `DELETE` retires the producer, so a stale generation never writes into a reconnect. let Some(generation) = state.signal_streams.admit(&session_id) else { // The bounded owner table is contended: refuse this admission instead of waiting. return StatusCode::TOO_MANY_REQUESTS.into_response(); }; let receiver = crate::protocol::spawn_signal_watch( Arc::clone(&state), crate::protocol::Watch { workspace_slug: path.workspace_slug.clone(), agent_slug: path.agent_slug.clone(), signals: crate::protocol::Signals::ALL, wire: crate::protocol::Wire::Legacy, legacy_stream: Some(( Arc::clone(&state.signal_streams), session_id.clone(), generation, )), deadline: Some(Instant::now() + Duration::from_millis(TRANSPORT_SESSION_TTL_MS)), }, ); // The stream permit lives in the response stream: a client that closes the SSE connection ends // the producer and releases the slot, and no signal is queued for a reader that is gone. let stream = crate::protocol::frames_stream(Vec::new(), receiver, permit); sse_response( StatusCode::OK, stream, Some(&session_id), Some(&session.protocol_version), ) } pub(super) async fn mcp_delete( Path(path): Path, State(state): State>, headers: HeaderMap, ) -> Response { if let Err(status) = require_traced_machine_access(&state, &path, &headers, PlatformApiKeyScope::Read).await { return status.into_response(); } // Identity admission and carrier validation run before the session-keyed rate accounting: a modern // identity must never terminate a legacy session, and a rejected request must not consume the // legitimate legacy bucket or reach the session store. if let Err(response) = crate::protocol::session_lifecycle_admission(&headers) { return *response; } let session_id = match session_id_from_headers(&headers) { Ok(Some(session_id)) => session_id, Ok(None) => return StatusCode::BAD_REQUEST.into_response(), Err(status) => return status.into_response(), }; if let Err(rejection) = enforce_traced_rate_limit(&state, &path, &headers).await { return rate_limited_status_response(rejection); } match state.sessions.get(&session_id).await { Ok(Some(session)) => { if session.workspace_slug != path.workspace_slug || session.agent_slug != path.agent_slug { return StatusCode::NOT_FOUND.into_response(); } // An unsupported persisted revision is never terminated as a live legacy session. if let Err(status) = crate::protocol::validate_session_revision(&session) { return status.into_response(); } match state.sessions.delete(&session_id).await { Ok(true) => { state.signal_streams.retire(&session_id); state.session_metrics.refresh(); StatusCode::NO_CONTENT.into_response() } Ok(false) => StatusCode::NOT_FOUND.into_response(), Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(), } } Ok(None) => StatusCode::NOT_FOUND.into_response(), Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(), } } pub(super) async fn mcp_post( Path(path): Path, State(state): State>, Extension(request_context): Extension, headers: HeaderMap, payload: Result, JsonRejection>, ) -> Response { let message = match payload { Ok(Json(message)) => message, Err(rejection) => { let mut request_metrics = McpRequestMetrics::invalid( request_context.started_at(), request_context.exemplar(), ); let response = rejection.into_response(); request_metrics.complete(&response); return with_request_id_header(response, request_context.request_id()); } }; let mut request_metrics = McpRequestMetrics::new( &message, request_context.started_at(), request_context.exemplar(), ); let transport_correlation = request_context.correlation; let transport_request_id = transport_correlation.request_id().to_string(); info!( name: "mcp.request.received", request_id = %transport_request_id, workspace_slug = %path.workspace_slug, agent_slug = %path.agent_slug, jsonrpc_method = method_name(&message).unwrap_or(""), "mcp request received" ); 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) } async fn mcp_post_response( path: &AgentRoutePath, state: Arc, headers: &HeaderMap, message: &Value, transport_correlation: &CorrelationContext, ) -> Response { // ADMISSION_ENTER (spec section 7.2): the external request entry, before any era resolution, // dispatch, service entry or outbound call. Test-only counter, no production effect. #[cfg(test)] crate::app::dispatch_observer::admission_enter(); if let Err(status) = validate_origin(&state.allowed_origins, headers) { return status.into_response(); } let mut response_mode = match negotiate_post_response_mode(headers) { 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 // the identity never has to guess and never sees a bare `400`. The precedence of this check is // unchanged (it still runs before era resolution and dispatch). `GET`/`DELETE` keep their own // session-lifecycle admission and are untouched. let request_session_id = match session_id_from_headers(headers) { Ok(session_id) => session_id, Err(_status) => return ambiguous_session_carrier_response(headers, message), }; // Responses ACK before era/session resolution, but must not bypass fresh credentials. // Method-bearing messages retain their existing scoped authorization path below. if message .as_object() .is_some_and(|object| !object.contains_key("method")) && let Err(error) = require_traced_machine_access(&state, path, headers, PlatformApiKeyScope::Read).await { return error.into_response(); } // Single JSON-RPC envelope guard: only a well-formed message reaches era resolution, dispatch, // approval or any outbound request. Syntactically valid JSON is not the same as a valid envelope. let envelope = match crate::protocol::validate_jsonrpc_envelope(message) { Ok(envelope) => envelope, Err(response) => return *response, }; if matches!(envelope, EnvelopeKind::Response) { return StatusCode::ACCEPTED.into_response(); } let identity = match resolve_request_identity(headers, message) { Ok(identity) => identity, Err(response) => return *response, }; let protocol_version = identity.version.clone(); // The modern revision is stateless: a session carrier is a conflicting identity and is rejected // here — before the rate-limit accounting, the session store and any dispatch — instead of being // silently ignored. if matches!(identity.era, RequestEra::Modern) && request_session_id.is_some() { return crate::protocol::modern_carrier_conflict_response(message); } let rate_limit_result = enforce_traced_rate_limit(&state, path, headers).await; if let Err(error) = rate_limit_result { return rate_limited_jsonrpc_response( message, response_mode, protocol_version .as_deref() .unwrap_or(crate::jsonrpc::LEGACY_PROTOCOL_VERSION), error, ); } if let Some(session_id) = request_session_id.as_deref() { let session = match state.sessions.get(session_id).await { Ok(session) => session, Err(_) => return StatusCode::INTERNAL_SERVER_ERROR.into_response(), }; if let Some(session) = session { // Same contract as the session-lifecycle methods: a persisted session that is no longer // operational under the supported legacy revision — because the request names another // revision, or because the session itself was negotiated on a withdrawn revision — is never // served, not even when the request omits the version header. The rejected request is // answered with the era-correct *legacy* structured error (matrix rows 15/16) instead of a // bare `400`: the modern `-32020`/`-32022` diagnostics describe a modern identity and are // not imposed on this legacy-sourced rejection (row 14). The persisted session stays // intact and no outbound call is made. if validate_session_protocol_version(headers, &session.protocol_version).is_err() || crate::protocol::validate_session_revision(&session).is_err() { return transport_response( StatusCode::BAD_REQUEST, jsonrpc_error( request_id(message), -32602, "the negotiated session revision is no longer supported", ), response_mode, None, None, ); } } } // 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, }; let access_result = require_traced_machine_access(&state, path, headers, required_scope).await; let credential = match access_result { Ok(credential) => credential, Err(error) => return error.into_response(), }; // Story 3.4 correction: the official SDK lists the media types JSON-first. For a `tools/call` // that carries a validated progress token and offered `text/event-stream`, the stream is the only // carrier that can deliver the progress the client asked for, so the media-type order is not a // preference for the JSON body here. Every other request — another method, no token, an unusable // token, a JSON-only `Accept` — keeps the negotiated mode, and no admission check moved. if matches!(response_mode, ResponseMode::Json) && method_name(message) == Some("tools/call") && accepts_event_stream(headers) && crate::app::lifecycle::token_from_meta(message.pointer("/params/_meta")).is_some() { response_mode = ResponseMode::Sse; } if matches!(identity.era, RequestEra::Modern) { // ERA_MODERN_ENTER (spec section 7.2): this request entered the modern era-adapter. #[cfg(test)] crate::app::dispatch_observer::era_modern_enter(); return handle_modern_request( &state, path, headers, message, response_mode, &identity, &credential, transport_correlation, ) .await; } // ERA_LEGACY_ENTER (spec section 7.2): this request entered the legacy era-adapter. #[cfg(test)] crate::app::dispatch_observer::era_legacy_enter(); // R5/F5: the owning registration decides which handler serves this method in the request's // revision; that legacy dispatch lives in `super::legacy_dispatch`. super::legacy_dispatch::handle_legacy_request( state, path, headers, message, response_mode, &identity, &credential, transport_correlation, ) .await }