mcpspy 0.2.2

Zero-config stdio MCP proxy, latency profiler, and token usage auditor in Rust
Documentation
//! End-to-end proxy round-trip test.
//!
//! Spawns `mcpspy wrap --name test -- <mock_server>`, sends
//! `initialize` + `tools/list` + `tools/call` over stdin, verifies exact
//! stdout responses, and asserts SQLite recorded accurate
//! `duration_ms`, `tool_name`, `req_tokens`, and `resp_tokens`.

use anyhow::{Context, Result};
use rusqlite::Connection;
use std::path::PathBuf;
use std::time::Duration;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::process::Command;

/// Path to the compiled mcpspy binary.
fn mcpspy_bin() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("target/debug/mcpspy")
}

/// Path to the mock MCP server script.
fn mock_server_path() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/mock_mcp_server.py")
}

#[tokio::test]
async fn proxy_round_trip_and_telemetry() -> Result<()> {
    let db_path = tempfile::NamedTempFile::new()?.path().to_path_buf();
    let db_path_clone = db_path.clone();

    let mock_server = mock_server_path();

    // Spawn mcpspy wrap with piped stdio
    let mut child = Command::new(mcpspy_bin())
        .arg("wrap")
        .arg("--name")
        .arg("test-server")
        .arg("--db")
        .arg(db_path.to_str().unwrap())
        .arg("--")
        .arg("python3")
        .arg(mock_server.to_str().unwrap())
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .spawn()
        .context("failed to spawn mcpspy wrap")?;

    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")?);

    // Helper to send a request and read the response
    async fn send_and_recv(
        stdin: &mut tokio::process::ChildStdin,
        stdout: &mut BufReader<tokio::process::ChildStdout>,
        line: &str,
    ) -> Result<String> {
        stdin.write_all(line.as_bytes()).await?;
        stdin.write_all(b"\n").await?;
        stdin.flush().await?;

        let mut resp = String::new();
        stdout.read_line(&mut resp).await?;
        Ok(resp.trim().to_string())
    }

    // 1. Send initialize
    let init_req = r#"{"jsonrpc":"2.0","id":"1","method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{}}}"#;
    let init_resp = send_and_recv(&mut child_stdin, &mut child_stdout, init_req).await?;
    let init_val: serde_json::Value = serde_json::from_str(&init_resp)?;
    assert_eq!(init_val.get("id").and_then(|v| v.as_str()), Some("1"));
    assert!(init_val.get("result").is_some());
    assert!(init_val.get("error").is_none());

    // 2. Send tools/list
    let list_req = r#"{"jsonrpc":"2.0","id":"2","method":"tools/list"}"#;
    let list_resp = send_and_recv(&mut child_stdin, &mut child_stdout, list_req).await?;
    let list_val: serde_json::Value = serde_json::from_str(&list_resp)?;
    assert_eq!(list_val.get("id").and_then(|v| v.as_str()), Some("2"));
    let tools = list_val
        .get("result")
        .and_then(|r| r.get("tools"))
        .and_then(|t| t.as_array())
        .context("tools/list result missing tools array")?;
    assert!(tools.len() >= 2);

    // 3. Send tools/call
    let call_req = r#"{"jsonrpc":"2.0","id":"3","method":"tools/call","params":{"name":"read_file","arguments":{"path":"/tmp/test"}}}"#;
    let call_resp = send_and_recv(&mut child_stdin, &mut child_stdout, call_req).await?;
    let call_val: serde_json::Value = serde_json::from_str(&call_resp)?;
    assert_eq!(call_val.get("id").and_then(|v| v.as_str()), Some("3"));
    assert!(call_val.get("result").is_some());
    assert!(call_val.get("error").is_none());

    // Close stdin to signal EOF to mcpspy
    drop(child_stdin);

    // Wait for mcpspy to exit
    let _status = child
        .wait()
        .await
        .context("mcpspy wrap exited with error")?;

    // Give the background SQLite writer time to flush
    tokio::time::sleep(Duration::from_millis(300)).await;

    // 4. Verify SQLite recorded the calls
    let conn = Connection::open(&db_path_clone)?;
    let mut stmt = conn.prepare(
        "SELECT method, tool_name, duration_ms, req_tokens, resp_tokens, is_error
         FROM rpc_calls WHERE server_name = ?1 ORDER BY id",
    )?;
    let rows = stmt.query_map([&"test-server"], |row| {
        Ok((
            row.get::<_, String>(0)?,
            row.get::<_, Option<String>>(1)?,
            row.get::<_, f64>(2)?,
            row.get::<_, i64>(3)?,
            row.get::<_, i64>(4)?,
            row.get::<_, i32>(5)? == 1,
        ))
    })?;

    let records: Vec<_> = rows.filter_map(Result::ok).collect();
    assert_eq!(records.len(), 3, "expected 3 recorded RPC calls");

    // Check initialize call
    let init_record = &records[0];
    assert_eq!(init_record.0, "initialize");
    assert_eq!(init_record.1, None);
    assert!(init_record.2 > 0.0, "duration_ms should be positive");
    assert!(init_record.3 > 0, "req_tokens should be positive");
    assert!(init_record.4 > 0, "resp_tokens should be positive");
    assert!(!init_record.5, "initialize should not be an error");

    // Check tools/list call
    let list_record = &records[1];
    assert_eq!(list_record.0, "tools/list");
    assert_eq!(list_record.1, None);
    assert!(list_record.2 > 0.0);

    // Check tools/call call
    let call_record = &records[2];
    assert_eq!(call_record.0, "tools/call");
    assert_eq!(call_record.1, Some("read_file".to_string()));
    assert!(call_record.2 > 0.0, "duration_ms should be positive");
    assert!(call_record.3 > 0, "req_tokens should be positive");
    assert!(call_record.4 > 0, "resp_tokens should be positive");
    assert!(!call_record.5, "tools/call should not be an error");

    // req_bytes must reflect the actual request size, not a hardcoded zero.
    let req_bytes: i64 = conn.query_row(
        "SELECT req_bytes FROM rpc_calls ORDER BY id LIMIT 1",
        [],
        |row| row.get(0),
    )?;
    assert!(req_bytes > 0, "req_bytes should be captured");

    Ok(())
}

