codemode-mcp
This server does not currently have a deployable release on Glama. Follow the repository's setup instructions to install and configure it for your MCP client, including any required credentials and local dependencies.
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 ( | 78,933 | 1,697 | 97.9% |
Scripted replay of "Top 3 Indian customers by spend", 14 tool calls, total input ( | 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 |
| 100/120 → 118/120 | 6.9M → 2.6M (−62%) | $0.75 → $0.83 (+11%) |
| 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.
Related MCP server: mcp-compressor
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 sandboxOr 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.
| Default | Meaning |
|
|
|
|
| Hybrid mode: these tools are also exposed directly, as regular MCP tools |
|
| Keep Python variables between |
| 30 | Seconds per |
| 60 | Seconds per upstream tool call |
| 200 | Upstream calls allowed per |
| 20000 | Output returned to the LLM is truncated beyond this |
| 1500 | If all signatures fit, embed them and expose only |
| 600 | Otherwise embed one-line signatures of every tool if they fit |
| 1500 | Otherwise embed the tool-name list if it fits |
| 8 / 600 | Search output size |
|
| Token accounting for the dashboard (counts only) |
|
|
|
| none | JSONL file recording each run's code, upstream calls (with arguments) and output |
| 512 | Memory a script may use: Python gets a |
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_TOKENDevelopment
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.pySee the contributing guide. Inspired by Cloudflare's Code Mode.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
This server cannot be deployed
Maintenance
Related MCP Connectors
MCP server for your apps' tools and custom tools, plus hosted AI agents and approval-gated workflows
The OpenRouter for tools. One MCP connection gives any AI agent 254 hosted tools, pay per call.
Single-connection meta-router indexing 500+ MCP servers & A2A tools with 85% token compression and
LLM cost optimization gateway, repo token-waste auditor & model arbitrage MCP server.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceActs as a proxy for multiple MCP servers, reducing context window usage from 15,000+ tokens to ~500 tokens by dynamically loading servers on-demand and exposing only 3 tools instead of all tool definitions.5GPL 3.0
- AlicenseNot gradedqualityAmaintenanceA proxy server that wraps existing MCP servers to significantly reduce token consumption by compressing tool descriptions into a two-step interface. It enables users to integrate extensive toolsets without exceeding context limits or incurring high API costs.146Apache 2.0
- AlicenseNot gradedqualityDmaintenanceA self-hosted MCP server that provides a single execute_code tool, enabling agents to write TypeScript to call multiple REST APIs via fetch() with transparent credential injection, reducing token usage by keeping intermediate results in the sandbox.11BSD 3-Clause
- AlicenseNot gradedqualityCmaintenanceAggregates many upstream MCP servers behind a single proxy so AI coding editors can access hundreds of tools without hitting tool-count limits, while trimming tool schemas to cut prompt token usage by up to ~98%. It also sandboxes tool calls by blocking path traversal, dangerous shell chaining, and host environment variable leakage.PolyForm Noncommercial 1.0.0