use std::{sync::Arc, time::Instant}; use axum::{http::header::CONTENT_TYPE, response::Response}; use crank_metrics::{ ExemplarTraceId, InFlightGuard, LimitStage, McpMethod, McpOutcome, McpResponseMode, record_limit_rejection, record_mcp_request_with_exemplar, }; use serde_json::Value; use tokio::sync::{OwnedSemaphorePermit, Semaphore}; use crate::jsonrpc::{is_notification, is_response, method_name}; pub(super) struct McpRequestMetrics { method: McpMethod, response_mode: McpResponseMode, outcome: McpOutcome, started_at: Instant, exemplar: Option, } impl McpRequestMetrics { pub(super) fn invalid(started_at: Instant, exemplar: Option) -> Self { Self { method: McpMethod::Invalid, response_mode: McpResponseMode::Unknown, outcome: McpOutcome::Aborted, started_at, exemplar, } } pub(super) fn new( message: &Value, started_at: Instant, exemplar: Option, ) -> Self { Self { method: normalized_mcp_method(message), response_mode: McpResponseMode::Unknown, outcome: McpOutcome::Aborted, started_at, exemplar, } } pub(super) fn complete(&mut self, response: &Response) { self.response_mode = response .headers() .get(CONTENT_TYPE) .and_then(|value| value.to_str().ok()) .map_or(McpResponseMode::Unknown, |content_type| { if content_type.starts_with("application/json") { McpResponseMode::Json } else if content_type.starts_with("text/event-stream") { McpResponseMode::Sse } else { McpResponseMode::Unknown } }); self.outcome = if response.status().is_success() { response .extensions() .get::() .copied() .unwrap_or_else(|| McpOutcome::from_http_status(response.status().as_u16())) } else { McpOutcome::from_http_status(response.status().as_u16()) }; } #[cfg(test)] pub(super) const fn outcome(&self) -> McpOutcome { self.outcome } #[cfg(test)] pub(super) const fn response_mode(&self) -> McpResponseMode { self.response_mode } } impl Drop for McpRequestMetrics { fn drop(&mut self) { record_mcp_request_with_exemplar( self.method, self.response_mode, self.outcome, self.started_at.elapsed(), self.exemplar, ); } } pub(super) fn normalized_mcp_method(message: &Value) -> McpMethod { match method_name(message) { Some("initialize") => McpMethod::Initialize, Some("notifications/initialized") => McpMethod::Initialized, Some("ping") => McpMethod::Ping, Some("tools/list") => McpMethod::ToolsList, Some("tools/call") => McpMethod::ToolsCall, Some(_) if is_notification(message) => McpMethod::Notification, Some(_) => McpMethod::Unsupported, None if is_response(message) => McpMethod::Response, None => McpMethod::Invalid, } } pub(super) struct ActiveStreamGuard { _permit: OwnedSemaphorePermit, _inflight: InFlightGuard, } impl ActiveStreamGuard { pub(super) fn try_acquire(slots: &Arc) -> Result { let permit = Arc::clone(slots).try_acquire_owned().map_err(|_| { record_limit_rejection(LimitStage::McpStream); })?; Ok(Self { _permit: permit, _inflight: InFlightGuard::mcp_stream(), }) } } #[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 ); } }