use std::{ io, sync::{Arc, Mutex}, }; use axum::body::to_bytes; use crank_core::InvocationStatus; use crank_metrics::{McpMethod, McpOutcome, McpResponseMode}; use crank_observability::{ ObservabilityConfig, OperationalIncident, RedactionLimits, ServiceIdentity, operational_incident_total, }; use crank_registry::{ InvocationHistoryLoss, InvocationHistoryLossCategory, InvocationHistoryWriteOutcome, }; use serde_json::{Value, json}; use tracing_subscriber::fmt::MakeWriter; use super::{ ResponseMode, metrics::{McpRequestMetrics, normalized_mcp_method}, observe_invocation_history_outcome, tool_error_response, }; use crate::jsonrpc::{CURRENT_PROTOCOL_VERSION, jsonrpc_error}; use crate::tool_error::{McpControlError, control_tool_error_contract}; use crate::transport::transport_response; #[tokio::test] async fn tool_error_response_includes_structured_context() { let message = json!({"jsonrpc": "2.0", "id": "req-1", "method": "tools/call"}); let mut request_metrics = McpRequestMetrics::new(&message, std::time::Instant::now(), None); let response = tool_error_response( &message, ResponseMode::Json, CURRENT_PROTOCOL_VERSION, control_tool_error_contract( McpControlError::CatalogRevisionChanged, "req-1", "0af7651916cd43dd8448eb211c80319c", crank_core::ExecutionLocale::Ru, ), ); assert_eq!( response.extensions().get::(), Some(&McpOutcome::ToolError) ); request_metrics.complete(&response); assert_eq!(request_metrics.outcome(), McpOutcome::ToolError); let body = to_bytes(response.into_body(), usize::MAX).await.unwrap(); let payload: Value = serde_json::from_slice(&body).unwrap(); assert_eq!( payload["result"]["structuredContent"]["error"], json!({ "code": "agent_catalog_result_stale", "error_code": "agent_catalog_result_stale", "message": "Версия каталога изменилась.", "stage": "authorization", "retryability": "after_delay", "outcome_certainty": "certain", "recoverable": true, "request_id": "req-1", "trace_id": "0af7651916cd43dd8448eb211c80319c", "suggested_action": "Повторите search_tools и вызовите инструмент с новой версией каталога." }) ); } #[test] fn jsonrpc_error_over_http_200_is_not_counted_as_success() { let message = json!({"jsonrpc": "2.0", "id": 1, "method": "unsupported"}); let mut request_metrics = McpRequestMetrics::new(&message, std::time::Instant::now(), None); let response = transport_response( axum::http::StatusCode::OK, jsonrpc_error(json!(1), -32601, "unsupported"), ResponseMode::Json, None, Some(CURRENT_PROTOCOL_VERSION), ); request_metrics.complete(&response); assert_eq!(request_metrics.outcome(), McpOutcome::JsonRpcError); } #[test] fn metric_uses_actual_json_response_when_sse_request_falls_back() { let message = json!({"jsonrpc": "2.0", "id": 1, "method": "unsupported"}); let mut request_metrics = McpRequestMetrics::new(&message, std::time::Instant::now(), None); let response = transport_response( axum::http::StatusCode::INTERNAL_SERVER_ERROR, jsonrpc_error(json!(1), -32603, "internal error"), ResponseMode::Json, None, Some(CURRENT_PROTOCOL_VERSION), ); request_metrics.complete(&response); assert_eq!(request_metrics.response_mode(), McpResponseMode::Json); assert_eq!(request_metrics.outcome(), McpOutcome::ServerError); } #[test] fn transport_failure_takes_priority_over_jsonrpc_payload() { let message = json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call"}); let mut request_metrics = McpRequestMetrics::new(&message, std::time::Instant::now(), None); let response = transport_response( axum::http::StatusCode::TOO_MANY_REQUESTS, jsonrpc_error(json!(1), -32000, "rate limited"), ResponseMode::Json, None, Some(CURRENT_PROTOCOL_VERSION), ); request_metrics.complete(&response); assert_eq!(request_metrics.outcome(), McpOutcome::ClientError); } #[test] fn unfinished_request_is_classified_as_aborted() { let message = json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call"}); let request_metrics = McpRequestMetrics::new(&message, std::time::Instant::now(), None); assert_eq!(request_metrics.response_mode(), McpResponseMode::Unknown); assert_eq!(request_metrics.outcome(), McpOutcome::Aborted); } #[test] fn emits_bounded_history_loss_incident() { let writer = SharedLogWriter::default(); let subscriber = crank_observability::build_subscriber( ObservabilityConfig::new( ServiceIdentity::try_new("mcp-server", "test", "test").unwrap(), "info", RedactionLimits::default(), ), writer.clone(), ) .unwrap(); let before = operational_incident_total(OperationalIncident::InvocationHistoryLost); let dispatch = tracing::Dispatch::new(subscriber); let _guard = tracing::dispatcher::set_default(&dispatch); observe_invocation_history_outcome( InvocationHistoryWriteOutcome::Lost(InvocationHistoryLoss { category: InvocationHistoryLossCategory::Unavailable, }), Some("req_mcp_dc08"), Some("0af7651916cd43dd8448eb211c80319c"), InvocationStatus::Ok, crank_core::InvocationSource::AgentToolCall, ); let output = writer.output(); assert!(!output.contains("dc08-canary-secret")); let event: Value = output .lines() .map(|line| serde_json::from_str(line).unwrap()) .find(|event: &Value| event["event"] == "mcp.invocation_history.lost") .unwrap(); assert_eq!(event["request_id"], "req_mcp_dc08"); assert_eq!(event["fields"]["source"], "agent_tool_call"); assert_eq!(event["fields"]["invocation_status"], "ok"); assert_eq!(event["fields"]["error_category"], "unavailable"); assert!(operational_incident_total(OperationalIncident::InvocationHistoryLost) > before); } #[test] fn mcp_metric_method_is_always_from_a_closed_set() { assert_eq!( normalized_mcp_method(&json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call"})), McpMethod::ToolsCall ); assert_eq!( normalized_mcp_method( &json!({"jsonrpc": "2.0", "id": 2, "method": "customer-controlled-method"}) ), McpMethod::Unsupported ); assert_eq!( normalized_mcp_method( &json!({"jsonrpc": "2.0", "method": "customer-controlled-notification"}) ), McpMethod::Notification ); } #[derive(Clone, Default)] struct SharedLogWriter { buffer: Arc>>, } impl SharedLogWriter { fn output(&self) -> String { String::from_utf8(self.buffer.lock().unwrap().clone()).unwrap() } } impl<'a> MakeWriter<'a> for SharedLogWriter { type Writer = SharedLogGuard; fn make_writer(&'a self) -> Self::Writer { SharedLogGuard { buffer: Arc::clone(&self.buffer), } } } struct SharedLogGuard { buffer: Arc>>, } impl io::Write for SharedLogGuard { fn write(&mut self, bytes: &[u8]) -> io::Result { self.buffer.lock().unwrap().extend_from_slice(bytes); Ok(bytes.len()) } fn flush(&mut self) -> io::Result<()> { Ok(()) } }