Code Mode for MCP: letting the model write code against your tools
On this page
Code Mode is a way of using MCP tools in which the model writes code instead of calling each tool directly. The agent converts each server’s tool schemas into typed functions, gives the model a single tool that runs code, and executes that code in an isolated sandbox. The code can call several tools, loop, filter and return only the final result, so tool definitions and intermediate data stay out of the model’s context. Cloudflare named the pattern in September 2025 and ships it as the experimental @cloudflare/codemode package. The tools are still MCP tools: each function call inside the sandbox ends up as an ordinary tools/call.
Checked as of November 2026 against Cloudflare’s original Code Mode post, the Agents SDK Code Mode docs, How Code Mode works, Use MCP tools with Code Mode, the packages/codemode README at version 0.5.6, and the MCP tools specification (revision 2026-07-28).
How Code Mode works
The original post, by Kenton Varda and Sunil Pai, argues that LLMs write code against an API better than they make tool calls, because they have seen far more real TypeScript than tool-call examples. Direct tool calling also passes every intermediate result through the model just to copy it into the next call.
The design has four parts:
- Typed API. The Agents SDK reads each MCP server’s tool list and generates TypeScript declarations with doc comments from the tool descriptions and schemas.
- One tool. The model gets a single code-execution tool and writes a JavaScript async function against those declarations.
- Isolated execution. The code runs in a fresh V8 isolate created on demand through the Worker Loader API, now part of Dynamic Workers.
fetch()andconnect()are blocked: the current executor setsglobalOutbound: nullunless you pass aFetcherto route traffic through. - Bindings, not keys. The sandbox reaches tools only through Workers RPC bindings. Calls go back to the host, which holds the credentials and forwards each call to the MCP server, so generated code never sees a token it could leak.
In the current connector runtime, model-written code looks like this example from the MCP page:
async () => {
const matches = await codemode.search("open pull requests");
const docs = await codemode.describe(matches.results[0].path);
const pullRequests = await github.list_pull_requests({
owner: "cloudflare",
repo: "agents",
state: "open",
});
return { docs, pullRequests };
};
On the host side, an McpConnector wraps an existing Agents SDK MCP connection. Its name() becomes the sandbox global (github above), it creates one typed method per MCP tool, and each method calls the original tool through connection.client.callTool(). A decoration hook can mark individual tools for approval:
protected override tool(
name: string,
tool: ConnectorTool,
): ConnectorTool {
if (name === "create_issue") {
return { ...tool, requiresApproval: true };
}
return tool;
}
What changed since September 2025
The original page was modified on November 9, 2026, but its text still describes the first release:
| Original post (September 2025) | Current docs (November 2026) | |
|---|---|---|
| Package | codemode helper from agents/codemode/ai | @cloudflare/codemode, with createCodeTool(), createCodemodeRuntime() and connectors |
| Tool definitions | Whole API loaded into context | codemode.search() and codemode.describe() load types on demand |
| Results | Read from console.log() output | The function’s return value; console output comes back as logs |
| Sandbox | Worker Loader API in closed beta | Dynamic Workers, open to all Workers Paid users since March 2026 |
| Approvals | Not covered | Durable runtime pauses, records and replays calls |
| Status | Introduced | Still marked experimental, “may have breaking changes” |
Dynamic Workers pricing: 1,000 unique Dynamic Workers per month included, then $0.002 per Dynamic Worker per day, plus standard Workers request and CPU charges, billed since May 26, 2026.
Cloudflare also applied the pattern to its own servers. The Cloudflare API MCP server at https://mcp.cloudflare.com/mcp, announced in February 2026, covers more than 2,500 endpoints with a search tool that runs code against the OpenAPI spec and an execute tool that calls the API through an authenticated client. Cloudflare measured about 1,000 tokens for those tools, against 1.17 million for an equivalent server without Code Mode. The server now also has a docs tool. In April 2026, MCP server portals gained a ?codemode=search_and_execute option that collapses every upstream server into two tools: 52 tools and about 9,400 tokens became about 600 tokens in Cloudflare’s example.
Why the name spread in October 2026
By October, Code Mode was no longer only a Cloudflare term:
- OpenCode 2, released in September, makes Code Mode the default for MCP servers. Its MCP docs group tools by server name, as in
tools.context_7.resolve_library_id(...), and a per-servercodemode: falseexposes tools directly. - Factory’s Droid 1.0 (October 29) made a JavaScript Script tool the default for several models.
- Cloudflare updated its MCP guide on October 27, released
@cloudflare/codemode0.5.6 on October 29, and hosted a Connect session, Giving an agent 10,000 tools with Code Mode.
In November, Claude Code v2.1.323 added an experimental Code Mode, off by default, where Claude writes JavaScript that calls its tools, MCP tools included. Each call in the code still goes through your deny and ask rules and PreToolUse hooks under the tool’s usual name. Codex’s configuration reference also lists code_mode as one of the surfaces an MCP server’s tools can be exposed on, beside direct and deferred.
Code Mode, tool calling and programmatic tool calling
Anthropic’s programmatic tool calling is the closest relative: Claude writes Python in Anthropic’s code execution container and your application runs each tool it calls.
| Plain tool calling | Cloudflare Code Mode | Programmatic tool calling | |
|---|---|---|---|
| What the model sees | Every tool definition | One code tool; types up front or on demand | Your tools as async Python functions, plus code execution |
| Where code runs | No code | Dynamic Worker isolate on your Cloudflare account | Anthropic’s code execution container |
| Language | None | JavaScript against TypeScript declarations | Python |
| Who runs each tool | The client | Host-side connector, via Workers RPC | Your application, after the API returns a tool_use block |
| Intermediate results | Enter the context | Stay in the sandbox | Stay in the container |
| MCP tools | Yes | Through McpConnector or codeMcpServer() | Not for tools from Anthropic’s MCP connector |
| Approval mid-run | Per call, in the client | Durable runtime pauses and replays | Your application decides when it returns each result |
MCP tool search cuts context a different way, by deferring tool definitions; context engineering covers the wider problem.
Tradeoffs
You need a sandbox you trust
Prompt injection can write some of the code Code Mode runs, so the isolate and its bindings are the security boundary. In August 2026, Check Point Research reported memory-safety bugs in workerd, the runtime underneath, including a sandbox escape it demonstrated on a self-hosted build with the V8 sandbox disabled. Cloudflare fixed its hosted platform; self-hosted users were told to update to v1.20260619.1. A custom executor inherits none of this: the README’s NodeVMExecutor example runs code with AsyncFunction in the host process, which isolates nothing.
Output types are often unknown
Many MCP tools declare inputSchema but no outputSchema, so the codemode type generator emits type ...Output = unknown for them. The original post’s example shows the same problem: every output type was { [key: string]: any }. The model guesses field names, and a wrong guess fails at runtime.
MCP already has the fix. A tool can declare an outputSchema; if it does, the server must return structuredContent that conforms, and clients should validate it. Code Mode uses both: the connector turns the output schema into a real return type, and when a tool returns non-null structuredContent, sandbox code gets that value directly. For server authors, adding output schemas is the most useful change for Code Mode clients.
Debugging code you didn’t write
A failed run is a program to read, not one bad call. Cloudflare’s tool returns completed, paused or error with an executionId and logs, and upstream MCP errors become exceptions the code can catch. Claude Code hides the code unless you press Ctrl+O.
Approvals in the middle of a script
Cloudflare’s durable runtime handles a tool marked requiresApproval mid-script: it records the call as pending and ends the pass. After approval it runs the same code again with the same execution ID, returns recorded results for calls that already ran, and then runs the approved one. Calls must happen in the same order on every pass, so the docs advise codemode.step() for Date.now() or Math.random() and sequential calls rather than Promise.all(). Rejection ends the execution without undoing earlier calls; rollback runs a revert only where you wrote one. The simpler codeMcpServer() and createCodeTool() paths have no durable approval.
If approval is enforced further along, by the MCP server or a gateway, the script gets an approval-required error where it expected data. Cloudflare’s McpConnector turns a result with isError: true into an exception carrying the message text; a broad catch can still swallow it, and an implementation that returns error results as values lets the code carry on with them. Running the whole script again after approval repeats every earlier side effect unless something replays them. Keep gated tools in a script of their own, or at its start, and check their results explicitly.
Loops multiply calls
A five-line loop can make 500 calls the model never weighed one by one. Each is a real upstream request, and the MCP specification requires servers to rate limit tool invocations, so expect errors partway through and cap loops in the code.
When plain tool calling is better
Cloudflare’s own docs recommend direct tool calls for simple tasks with a small, known tool set. Anthropic’s guidance for its version agrees: a few small calls, workflows where every step needs the model’s judgment, and tools that need user feedback between calls gain little from a script.
What Code Mode means for MCP servers and gateways
Code Mode doesn’t replace MCP; it changes who writes the calls. The design still needs a component outside the sandbox that holds credentials and decides which calls go through: in Cloudflare’s design, that’s the host and its connectors. Each generated call is still an MCP tools/call with a name and arguments, so per-call policy, approval and logging still work, as long as they run per call and not per script. Claude Code’s docs say the same: its auto-mode classifier can’t see values computed at run time, so keep rules on individual calls.
Two other things matter more with generated code. Tool names become identifiers saved in code, so they need to stay stable and point at the same account. Tool definitions become types, so a server that silently changes a tool changes the API under scripts already written against it. The MCP security guide covers changed definitions, and what is an MCP gateway covers where these controls sit.
Code Mode agents and Toolstile
Toolstile doesn’t run code or generate APIs. A Code Mode agent connected to it still sends each call as an MCP tools/call, so per-agent allow, block and Require approval rules and the call log apply to every call a script makes. Toolstile holds the upstream credentials. Tools appear as <namespace>__<upstream name>, such as linear__get_issue, which maps cleanly onto a generated method, and a namespace is never reassigned to a different connection, so a name in saved code can’t silently reach another account. Tool review hides new or changed tool definitions until someone accepts them. For a gated tool, the MCP client gets a tool error (isError: true) whose _meta["toolstile/approval"] holds the request ID, status, expiry and review link. The host can check that metadata; with Cloudflare’s connector, sandbox code sees only an exception with the message, which includes the request ID. Approving doesn’t run anything, and the identical call must be retried, which is why gated calls belong in their own short script.