Code Mode MCP
# codemode-mcp
Two tools for a trusted local MCP client: **discover** what is available, then **execute** Python next to the data. The host sees the answer instead of every intermediate tool response. Python 3.11+ and POSIX are required. No package installation, listener port, or Python dependencies are needed.
## Run from source
```sh
export PYTHONPATH="$PWD/src"
export CODEMODE_CONFIG="$PWD/examples/codemode.toml"
python3 -m codemode_mcp discover
python3 -m codemode_mcp exec --cwd "$PWD" "emit({'files':fs.glob('*.toml')})"
python3 -m codemode_mcp qrun --max-chars 600 -- git status --short
python3 -m codemode_mcp serve # newline-delimited JSON-RPC on stdin/stdout
```
For a GUI or CLI client, make the following executable launcher with **absolute paths**. Replace all three paths; do not rely on shell startup files.
```sh
#!/bin/sh
export PYTHONPATH=/absolute/path/to/codemode-mcp/src
export CODEMODE_CONFIG=/absolute/path/to/codemode.toml
exec /absolute/path/to/python3 -m codemode_mcp serve
```
Register the launcher with **one** client at a time:
| Client | Registration command |
| --- | --- |
| AGY | `agy mcp add --type stdio cm /absolute/path/to/launcher` |
| Claude Code | `claude mcp add --transport stdio cm -- /absolute/path/to/launcher` |
| Codex | `codex mcp add cm -- /absolute/path/to/launcher` |
| Pi (with native MCP support) | `pi mcp add cm -- /absolute/path/to/launcher` |
| OpenCode | `opencode mcp add cm -- /absolute/path/to/launcher` |
Ask for the list of tools, run `cm_discover({})`, then `cm_exec({"code":"6*7"})`. The last result is `42`. **Additive registration** keeps the host's original upstreams and their preflight checks intact. **Wrapper-only registration** hides native upstream schemas from the host prefix; use it only after verifying that other consumers no longer require those registrations.
## Architecture and permissions
The stdio server keeps a warm pool of HTTP or stdio upstreams. HTTP handles JSON, SSE, session headers, and catalog cursors. Each stdio peer has one response reader and matches replies by ID. A fresh Python process per execution calls the pool over a private Unix socket. A shell command and its output streams cannot block the RPC reader. Timeouts kill the execution process group; a request already delivered upstream may still finish. Tool calls are never replayed automatically.
This is shell-equivalent execution **with the local user's permissions**, not a sandbox. A host permission hook sees the outer tool call, not each nested operation. Only trusted clients should have access. Each Swarm worker MUST set `cwd` to its own worktree. Deliberately detached runner jobs survive an execution; use `agents.stop(id)` to stop one.
## Discovery, execution, and retention
- Empty discovery returns counts. Filter with `namespace` or `query` for signatures (default 25); use `detail="schema"` for at most five schemas. A question mark marks an optional argument.
- Call `mcp.catalog.lookup(key=7)` or `mcp.call("catalog","dashed-tool",{"raw":True},raw=True)`. A single JSON text result becomes a Python value. Use `raw=True` to keep the envelope.
- Use `fs`, `sh`, `cli`, and ordered `batch` for local work. `emit` prints compact JSON; a final expression is displayed only if the script printed nothing. The default deadline is 30 seconds and the response budget is 4,000 characters.
- The shared stdout/stderr capture ceiling defaults to 4 MiB. The shaper redacts known token patterns before returning text or saving spills. A truncated reply carries a spill ID; use `spill.get`, `spill.grep`, `spill.info`, or `spill.json`. A capture truncation marker means the spill itself is incomplete. Redaction does not find arbitrary secrets.
- Set `spill_dir`, `jobs_dir`, `max_capture_bytes`, `spill_max_bytes`, and `redact_secrets` at the config root. Raw agent events and native final files are private **local job records**, outside the spill eviction policy. Protect and retire those records yourself.
- See [HTTP](examples/http-mcp.toml), [stdio](examples/stdio-mcp.toml), and [CLI and agent profiles](examples/cli-and-agents.toml). Configuration accepts TOML or JSON, `${ENV}`, and `url_from_mcp_config = "/path/to/client.json#alias"`. Commands are argv arrays; use `unset_env` on a subprocess profile to remove inherited variables.
## External agents
Use `agents.run("codex", prompt, model=..., effort=...)` for a final answer, or `start/status/wait/read/tail/stop` for a longer job. Codex writes a final-message file; Pi separates text output from stderr; OpenCode extracts assistant text from events without forcing standalone startup. `extra_args` is passed as individual native argv entries, without shell parsing. Custom profiles can set `default_flags`, a keyword-to-flag map, `milestone_regex`, and `extract` (`stdout`, `file`, or `json_text`). Command arguments may contain `{prompt}`, `{final}`, and `{cwd}`. For interactive panes use `herdr.list()`, `read`, `prompt`, `wait`, or `send_keys`.
**Claude Code:** This Python MCP is separate from Claude's built-in experimental JavaScript Code Mode. In the 2.1.332 behavior targeted here, ordinary `claude -p` does not enable native JS Code Mode; non-interactive enablement is gated to Agent SDK flag settings. Use an interactive session for native Code Mode. An API-key `claude -p` invocation can attach this MCP with `--mcp-config`. Repeated cold runs can consume more weekly quota through cache writes; this project does not measure that effect.
## Prompt Cache invariants
The ordered tool definitions are static. They do not depend on config, upstream catalog, session, elapsed time, or discovery results. The server advertises `tools.listChanged: false`; negotiated protocol versions affect initialization only. The test suite freezes the serialized list, tests negotiation separately, and checks discovery against a pinned catalog. This stabilizes **this server's** contribution to a prompt prefix; it cannot guarantee a host cache hit.
## Benchmark results
Run `./check` for offline tests (28 tests) and the reproducible 8-shard fixture benchmark (`python3 benchmarks/bench.py`). Each baseline must return the exact same eight per-shard totals. Totals include tool schemas, requests, responses, discovery, generated Python, spill reread, and final answer. Default counts use a deterministic fixture lexical tokenizer (**not provider billing**); pass `--token-counter /path/to/program` for a specific tokenizer.
| Mode | Correct | Fixture tokens | Delta vs sequential | Observed wall time |
| --- | --- | ---: | ---: | ---: |
| Sequential native (`run_command` x8) | Yes | 5,819 | baseline | 0.70 s |
| Parallel filtered shell (`run_command` + `awk` x8) | Yes | 1,003 | -82.8% | 0.12 s |
| `codemode-mcp` parallel (`batch()` + spill reread) | Yes | 925 | -84.1% (-7.8% vs parallel) | 0.24 s |
| `codemode-mcp` serial control | Yes | 917 | -84.2% | 0.80 s |
On a single simple `awk`-filterable pass, parallel native shell pipelines remain slightly faster in wall time (0.12 s vs 0.24 s) because `cm_exec` starts a fresh Python process; `batch()` runs 3.3x faster than the serial `codemode-mcp` control (0.24 s vs 0.80 s). The larger token wins appear on multi-step cross-tool joins, repeated pane/agent polling, and long-context sessions where every avoided round-trip skips a full prefix cache read.
Use `python3 benchmarks/bench.py --live-config /path/to/config.toml` to include read-only live catalog discovery. For `pi` headless one-shots with heavy extensions/MCP configs, passing `no_extensions=True, no_skills=True, no_mcp=True, offline=True` avoids startup discovery overhead while leaving all native flags intact.
TDQS
Scored across 2 tools
cm_discover is purely introspective (finding namespaces, signatures, schemas) while cm_exec runs Python code. The two purposes are orthogonal with no overlap, so an agent can always pick the right tool.
Both tools use the same cm_ prefix followed by a short verb (discover, exec) in consistent snake_case. The pattern is predictable and readable despite the verb-only names.
Two tools is slightly below the typical 3-15 range, but each is essential to the code-mode loop: one to introspect the API surface and one to execute. A larger surface would likely be redundant for this meta-server.
Discovery plus execution forms a complete lifecycle for a code-mode server. Minor gaps exist (e.g., cancellation, validation-without-execution, or worktree listing), but the core discover-then-run workflow is fully covered.