Cloudflare Code Mode: Let the Model Write Code, Not Tool Calls

Cloudflare's Code Mode turns MCP tools into a TypeScript API and runs the model's code in a V8 isolate. How it works, what Anthropic found next, and where it falls short.

Jahanzaib Ahmed
8 min read

Cloudflare's Code Mode is an argument that an agent should stop calling MCP tools one at a time and instead write a short TypeScript program against them. Kenton Varda and Sunil Pai published it on September 26, 2025, and it has aged well: Anthropic described the same pattern in November, and Cloudflare now enables Code Mode by default in its MCP portals. Below is how it works, what the evidence does and does not show, and when I would use it on a client build.

1 toolwhat the model sees in Code Mode: a sandbox that runs TypeScript
150,000 to 2,000tokens in Anthropic's example workflow after moving to code execution
Mar 26, 2026date Cloudflare's changelog shows Code Mode on by default in MCP portals

What Cloudflare Code Mode does

The usual way to use an MCP server is to hand every tool to the model through native tool calling. The model emits a structured call, your framework runs it, and the result goes back into the model's context. Code Mode replaces that loop. Cloudflare's Agents SDK reads the MCP server's schema and generates TypeScript interfaces with doc comments. The post shows the shape for a documentation server:

declare const codemode: {
  fetch_agents_documentation: (
    input: FetchAgentsDocumentationInput
  ) => Promise<FetchAgentsDocumentationOutput>;
  // ...other tools
};

That definition goes into the model's context. The model then gets one tool, which runs TypeScript in a sandbox, and it writes code that calls the codemode object. Wiring it into an app is a wrapper around your existing tools and system prompt:

const {system, tools} = codemode({
  system: "You are a helpful assistant",
  tools: { /* tool definitions */ },
})

The post makes three complaints about native tool calling:

  • Models are not fluent in it. Tool calls depend on special tokens the model learned from synthetic training data. The authors compare it to "putting Shakespeare through a month-long class in Mandarin" and then asking for a play. Models have seen far more real code than tool-call transcripts.
  • Big tool sets confuse the model. Too many tools, or tools that are too complex, make selection worse, which is why MCP servers often ship simplified APIs.
  • Chaining wastes tokens. In the post's words, with the traditional approach "the output of each tool call must feed into the LLM's neural network" only to be copied into the next call. That costs time, energy and tokens.

The one-line version of the thesis: "LLMs are better at writing code to call MCP, than at calling MCP directly." Cloudflare also reframes what MCP is for. In this view it is less a tool-calling mechanism and more a uniform way to describe an API, document it and handle authorization outside the model, which is what lets an agent connect to a server it has never seen.

How the sandbox is built

Running model-written code is the dangerous part, so the design decisions there matter more than the TypeScript trick. The post describes four:

  1. V8 isolates, not containers. "An isolate can start in a handful of milliseconds using only a few megabytes of memory," so the system can create a fresh isolate for each snippet and throw it away afterward.
  2. No internet. The sandbox cannot reach the network. Its only outside access is the generated APIs, which call back to the agent loop over RPC, and the SDK then dispatches each call to the right MCP server.
  3. Output through console.log(). Logs are collected and returned to the model when the script ends.
  4. A loader API. To start isolates on demand, Cloudflare added the Worker Loader API. The post gives this sketch, where setting globalOutbound to null blocks the internet:
let worker = env.LOADER.get(id, async () => ({
  compatibilityDate: "2025-06-01",
  mainModule: "foo.js",
  modules: { "foo.js": "/* worker code */" },
  env: { /* serializable values and RPC bindings */ },
  globalOutbound: null,
}));

At publication the post said the loader was in closed beta and worked locally through Wrangler and workerd. Cloudflare now documents it under Worker Loader in its runtime API docs, so check there for current availability before you plan around it.

Bindings keep the keys out of the code

The security argument rests on bindings. A Worker's env holds live objects, not only strings. In Code Mode the sandbox receives bindings to its MCP servers and nothing else. Those bindings are pre-authorized clients: the call goes to the agent supervisor, which holds the credentials and attaches them before forwarding to the MCP server. The authors conclude that "the AI cannot possibly write code that leaks any keys."

My read: that is a real improvement over pasting an API key into a prompt or an environment the model can print. It is narrower than it sounds, though. A binding that is allowed to call a tool will still call it if a prompt-injected model asks, so the supervisor needs its own allow list and limits. I covered a related lesson in OpenAI Blocked POST Requests. The Wiki Its Agents Found Writes on GET: an egress rule that looks restrictive was never a write control. The lesson transfers. Decide what each binding can do, not only what the sandbox cannot reach.

What happened after the post

Two later sources show the idea spreading.

