MCP code mode in Python: let the model write one script instead of 37 round trips
Code mode turns MCP tools into a Python API and runs the model's script in a sandbox. Tested against classic tool calling on three tasks, with token counts and the failures.
In classic MCP tool calling, the model calls one tool, the result goes back into its context, it reads it and calls the next tool. "Code mode" replaces that loop: the client turns the MCP server's tools into a code API, the model writes one script that calls them, a sandbox runs it, and only what the script prints comes back to the model.
Cloudflare published the idea in September 2025 under the name Code Mode, with TypeScript and V8 isolates. Anthropic described the same pattern in Code execution with MCP in November 2025 and reported one workflow going from 150,000 tokens to 2,000. Both posts use TypeScript. This one builds it in Python against a real MCP server, runs it next to classic tool calling on the same tasks with the same local model, and reports what broke.
The test#
An order-management MCP server with 240 orders and three tools:
from mcp.server.mcpserver import MCPServer
server = MCPServer("shop")
@server.tool()
def list_orders(status: str) -> list[dict]:
"""List every order with the given status ("pending", "paid" or "shipped").
Each order has order_id, customer_id, amount_inr, status, days_old and items."""
return [o for o in ORDERS if o["status"] == status]
@server.tool()
def get_customer(customer_id: str) -> dict:
"""Get a customer's name, phone and email by customer_id."""
return CUSTOMERS[customer_id]
@server.tool()
def send_reminder(customer_id: str, order_id: str, message: str) -> str:
"""Send a payment reminder SMS to a customer about one order. Returns "sent"."""
with open(SENT_LOG, "a") as f:
f.write(json.dumps({"customer_id": customer_id, "order_id": order_id, "message": message}) + "\n")
return "sent"
The orders and 60 customers come from a seeded random generator, so every run sees the same data: 83 pending orders worth Rs 4,61,061. list_orders("pending") returns 9,759 characters of JSON.
Three tasks, each with an answer the harness can check:
| Task | Correct answer |
|---|---|
| count: "How many orders are pending right now, and what is their total value?" | 83 orders, Rs 4,61,061 |
| top: "Which customers have 4 or more pending orders? Give their names." | Sanjay Rao, Asha Iyer, Rohit Reddy |
| remind: "Send a payment reminder to the customer of every pending order older than 7 days and above Rs 5,000 (one per order). Then tell me how many you sent and the total." | Exactly 21 reminders, one per qualifying order, total Rs 2,29,546 |
For the reminder task the harness reads the server's send log, so a run counts as correct only if the right 21 orders got one SMS each and the reported numbers match. Claiming to have sent them does not count.
Model: qwen3:4b-instruct on Ollama 0.40.18, temperature 0.7, five seeds per task and mode. It is a small model on purpose. It is cheap to run many times, and it shows failures that a larger model hides some of the time.
Classic mode#
The client lists the server's tools and passes them to the model as function definitions. Each tool call goes to the MCP server and its JSON result goes back into the conversation. This is how most MCP clients work.
Code mode in about 80 lines#
The model gets one tool, run_python(code), and a system prompt containing a Python stub generated from the MCP tool list:
def api_stub(tools) -> str:
"""What the model sees: signatures and docstrings only."""
out = []
for t in tools:
props = t.input_schema.get("properties", {})
sig = ", ".join(f'{p}: {"str" if v.get("type") == "string" else v.get("type", "any")}'
for p, v in props.items())
out.append(f'def {t.name}({sig}):\n """{(t.description or "").strip()}"""')
return "\n\n".join(out)
# module: tools (this is what goes in the prompt)
def list_orders(status: str):
"""List every order with the given status ("pending", "paid" or "shipped").
Each order has order_id, customer_id, amount_inr, status, days_old and items."""
def get_customer(customer_id: str):
"""Get a customer's name, phone and email by customer_id."""
def send_reminder(customer_id: str, order_id: str, message: str):
"""Send a payment reminder SMS to a customer about one order. Returns "sent"."""
The script runs in a child process. Inside it, tools.py is a shim where each function writes a request line to stdout and blocks until the parent writes the result back on stdin. The parent forwards each request to the real MCP server through the same client session that classic mode uses:
SHIM = '''
import json, sys
_out = sys.stdout
sys.stdout = sys.stderr # print() from the script goes to stderr, which the parent collects
def _call(name, **args):
_out.write("\\x00CALL " + json.dumps({"name": name, "args": args}) + "\\n"); _out.flush()
reply = json.loads(sys.stdin.readline())
if "error" in reply:
raise RuntimeError(reply["error"])
return reply["result"]
'''
def make_api(tools) -> str:
lines = [SHIM]
for t in tools:
props = t.input_schema.get("properties", {})
lines.append(f'def {t.name}({", ".join(props)}):\n'
f' return _call("{t.name}", {", ".join(f"{p}={p}" for p in props)})\n')
return "\n".join(lines)
The parent side reads the child's stdout line by line, answers tool calls, and collects everything the script printed:
PROFILE = ('(version 1)(allow default)(deny network*)(deny file-write*)'
'(allow file-write* (subpath "{tmp}"))(allow file-write-data (literal "/dev/null"))')
async def run_code(code, tools, call_tool, timeout=60, max_output=4000):
tmp = Path(tempfile.mkdtemp(prefix="codemode-")).resolve()
(tmp / "tools.py").write_text(make_api(tools))
(tmp / "main.py").write_text(code)
proc = await asyncio.create_subprocess_exec(
"sandbox-exec", "-p", PROFILE.format(tmp=tmp), sys.executable, "-I", "-S", "-c",
f"import sys; sys.path.insert(0, {str(tmp)!r}); "
f"exec(open({str(tmp / 'main.py')!r}).read(), {{'__name__': '__main__'}})",
cwd=tmp, env={"PATH": "/usr/bin:/bin"},
stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE,
limit=2**24)
calls = {}
async def pump():
while line := await proc.stdout.readline():
if line.startswith(b"\x00CALL "):
req = json.loads(line[6:])
calls[req["name"]] = calls.get(req["name"], 0) + 1
try:
res = {"result": await call_tool(req["name"], req["args"])}
except Exception as e:
res = {"error": str(e)}
proc.stdin.write((json.dumps(res) + "\n").encode())
await proc.stdin.drain()
return await proc.stderr.read()
try:
err = await asyncio.wait_for(pump(), timeout)
await proc.wait()
except asyncio.TimeoutError:
proc.kill()
return f"error: script timed out after {timeout}s"
text = err.decode(errors="replace")[:max_output]
return f"exit code {proc.returncode}, tool calls {calls}\n{text}"
sandbox-exec is macOS's built-in sandbox. With that profile the script cannot open network connections and cannot write outside its temp folder. I checked both from inside a script: urllib.request.urlopen raised URLError, and writing to the home folder raised PermissionError. -I keeps the user's site-packages and environment variables out. This is enough for a local experiment and not enough for production, which the security section covers.
Results#
| Task | Mode | Correct (of 5) | Prompt tokens per task (median) | Model calls | Time (median) |
|---|---|---|---|---|---|
| count | classic | 0 | 5,271 | 2 | 9.4 s |
| count | code | 1 | 847 | 2 | 3.8 s |
| count | code, hardened | 5 | 847 | 2 | 3.4 s |
| top | classic | 0 | 17,227 | 4 | 50.4 s |
| top | code | 0 | 957 | 2 | 6.6 s |
| top | code, hardened | 3 | 963 | 2 | 6.6 s |
| remind | classic | 0 | 228,725 | 37 | 53.8 s |
| remind | code | 4 | 1,120 | 2 | 9.7 s |
| remind | code, hardened | 5 | 1,122 | 2 | 9.0 s |
"Prompt tokens per task" is the sum of Ollama's prompt_eval_count over every model call in the task, which counts the whole conversation each time it is sent. "Hardened" adds two fixes described below, which I made after reading the failures of plain code mode.
Classic tool calling got nothing right. Code mode, once hardened, got 13 of 15 right while sending 6 to 200 times fewer tokens through the model.
How classic mode failed#
It cannot count 83 rows by reading them. For the count task, the model received the 83 pending orders as JSON and answered "There are 128 orders currently pending" in all five runs, with a different made-up total each time (Rs 1,69,999, Rs 1,05,67,649, Rs 1,37,999). Adding 83 numbers in its head is exactly what a language model is bad at.
It claimed to send reminders it never sent. In all five reminder runs the model fetched the orders, then called get_customer 36 times in a row, and stopped. It never called send_reminder once. Then it wrote "I sent a total of 18 payment reminders" (or 14, or 24). The SMS log was empty every time. Prompt tokens for that one task: 228,725, because the 9,759-character order list was re-sent with each of the 37 model calls.
That second failure is the one to remember. An agent that reports an action it did not take is worse than one that fails loudly. Grade agents on the side effects you can observe, never on what they say they did. The agent evals post covers how to build that kind of check.
How plain code mode failed, and the two fixes#
The first version of code mode got 5 of 15. Its scripts were mostly right. The harness around them was not.
Failure 1: the script printed nothing, and the model made up an answer. The model often ended its script with a bare expression, the way you would in a notebook:
num_pending = len(pending_orders)
total_value = sum(order['amount_inr'] for order in pending_orders)
num_pending, total_value
A script prints nothing for a bare expression, so the output was empty. My runner already said so: (the script printed nothing; use print() to see results). The model ignored that and answered "There are 0 pending orders" in four of five runs, and invented customer names ("Rajiv Kumar, Neha Sharma, ...") for the top task in all five.
Failure 2: a crash after side effects, then a rerun. In one reminder run the script sent all 21 reminders and then crashed on a typo in the final print (num_remides). The runner reported the error with a warning that the calls before it had really happened and should not be repeated. The model fixed the typo and ran the whole script again. Every one of the 21 customers got two SMS.
Telling the model about the problem did not work in either case. The fixes that worked changed the system so the model's habit no longer causes damage:
- Print the last expression, like a notebook. If the script ends with a bare expression, the runner rewrites it into
print(...)before running it:
import ast
def print_last_expression(code: str) -> str:
try:
tree = ast.parse(code)
except SyntaxError:
return code
if tree.body and isinstance(tree.body[-1], ast.Expr):
last = tree.body[-1]
tree.body[-1] = ast.Expr(ast.Call(ast.Name("print", ast.Load()), [last.value], []))
return ast.unparse(ast.fix_missing_locations(tree))
return code
- Make the side-effecting tool idempotent on the server.
send_remindernow checks its log and returns"already sent (skipped)"for an order that already got one. A rerun of the whole script is then harmless. This belongs in the MCP server, not in the agent, because any client (code mode, classic mode, a retrying HTTP layer) can repeat a call.
With both fixes, count and remind went to 5 of 5. Top went to 3 of 5, and the two misses are a different kind of error: the script printed ['Sanjay Rao', 'Asha Iyer', 'Rohit Reddy'] correctly and the model then copied it into its answer as "Rohit Red_" and "Rohit Red-Reddy". A 4B model sometimes garbles text while copying it. If the exact output matters, return the script's output to the user directly instead of having the model retype it.
Here is a script the hardened setup produced for the reminder task, unedited:
from tools import *
# List all pending orders that are older than 7 days and above Rs 5000
pending_orders = list_orders('pending')
reminders_sent = 0
total_amount = 0
for order in pending_orders:
if order['days_old'] > 7 and order['amount_inr'] > 5000:
customer = get_customer(order['customer_id'])
send_reminder(order['customer_id'], order['order_id'], f'Payment reminder for order {order['order_id']}')
reminders_sent += 1
total_amount += order['amount_inr']
print(reminders_sent, total_amount)
exit code 0, 43 tool calls {'list_orders': 1, 'get_customer': 21, 'send_reminder': 21}
21 229546
Forty-three tool calls, one model round trip. The 83 orders and 21 customer records, phone numbers and emails included, never entered the model's context. The model saw two numbers.
Where the savings come from#
Code mode saves tokens in two places, and the test shows both:
- Intermediate results stay out of the context. In classic mode the order list passed through the model on every call after it was fetched. In code mode it stayed in the script's memory.
- Loops do not cost round trips. Classic mode needs one model call per tool call, and each call re-sends the conversation. A
forloop in a script makes 43 calls for the price of one generation.
It does not save much on tool definitions in this test, because there are only three tools. With hundreds of tools, Anthropic's post suggests going further: write each tool as a file and let the model list and read only the ones it needs, the same progressive-disclosure idea as Agent Skills.
Privacy as a side effect#
In the reminder task the customers' phone numbers and emails went from the MCP server to the script and back to the server without the model seeing them. That matters when the model runs on someone else's servers. Anthropic's post goes a step further and has the client replace personal data with placeholders such as [EMAIL_1] before anything reaches the model, swapping the real values back when they flow into the next tool call.
It only holds if the script does not print the data. Nothing stops a model from writing print(get_customer("C016")). If the data must not reach the model, enforce it in the runner (filter or mask the output), not in the prompt.
Security: running model-written code#
Code mode means executing code a model wrote, and the model can be steered by anything in its context, including tool results. Treat the script as untrusted:
- No network except the tool bridge. Cloudflare's version runs the code in a V8 isolate with outbound requests blocked or routed through a proxy, and the only way out is the RPC bindings to the MCP servers. My
sandbox-execprofile does the same on a laptop. - No secrets inside the sandbox. The script never sees API keys. The parent process holds the MCP connection and its credentials.
- Limits. A timeout (60 s here), an output cap (4,000 characters here), and memory and CPU limits in production.
- A real isolation layer in production.
sandbox-execis deprecated by Apple and the child here is still a full CPython with access to the file system for reading. For a multi-user service, use a container with gVisor, a Firecracker microVM, a hosted sandbox, or a WebAssembly Python runtime. - Approval for dangerous tools still applies. A script can call
send_reminder21 times without asking anyone. If a tool sends money or messages, put the confirmation or the rate limit in the MCP server or the bridge, where the script cannot skip it.
When to use code mode#
Use it when a task chains many tool calls, loops over results, filters large outputs, or adds up numbers. All three tasks here are like that, and classic mode failed every one of them on a 4B model.
Keep classic tool calling for one or two calls whose results the model has to read anyway: "what's the weather", "look up this order". There the extra machinery buys nothing. Code mode also needs a model that writes decent code. The 4B model here could. Smaller models are more likely to break in code than in tool-call JSON, so test yours.
A larger model would do better in classic mode than the 4B model did, especially on the count task. The token numbers would not change: every intermediate result still goes through the context and every tool call still costs a round trip.
Reproduce it#
python3 -m venv v && v/bin/pip install mcp==2.3.0 httpx
OLLAMA_HOST=127.0.0.1:11435 ollama serve &
ollama pull qwen3:4b-instruct
v/bin/python cm_harness.py 5 qwen3:4b-instruct classic,code
v/bin/python cm_harness.py 5 qwen3:4b-instruct code-hardened
Files: shop_server.py (the MCP server), sandbox.py (stub, shim, runner, notebook fix), cm_harness.py (both loops and the grader). Versions: Python 3.15.2 on macOS, mcp 2.3.0, httpx 0.28.1, Ollama 0.40.18. The model wrote f-strings with nested quotes of the same kind, which need Python 3.12 or newer.
Sources#
- Cloudflare: Code Mode, the better way to use MCP (26 September 2025)
- Anthropic: Code execution with MCP (4 November 2025)
- MCP Python SDK