codemode-mcp
Code Mode for MCP, in Python. Put any number of MCP servers behind one or two small tools. The LLM writes a short Python script that calls your tools as typed async functions; the script runs in a locked-down WebAssembly sandbox and only the final, compact result goes back to the model. A built-in savings dashboard shows how many tokens that saved compared with classic MCP.
Documentation: https://codemode-mcp.vercel.app/
classic MCP codemode-mcp
LLM - tool schemas (every request, all tools) LLM - 1-2 tiny tool definitions
| <- result 1 (raw JSON into context) | -> run_code("""
| -> call 2 | for c in await shop.list_customers():
| <- result 2 (raw JSON into context) | ... await shop.get_orders(c["id"])
| ... N round-trips | top3 """)
| | <- [["Customer 8", 12086], ...] (only this)
Why it saves tokens
| Cost driver | Classic MCP | codemode-mcp |
|---|---|---|
| Tool definitions | Every tool's JSON schema, on every request | Bounded at ~1-2k tokens regardless of API size; signatures fetched on demand |
| Intermediate results | Every raw result goes through the LLM context | Stays in the sandbox |
| Loops, filters, joins | One LLM turn per step | Plain Python in one execution |
| LLM round-trips | N | 1-3 when the model uses the tools as intended |
Token counts from the bundled example servers (tiktoken o200k_base, no model involved):
| Scenario | Classic MCP | codemode-mcp | Saved |
|---|---|---|---|
A synthetic 306-tool catalog: definitions per request (codemode-mcp stats -c examples/mcp.big.json) |
78,933 | 1,697 | 97.9% |
Scripted replay of "Top 3 Indian customers by spend", 14 tool calls, total input (python examples/benchmark.py) |
8,463 | 1,634 | 80.7% |
These show how the mechanism scales; they are not measurements of a real model. Code Mode also has a fixed cost of about 450 tokens, so with one or two small tools and single-call tasks it uses more tokens, not fewer.
Measured with real models
benchmarks/ holds a suite of ten tasks over five real MCP servers (46
tools), including tasks where Code Mode is expected to lose. The first six were each run 20
times in each style on two Gemini models through Google Cloud Vertex AI:
| Model | Right answers: classic → Code Mode | Total tokens: classic → Code Mode | Total cost: classic → Code Mode |
|---|---|---|---|
gemini-3.5-flash-lite |
100/120 → 118/120 | 6.9M → 2.6M (−62%) | $0.75 → $0.83 (+11%) |
gemini-3.8-flash |
119/120 → 120/120 | 32.0M → 3.0M (−91%) | $12.85 → $2.79 (−78%) |
Two further checks, on the same models:
- Through the MCP proxy (
codemode-mcp serve, the way a client app uses it): 357 of 360 runs right, with 64% and 90% fewer tokens than classic. Turning onpersistent_statemade no measurable difference. - On four tasks added after the fixes, which the library was not tuned on: Code Mode was right in 238 of 240 runs against 108 of 120 for classic, with 38% to 65% fewer tokens.
Read these with three things in mind:
- They are for version 0.3.0, not 0.2.0. Version 0.2.0 failed its first measurement: small models wrote scripts that never called the tools, and Code Mode was right in 5 of 18 runs. The instructions given to the model were rewritten. If you installed 0.2.0, upgrade.
- Fewer tokens is not always less money. On the smaller model Code Mode cost 10% to 20% more, because Google bills repeated input at a tenth of the price and classic's fixed block of tool definitions benefits most from that.
- Simple one-call tasks are still not its strength, and the test set is small: ten tasks over five servers, two models from one provider.
See the benchmarks page for the full tables
and how to run the suite, or use codemode-mcp benchmark to compare one prompt on your own
servers.
Install
pip install codemode-mcp # brings its own Deno runtime via the `deno` wheel
pip install "codemode-mcp[all]" # + OpenAI & Anthropic SDKs and tiktoken for exact token counts
codemode-mcp setup # one-time: downloads Pyodide (~10 MB) and checks the sandbox
Or without installing: uvx codemode-mcp serve -c mcp.json, or Docker (see below).
Quick start: use it with the MCP client you already have
codemode-mcp init --from claude # or cursor | vscode | windsurf | path/to/config.json
codemode-mcp init --from claude --install # also points Claude Desktop at codemode-mcp (keeps a backup)
init copies your client's servers into mcp.json and prints, or with --install
writes, the single entry the client needs. Restart the client, and all your tools now go
through Code Mode. See the client guide for manual configs for Claude
Desktop, VS Code, Cursor, Windsurf and others.
Configure
Use the same mcp.json format your MCP client uses, with an optional codemode block:
{
"mcpServers": {
"github": {"command": "npx", "args": ["-y", "@modelcontextprotocol/server-github"],
"env": {"GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_TOKEN}"}},
"linear": {"url": "https://mcp.linear.app/mcp", "oauth": true},
"docs": {"url": "https://example.com/mcp", "headers": {"Authorization": "Bearer ${DOCS_TOKEN}"}},
"legacy": {"type": "sse", "url": "https://example.com/sse", "exclude_tools": ["drop_database"]}
},
"codemode": {
"require_approval": ["*.delete_*", "github.merge_pull_request"],
"expose_tools": ["github.get_me"],
"timeout": 30
}
}
Per server:
${VAR}and${VAR:-default}are filled in from environment variables.include_tools/exclude_toolslimit which tools are available."disabled": trueskips the server."oauth": true(or an object withclient_id,client_secret,scopes,redirect_port) turns on OAuth sign-in for remote servers.
codemode setting |
Default | Meaning |
|---|---|---|
require_approval |
[] |
server.tool globs that need a human "yes" before each call, or "@destructive" for every tool its server marks destructive (see Approvals) |
expose_tools |
[] |
Hybrid mode: these tools are also exposed directly, as regular MCP tools |
persistent_state |
false |
Keep Python variables between run_code calls |
timeout |
30 | Seconds per run_code (paused while waiting for approval; the sandbox is reset if exceeded) |
tool_call_timeout |
60 | Seconds per upstream tool call |
max_tool_calls |
200 | Upstream calls allowed per run_code |
max_output_chars |
20000 | Output returned to the LLM is truncated beyond this |
inline_catalog_tokens |
1500 | If all signatures fit, embed them and expose only run_code |
inline_signatures_tokens |
600 | Otherwise embed one-line signatures of every tool if they fit |
inline_names_tokens |
1500 | Otherwise embed the tool-name list if it fits |
max_search_results / max_description_chars |
8 / 600 | Search output size |
usage_tracking / usage_db |
true / ~/.codemode-mcp/usage.db |
Token accounting for the dashboard (counts only) |
tokenizer |
auto |
tiktoken if installed, else ~4 chars per token |
audit_log |
none | JSONL file recording each run's code, upstream calls (with arguments) and output |
memory_mb |
512 | Memory a script may use: Python gets a MemoryError at the limit, and a sandbox that grows well past it is restarted |
Use it
1. As an MCP server (works with Claude Desktop, VS Code, Cursor, Copilot and others)
{"mcpServers": {"codemode": {"command": "codemode-mcp", "args": ["serve", "-c", "/path/to/mcp.json"]}}}
The proxy exposes:
run_code, plussearch_toolswhen the catalog is large;- any hybrid
expose_tools; - upstream prompts and resources, passed through unchanged.
codemode-mcp serve --transport http --port 8000 serves Streamable HTTP, with the
dashboard at /dashboard/. It listens on this machine only; any other --host needs an
access token in CODEMODE_TOKEN, which clients send as Authorization: Bearer <token>.
2. As a Python library, with any LLM
import asyncio
from openai import AsyncOpenAI
from codemode_mcp import CodeMode
async def main():
async with CodeMode.from_config("mcp.json") as cm:
client = AsyncOpenAI()
messages = [
{"role": "system", "content": cm.system_prompt},
{"role": "user", "content": "Which of my repos have open PRs older than 30 days?"},
]
while True:
resp = await client.chat.completions.create(model="gpt-4.1", messages=messages, tools=cm.tools("openai"))
msg = resp.choices[0].message
if not msg.tool_calls:
print(msg.content)
break
messages.append(msg)
for tc in msg.tool_calls:
messages.append(await cm.handle_openai_tool_call(tc))
print(cm.usage()) # {'codemode_tokens': ..., 'classic_tokens': ..., 'saved_pct': ...}
asyncio.run(main())
You can also use the ready-made loops:
await run_openai(cm, prompt, model=..., base_url=...) (any OpenAI-compatible API,
including Ollama, OpenRouter, Azure and GitHub Models) or await run_anthropic(cm, prompt, model=...).
Other frameworks only need cm.tools(format) (openai, openai-responses, anthropic
or mcp) and await cm.call(name, arguments).
3. From the CLI
codemode-mcp chat -c mcp.json -m gpt-4.1-mini -v "Summarise my open issues"
codemode-mcp chat -c mcp.json -m llama3.1 --base-url http://localhost:11434/v1
codemode-mcp run -c mcp.json "len(await github.list_repos(owner='me'))"
codemode-mcp search -c mcp.json "create issue" # what the LLM sees from search_tools
codemode-mcp tools -c mcp.json --format anthropic
codemode-mcp login -c mcp.json linear # OAuth sign-in ahead of time (optional)
Monitoring: see what you saved
codemode-mcp usage # summary in the terminal (--range 1d|7d|30d|all, --json)
codemode-mcp dashboard # local web dashboard at http://127.0.0.1:8765
codemode-mcp serve --dashboard-port 8765 # dashboard alongside a stdio server
codemode-mcp benchmark -c mcp.json -m gpt-4.1-mini "Find my 3 biggest customers in India"
The dashboard shows:
- tokens used by Code Mode against a lower-bound estimate for classic MCP;
- savings per day, by call type and by tool;
- recent activity;
- measured benchmarks.
benchmark runs the same prompt through a real LLM twice: once with classic tool
calling (every upstream tool exposed) and once with Code Mode. It reports the provider's
actual token counts, turns and answers, and records the result for the dashboard. How the
estimates are calculated, and their limits, is described in
the monitoring guide. Only counts and tool names are stored, never
code, arguments or results.
What the model sees
class shop:
async def list_customers(
*, country: str | None = None, tier: Literal["free", "pro", "enterprise"] | None = None
) -> list[dict]:
"""List customers, optionally filtered by ISO country code and/or tier."""
async def get_orders(customer_id: int) -> list[dict]:
"""Get all orders for a customer, including line items and totals."""
Inside run_code:
- Each server is a global object, and its tools are async functions. Names are turned into
valid Python identifiers (
send-emailbecomessend_email). await resources.list()andawait resources.read(uri)give access to MCP resources.- Top-level
awaitandasyncio.gatherwork. - The last expression is returned as JSON, along with any
print()output. - A failed tool call raises
ToolError.
Approvals
Tools that match require_approval pause the script until a person answers:
- MCP server mode: the question goes to the user through MCP elicitation.
- On 2026-07-28+ connections the sandbox run is suspended and resumed after the client's retry, so tool calls made before the approval point are never repeated.
- Clients that don't support elicitation get a clear error instead of a silent call.
- CLI (
run,chat): a y/N prompt in the terminal. - Library: pass
approval_callback=async (server, tool, args) -> bool.
Security model
The model's code runs in Pyodide (CPython compiled to WebAssembly) inside a Deno process
started with --deny-net --deny-env --deny-run --deny-write --deny-ffi --deny-sys. It can
read only Deno's npm cache, which Pyodide needs in order to load. On top of that, the
Deno, fetch and other JavaScript globals are removed before user code runs.
- The only way out of the sandbox is a JSON channel to the host. The host calls only catalogued, allowed tools, and checks approvals.
- Credentials, including OAuth tokens (stored in
~/.codemode-mcp/oauth), stay in the host. - Limits: wall-clock time, tool calls per run, output size and heap size.
See the security policy for the threat model, and the test suite for escape
attempts: files, env, network, processes, NODEFS mounts and dynamic import().
Docker
docker build -t codemode-mcp .
docker run -p 127.0.0.1:8000:8000 -e CODEMODE_TOKEN -v $PWD/mcp.json:/config/mcp.json codemode-mcp
# http://localhost:8000/mcp, with the header Authorization: Bearer $CODEMODE_TOKEN
Development
uv sync --all-extras
uv run pytest # 48 tests: sandbox, security, OAuth, approvals, proxy, usage, benchmark...
uv run ruff check . && uv run ruff format --check .
uv run python examples/benchmark.py
See the contributing guide. Inspired by Cloudflare's Code Mode.
Metadata
Release files for codemode-mcp 0.3.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| codemode_mcp-0.3.1.tar.gz | 62.2 kB | Without provenance | Details for codemode_mcp-0.3.1.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| codemode_mcp-0.3.1-py3-none-any.whl | Python 3 | none | any | Details for codemode_mcp-0.3.1-py3-none-any.whl |
Total release size: 131.9 kB
Release files / codemode_mcp-0.3.1.tar.gz
| Download URL | codemode_mcp-0.3.1.tar.gz |
|---|---|
| Size | 62.2 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
0d89e1db8f316d351cc4c821bc3573efe6277181846bd3aea4200da5accfb29c
|
|
BLAKE2b-256 checksum How to use checksums |
ff3cc8a8a42cb24ccffcacb34d60096945026354ae937d50c47882ccc4157242
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.8.22
|
Release files / codemode_mcp-0.3.1-py3-none-any.whl
| Download URL | codemode_mcp-0.3.1-py3-none-any.whl |
|---|---|
| Size | 69.7 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
f7fba6b470a0e52272944c15dc5a35a086f144064d5931ddd24e277f38d43186
|
|
BLAKE2b-256 checksum How to use checksums |
08ba7f1d0b38f7a06913b323a226c8f61c290a9de75072be90849a49d0052fc0
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.8.22
|
Security for codemode-mcp 0.3.1
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.