mcpspy 0.2.4

Zero-config stdio MCP proxy, latency profiler, and token usage auditor in Rust
Documentation
/// Async bidirectional stdio proxy for MCP child processes.
/// Spawns `<CMD> [ARGS...]` with piped stdio and forwards frames
/// between the host and child without altering protocol behavior.
/// Records telemetry via the provided `TelemetryDb`.
use crate::models::{RpcRecord, SchemaViolation};
use crate::redactor::Redactor;
use anyhow::{Context, Result};
use std::collections::HashMap;
use std::sync::Arc;
use std::time::{Instant, SystemTime, UNIX_EPOCH};
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::process::Command;
use tokio::sync::Mutex;

/// Maximum length of a stored payload preview.
const MAX_PREVIEW_LEN: usize = 500;

/// Track a pending JSON-RPC call awaiting its response.
struct PendingCall {
    req_tokens: i64,
    req_bytes: i64,
    started_at: Instant,
    started_at_ms: i64,
    method: String,
    tool_name: Option<String>,
    req_preview: Option<String>,
}

/// Run the transparent proxy: forward host<->child stdio and record telemetry.
pub async fn run_proxy(
    cmd: &str,
    args: &[String],
    server_name: &str,
    session_id: &str,
    db: &crate::core::db::TelemetryDb,
    no_payloads: bool,
) -> Result<()> {
    let server_name_owned = server_name.to_string();
    let session_id_owned = session_id.to_string();

    let mut child = Command::new(cmd)
        .args(args)
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .spawn()
        .with_context(|| format!("failed to spawn {cmd}"))?;

    let mut child_stdin = child.stdin.take().context("failed to open child stdin")?;
    let mut child_stdout =
        BufReader::new(child.stdout.take().context("failed to open child stdout")?);
    let child_stderr = child.stderr.take().context("failed to open child stderr")?;

    let host_stdin = tokio::io::stdin();
    let mut host_stdin = BufReader::new(host_stdin);
    let mut host_stdout = tokio::io::stdout();
    let mut host_stderr = tokio::io::stderr();

    let tokenizer = crate::tokens::TokenEstimator::new();
    let redactor = Redactor::new();

    // Shared map of rpc_id -> PendingCall
    let call_map: Arc<Mutex<HashMap<String, PendingCall>>> = Arc::new(Mutex::new(HashMap::new()));

    // Task 1: host.stdin -> child.stdin (with request recording)
    let call_map1 = call_map.clone();
    let db1 = db.clone();
    let tokenizer1 = tokenizer.clone();
    let redactor1 = redactor.clone();
    let session_id_stdin = session_id_owned.clone();
    let server_name_stdin = server_name_owned.clone();
    let stdin_task = tokio::spawn(async move {
        let mut line = String::new();
        loop {
            line.clear();
            match host_stdin.read_line(&mut line).await {
                Ok(0) => break, // EOF
                Ok(_) => {
                    // Parse JSON-RPC request and track it BEFORE forwarding,
                    // so a fast response can always find the pending call.
                    let rpc_id = parse_rpc_id(&line);
                    let req_bytes = line.len() as i64;
                    let req_tokens = tokenizer1.estimate(&line).estimated_tokens as i64;
                    let method = parse_method(&line).unwrap_or_default();
                    let tool_name = parse_tool_name(&line);
                    let req_preview = if no_payloads {
                        None
                    } else {
                        redactor1.preview(&line, MAX_PREVIEW_LEN)
                    };

                    if !rpc_id.is_empty() {
                        let now_ms = SystemTime::now()
                            .duration_since(UNIX_EPOCH)
                            .map(|d| d.as_millis() as i64)
                            .unwrap_or(0);
                        call_map1.lock().await.insert(
                            rpc_id.clone(),
                            PendingCall {
                                req_tokens,
                                req_bytes,
                                started_at: Instant::now(),
                                started_at_ms: now_ms,
                                method,
                                tool_name,
                                req_preview,
                            },
                        );
                    }

                    record_violations(
                        &db1,
                        &line,
                        "request",
                        &session_id_stdin,
                        &server_name_stdin,
                        &redactor1,
                        no_payloads,
                    );

                    // Forward immediately — never hold back a line
                    let _ = child_stdin.write_all(line.as_bytes()).await;
                    let _ = child_stdin.flush().await;
                }
                Err(_) => break,
            }
        }
        // Close child stdin when host stdin closes
        let _ = child_stdin.shutdown().await;
    });

    // Task 2: child.stdout -> host.stdout (with response recording)
    let call_map2 = call_map.clone();
    let db2 = db.clone();
    let tokenizer2 = tokenizer.clone();
    let redactor2 = redactor.clone();
    let stdout_task = tokio::spawn(async move {
        let mut line = String::new();
        loop {
            line.clear();
            match child_stdout.read_line(&mut line).await {
                Ok(0) => break, // EOF
                Ok(_) => {
                    let resp_bytes = line.len() as i64;
                    // Forward immediately to host stdout — byte-for-byte
                    let _ = host_stdout.write_all(line.as_bytes()).await;
                    let _ = host_stdout.flush().await;

                    // Parse JSON-RPC response and record telemetry
                    record_violations(
                        &db2,
                        &line,
                        "response",
                        &session_id_owned,
                        &server_name_owned,
                        &redactor2,
                        no_payloads,
                    );

                    let rpc_id = parse_rpc_id(&line);
                    let resp_tokens = tokenizer2.estimate(&line).estimated_tokens as i64;
                    let is_error = is_error_from_line(&line);
                    let error_message =
                        error_message_from_line(&line).map(|m| redactor2.redact(&m));
                    let resp_preview = if no_payloads {
                        None
                    } else {
                        redactor2.preview(&line, MAX_PREVIEW_LEN)
                    };

                    if !rpc_id.is_empty()
                        && let Some(pending) = call_map2.lock().await.remove(&rpc_id)
                    {
                        let duration = pending.started_at.elapsed().as_secs_f64() * 1000.0;
                        let _ = db2.record(RpcRecord {
                            session_id: session_id_owned.clone(),
                            server_name: server_name_owned.clone(),
                            rpc_id: Some(rpc_id),
                            method: pending.method,
                            tool_name: pending.tool_name,
                            started_at_ms: pending.started_at_ms,
                            duration_ms: duration,
                            req_bytes: pending.req_bytes,
                            resp_bytes,
                            req_tokens: pending.req_tokens,
                            resp_tokens,
                            is_error,
                            error_message,
                            req_preview: pending.req_preview,
                            resp_preview,
                        });
                    }
                }
                Err(_) => break,
            }
        }
    });

    // Task 3: child.stderr -> host.stderr (transparent, never to stdout).
    let stderr_task = tokio::spawn(async move {
        let mut stderr_line = String::new();
        let mut child_stderr = BufReader::new(child_stderr);
        loop {
            stderr_line.clear();
            match child_stderr.read_line(&mut stderr_line).await {
                Ok(0) => break,
                Ok(_) => {
                    let _ = host_stderr.write_all(stderr_line.as_bytes()).await;
                    let _ = host_stderr.flush().await;
                }
                Err(_) => break,
            }
        }
    });

    // Wait for the forwarding tasks
    let _ = tokio::join!(stdin_task, stdout_task, stderr_task);

    // Wait for child to exit
    let _ = child.wait().await;

    Ok(())
}

