Skip to main content
Glama

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.

PyPI Python CI License: MIT

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.

Related MCP server: fde-assessment

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.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    Related MCP Connectors

    Related MCP Servers

    • F
      license
      Not graded
      quality
      D
      maintenance
      Enables an LLM to dynamically discover and call tools across multiple MCP servers (file, GitHub, SQL, Python execution) with authentication, rate limiting, and observability, supporting parallel execution and secure deployment.
      -
    • F
      license
      Not graded
      quality
      D
      maintenance
      Enables MCP tool calls with strict schema validation and stdio isolation, while providing a security gateway for tool-level authorization, streaming PII redaction, and model failover routing.
      -
    • A
      license
      Not graded
      quality
      C
      maintenance
      Fronts every MCP server you have with two tools: search shortlists relevant tools, and execute runs sandboxed Python that calls upstream tools as mcp..(). It enables agents to make bulk, repeated, or conditional tool calls using calibrated decision-model choices instead of per-item LLM generation.
      3
      MIT
    • A
      license
      A
      quality
      B
      maintenance
      Enables a model to write short Python programs that call a wrapped MCP server's tools as async functions, rather than invoking them one at a time. The program runs in a locked-down Docker sandbox, and every tool call passes through a host-side bridge that enforces an allowlist, schema-validated arguments, call budgets, timeouts and output caps.
      1
      MIT