Code Mode for MCP: Let Agents Write Code Instead of Chaining Tool Calls
Classic tool calling makes the model a very expensive loop: call a tool, read the whole result, decide, call again. Code mode flips it — the agent writes one short program against your tools, runs it in a locked-down sandbox and only reads the final answer. Fewer round trips, fewer tokens, and a much smaller blast radius if you sandbox it properly.
The Model Context Protocol (MCP) made it easy to plug tools into agents. It also made a cost visible: every tool definition sits in the context window, and every call is a full round trip through the model, with each intermediate result pasted back in. A task like "find stale high-priority tickets and escalate them" can take a dozen calls and tens of thousands of tokens — most of them spent reading data the model only needed to filter.
The problem with one tool call at a time
- Round trips. Each step waits for model inference before the next tool call starts.
- Context bloat. Full tool outputs flow through the context, even when the model only needs three fields from 500 rows.
- Large tool catalogs. Hundreds of tool schemas loaded up front crowd out the actual task.
- Fragile orchestration. Loops, joins and retries expressed as a chain of chat turns are slow and error-prone.
The idea: tools as an API, the agent writes the code
Instead of exposing tools as individual calls, code mode presents them as a typed API — for example TypeScript functions generated from the MCP tool schemas. The model writes a short program that uses that API, the program runs in an isolated sandbox, and only its return value goes back into the context.
// Generated, typed bindings for the MCP server's tools are the only thing in scope.
const tickets = await crm.searchTickets({ status: "open", priority: "high" });
const threeDays = 3 * 24 * 60 * 60 * 1000;
const stale = tickets.filter(t => Date.now() - Date.parse(t.updatedAt) > threeDays);
for (const t of stale) {
await crm.addComment({ id: t.id, body: "Escalated: no update in 3 days." });
}
return { escalated: stale.map(t => t.id) }; // the only data the model reads back
One model turn produces the program; the loop, the filter and the writes happen inside the sandbox. Language models are very good at writing this kind of code — far better than at juggling twelve tool calls in a row.
Cloudflare popularised the pattern under the name "Code Mode" in its Agents SDK, running the generated code in a lightweight V8 isolate whose only way to reach the outside world is through bindings to the MCP tools. The approach isn't tied to one vendor: any runtime that can execute untrusted code in a tight sandbox can do the same. Implementation details evolve quickly, so check the current documentation for the platform you use.
Why it helps
- Fewer round trips — one generation instead of one per tool call.
- Fewer tokens — intermediate results stay in the sandbox; only the summary returns.
- Better composition — loops, conditionals, parallel calls and error handling are plain code.
- Reviewable behaviour — the exact program the agent ran can be logged, diffed and audited.
Guardrails: the sandbox is the product
Running model-written code is only acceptable if the environment is designed for it. This is where secure agent development matters most:
- No ambient access. No general network, filesystem or environment variables — only explicit, allow-listed tool bindings.
- Secrets stay outside. Credentials live in the bindings on the host side; the generated code never sees an API key.
- Hard limits. CPU time, memory, wall-clock timeout and a cap on tool calls per run.
- Least privilege per task. Read-only bindings by default; write tools only where the task needs them.
- Human approval for risky actions. Deletes, payments and bulk writes pause for confirmation, or run first as a dry run that reports what would change.
- Full audit trail. Log the generated program, every tool call it made and the result, tied to the user and session.
When not to use it
- One or two simple tool calls — classic tool calling is simpler and just as fast.
- Steps that need human judgement between them — keep a person in the loop rather than one big program.
- Environments where you can't run a properly isolated sandbox — don't execute model-written code at all.
Key takeaways
- Classic tool calling costs a model round trip and a context paste per call.
- Code mode exposes MCP tools as a typed API; the agent writes one program and only the result returns.
- Fewer round trips and tokens, better composition, and an auditable record of what ran.
- It is only safe in a locked-down sandbox: allow-listed bindings, no secrets in code, hard limits, approvals and audit logs.