Code Mode MCP
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@Code Mode MCP Discover available tools and use Python to list the five largest files here."
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
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
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/stdoutFor a GUI or CLI client, make the following executable launcher with absolute paths. Replace all three paths; do not rely on shell startup files.
#!/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 serveRegister the launcher with one client at a time:
Client | Registration command |
AGY |
|
Claude Code |
|
Codex |
|
Pi (with native MCP support) |
|
OpenCode |
|
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.
Related MCP server: python-session-mcp
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
namespaceorqueryfor signatures (default 25); usedetail="schema"for at most five schemas. A question mark marks an optional argument.Call
mcp.catalog.lookup(key=7)ormcp.call("catalog","dashed-tool",{"raw":True},raw=True). A single JSON text result becomes a Python value. Useraw=Trueto keep the envelope.Use
fs,sh,cli, and orderedbatchfor local work.emitprints 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, orspill.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, andredact_secretsat 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, stdio, and CLI and agent profiles. Configuration accepts TOML or JSON,
${ENV}, andurl_from_mcp_config = "/path/to/client.json#alias". Commands are argv arrays; useunset_envon 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 ( | Yes | 5,819 | baseline | 0.70 s |
Parallel filtered shell ( | Yes | 1,003 | -82.8% | 0.12 s |
| Yes | 925 | -84.1% (-7.8% vs parallel) | 0.24 s |
| 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.
Available Tools
2 toolscm_discoverC
Find namespaces, callable signatures, or schemas.
Inputs: limit, query, detail, namespace.
cm_execD
Run trusted Python; pass the worker worktree as cwd.
Inputs: code (required), cwd, max_chars, timeout_s.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
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.
Maintenance
Related MCP Connectors
Hosted MCP runtime where your agent publishes its own tools by tool call and keeps working.
MCP server for your apps' tools and custom tools, plus hosted AI agents and approval-gated workflows
Build and run AI workflows, agents, data tables and 1000+ API integrations from any MCP client.
Remote MCP utilities for agents: structured data, commerce checks, and x402 paid API discovery.
Related MCP Servers
- FlicenseNot gradedqualityCmaintenanceEnables coding agents to execute Python code, run script files, and install pip packages locally via MCP.-
- AlicenseNot gradedqualityDmaintenanceEnables LLM clients to run Python code in a persistent, user-selected interpreter via MCP, with tools for data loading, summaries, regressions, diagnostics, and plotting, while keeping sessions alive between calls and isolating crashes.MIT
- AlicenseNot gradedqualityBmaintenanceEnables LLM agents to run persistent Python code in a workspace-scoped shared kernel, with tools for execution, background tasks, file operations, and external MCP integrations.AGPL 3.0
- AlicenseNot gradedqualityNot gradedmaintenanceEnables agents to dynamically generate typed MCP tool schemas, validate Python execution ASTs against unsafe imports, and hot-plug sandboxed callable handlers into an active runtime. This allows new tools to be synthesized and safely executed on demand.MIT