mcpspy 0.2.1

Zero-config stdio MCP proxy, latency profiler, and token usage auditor in Rust
Documentation
# mcpspy — Project Master Specification

## 1. Mission & Product Identity
Build **`mcpspy`**, a zero-config, local-first Rust **MCP Traffic Inspector, Latency Profiler & Token Auditor**.
`mcpspy` wraps any `stdio` MCP server command transparently (e.g., `mcpspy wrap --name treecut -- treecut mcp`), forwarding JSON-RPC 2.0 frames with sub-millisecond overhead while recording request/response latency, byte/token counts, error rates, and schema violations into a local SQLite telemetry database.

It compiles into a single unified Rust binary supporting three workflows:
1. **Transparent Proxy Mode (`mcpspy wrap [--name LABEL] -- <CMD> [ARGS...]`)**: Drop-in wrapper for `opencode.json`, `.mcp.json`, or `.cursor/mcp.json` that forwards `stdin`/`stdout` between the MCP host and child server without altering protocol behavior.
2. **Live TUI & CLI Reporting (`mcpspy top` / `mcpspy stats` / `mcpspy tail`)**: Real-time `ratatui` dashboard and CLI summary tables showing token usage, p50/p95 latency, heaviest tools, and failing JSON-RPC calls across all wrapped MCP servers.
3. **Self-Inspecting MCP Server (`mcpspy mcp`)**: Exposes telemetry queries over `stdio` MCP so an AI agent can audit its own tool token burn and slow servers.

---

## 2. Hard Architectural Invariants (Do Not Violate)
1. **Zero Frame Corruption in `wrap` Mode**: In `mcpspy wrap`, `stdout` is strictly a byte-for-byte / newline-delimited JSON-RPC pipe from the child MCP server back to the host. Never write logs, banners, or TUI output to `stdout` during `wrap` or `mcp` modes—route all diagnostics to `stderr` or SQLite.
2. **Pass-Through Resilience**: Even if a JSON-RPC line contains malformed JSON or an unknown method, `mcpspy wrap` must still forward the raw line immediately so it never breaks the underlying MCP session; log the parse warning asynchronously to SQLite.
3. **Zero UI Coupling in `core/`**: `src/core/` must remain completely free of `clap`, `ratatui`, `crossterm`, and `rmcp`.
4. **Shared SQLite Telemetry Store (`~/.mcpspy/telemetry.db` or `--db <PATH>`)**: Use `rusqlite` (`bundled`) with WAL mode (`PRAGMA journal_mode=WAL;`) and `busy_timeout(5000)` so multiple wrapped MCP servers can log concurrently without `SQLITE_BUSY` lock errors.
5. **Secret Redaction on Stored Payloads**: Scrub Bearer tokens, API keys (`sk-...`, `ghp_...`, `AKIA...`), and database credentials before persisting payload previews in SQLite (or support `--no-payloads` to store metadata/metrics only).

---

## 3. Directory & Module Architecture

```text
mcpspy/
├── Cargo.toml
├── README.md
├── LICENSE-MIT
├── LICENSE-APACHE
├── SPEC.md
├── src/
│   ├── main.rs                  # Clap CLI router (`wrap`, `top`, `stats`, `tail`, `prune`, `mcp`, `init`)
│   ├── lib.rs                   # Re-exports `core` for integration tests
│   ├── core/
│   │   ├── mod.rs               # Public API facade
│   │   ├── models.rs            # Telemetry structs, summary reports, & JsonSchema types
│   │   ├── db.rs                # WAL-mode SQLite schema, concurrent writer, & analytics queries
│   │   ├── jsonrpc.rs           # Non-blocking JSON-RPC 2.0 request/response correlator (`id` matcher)
│   │   ├── tokens.rs            # Fast token estimator (~4 chars/token + JSON overhead) & payload previewer
│   │   ├── redactor.rs          # Secret scrubber for stored payload previews
│   │   └── proxy.rs             # Async Tokio bidirectional child-process stdio proxy
│   ├── tui.rs                   # Live `ratatui` + `crossterm` dashboard (`mcpspy top`)
│   └── mcp.rs                   # `rmcp` stdio server exposing `get_mcp_stats` & `get_slow_calls`
└── tests/
    ├── mock_mcp_server.rs       # Test helper binary/script speaking JSON-RPC over stdio
    └── proxy_tests.rs           # End-to-end proxy round-trip, latency, token count, & concurrency tests
```

---

## 4. `Cargo.toml` Specification

```toml
[package]
name = "mcpspy"
version = "0.1.0"
edition = "2024"
description = "Zero-config stdio MCP proxy, latency profiler, and token usage auditor in Rust"
license = "MIT OR Apache-2.0"
keywords = ["mcp", "profiler", "proxy", "tokens", "cli"]
categories = ["command-line-utilities", "development-tools"]

[features]
default = ["tui", "mcp"]
tui = ["dep:ratatui", "dep:crossterm"]
mcp = ["dep:rmcp"]

[dependencies]
anyhow = "1.0"
chrono = { version = "0.4", features = ["serde"] }
clap = { version = "4.5", features = ["derive", "env"] }
dirs = "6.0"
regex = "1.11"
rusqlite = { version = "0.34", features = ["bundled"] }
schemars = "1.0"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
tokio = { version = "1", features = ["macros", "rt-multi-thread", "io-std", "io-util", "process", "sync", "time"] }
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter", "fmt"] }

# Optional interface layers
ratatui = { version = "0.30.2", optional = true }
crossterm = { version = "0.29", optional = true }
rmcp = { version = "3.9", features = ["server", "macros", "transport-io"], optional = true }

[dev-dependencies]
tempfile = "3.15"
```