On November 4, 2025, Anthropic published Code execution with MCP. It says Cloudflare "published similar findings" and that the core insight is the same. Anthropic's version presents each MCP server as a directory and each tool as a TypeScript file, such as ./servers/google-drive/getDocument.ts, so the agent reads only the definitions it needs. Large results are filtered in code before the model sees them: in its example "the agent sees five rows instead of 10,000." For one workflow it reports a drop from 150,000 tokens to 2,000, a saving of 98.7%.

On March 26, 2026, Cloudflare's changelog said MCP server portals support Code Mode and enable it by default. The portal exposes a single code tool instead of listing every upstream tool. The agent writes JavaScript against typed codemode.* methods, and the code runs in an isolated Dynamic Worker that keeps credentials and environment variables out of the model context. The entry gives no token figures.

PointNative tool callingCode Mode
What the model is givenEvery tool definition as a toolOne code tool plus a TypeScript API
Chained callsEach result passes through the modelIntermediate results stay in the script
Large outputsEnter the context in fullCan be filtered in code first
CredentialsHeld by your frameworkHeld by the supervisor, never in the code
What you must runNothing extraA sandbox with resource limits and monitoring

What the evidence does not show

The Cloudflare post says "the results are striking" and that agents handled many more tools, and more complex ones, when they were presented as a TypeScript API. I could not find a benchmark table behind that claim in the post, so treat it as the authors' observation, not a measured result. Anthropic's 98.7% is a figure for one example workflow, not an average across workloads. And the cost side is real: Anthropic itself notes that running agent-generated code needs secure sandboxing, resource limits and monitoring, which adds operational overhead that direct tool calls avoid.

The Cloudflare authors also flag a limit of their current design: the whole generated TypeScript definition is loaded into context. They suggest agents could browse the API more dynamically later. That matters if your server has hundreds of tools, since you are trading many tool definitions for one large type file.

Note: I have not benchmarked Code Mode myself. Everything above comes from Cloudflare's and Anthropic's own write-ups, and the numbers are theirs.

When I would use it

My rule of thumb, which is judgment and not a measurement: use Code Mode when a task chains several calls, returns payloads far larger than the answer, or sits on a server with a long tool list. A support agent that looks up an order, checks a policy and drafts a reply from three small tools gains little. A reporting agent that pulls 10,000 rows from one tool, filters them and writes a summary gains a lot.

  1. Measure first. Count the tokens your tool definitions take and how often one task chains three or more calls. If both are low, stay on native tool calling.
  2. Pick the sandbox before the prompt. Deny network access by default and give the code only the bindings it needs. An isolate gives you fast start and low memory, per Cloudflare's numbers.
  3. Keep credentials in the supervisor. The generated code should never see a key, and each binding should enforce its own limits.
  4. Log the generated code with every run. When an agent misbehaves, the script it wrote is your audit trail.
  5. Compare on your own tasks. Run the same workflow both ways and compare tokens, latency and failure rate before you commit.

If you are still wiring up servers, my guides to adding MCP servers to Claude Code and using MCP servers in LangGraph cover the native route that Code Mode wraps. If you want an agent built with the sandbox, the tool surface and the logging designed in from the start, here is how I build and maintain AI agents.

Frequently asked questions

What is Cloudflare Code Mode?

It is an approach from Cloudflare's Agents SDK where MCP tools are converted into a TypeScript API and the model writes code against it, instead of calling the tools directly. The code runs in a sandbox, and results come back through console.log(). Kenton Varda and Sunil Pai introduced it in a September 26, 2025 blog post.

Why do LLMs do better writing code than calling tools?

Cloudflare's argument is that models have seen far more real-world code than tool-call examples, which come from synthetic training data. That is the authors' reasoning, and the post does not include a benchmark table to prove it.

How does Code Mode keep API keys away from the model?

The sandbox gets bindings to MCP servers instead of credentials. Calls go to a supervisor that holds the keys and adds them when forwarding the request, so the generated code never contains them. The supervisor still has to limit what each binding may do.

Do I need Cloudflare to use this pattern?

No. Anthropic described the same idea with its own file tree of tool definitions, and what you need is any sandbox that runs generated code with no network access and enforced resource limits. Cloudflare's isolates are one way to build it, and the Worker Loader docs list its current status.

Feed to Claude or ChatGPT

Published

October 21, 2026

Category

AI Agents
Jahanzaib Ahmed

Jahanzaib Ahmed

AI Systems Engineer & Founder

AI Systems Engineer with 126 production systems shipped. I run AgenticMode AI (AI agents, RAG systems, voice AI) and ECOM PANDA (ecommerce agency). I build AI that works in the real world for businesses across home services, healthcare, ecommerce, SaaS, and real estate.

Want this built for your business? See AI Agent Development, or browse the free tools and guides.