Skip to main content

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 Usually 1-3

Measured with the bundled examples (tiktoken o200k_base):

Scenario Classic MCP codemode-mcp Saved
306 tools: definitions per request (codemode-mcp stats -c examples/mcp.big.json) 78,933 1,505 98.1%
"Top 3 Indian customers by spend", 14 tool calls, total input (python examples/benchmark.py) 8,463 1,302 84.6%

Run codemode-mcp benchmark to measure the same thing with your own servers, prompt and LLM.

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_tools limit which tools are available.
  • "disabled": true skips the server.
  • "oauth": true (or an object with client_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 (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_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 V8 heap limit of the sandbox process

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, plus search_tools when 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/.

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 conservative 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-email becomes send_email).
  • await resources.list() and await resources.read(uri) give access to MCP resources.
  • Top-level await and asyncio.gather work.
  • 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 8000:8000 -v $PWD/mcp.json:/config/mcp.json codemode-mcp     # http://localhost:8000/mcp

Development

uv sync --all-extras
uv run pytest                      # 32 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.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for codemode-mcp 0.2.0
File Size Uploaded Provenance Actions
codemode_mcp-0.2.0.tar.gz 52.1 kB Without provenance Details for codemode_mcp-0.2.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for codemode-mcp 0.2.0
File Interpreter ABI Platform Actions
codemode_mcp-0.2.0-py3-none-any.whl Python 3 none any Details for codemode_mcp-0.2.0-py3-none-any.whl

Total release size: 111.1 kB

Release files / codemode_mcp-0.2.0.tar.gz

Download URL codemode_mcp-0.2.0.tar.gz
Size 52.1 kB
Tags Source
SHA-256 checksum
How to use checksums
94a513fa346c581137f2c2326d3be277b2795ab3430d5f6527559d684a8e8a04
BLAKE2b-256 checksum
How to use checksums
bdb501f514f623f6ea9bf12a4b16cb5299496f3b9499eda7f74b8d0706632360
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.12 {"installer":{"name":"uv","version":"0.13.12","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Release files / codemode_mcp-0.2.0-py3-none-any.whl

Download URL codemode_mcp-0.2.0-py3-none-any.whl
Size 59.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
e5b2b05023cf75340b7d1143d0a6be0aba00b1c09d23bc3d2acb64178b330c89
BLAKE2b-256 checksum
How to use checksums
19f24c4d142f8fa04726520118ffc8e01ec21658480c3f1daa6fcba8d98e3a45
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.12 {"installer":{"name":"uv","version":"0.13.12","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Security for codemode-mcp 0.2.0

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.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page