/// Record JSON-RPC schema violations without ever blocking frame forwarding.
fn record_violations(
    db: &crate::core::db::TelemetryDb,
    line: &str,
    direction: &str,
    session_id: &str,
    server_name: &str,
    redactor: &Redactor,
    no_payloads: bool,
) {
    let value: serde_json::Value = match serde_json::from_str(line.trim()) {
        Ok(v) => v,
        Err(_) => {
            let _ = db.record_violation(SchemaViolation {
                session_id: session_id.to_string(),
                server_name: server_name.to_string(),
                rpc_id: None,
                direction: direction.to_string(),
                code: "malformed_json".into(),
                detail: "line is not valid JSON".into(),
                raw_preview: if no_payloads {
                    None
                } else {
                    redactor.preview(line, MAX_PREVIEW_LEN)
                },
                started_at_ms: now_ms(),
            });
            return;
        }
    };

    let violations = crate::jsonrpc::validate_frame(&value);
    if violations.is_empty() {
        return;
    }
    let rpc_id = parse_rpc_id(line);
    let raw_preview = if no_payloads {
        None
    } else {
        redactor.preview(line, MAX_PREVIEW_LEN)
    };
    for violation in violations {
        let _ = db.record_violation(SchemaViolation {
            session_id: session_id.to_string(),
            server_name: server_name.to_string(),
            rpc_id: if rpc_id.is_empty() {
                None
            } else {
                Some(rpc_id.clone())
            },
            direction: direction.to_string(),
            code: violation.code.to_string(),
            detail: violation.detail,
            raw_preview: raw_preview.clone(),
            started_at_ms: now_ms(),
        });
    }
}

fn now_ms() -> i64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_millis() as i64)
        .unwrap_or(0)
}

/// Parse the rpc_id from a JSON-RPC line.
fn parse_rpc_id(line: &str) -> String {
    let value: serde_json::Value = match serde_json::from_str(line.trim()) {
        Ok(v) => v,
        Err(_) => return String::new(),
    };
    value
        .get("id")
        .and_then(|v| match v {
            serde_json::Value::String(s) => Some(s.clone()),
            serde_json::Value::Number(n) => Some(n.to_string()),
            _ => None,
        })
        .unwrap_or_default()
}

/// Parse the method from a JSON-RPC request line.
fn parse_method(line: &str) -> Option<String> {
    let value: serde_json::Value = match serde_json::from_str(line.trim()) {
        Ok(v) => v,
        Err(_) => return None,
    };
    value
        .get("method")
        .and_then(|v| v.as_str())
        .map(|s| s.to_string())
}

/// Parse the tool_name from a JSON-RPC request line.
fn parse_tool_name(line: &str) -> Option<String> {
    let value: serde_json::Value = match serde_json::from_str(line.trim()) {
        Ok(v) => v,
        Err(_) => return None,
    };
    if value.get("method").and_then(|v| v.as_str()) == Some("tools/call") {
        value
            .get("params")
            .and_then(|p| p.get("name"))
            .and_then(|v| v.as_str())
            .map(|s| s.to_string())
    } else {
        None
    }
}

/// Get is_error from a JSON-RPC line.
fn is_error_from_line(line: &str) -> bool {
    let value: serde_json::Value = match serde_json::from_str(line.trim()) {
        Ok(v) => v,
        Err(_) => return false,
    };
    value.get("error").is_some() || {
        value
            .get("result")
            .and_then(|r| r.get("isError"))
            .and_then(|v| v.as_bool())
            .unwrap_or(false)
    }
}

/// Get error_message from a JSON-RPC line.
fn error_message_from_line(line: &str) -> Option<String> {
    let value: serde_json::Value = match serde_json::from_str(line.trim()) {
        Ok(v) => v,
        Err(_) => return None,
    };
    value
        .get("error")
        .and_then(|e| e.get("message"))
        .and_then(|v| v.as_str())
        .map(|s| s.to_string())
}