Watch a coding agent work and you see a rhythm: read a file, think, read another file, think, run a command, think. Each step looks small. The bill says otherwise. Every one of those steps re-sends the entire conversation to the model, and every tool result lands in the context window and stays there. Ten file reads to answer one question means ten full round trips, each carrying everything that came before.
Code mode is the fix: instead of one JSON tool call per step, the model writes a short script that calls many tools, a sandbox runs it, and only what the script prints goes back into the conversation. The intermediate results — the ten files, the raw API responses, the rows you wanted filtered — never enter the model's context at all.
The savings are not theoretical. Anthropic's engineering team showed a workflow dropping from 150,000 tokens to 2,000 — a 98.7% reduction — when tools were called from code instead of directly. In our own benchmark, a harness — the client program that runs the agent loop — built around code mode matched Codex's solve rate with the same model at about 24% lower cost per solved task. This post explains what code mode is, why it works, where the popular clients use it, and what we measured.
The problem: tool calls are priced per round trip
An agent loop works like this. The model emits a tool call — a small JSON object naming a tool and its arguments. The harness runs it, appends the result to the conversation, and sends the whole conversation back to the model so it can decide the next step. Then again. And again.
Two costs compound with every round:
- Tokens. Each round trip re-sends the system prompt, the tool definitions, and every message so far. Prompt caching softens this, but cached tokens still cost money — here is what a million tokens actually costs — and every new tool result is fresh input the next round must carry.
- Context. Tool definitions load upfront. Connect enough Model Context Protocol (MCP) servers — the standard that plugs external tools into agents — and the definitions alone can eat tens of thousands of tokens before you type a word. Anthropic's example workflow burned 150,000 tokens mostly on tool definitions and intermediate results. A fuller window also means a model that picks tools worse and forgets instructions sooner.
None of this matters much for a two-step task. It matters a lot for the work agents actually do: compare twelve files, page through an API, join two datasets, check every item in a list. The model does not need to see every intermediate byte. It needs the answer. Before changing anything, measure which tokens come from definitions and which from results — the split decides whether code mode is your fix at all.
What code mode is
Code mode gives the model one tool — usually called code, exec, or execute — that accepts a script. The tools the agent would normally call one by one are exposed inside the script's runtime as functions. The model writes the orchestration itself: loops, filters, parallel calls, conditionals. A sandbox executes it and returns only the printed or returned value.
The same task, two ways. Direct tool calls — three sequential calls, three round trips, every file's full content in context:
{"tool": "read_file", "arguments": {"path": "src/a.rs"}}
{"tool": "read_file", "arguments": {"path": "src/b.rs"}}
{"tool": "read_file", "arguments": {"path": "src/c.rs"}}
Code mode — one round trip, only the summary in context:
const [a, b, c] = await Promise.all([
files.read({ path: "src/a.rs" }),
files.read({ path: "src/b.rs" }),
files.read({ path: "src/c.rs" }),
]);
for (const f of [a, b, c]) {
print(`${f.split("\n").length} lines`);
}
Three things make this work:
- Intermediate results stay in the sandbox. The script can read a 5,000-line file, grep it, and print the two lines that matter. The model pays for two lines, not 5,000.
- One round trip instead of many. Each
codecall still re-sends the conversation — but there is one call where there were ten. Independent calls inside the script run in parallel. - Models are better at code than at tool-call JSON. This is Cloudflare's core argument for Code Mode: LLMs have seen millions of lines of real code in training, but tool-calling is a narrow, artificial format they only meet in fine-tuning. Writing a
forloop is a well-practiced skill; emitting ten perfectly-shaped JSON calls in sequence is not.
The academic result predates the product wave. The CodeAct paper (Wang et al., ICML 2024) tested 17 LLMs on API-Bank and the authors' M³ToolEval benchmark: agents acting through executable Python code succeeded up to 20% more often than agents acting through JSON or text tool calls, and needed fewer steps. Code gives the model control flow, variables, and readable error messages it can debug from — a JSON call gives it none of those.
Code mode vs direct tool calls vs tool search
These are the four ways a client can wire tools to a model, and they solve different halves of the problem:
| Approach | What the model emits | What stays in context | Where it fits |
|---|---|---|---|
| Direct tool calls | One JSON call per step | Every call and its full result | Small tasks, few tools |
| Shell scripts | Bash or Python via a shell tool | The script and its printed output | Ad-hoc orchestration; no typed tool access or per-call guardrails |
| Tool search | Direct calls; definitions loaded on demand | Loaded schemas plus full results | Many tools, few calls per task |
| Code mode | One script calling typed tool functions | The script and its printed output | Multi-step work, large intermediate results |
Tool search fixes the definitions tax; code mode fixes both the definitions tax and the round-trip tax. They compose — Octomind and Claude Code ship both.
What the published numbers say
Published results range from about 37% fewer tokens on mixed workloads to over 99% on tool-heavy extremes; the size of the win depends on how much of your context is tool overhead.
| Source | Date | What was measured | Result |
|---|---|---|---|
| CodeAct, ICML 2024 | Feb 2024 | 17 LLMs, API-Bank + M³ToolEval | Up to 20% higher success rate vs JSON/text actions |
| Anthropic: Code execution with MCP | Nov 2025 | Example workflow, tools called from code | 150K → 2K tokens (−98.7%) |
| Anthropic: Advanced tool use | Nov 2025 | Programmatic Tool Calling on their evals | −37% tokens on average (43.5K → 27.3K) |
| Anthropic: Advanced tool use | Nov 2025 | Tool Search Tool, MCP evaluation | Opus 4.5 accuracy 79.5% → 88.1% |
| Cloudflare: Code Mode MCP server | Mar 2026 | Whole Cloudflare API via 2 tools (tiktoken) | ~1,000 tokens vs 1.17M for equivalent tool definitions (−99.9%) |
Read these as existence proofs, not guarantees. The 98.7% and 99.9% figures are best-case demos — a large-document workflow and a huge API surface, exactly where code mode shines. Anthropic's −37% is an average across their evaluation set, closer to what a mixed workload sees. Your two-step task will save nothing.
Code mode in the clients you use
As of November 2026, the pattern has shipped in most of the major agent stacks — under different names and with different scope.
Claude API: Programmatic Tool Calling
Anthropic ships code mode as two API features. Programmatic Tool Calling lets Claude write Python that calls your tools inside Anthropic's code-execution sandbox; tool results go to the script, not the context. Tool Search Tool solves the definitions half: mark tools defer_loading: true and Claude searches for the ones it needs instead of loading every schema upfront. Both arrived in beta on November 24, 2025 (anthropic-beta: advanced-tool-use-2025-11-20); the tool reference documents the current code_execution versions and the allowed_callers field that marks which tools a script may call. OpenAI ships the same pattern in its API as Programmatic Tool Calling: the model writes a program that calls your tools, and the results stay in the execution environment instead of the conversation.
Claude Code: Code Mode (experimental) plus tool search
Claude Code ships Code Mode as an experimental feature, off by default: Claude writes JavaScript that makes several tool calls in one step, the script runs in the session, and the conversation shows the underlying tool calls rather than the code — the full transcript shows the script. It works in subagents, and the usual permission checks still apply to each call. Separately, MCP tool search attacks definition bloat: MCP tool definitions load on demand, and ENABLE_TOOL_SEARCH=auto enables it when the definitions would take roughly 10% or more of the context window.
OpenAI Codex: the exec tool
Codex has a code-mode runtime in the open-source client: codex-rs/core/src/tools/code_mode/. The model sees an exec tool that takes JavaScript; inside the script it calls nested tools like tools.exec_command(...) and tools.apply_patch(...). The hooks documentation covers how hooks observe these nested calls. Whether a given model routes through code mode depends on the model and turn type — there are open issues about exactly that.
Cloudflare: code mode on the server side
Cloudflare's twist: the server provides the sandbox, so any MCP client gets code mode without implementing anything. Its Code Mode MCP server exposes the entire Cloudflare API through two tools — search() to explore a typed OpenAPI spec, execute() to run JavaScript against the API — for about 1,000 tokens of context, regardless of how many endpoints exist. The equivalent traditional MCP server would need 1.17 million tokens of tool definitions, more than most models' context windows. The Code Mode SDK is open source in the Agents SDK, so you can wrap your own API the same way.
Octomind: every external tool call goes through a script
Octomind, our open-source coding agent, builds code mode into the harness itself and ships it on by default. The model gets a code tool; external MCP tools are listed as callable functions in its description rather than sent as full schemas. A script is TypeScript, type-checked in strict mode by an embedded compiler before anything runs — an unknown tool, a wrong argument, or a missing await rejects the whole script before a single tool is called. Each call inside the script passes the same guardrails as a direct call, and the session keeps a record of every call the script made. Only what the script prints reaches the model. When the tool list itself grows past the response budget, a search_tools tool (BM25 keyword ranking + local embeddings) finds the right ones by description. The whole mechanism is documented in the documentation, and [mcp] code_mode = false turns it off if you want plain tool definitions.
Everyone else
Cursor, Gemini CLI, GitHub Copilot CLI and opencode expose tools as direct calls plus a shell, and we found no documented code-mode feature in their public docs as of November 2026. That is an observation about documentation, not a verdict on internals — and the shell escape hatch means their agents can approximate the pattern when they choose to.
What we measured
We benchmark coding agents on real tasks harvested from merged pull requests — octobench, 5 languages, held-out tests from the projects themselves, network sealed so no agent can look up the upstream fix. The GOLD suite runs 13 one-shot tasks plus 2 long-run sequences, 5 rounds per column.
The November 8–10, 2026 run compared two harnesses on the same model (gpt-6.1-sol), same reasoning effort, same containers: Codex CLI 0.167.0 and Octomind 0.70.1, whose harness routes every external tool call through code mode.
| Per round, GOLD results | Codex | Octomind |
|---|---|---|
| One-shot solve rate (pooled, 5 rounds) | 58.5% (38/65) | 58.5% (38/65) |
| Cost per solved task | $0.59 | $0.45 |
| Tokens per solved task | 3.4M | 2.2M |
| Output tokens | 478K | 253K |
| Total tokens (incl. cache reads) | 122.4M | 76.6M |
| Wall time per solved task | 0.13h | 0.13h |
Same solve rate, about 24% lower cost per solve, about 35% fewer tokens per solve, and roughly half the output tokens. On work both harnesses solved in the same round, the relative token index (each item normalized to the cross-column median) is 1.10 for Codex versus 0.80 for Octomind.
Two honest caveats. First, this is a harness-level comparison, not an isolated code-mode ablation: the two clients also differ in system prompts, compression, and tool design, and Codex has its own code mode — the table credits the whole harness. Second, wall time came out even. Octomind's API route ran about 14% slower per request in our sample, but the confidence interval includes no difference; either way, the token savings did not turn into time savings. The per-round records and protocol are public; run it yourself.
Try it today
- Claude API: add the
advanced-tool-use-2025-11-20beta header, mark tools withallowed_callers, and enable the code-execution tool. Anthropic's guide has the request shape. - Claude Code: enable the experimental Code Mode feature (it is off by default); connect your MCP servers as usual and tool search handles definition bloat on current versions.
- Codex: current versions ship the code-mode runtime; the model decides when to route through
exec. - Octomind: install from octomind.run and run
octomind run developer— code mode is on by default for every external tool. - Your own API: wrap it with the Cloudflare Code Mode SDK and any MCP client benefits, no client changes needed.
Where code mode does not help
Code mode pays off on medium and heavy multi-step work; on small tasks it can cost more tokens than direct calls. Writing a script costs output tokens, and the savings come from two places a small task does not have: many round trips and large intermediate results. One call to read one small file is already optimal — wrapping it in a script adds overhead and subtracts nothing.
Our per-task numbers show both directions. On python_pydantic_deque_schema, a small Python task both harnesses solved in all five rounds, the code-mode harness used more: a median of 3.27M tokens ($0.66) per round versus Codex's 2.13M ($0.51). On the suite's heaviest sequence — a 14-turn DuckDB optimizer run both harnesses completed in every round — it used far less: 18.42M tokens ($3.55) versus 43.70M ($7.05), under half. Same model, same caveat as above: harness-level, not an ablation. Across the per-task results, the big wins sit on the heavy tasks; the small ones are a coin flip or a loss.
The more MCP servers you connect, the more this tilts toward code mode. Definition savings scale with the size of your tool surface: Cloudflare's 1.17M-token example is the extreme, but a dozen connected servers already put tens of thousands of definition tokens into every round, on every task, forever. Code mode and tool search remove that tax; an agent with two tools never pays it in the first place.
There are real costs. Someone must run a sandbox with resource limits and monitoring — Anthropic is explicit about this. Debugging gets one layer deeper: when a script fails halfway, you need to know which calls ran, which is why Octomind keeps a per-call record and type-checks scripts before execution. And the first script in an Octomind process waits about a second for the embedded compiler to load. Small, but real.
Is code mode safe?
Code mode changes how the model reaches its tools, not which tools it can reach: in Octomind a script has no imports, no filesystem, no network — tools are the only way out, and every call passes the same guardrails as a direct one. But the sandbox itself is code, and code has bugs. Check Point Research escaped Cloudflare's Code Mode sandbox in 2026 through vulnerabilities in the underlying workerd runtime, reaching code execution on the host. Guardrails bound what a script is allowed to do; only a patched, well-run sandbox bounds what it can do. Keep the runtime updated and treat it as the security boundary it is.
If your agent work is mostly multi-step — and most real work is — the pattern is worth turning on everywhere it exists. The research says agents can succeed more often with it, especially on complex tasks. The vendor numbers say the token savings are large when the workload fits. Our benchmark says a harness built around it can match solve rate at materially lower cost. That is about as well-supported as an agent architectural choice gets.
References
- CodeAct: Executable Code Actions Elicit Better LLM Agents — Wang et al., ICML 2024
- Anthropic: Code execution with MCP (Nov 4, 2025)
- Anthropic: Introducing advanced tool use (Nov 24, 2025)
- Claude tool reference — code execution versions
- Claude Code: Code Mode and MCP tool search
- OpenAI: Programmatic Tool Calling and Codex hooks
- OpenAI Codex — code-mode runtime source
- Cloudflare: Code Mode MCP server and Build a Code Mode MCP server
- Check Point Research: When Agentic Glue Melts — exploiting Cloudflare Code Mode and Workers
- Octomind and octobench GOLD results



