mcpspy 0.2.1

Zero-config stdio MCP proxy, latency profiler, and token usage auditor in Rust
Documentation
//! JSON-RPC 2.0 request/response correlator.
//!
//! Matches outbound requests (by `id`) with inbound responses so the
//! proxy can compute `duration_ms`, detect errors, and attribute
//! `tool_name` to each completed call. Phase 2 implementation.

use crate::models::PendingCall;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};

/// Thread-safe map of in-flight JSON-RPC calls keyed by their `id`.
/// Uses `Arc<Mutex<...>>` so the correlator can be cheaply cloned
/// into async tasks.
#[derive(Debug, Clone, Default)]
pub struct JsonRpcCorrelator {
    inner: Arc<Mutex<HashMap<String, PendingCall>>>,
}

impl JsonRpcCorrelator {
    /// Create a new empty correlator.
    pub fn new() -> Self {
        Self {
            inner: Arc::new(Mutex::new(HashMap::new())),
        }
    }

    /// Register a new outbound call.
    pub fn register(&self, id: String, call: PendingCall) {
        self.inner.lock().unwrap().insert(id, call);
    }

    /// Remove and return the pending call matching `id`, if any.
    pub fn match_response(&self, id: &str) -> Option<PendingCall> {
        self.inner.lock().unwrap().remove(id)
    }

    /// Number of in-flight calls.
    pub fn pending_count(&self) -> usize {
        self.inner.lock().unwrap().len()
    }
}

/// A schema violation found in a JSON-RPC 2.0 frame.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Violation {
    /// Machine-readable code, e.g. `bad_version`.
    pub code: &'static str,
    /// Human-readable detail for storage and reporting.
    pub detail: String,
}

fn violation(code: &'static str, detail: impl Into<String>) -> Violation {
    Violation {
        code,
        detail: detail.into(),
    }
}

/// Validate a parsed JSON-RPC 2.0 frame without mutating or blocking it.
///
/// An empty result means the frame is schema-valid. Validation is advisory:
/// the proxy always forwards the raw line even when violations are found.
pub fn validate_frame(value: &serde_json::Value) -> Vec<Violation> {
    let mut found = Vec::new();

    match value.get("jsonrpc").and_then(|v| v.as_str()) {
        Some("2.0") => {}
        Some(other) => found.push(violation("bad_version", format!("jsonrpc={other}"))),
        None => found.push(violation("missing_version", "jsonrpc field is missing")),
    }

    let has_method = value.get("method").is_some();
    let has_result = value.get("result").is_some();
    let has_error = value.get("error").is_some();

    if has_result && has_error {
        found.push(violation(
            "both_result_and_error",
            "response has both result and error",
        ));
    }

    if has_method {
        let empty = value
            .get("method")
            .and_then(|v| v.as_str())
            .map(str::is_empty)
            .unwrap_or(true);
        if empty {
            found.push(violation(
                "invalid_method",
                "method is missing or not a non-empty string",
            ));
        }
        if let Some(params) = value.get("params")
            && !params.is_object()
            && !params.is_array()
        {
            found.push(violation(
                "invalid_params",
                "params must be an object or array",
            ));
        }
    } else if !has_result && !has_error {
        found.push(violation(
            "unknown_frame_type",
            "frame has neither method, result, nor error",
        ));
    }

    if let Some(id) = value.get("id")
        && !matches!(
            id,
            serde_json::Value::String(_) | serde_json::Value::Number(_) | serde_json::Value::Null
        )
    {
        found.push(violation(
            "invalid_id",
            "id must be a string, number, or null",
        ));
    }

    found
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::time::Instant;

    #[test]
    fn register_and_match() {
        let c = JsonRpcCorrelator::new();
        c.register(
            "1".to_string(),
            PendingCall {
                started_at: Instant::now(),
                method: "tools/list".to_string(),
                tool_name: None,
                req_bytes: 10,
                req_tokens: 3,
                req_preview: None,
            },
        );
        assert_eq!(c.pending_count(), 1);

        let popped = c.match_response("1");
        assert!(popped.is_some());
        assert_eq!(popped.unwrap().method, "tools/list");

        // Already consumed
        assert!(c.match_response("1").is_none());
        assert_eq!(c.pending_count(), 0);
    }

    #[test]
    fn match_unknown_id_returns_none() {
        let c = JsonRpcCorrelator::new();
        assert!(c.match_response("nope").is_none());
    }

    #[test]
    fn correlator_is_cloneable() {
        let c1 = JsonRpcCorrelator::new();
        c1.register("1".to_string(), PendingCall::default());
        let c2 = c1.clone();
        assert_eq!(c2.pending_count(), 1);
        assert!(c2.match_response("1").is_some());
    }

    fn codes(value: serde_json::Value) -> Vec<&'static str> {
        validate_frame(&value).into_iter().map(|v| v.code).collect()
    }

    #[test]
    fn valid_request_has_no_violations() {
        let v = serde_json::json!({
            "jsonrpc": "2.0", "id": "1", "method": "tools/call",
            "params": { "name": "read_file" }
        });
        assert!(codes(v).is_empty());
    }

    #[test]
    fn valid_response_has_no_violations() {
        let v = serde_json::json!({"jsonrpc": "2.0", "id": 1, "result": {}});
        assert!(codes(v).is_empty());
    }

    #[test]
    fn invalid_version_is_reported() {
        let v = serde_json::json!({"jsonrpc": "1.0", "id": "1", "method": "tools/list"});
        assert!(codes(v).contains(&"bad_version"));
        let v = serde_json::json!({"id": "1", "method": "tools/list"});
        assert!(codes(v).contains(&"missing_version"));
    }

    #[test]
    fn response_with_result_and_error_is_reported() {
        let v = serde_json::json!({
            "jsonrpc": "2.0", "id": "1", "result": {}, "error": {"code": -1, "message": "x"}
        });
        assert!(codes(v).contains(&"both_result_and_error"));
    }

    #[test]
    fn invalid_params_and_id_are_reported() {
        let v = serde_json::json!({
            "jsonrpc": "2.0", "id": true, "method": "tools/list", "params": "oops"
        });
        let found = codes(v);
        assert!(found.contains(&"invalid_params"), "{found:?}");
        assert!(found.contains(&"invalid_id"), "{found:?}");
    }

    #[test]
    fn empty_method_and_unknown_frame_are_reported() {
        let v = serde_json::json!({"jsonrpc": "2.0", "id": "1", "method": ""});
        assert!(codes(v).contains(&"invalid_method"));
        let v = serde_json::json!({"jsonrpc": "2.0", "id": "1"});
        assert!(codes(v).contains(&"unknown_frame_type"));
    }
}