mcpspy 0.2.4

Zero-config stdio MCP proxy, latency profiler, and token usage auditor in Rust
Documentation
# Architecture guide

## Layout

```text
src/
├── main.rs          Clap router; initializes tracing on stderr
├── lib.rs           Re-exports `core` for tests and consumers
├── cli_*.rs         Binary-only command implementations and pure formatters
├── tui.rs           ratatui dashboard + testable line formatters
├── mcp.rs           rmcp stdio server + testable JSON payload builders
└── core/            UI-free, transport-free library
    ├── mod.rs       Public facade
    ├── models.rs    Telemetry structs and summaries
    ├── db.rs        WAL SQLite store and analytics queries
    ├── jsonrpc.rs   In-memory request/response correlator
    ├── tokens.rs    Fast token estimator and preview helper
    ├── redactor.rs  Secret scrubber
    └── proxy.rs     Async bidirectional child-process proxy
```

`core/` never imports `clap`, `ratatui`, `crossterm`, or `rmcp`. All UI and transport concerns live in the binary modules.

## Proxy data flow

`run_proxy` spawns the child with piped `stdin`, `stdout`, and `stderr`, then runs three concurrent tasks:

1. **Host stdin → child stdin.** Each line is parsed first (id, method, tool name, token estimate, byte count, redacted preview) and recorded in a `Arc<tokio::sync::Mutex<HashMap<id, PendingCall>>>` *before* being written to the child. This ordering avoids a race where a fast response arrives before the pending call exists. Forwarding is a single `write_all` + `flush`, so a line is never duplicated or held back.
2. **Child stdout → host stdout.** Each line is written byte-for-byte to the host immediately. The response's `id` matches a pending call; duration, token counts, error status, and previews are assembled into an `RpcRecord` and written synchronously to SQLite.
   Both tasks also run `jsonrpc::validate_frame` on each parsed line. Violations (bad version, invalid method/params/id, response with both result and error, unknown frame type, malformed JSON) are recorded to a separate `schema_violations` table with a redacted raw preview. Validation is advisory and never delays forwarding.
3. **Child stderr → host stderr.** Forwarded verbatim so chatty children cannot fill the pipe buffer and deadlock.

The proxy waits for all three tasks, then reaps the child.

## Hard invariants

From [SPEC.md](../SPEC.md):

1. **Zero frame corruption in `wrap`.** `stdout` is exclusively the child's JSON-RPC pipe. Tracing is explicitly writer-bound to `stderr`; no CLI command prints to `stdout` in proxy mode.
2. **Pass-through resilience.** Malformed JSON or unknown methods are forwarded immediately. Parse failures are silent from the protocol's perspective.
3. **Zero UI coupling in `core/`.** Enforced by module boundaries and the dependency list.
4. **Shared WAL telemetry store.** `rusqlite` bundled, `journal_mode=WAL`, `synchronous=NORMAL`, `busy_timeout=5000`. Multiple wrapped servers can write concurrently.
5. **Secret redaction on stored payloads.** Bearer tokens, `sk-`/`ghp_`/`AKIA...` keys, generic key/password/token values, and DB URLs are scrubbed before previews and error messages are persisted. `--no-payloads` disables preview storage entirely.

## Database schema

`rpc_calls` holds session/server/rpc ids, method and tool name, `started_at_ms`, `duration_ms`, request/response bytes and tokens, error flag and message, and optional previews. A second table, `schema_violations`, holds direction, violation code, detail, redacted preview, and timestamp. Indexes cover `(server_name, started_at_ms DESC)`, `tool_name`, and the violation server/time pair.

Query helpers:

- `server_summary(server, since)` — counts, token totals, average and p95 latency, error count.
- `tool_summary(server, since)` — same per tool, with p95 and error counts computed separately.
- `recent_calls(limit, server, errors_only)` — newest first.
- `recent_violations(limit, server)` / `violation_count(server, since)` — schema violations.
- `prune(older_than_ms)` — delete old rows from both tables and VACUUM.

Both summary structs carry `avg_duration_ms`, `p50_duration_ms`, and `p95_duration_ms`; percentiles are computed from sorted per-server and per-tool durations.

## Token estimation

`TokenEstimator` uses a fast heuristic: roughly four characters per token plus a small overhead for JSON structural characters. It is intended for comparative auditing across calls, not as a replacement for a model-specific tokenizer.

## Feature flags

| Feature | Dependencies | Provides |
| --- | --- | --- |
| default | `tui`, `mcp` | Full binary |
| `tui` | `ratatui`, `crossterm` | `mcpspy top` |
| `mcp` | `rmcp` | `mcpspy mcp` |

Build a minimal binary with `cargo build --no-default-features`; the proxy and CLI analytics remain available.

## Where to extend

- **New telemetry field** — add it to `RpcRecord`, `models.rs` summaries, the schema in `db.rs`, and the record construction in `proxy.rs`.
- **New CLI command** — add a `cli_*.rs` module with pure formatter functions plus a thin `run`, then wire it in `main.rs`.
- **New secret pattern** — add a regex to `Redactor::new()` with a unit test.
- **New MCP tool** — add an async `#[tool]` method on `TelemetryServer` in `mcp.rs`.