# mcpspy
[](https://crates.io/crates/mcpspy)
[](https://docs.rs/mcpspy)
[](https://github.com/bigwalkdoe/mcpspy/actions/workflows/ci.yml)
[](https://crates.io/crates/mcpspy)
[](https://mcprush.com/to/mcpspy-mcp?ref=badge)
A zero-config, local-first **MCP Traffic Inspector, Latency Profiler & Token Auditor** in a single Rust binary.
`mcpspy` wraps any stdio MCP server transparently, forwards JSON-RPC 2.0 frames byte-for-byte with sub-millisecond overhead, and records latency, token usage, errors, and redacted payload previews into a local SQLite database. It never writes diagnostics to `stdout` in proxy mode, so it is a drop-in replacement for an MCP server command in OpenCode, Claude Code, or Cursor.
## Features
- **Transparent proxy** — `mcpspy wrap [--name LABEL] -- <CMD> [ARGS...]` forwards `stdin`/`stdout` verbatim; malformed JSON is still passed through untouched.
- **Shared WAL telemetry store** — `rusqlite` (bundled) with `journal_mode=WAL` and a 5s busy timeout, so multiple wrapped servers can log concurrently.
- **Token & latency accounting** — per-call duration, request/response token estimates, byte counts, average/p50/p95 latency, and error detection for both JSON-RPC `error` objects and `result.isError`.
- **Schema violation audit** — malformed version, invalid method/params/id, and contradictory responses are recorded to a separate table and viewable with `mcpspy tail --violations`, without ever blocking the forwarded frame.
- **Secret redaction** — Bearer tokens, `sk-`/`ghp_`/`AKIA...` keys, generic `key=`/`password=` values, and DB connection URLs are scrubbed before previews hit disk. `--no-payloads` stores metadata only.
- **CLI analytics** — ranked `stats` tables (plus `--json`), recent-call `tail`, and `prune`.
- **Live TUI** — `mcpspy top` shows per-server token-burn bars, per-tool averages, latency percentiles, and recent calls (`q` quit, `c` clear).
- **Self-inspecting MCP server** — `mcpspy mcp` exposes `get_mcp_stats` and `get_slow_calls` over stdio so an agent can audit its own token burn.
- **Config auto-wrapping** — `mcpspy init <CONFIG_FILE>` rewrites existing MCP server entries to run through the proxy, keeping a `.bak` backup.
## Install
```bash
cargo install --path .
```
Or build from source:
```bash
cargo build --release
./target/release/mcpspy --help
```
Feature flags: `tui` (ratatui + crossterm) and `mcp` (rmcp) are enabled by default. Build without them via `cargo build --no-default-features`.
## Usage
### 1. Wrap an MCP server
```bash
# Direct use
mcpspy wrap --name treecut -- treecut mcp
# With a custom database and no stored payloads
mcpspy --db /tmp/telemetry.db wrap --name logcut --no-payloads -- logcut mcp
```
Everything after `--` is the child command and its arguments. `stdout` contains only the child's JSON-RPC lines; logs and warnings go to `stderr`/SQLite.
### 2. Auto-wrap an existing config
```bash
mcpspy init ~/.config/opencode/opencode.json
mcpspy init ~/.mcp.json
mcpspy init ~/.cursor/mcp.json
```
This turns each server entry from:
```json
"treecut": { "command": "treecut", "args": ["mcp"] }
```
into:
```json
"treecut": { "command": "mcpspy", "args": ["wrap", "--name", "treecut", "--", "treecut", "mcp"] }
```
Other fields (such as `env`) are preserved. Running `init` again is a no-op for already-wrapped servers. The original file is saved as `<config>.bak`.
### 3. Inspect the telemetry
```bash
# Ranked summary table, last 24 hours
mcpspy stats
# Machine-readable output, one server
mcpspy stats --server treecut --since 7d --json
# Recent calls, errors only
mcpspy tail -n 20 --errors-only
# Live dashboard
mcpspy top
# Drop records older than a week and VACUUM
mcpspy prune --older-than 7d
```
Durations accept `ms`, `s`, `m`, `h`, `d`, and `w` suffixes — either as a single value (`30m`, `24h`, `7d`) or compounded (`1h30m`, `2d12h`, `1w2d3h4m5s`). Segments may be separated by whitespace; overflow and malformed values are rejected.
### 4. Let an agent audit itself
Register `mcpspy mcp` as an MCP server and call:
- `get_mcp_stats` — aggregated calls, tokens, avg/p95 latency, and errors per server/tool.
- `get_slow_calls` — the slowest recorded calls with token counts.
## Benchmarking treecut and logcut token savings
A typical workflow measures how much context the agent consumes when using
[`treecut`](https://crates.io/crates/treecut) (codebase mapping) and
[`logcut`](https://crates.io/crates/logcut) (log/stacktrace slicing):
```bash
# 1. Wrap both servers so every tool call is recorded
mcpspy init ~/.config/opencode/opencode.json # or .mcp.json / .cursor/mcp.json
# 2. Run a normal debugging session in your MCP host, then compare token burn
mcpspy stats --since 24h
mcpspy stats --server treecut --json
mcpspy stats --server logcut --json
# 3. Drill into the heaviest tools
`mcpspy stats` reports `REQ TOK` and `RESP TOK` per server and per tool, so you can compare a session with raw tool output against one using `treecut slice_symbol` / `logcut slice` to see the reduction in tokens sent to the model. `p95` and `ERR` columns highlight slow servers and failing calls that inflate context.
## Telemetry schema
The SQLite database (`~/.mcpspy/telemetry.db` by default, override with `--db`) contains one `rpc_calls` table with session/server/rpc ids, method/tool name, timestamps, duration, byte and token counts, error status, and optionally redacted request/response previews. Indexes on `(server_name, started_at_ms)` and `tool_name` keep reporting fast.
## Safety
- No logs, banners, or TUI output are ever written to `stdout` in `wrap` or `mcp` mode.
- Malformed JSON lines are forwarded immediately and never block the MCP session.
- Secret patterns are redacted **before** payload previews are persisted.
- `--no-payloads` stores metrics only — no request or response text is saved.
MCP Registry: `mcp-name: io.github.bigwalkdoe/mcpspy`
## Documentation
- [Usage guide](docs/usage.md) — every command, flag, and duration syntax.
- [MCP and agent reference](docs/mcp.md) — self-inspection tools and host registration.
- [Architecture guide](docs/architecture.md) — modules, data flow, invariants, and schema.
- [Troubleshooting](docs/troubleshooting.md) — symptom-first fixes.
- [SPEC.md](SPEC.md), [CHANGELOG.md](CHANGELOG.md), [CONTRIBUTING.md](CONTRIBUTING.md).
## License
MIT OR Apache-2.0. See `LICENSE-MIT` and `LICENSE-APACHE`.