How it works¶
┌─────────────┐ run_code / search_tools ┌──────────────────────────────┐
│ LLM / MCP │ ──────────────────────────▶ │ codemode-mcp (host process) │
│ client │ ◀────────────────────────── │ catalog · approvals · usage │
└─────────────┘ compact result only └──────┬──────────────▲────────┘
│ JSON lines │ tool calls
┌────────▼──────────────┴────────┐
│ Deno (no net/env/fs/run) │
│ └─ Pyodide: model's Python │
└────────────────────────────────┘
host ⇄ upstream MCP servers
(stdio · Streamable HTTP · SSE · OAuth)
1. Catalog¶
On start, codemode-mcp connects to every server in mcp.json and lists their tools.
Each tool's JSON Schema is turned into a compact Python stub:
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."""
- Server and tool names are converted to valid Python identifiers (
send-emailbecomessend_email). The original names are still used on the wire. - Required parameters come first; optional ones are keyword-only and show their defaults.
- Nested objects are shown inline (
{id: int, tags?: list[str]}), and$refschemas are resolved. - Output schemas become return types. The SDK's
{"result": …}wrapper is removed.
2. What the LLM is given¶
codemode-mcp picks the cheapest presentation that still tells the model everything it needs:
| Catalog size | Tools exposed | What's in the description |
|---|---|---|
Small: stubs fit in inline_catalog_tokens (1,500) |
run_code only |
Every stub, so the model can call tools straight away |
Small to medium: one-line signatures fit in inline_signatures_tokens (600) |
search_tools + run_code |
Every tool's parameters, one line each, so the first script needs no look-up |
Medium: names fit in inline_names_tokens (1,500) |
search_tools + run_code |
Every tool name, grouped by server |
| Large: thousands of tools | search_tools + run_code |
Server names and tool counts |
search_tools("create issue") returns the stubs of the best matches. Exact names fetch
specific tools in one call (search_tools("git.git_log git.git_show")), and a server name
lists everything on that server, one line per tool. It uses BM25-style
keyword ranking over names, descriptions and parameters, so the model only reads the
signatures it needs.
3. Running the code¶
run_code(code) sends the script to a warm sandbox. The sandbox is a long-lived Deno
process running Pyodide (CPython compiled to WebAssembly):
- Fresh namespace: every run starts with no variables (unless persistent state is on).
- Tools: each server is a global object, and its tools are
asyncfunctions. Top-levelawaitandasyncio.gatherwork. - Bridge: when the script calls a tool, the sandbox sends a JSON message to the host.
The host checks it, applies approvals, calls the real MCP server and returns the result
as plain Python data (
dict,list,str). Errors raiseToolError. - Result: the value of the last expression is returned as JSON, together with any
print()output, truncated atmax_output_chars.
import asyncio
custs = await shop.list_customers(country="IN") # 1 call
orders = await asyncio.gather(*(shop.get_orders(c["id"]) for c in custs)) # N calls in parallel
best = max(zip(custs, orders), key=lambda co: sum(o["total"] for o in co[1]))
{"name": best[0]["name"], "orders": len(best[1])} # ← only this reaches the LLM
4. Why this saves tokens¶
- Bounded definitions. Classic MCP sends every tool schema with every request. Code Mode sends one or two short tools, so the cost doesn't grow with the size of the catalog.
- Data never round-trips. Raw results (lists of records, documents, logs) stay in the sandbox. Only the filtered answer goes back to the model.
- Fewer turns. A loop over 50 items is one script, not 50 LLM turns, and each classic turn re-sends the whole conversation.
- No copying. Moving data from tool A to tool B doesn't require the model to read it and write it out again.
5. Isolation¶
The sandbox process starts with --deny-net --deny-env --deny-run --deny-write --deny-ffi --deny-sys.
Its only read access is Deno's npm cache, which Pyodide needs. JavaScript escape hatches
(Deno, fetch, WebSocket, …) are removed before any user code runs. If a run goes
over its timeout, the process is killed and restarted automatically. See
Security.
The runtime API inside run_code¶
| Name | Description |
|---|---|
<server>.<tool>(...) |
Async function for each upstream tool. Positional and keyword arguments are checked against the schema. |
ToolError |
Raised when an upstream tool fails, is denied, or isn't allowed |
resources.list(server=None) |
Lists MCP resources: [{server, uri, name, description, mime_type}] |
resources.read(uri, server=None) |
Reads a resource: text, or {mime_type, blob, size_bytes} for binary content |
print(...) |
Output that is returned to the model |
| Last expression | Returned to the model as JSON |
| Standard library | Available (json, re, datetime, asyncio, statistics, …). No third-party packages, no network |