#[tokio::test]
async fn proxy_passthrough_resilience() -> Result<()> {
    let db_path = tempfile::NamedTempFile::new()?.path().to_path_buf();

    let mock_server = mock_server_path();

    let mut child = Command::new(mcpspy_bin())
        .arg("wrap")
        .arg("--name")
        .arg("resilience-test")
        .arg("--db")
        .arg(db_path.to_str().unwrap())
        .arg("--")
        .arg("python3")
        .arg(mock_server.to_str().unwrap())
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .spawn()
        .context("failed to spawn mcpspy wrap")?;

    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")?);

    // Send malformed JSON — should be forwarded as-is (pass-through)
    let malformed = "this is not json";
    child_stdin.write_all(malformed.as_bytes()).await?;
    child_stdin.write_all(b"\n").await?;
    child_stdin.flush().await?;

    let mut resp = String::new();
    child_stdout.read_line(&mut resp).await?;
    assert_eq!(
        resp.trim(),
        malformed,
        "malformed line should be forwarded byte-for-byte"
    );

    // Send valid JSON-RPC after the malformed line — session should still work
    let valid_req = r#"{"jsonrpc":"2.0","id":"99","method":"initialize","params":{}}"#;
    child_stdin.write_all(valid_req.as_bytes()).await?;
    child_stdin.write_all(b"\n").await?;
    child_stdin.flush().await?;

    let mut resp2 = String::new();
    child_stdout.read_line(&mut resp2).await?;
    let resp_val: serde_json::Value = serde_json::from_str(&resp2)?;
    assert_eq!(resp_val.get("id").and_then(|v| v.as_str()), Some("99"));

    drop(child_stdin);
    let _status = child
        .wait()
        .await
        .context("mcpspy wrap exited with error")?;

    tokio::time::sleep(Duration::from_millis(300)).await;

    // Verify the malformed line was NOT recorded as a valid call (it has no id/method)
    // but the valid one was
    let conn = Connection::open(&db_path)?;
    let mut stmt = conn.prepare("SELECT COUNT(*) FROM rpc_calls WHERE server_name = ?1")?;
    let count: i64 = stmt.query_row([&"resilience-test"], |row| row.get(0))?;
    // At minimum the valid initialize call was recorded
    assert!(
        count >= 1,
        "valid call should be recorded even after malformed line"
    );

    Ok(())
}