---

## 5. Core Capabilities & Exact Contracts

### SQLite Telemetry Schema (`src/core/db.rs`)
Enable `PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL;` on open:
```sql
CREATE TABLE IF NOT EXISTS rpc_calls (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    session_id TEXT NOT NULL,
    server_name TEXT NOT NULL,
    rpc_id TEXT,
    method TEXT NOT NULL,
    tool_name TEXT,
    started_at_ms INTEGER NOT NULL,
    duration_ms REAL NOT NULL,
    req_bytes INTEGER NOT NULL,
    resp_bytes INTEGER NOT NULL,
    req_tokens INTEGER NOT NULL,
    resp_tokens INTEGER NOT NULL,
    is_error INTEGER NOT NULL DEFAULT 0,
    error_message TEXT,
    req_preview TEXT,
    resp_preview TEXT
);
CREATE INDEX IF NOT EXISTS idx_rpc_server_time ON rpc_calls(server_name, started_at_ms DESC);
CREATE INDEX IF NOT EXISTS idx_rpc_tool ON rpc_calls(tool_name);
```

### Bidirectional Proxy & Request Correlator (`src/core/proxy.rs` & `jsonrpc.rs`)
1. Spawn `<CMD> [ARGS...]` via `tokio::process::Command` with `Stdio::piped()` for `stdin`, `stdout`, and `stderr`.
2. **Task 1 (`Host -> Child stdin`)**: Read lines from `mcpspy`'s `stdin`, forward each line immediately to `child.stdin`, parse JSON-RPC `id`, `method` (e.g. `tools/call`), and `params.name` (when `method == "tools/call"`), and record `(Instant::now(), req_bytes, req_tokens, preview)` in a `DashMap` / `Mutex<HashMap<String, PendingCall>>`.
3. **Task 2 (`Child stdout -> Host`)**: Read lines from `child.stdout`, write each line immediately to `mcpspy`'s `stdout` + `flush()`, match `id` against `PendingCall`, compute `duration_ms`, check `result.isError` or JSON-RPC `error` object, scrub secrets via `redactor.rs`, and send the completed `RpcRecord` over an unbounded `mpsc` channel to a background SQLite writer task (so disk I/O never blocks JSON-RPC forwarding).
4. **Task 3 (`Child stderr -> Host stderr`)**: Forward `child.stderr` directly to `mcpspy`'s `stderr` transparently.

### CLI Commands (`src/main.rs`)
* `mcpspy wrap [--name <SERVER>] [--db <PATH>] [--no-payloads] -- <CMD> [ARGS...]` — Transparent `stdio` proxy.
* `mcpspy stats [--server <NAME>] [--since 24h] [--json]` — Prints ranked summary table of total calls, total input/output tokens, avg/p95 latency, and error count per server and per tool.
* `mcpspy top [--db <PATH>]` — Live auto-refreshing `ratatui` dashboard showing active MCP servers, per-tool token burn bars, latency percentiles, and recent calls (press `q` to quit, `c` to clear view).
* `mcpspy tail [-n 20] [--server <NAME>] [--errors-only]` — Streams recent recorded MCP tool calls with token counts and latency.
* `mcpspy prune --older-than 7d` — Deletes old telemetry records and runs `VACUUM`.
* `mcpspy init <CONFIG_FILE>` — Automatically wraps existing MCP server commands in `opencode.json`, `.mcp.json`, or `.cursor/mcp.json` with `mcpspy wrap --name <key> -- ...` (creating a `.bak` backup first).

---

## 6. Phased Execution Plan for OpenCode

1. **Phase 1 — Scaffold, WAL SQLite DB & Secret Redactor**:
   * Initialize `Cargo.toml`, `db.rs` (with WAL mode + concurrent write tests), `tokens.rs`, and `redactor.rs`.
2. **Phase 2 — Async Bidirectional `stdio` Proxy & JSON-RPC Correlator**:
   * Implement `jsonrpc.rs` and `proxy.rs`.
   * Write an end-to-end integration test in `tests/proxy_tests.rs` that 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`.
3. **Phase 3 — CLI Analytics (`stats`, `tail`, `prune`, `init`), `ratatui` TUI (`top`), & MCP Server**:
   * Implement `stats`, `tail`, `prune`, and `init` (auto-wrapping existing `opencode.json` / `.mcp.json` entries).
   * Implement `src/tui.rs` (`mcpspy top`) and `src/mcp.rs` (`get_mcp_stats`, `get_slow_calls`).
4. **Phase 4 — Docs, Licenses & Release Prep**:
   * Write `README.md` showing how `mcpspy` benchmarks `treecut` and `logcut` token savings, add `LICENSE-MIT` + `LICENSE-APACHE`, and verify `cargo publish --dry-run`.