mcpspy 0.2.4

Zero-config stdio MCP proxy, latency profiler, and token usage auditor in Rust
Documentation
//! `mcpspy init` — auto-wrap existing MCP config.

use anyhow::{Context, Result, bail};
use serde_json::Value;

/// Find the MCP server map in a config and wrap each unwrapped server command.
/// Returns the number of servers that were wrapped.
pub fn wrap_servers(root: &mut Value) -> Result<usize> {
    let key = if root.get("mcpServers").is_some() {
        "mcpServers"
    } else if root.get("mcp").is_some() {
        "mcp"
    } else {
        bail!("config has no `mcpServers` or `mcp` object");
    };

    let servers = root
        .get_mut(key)
        .and_then(|v| v.as_object_mut())
        .with_context(|| format!("`{key}` must be an object"))?;

    let mut wrapped = 0;
    for (name, entry) in servers.iter_mut() {
        let Some(obj) = entry.as_object_mut() else {
            continue;
        };
        let Some(command) = obj
            .get("command")
            .and_then(|v| v.as_str())
            .map(str::to_string)
        else {
            continue;
        };
        if command == "mcpspy" {
            continue; // idempotent
        }

        let old_args: Vec<String> = obj
            .get("args")
            .and_then(|v| v.as_array())
            .map(|arr| {
                arr.iter()
                    .filter_map(|v| v.as_str().map(str::to_string))
                    .collect()
            })
            .unwrap_or_default();

        let mut new_args = vec![
            "wrap".to_string(),
            "--name".to_string(),
            name.clone(),
            "--".to_string(),
            command,
        ];
        new_args.extend(old_args);

        obj.insert("command".into(), Value::String("mcpspy".into()));
        obj.insert(
            "args".into(),
            Value::Array(new_args.into_iter().map(Value::String).collect()),
        );
        wrapped += 1;
    }

    Ok(wrapped)
}

/// Open a config file, back it up, wrap its MCP servers, and write it back.
pub fn run(config_file: &str) -> Result<()> {
    let path = std::path::Path::new(config_file);
    let text =
        std::fs::read_to_string(path).with_context(|| format!("failed to read {config_file}"))?;
    let mut root: Value =
        serde_json::from_str(&text).with_context(|| format!("{config_file} is not valid JSON"))?;

    let count = wrap_servers(&mut root)?;

    let backup = format!("{config_file}.bak");
    std::fs::copy(path, &backup).with_context(|| format!("failed to create backup {backup}"))?;

    let pretty = serde_json::to_string_pretty(&root)?;
    std::fs::write(path, format!("{pretty}\n"))
        .with_context(|| format!("failed to write {config_file}"))?;

    println!("Wrapped {count} MCP server(s) in {config_file} (backup: {backup}).");
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    fn config() -> serde_json::Value {
        json!({
            "mcpServers": {
                "treecut": { "command": "npx", "args": ["-y", "treecut-mcp"] },
                "logcut": { "command": "/usr/bin/logcut", "args": ["mcp"], "env": {"TOKEN": "abc"} }
            }
        })
    }

    #[test]
    fn wraps_each_server_command() {
        let mut cfg = config();
        let n = wrap_servers(&mut cfg).unwrap();
        assert_eq!(n, 2);
        let servers = &cfg["mcpServers"];
        let t = &servers["treecut"];
        assert_eq!(t["command"], "mcpspy");
        assert_eq!(t["args"][0], "wrap");
        assert_eq!(t["args"][1], "--name");
        assert_eq!(t["args"][2], "treecut");
        assert_eq!(t["args"][3], "--");
        assert_eq!(t["args"][4], "npx");
        assert_eq!(t["args"][5], "-y");
        assert_eq!(t["args"][6], "treecut-mcp");
    }

    #[test]
    fn preserves_extra_server_fields() {
        let mut cfg = config();
        wrap_servers(&mut cfg).unwrap();
        let l = &cfg["mcpServers"]["logcut"];
        assert_eq!(l["env"]["TOKEN"], "abc");
    }

    #[test]
    fn init_is_idempotent() {
        let mut cfg = config();
        wrap_servers(&mut cfg).unwrap();
        let n = wrap_servers(&mut cfg).unwrap();
        assert_eq!(n, 0, "already-wrapped servers must be skipped");
        assert_eq!(cfg["mcpServers"]["treecut"]["args"][4], "npx");
    }

    #[test]
    fn handles_alternate_mcp_key() {
        let mut cfg = json!({
            "mcp": {
                "srv": { "command": "python3", "args": ["server.py"] }
            }
        });
        let n = wrap_servers(&mut cfg).unwrap();
        assert_eq!(n, 1);
        assert_eq!(cfg["mcp"]["srv"]["command"], "mcpspy");
    }

    #[test]
    fn missing_mcp_map_is_error() {
        let mut cfg = json!({"other": {}});
        let err = wrap_servers(&mut cfg).unwrap_err().to_string();
        assert!(err.contains("mcpServers"), "error: {err}");
    }
}