#[tokio::test]
async fn proxy_forwards_child_stderr() -> Result<()> {
    let db_path = tempfile::NamedTempFile::new()?.path().to_path_buf();

    let mut child = Command::new(mcpspy_bin())
        .arg("wrap")
        .arg("--name")
        .arg("stderr-test")
        .arg("--db")
        .arg(db_path.to_str().unwrap())
        .arg("--")
        .arg("python3")
        .arg("-c")
        .arg("import sys; sys.stderr.write('child diagnostic line\\n'); sys.stderr.flush()")
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .spawn()
        .context("failed to spawn mcpspy wrap")?;

    // Close mcpspy's stdin so the child can finish without any input.
    drop(child.stdin.take());

    let stderr = child.stderr.take().context("no stderr pipe")?;
    let mut stderr = BufReader::new(stderr);
    let mut line = String::new();
    stderr.read_line(&mut line).await?;

    let _status = child.wait().await?;
    assert!(
        line.contains("child diagnostic line"),
        "child stderr should be forwarded: {line:?}"
    );
    Ok(())
}

#[tokio::test]
async fn proxy_redacts_secrets_in_error_messages() -> Result<()> {
    let db_path = tempfile::NamedTempFile::new()?.path().to_path_buf();

    let script = concat!(
        "import sys,json; ",
        "sys.stdin.readline(); ",
        "sys.stdout.write(json.dumps({'jsonrpc':'2.0','id':'1',",
        "'error':{'code':-1,'message':'failed with sk-abcdefghijklmnopqrstuvwxyz1234'}})+'\\n'); ",
        "sys.stdout.flush()"
    );

    let mut child = Command::new(mcpspy_bin())
        .arg("wrap")
        .arg("--name")
        .arg("redaction-test")
        .arg("--db")
        .arg(db_path.to_str().unwrap())
        .arg("--")
        .arg("python3")
        .arg("-c")
        .arg(script)
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .spawn()
        .context("failed to spawn mcpspy wrap")?;

    let mut stdin = child.stdin.take().context("no stdin")?;
    let mut stdout = BufReader::new(child.stdout.take().context("no stdout")?);
    stdin
        .write_all(b"{\"jsonrpc\":\"2.0\",\"id\":\"1\",\"method\":\"tools/call\",\"params\":{\"name\":\"x\"}}\n")
        .await?;
    stdin.flush().await?;
    let mut response = String::new();
    stdout.read_line(&mut response).await?;
    drop(stdin);
    let _status = child.wait().await?;

    let conn = Connection::open(&db_path)?;
    let message: String = conn.query_row(
        "SELECT error_message FROM rpc_calls WHERE server_name = ?1",
        ["redaction-test"],
        |row| row.get(0),
    )?;
    assert!(
        !message.contains("sk-abcdefghijklmnopqrstuvwxyz1234"),
        "secret leaked into error_message: {message:?}"
    );
    assert!(
        message.contains("[REDACTED]"),
        "expected redaction: {message:?}"
    );
    Ok(())
}

#[tokio::test]
async fn proxy_records_schema_violations_without_blocking_forwarding() -> Result<()> {
    let db_path = tempfile::NamedTempFile::new()?.path().to_path_buf();

    let mut child = Command::new(mcpspy_bin())
        .arg("wrap")
        .arg("--name")
        .arg("schema-test")
        .arg("--db")
        .arg(db_path.to_str().unwrap())
        .arg("--")
        .arg("python3")
        .arg("-u")
        .arg("-c")
        .arg("import sys; [sys.stdout.write(l) for l in sys.stdin]")
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .spawn()
        .context("failed to spawn mcpspy wrap")?;

    let mut stdin = child.stdin.take().context("no stdin")?;
    let mut stdout = BufReader::new(child.stdout.take().context("no stdout")?);

    // A frame with a bad version is still forwarded byte-for-byte.
    let bad = r#"{"jsonrpc":"1.0","id":"7","method":"tools/list"}"#;
    stdin.write_all(format!("{bad}\n").as_bytes()).await?;
    stdin.flush().await?;
    let mut echoed = String::new();
    stdout.read_line(&mut echoed).await?;
    assert_eq!(echoed.trim(), bad, "frame must still be forwarded");

    drop(stdin);
    let _status = child.wait().await?;
    tokio::time::sleep(Duration::from_millis(200)).await;

    let conn = Connection::open(&db_path)?;
    let count: i64 = conn.query_row(
        "SELECT COUNT(*) FROM schema_violations WHERE server_name = ?1 AND code = 'bad_version'",
        ["schema-test"],
        |row| row.get(0),
    )?;
    assert!(count >= 1, "bad_version violation should be persisted");
    Ok(())
}