mcpspy 0.2.4

Zero-config stdio MCP proxy, latency profiler, and token usage auditor in Rust
Documentation
//! Self-inspecting MCP server over stdio (`mcpspy mcp`).

use anyhow::Result;
#[cfg(feature = "mcp")]
use mcpspy::core::db::TelemetryDb;
#[cfg(any(feature = "mcp", test))]
use mcpspy::core::models::{RecentCall, ServerSummary, ToolSummary};
#[cfg(feature = "mcp")]
use serde::Deserialize;
#[cfg(any(feature = "mcp", test))]
use serde_json::{Value, json};
#[cfg(feature = "mcp")]
use std::path::Path;

/// Build the JSON payload returned by the `get_mcp_stats` tool.
#[cfg(any(feature = "mcp", test))]
pub fn stats_payload(servers: &[ServerSummary], tools: &[ToolSummary], violations: i64) -> Value {
    json!({
        "servers": servers,
        "tools": tools,
        "schema_violations": violations,
    })
}

/// Build the JSON payload returned by the `get_slow_calls` tool.
#[cfg(any(feature = "mcp", test))]
pub fn slow_calls_payload(calls: &[RecentCall]) -> Value {
    json!({ "calls": calls })
}

#[cfg(feature = "mcp")]
mod server {
    use super::*;
    use rmcp::handler::server::wrapper::Parameters;
    use rmcp::{Json, ServerHandler, tool, tool_router};

    #[derive(Debug, Deserialize, schemars::JsonSchema)]
    pub struct StatsParams {
        /// Filter by server name.
        pub server: Option<String>,
        /// Time window in hours (default: 24).
        pub since_hours: Option<i64>,
    }

    #[derive(Debug, Deserialize, schemars::JsonSchema)]
    pub struct SlowParams {
        /// Maximum number of calls to return (default: 10).
        pub limit: Option<usize>,
        /// Filter by server name.
        pub server: Option<String>,
    }

    pub struct TelemetryServer {
        pub db: TelemetryDb,
    }

    #[tool_router]
    impl TelemetryServer {
        #[tool(
            description = "Get aggregated MCP telemetry: calls, tokens, latency and errors per server and tool"
        )]
        async fn get_mcp_stats(&self, Parameters(params): Parameters<StatsParams>) -> Json<Value> {
            let hours = params.since_hours.unwrap_or(24).max(0);
            let since = chrono::Utc::now().timestamp_millis() - hours * 3_600_000;
            let servers = self
                .db
                .server_summary(params.server.as_deref(), Some(since))
                .await
                .unwrap_or_default();
            let tools = self
                .db
                .tool_summary(params.server.as_deref(), Some(since))
                .await
                .unwrap_or_default();
            let violations = self
                .db
                .violation_count(params.server.as_deref(), Some(since))
                .await
                .unwrap_or_default();
            Json(stats_payload(&servers, &tools, violations))
        }

        #[tool(description = "Get the slowest recorded MCP calls with token counts")]
        async fn get_slow_calls(&self, Parameters(params): Parameters<SlowParams>) -> Json<Value> {
            let limit = params.limit.unwrap_or(10).clamp(1, 100);
            let mut calls = self
                .db
                .recent_calls(500, params.server.as_deref(), false)
                .await
                .unwrap_or_default();
            calls.sort_by(|a, b| {
                b.duration_ms
                    .partial_cmp(&a.duration_ms)
                    .unwrap_or(std::cmp::Ordering::Equal)
            });
            calls.truncate(limit);
            Json(slow_calls_payload(&calls))
        }
    }

    #[rmcp::tool_handler]
    impl ServerHandler for TelemetryServer {
        fn get_info(&self) -> rmcp::model::ServerConfig {
            use rmcp::model::{Implementation, ServerCapabilities, ServerConfig};
            ServerConfig::new(ServerCapabilities::builder().enable_tools().build())
                .with_server_info(Implementation::new("mcpspy", env!("CARGO_PKG_VERSION")))
                .with_instructions("Inspect mcpspy MCP traffic telemetry from this database.")
        }
    }

    /// Serve the telemetry MCP server over stdio until the client disconnects.
    pub async fn serve(db_path: &str) -> Result<()> {
        use rmcp::ServiceExt;
        use rmcp::transport::stdio;

        let db = TelemetryDb::open(Path::new(db_path))?;
        let service = TelemetryServer { db }
            .serve(stdio())
            .await
            .map_err(|e| anyhow::anyhow!("MCP service failed: {e}"))?;
        service
            .waiting()
            .await
            .map_err(|e| anyhow::anyhow!("MCP service error: {e}"))?;
        Ok(())
    }
}

/// Open the DB and run the self-inspecting MCP server on a Tokio runtime.
pub fn run(db_path: &str) -> Result<()> {
    #[cfg(feature = "mcp")]
    {
        let rt = tokio::runtime::Runtime::new()?;
        rt.block_on(server::serve(db_path))?;
        Ok(())
    }
    #[cfg(not(feature = "mcp"))]
    {
        let _ = db_path;
        anyhow::bail!("`mcp` requires the `mcp` feature")
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::{TimeZone, Utc};

    fn server(name: &str) -> ServerSummary {
        ServerSummary {
            server_name: name.into(),
            total_calls: 10,
            total_req_tokens: 1_200,
            total_resp_tokens: 3_400,
            avg_duration_ms: 12.5,
            p95_duration_ms: 45.0,
            p50_duration_ms: 12.5,
            error_count: 1,
        }
    }

    fn call(duration: f64) -> RecentCall {
        RecentCall {
            started_at: Utc.timestamp_millis_opt(1_700_000_000_000).unwrap(),
            server_name: "alpha".into(),
            method: "tools/call".into(),
            tool_name: Some("read_file".into()),
            duration_ms: duration,
            req_tokens: 100,
            resp_tokens: 200,
            is_error: false,
        }
    }

    #[test]
    fn stats_payload_contains_servers_and_tools() {
        let tools = vec![ToolSummary {
            server_name: "alpha".into(),
            tool_name: "read_file".into(),
            total_calls: 5,
            total_req_tokens: 600,
            total_resp_tokens: 1_700,
            avg_duration_ms: 8.0,
            p95_duration_ms: 20.0,
            p50_duration_ms: 12.5,
            error_count: 0,
        }];
        let val = stats_payload(&[server("alpha")], &tools, 4);
        assert_eq!(val["servers"][0]["server_name"], "alpha");
        assert_eq!(val["tools"][0]["tool_name"], "read_file");
        assert_eq!(val["schema_violations"], 4);
    }

    #[test]
    fn slow_calls_payload_contains_calls() {
        let val = slow_calls_payload(&[call(12.5)]);
        assert_eq!(val["calls"].as_array().unwrap().len(), 1);
        assert_eq!(val["calls"][0]["duration_ms"], 12.5);
    }
}