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

Cloudflare Code Mode (codemode) has the model write code against MCP tools inside a V8 isolate. Where it lives on GitHub, Code Mode vs MCP, adoption numbers and my token measurements on real servers.

Jahanzaib Ahmed
Updated 17 min read

Explore with AI

Cloudflare Code Mode for MCP: Cloudflare and Model Context Protocol logos on two glass icon tiles joined by a copper connector with a small copper ring on it

Cloudflare Code Mode (spelled codemode in its npm package) has an agent write a short program against your MCP tools instead of calling them one at a time. I measured it on four real MCP servers, and the single code tool Cloudflare's SDK generates came out 4% to 53% larger than the definitions it replaces, depending on how you count. The savings are real, but they come from chained calls, big results and huge APIs.

+17% to +35%tokens added when four real MCP servers are wrapped in Code Mode's single code tool, depending on how the description is counted (my measurement)
1,170,523 to 1,069tokens for the whole Cloudflare API, native MCP versus Code Mode, in Cloudflare's own table
483,276 to 266tokens of calls and results in my 140 file audit, every file read versus one script (tool definitions not counted, see below)
150,000 to 2,000tokens in Anthropic's example workflow after moving to code execution

Updated November 1, 2026. The package is now at version 0.5.6 on npm. I added where Code Mode lives on GitHub, how it compares with plain MCP tool calling, adoption numbers and a decision chart.

Cloudflare Code Mode in plain terms

Kenton Varda and Sunil Pai introduced Code Mode on September 26, 2025. The usual way to use an MCP server is native function 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. The Agents SDK reads the server's schema and generates TypeScript interfaces with doc comments, and the model gets one tool that runs code against them.

Diagram comparing native tool calling, where the model and tools talk back and forth, with Code Mode, where the model writes code that runs in a sandbox which calls MCP tools and returns one answer
In native tool calling every result passes back through the model. In Code Mode the loop happens inside the sandbox, and only the final answer returns.

The original post shows the shape of the generated API for a documentation server:

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

That definition goes into the model's context, and the model writes code that calls the codemode object. The wrapper in the 2025 post was a codemode() call around your tools and system prompt. The current @cloudflare/codemode package (version 0.5.5 when I tested it, and 0.5.6 on npm as of October 29, 2026) does the same job for an existing server with codeMcpServer().

Cloudflare Code Mode on GitHub, npm and the blog

People search for this as Cloudflare Code Mode, codemode and Code Mode for MCP. All three point at the same thing: the Agents SDK feature, the npm package named codemode and the generated codemode object that the model's code calls. Here is where each piece lives.

WhatWhereNotes
The SDK package@cloudflare/codemode on npmVersion 0.5.6 as of October 29, 2026
Its source on GitHubcloudflare/agents, packages/codemodeMIT license. The Agents SDK repository had 5,928 stars on November 1, 2026
The hosted Cloudflare API servercloudflare/mcpApache 2.0 license, 1,032 stars on November 1, 2026. The search and execute server
The original blog postblog.cloudflare.com/code-modeKenton Varda and Sunil Pai, September 26, 2025
The server blog postCode Mode: give agents an entire API in 1,000 tokensMatt Carey, February 20, 2026
The docsCloudflare Agents docsNames the two patterns, single code tool and search and execute
Sandbox pricing and limitsDynamic Workers docsCovered under Inside the sandbox

The post makes three complaints about native tool calling. First, models learned tool calls from synthetic examples, and they've seen far more real code. Second, big tool sets confuse selection, which is why MCP servers keep shipping simplified APIs. Third, chaining wastes tokens, because each result is read by the model only to be copied into the next call.

The one line thesis: "LLMs are better at writing code to call MCP, than at calling MCP directly." Cloudflare also reframes what MCP is for: a uniform way to describe an API, document it and handle authorization outside the model, which is what lets an agent use a server it has never seen.

Inside the sandbox

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

  1. Code runs in V8 isolates, not containers. An isolate starts in a few milliseconds with a few megabytes of memory, so the system can create a fresh one per snippet and throw it away.
  2. The sandbox has no internet. The only way out is the generated API, which calls back to the agent loop over RPC.
  3. Output comes back through console.log(). Logs are collected and returned to the model when the script ends.
  4. A loader API starts isolates on demand. Cloudflare added the Worker Loader API for this, and 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,
}));

When the post came out the loader was in closed beta. It now has its own Dynamic Workers documentation and pricing. It runs on the Workers Paid plan and includes 1,000 unique Dynamic Workers a month, then charges $0.002 per Dynamic Worker per day, plus normal Workers request and CPU rates. The docs also add per invocation limits, which I'd set on day one. Their example is limits: { cpuMs: 10, subRequests: 5 }, so tune the numbers to your workload. The worker throws as soon as it reaches either.

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. Each binding is a pre authorized client: 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."

Diagram of Code Mode security: model code runs in a sandbox with no internet and reaches the MCP server only through a binding to a supervisor that holds the API keys
The credentials live on the supervisor side of the binding. If the model prints every variable it can see, the keys are not among them.

My read: that's a real improvement over pasting an API key into a prompt or an environment the model can print. It's narrower than it sounds, though. A binding that may call a tool will call it if a prompt injected model asks, so the supervisor needs its own allow list and limits. I covered the same trap in OpenAI Blocked POST Requests. The Wiki Its Agents Found Writes on GET: an egress rule that looks restrictive was never a write control. Decide what each binding can do, as well as what the sandbox can't reach.

A whole API in two tools

On February 20, 2026, Matt Carey published Code Mode: give agents an entire API in 1,000 tokens. It moved the idea from the client to the server. Cloudflare released an MCP server for its whole API built around two tools, search() and execute(). Both take JavaScript. The model writes code against a typed copy of the OpenAPI spec to find endpoints, then writes code that calls the ones it picked, with pagination and chained requests handled in one run.

Cloudflare table of token costs for the Cloudflare API: 1,170,523 tokens as native MCP with full schemas, 244,047 with required parameters only, and 1,069 tokens with Code Mode
Cloudflare's own count for 2,594 API tools. Even the trimmed native version, required parameters only, needs 122% of a 200,000 token window. Source: Cloudflare blog.

The footprint stays fixed however many endpoints exist, because the spec never enters the context. The model only sees what its search code returns. Credentials follow the same rule as before. Per the repo's AGENTS.md, the API token is passed to the sandbox's host through worker props and never enters the isolate that runs model code. search has no network access, and execute can reach Cloudflare API URLs only. The server also caps each tool result at about 6,000 tokens by default, so one greedy query can't flood the context.

Cloudflare's docs now name two patterns, and the choice between them decides whether Code Mode helps you at all:

Cloudflare Agents docs table comparing the single code tool pattern with the search and execute pattern for Code Mode MCP servers
Single code tool is for a server with a manageable set of tools. Search and execute is for a large API whose complete schema should stay out of context. Source: Cloudflare Agents docs.

To try the hosted server, point an MCP client at it and approve the permissions on Cloudflare's page. For CI you can pass a Cloudflare API token as a bearer token instead:

{
  "mcpServers": {
    "cloudflare-api": {
      "url": "https://mcp.cloudflare.com/mcp"
    }
  }
}
Cloudflare Developers' 2 minute 58 second demo: an agent connects over OAuth, buys a domain, deploys a Worker, diagnoses a production error and fixes it.

I measured it: where the tokens go

Everything above is Cloudflare's and Anthropic's own numbers, so I ran my own on October 21, 2026. I listed the tools on four MCP servers (memory, filesystem, everything and the npm GitHub server) with MCP SDK 1.32.1, then counted tokens with tiktoken's o200k_base encoding. That's OpenAI's tokenizer, so absolute counts for Claude will differ, and I didn't check whether the ratios hold there. Native means the JSON of each tool's name, description and input schema. Code Mode means the code tool description that codeMcpServer() builds, rebuilt with the package's own type generator and prompt template: generated TypeScript types plus a short wrapper prompt.

Bar chart of tool definition tokens for four MCP servers: the Code Mode code tool is 4 to 33 percent larger than native definitions, 17 percent across all four
The wrapper adds roughly 80 to 110 tokens of fixed text, and the TypeScript types repeat each description next to its input and output types.
ServerNative JSONTypes onlyCode tool as textCode tool as JSON string
memory (9 tools)9498729881,171
filesystem (14 tools)1,6801,7221,8462,081
everything (13 tools)1,0771,3221,4371,652
github (26 tools)3,5484,0914,2334,895
All four (62 tools)7,2548,0078,5049,799

The range is plus 4% to plus 33% when the code tool is counted as plain text, and plus 17% across all four. My native baseline is JSON, so the closest like for like comparison is the last column: plus 23% to plus 53%, and plus 35% across all four. The types alone run from 8% below native (memory) to 2% above (filesystem) on the two small servers, and 15% to 23% above it on the other two. The last column is what you get if your client ships the TypeScript as an escaped JSON string, which inflates every newline and quote. One server, memory, came out smaller as types alone. None came out meaningfully smaller once the wrapper was on.

That fits what Cloudflare's own docs say: the single code tool works when the generated type declarations "fit comfortably" in its description. It also explains something the original post admitted, that the whole generated definition loads into context. Wrapping a ten tool server in Code Mode saves nothing on definitions and costs you a sandbox.

Where the savings are real

Two other results behave very differently. First, I downloaded Cloudflare's public OpenAPI spec (3,767 operations today) and built a native tool for every operation. With refs inlined one level deep that's 1,102,037 tokens. Without following refs it's 739,008, and three levels deep it's 1,612,769. Cloudflare's published figure of 1,170,523 for 2,594 tools lands inside that range, so the order of magnitude reproduces, though my spec has more operations than their tool count and I can't tell how they serialized each tool.

The two tool search and execute pair, built with the SDK's openApiMcpServer(), came to 1,264 tokens in my run against 1,069 in Cloudflare's table. The spec never enters those definitions, so the gap is the SDK's own tool descriptions, which carry type declarations and examples, against Cloudflare's shorter ones.

Second, a chained task. I pointed the filesystem server at this site's own lib/ folder and asked for the five files with the most fetch( calls. That server has no grep, so a native agent has to read every file: 3,444 tokens for the directory tree, 474,897 for the contents of 140 TypeScript files and 4,935 for the call arguments, 483,276 in total. The same loop as a script, run in plain Node against the same server, put 195 tokens of code and a 71 token result in front of the model, 266 in total. Add the one time tool definitions the model also has to read (1,680 tokens native, 1,846 for the code tool on this server) and it is 484,956 against 2,112, about 230 to one. Both routes produced the same counts, 5, 5, 4, 1 and 1. Only six files under lib/ call fetch( at all, so fifth place was a three way tie that I broke by file order.

Log scale bar chart: Cloudflare API tool definitions 1,102,037 tokens native versus 1,264 with search and execute, and a 140 file audit of calls and results at 483,276 tokens versus 266 with one script
Both gaps are more than two orders of magnitude, and both come from keeping data out of the context instead of shrinking a tool description. The audit bars count calls and results only, with tool definitions added it is 484,956 against 2,112.

The chain script was short and needed one fix. The generated API types every result as unknown when a server declares no output schema, and the filesystem server wraps its text in a content field. My script had to unwrap .content before parsing. A model writing this blind would probably hit the same wall and spend a retry finding the shape out.

const tree = JSON.parse(
  (await codemode.directory_tree({ path: `${root}/lib`, excludePatterns: [] })).content
);
// walk the tree, then for each .ts file:
const body = (await codemode.read_text_file({ path: file })).content;
counts.push({ file, fetchCalls: (body.match(/fetch\(/g) || []).length });
// return only the top five

What this does not show: I wrote the script by hand and ran it in plain Node through a proxy that stands in for the sandbox, so it measures what stays out of the context, not whether a model writes it correctly the first time. I ran each count once on one machine. The package root imports cloudflare:workers, so plain Node can't load it, so I took the type generator from its dist file and rebuilt the description with the package's own prompt template. I didn't test accuracy, latency or cost per finished task, and a native agent with a grep tool would read far less than 483,276 tokens.

Anthropic's version and the portal rollout

On November 4, 2025, Anthropic published Code execution with MCP. It says Cloudflare found the same thing, and its 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 get filtered in code before the model sees them: in its spreadsheet example the agent sees five rows instead of 10,000.

Passage from Anthropic's Code execution with MCP article describing the drop from 150,000 tokens to 2,000 tokens, a saving of 98.7 percent
Anthropic's 98.7% comes from loading only the tool files a task needs, a file tree approach. It is a figure for one example workflow, not an average. Source: Anthropic Engineering.

On March 26, 2026, Cloudflare's changelog said MCP server portals support Code Mode and turn it on by default. The portal exposes a single code tool instead of listing every upstream tool, and the generated code runs in an isolated Dynamic Worker that keeps credentials out of the model context.

Cloudflare changelog entry dated March 26, 2026 announcing Code Mode for MCP server portals, turned on by default
The portal setting lives under Access controls, then AI controls. Turning Code Mode off is a toggle on the portal. Source: Cloudflare changelog.

Code Mode vs MCP tool calling

Code Mode is not a rival protocol to MCP. The servers stay ordinary MCP servers, with the same tools, schemas and authorization. What changes is how the model reaches them. Native tool calling emits one structured call per step. Code Mode generates a TypeScript API from the same schema and lets the model write a script against it. So the useful comparison is native MCP tool calling against Code Mode on the same server, which is the comparison my measurements above make.

PointNative tool callingCode Mode
What the model is givenEvery tool definition as a toolOne code tool plus a TypeScript API, or search and execute
Definition size on a small serverBaseline4% to 53% larger in my test
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

Has Code Mode been adopted?

As a pattern, yes. Anthropic published its own version, Cloudflare turned Code Mode on by default in its MCP server portals, and the package is installed a lot. The numbers I could check on November 1, 2026:

SignalNumber or eventWhen
npm downloads of @cloudflare/codemode, last week1,153,535October 23 to 29, 2026
npm downloads, last 30 days2,878,812September 30 to October 29, 2026
GitHub stars, cloudflare/agents5,928November 1, 2026
GitHub stars, cloudflare/mcp1,032November 1, 2026
Cloudflare MCP server portals turn Code Mode on by defaultChangelog entryMarch 26, 2026
Anthropic publishes Code execution with MCPEngineering articleNovember 4, 2025

Source: the npm downloads API, the GitHub API and the two vendor pages, read on November 1, 2026.

Read the download counts with care. npm counts every install, including CI runs, mirrors and packages that pull it in as a dependency, so it shows that the package is widely installed and not that 1.1 million agents run it in production. I did not find a public count of production users, and I did not find a benchmark showing that agents finish more tasks with it. The next section covers that gap.

Evidence gaps

The 2025 Cloudflare post calls its results striking and says agents handled more and harder tools as a TypeScript API. I couldn't find a benchmark table behind that, so it's the authors' observation. The 2026 numbers are token counts for tool definitions, which are solid, but a count isn't a test that the agent finishes more tasks. Cloudflare's Dynamic Workers overview goes further and says you can save up to 80% in inference tokens, with no method given on that page. Anthropic's 98.7% is one example workflow. And the cost side is real: Anthropic notes that running agent generated code needs secure sandboxing, resource limits and monitoring, which direct tool calls avoid.

When I would use it

My rule of thumb, and I could be wrong about the cutoffs: copy the search and execute pattern, and skip the single code tool wrapper unless chaining is your actual problem. A server with under 30 tools (my largest had 26) and short results pays 4% to 53% more for definitions and gets nothing back, as the measurements above show. A support agent that looks up an order, checks a policy and drafts a reply from three small tools doesn't need it. A reporting agent that pulls 10,000 rows, filters them and writes a summary does. An API with hundreds of operations needs search and execute, because no description of it fits.

Decision diagram for Cloudflare Code Mode: under 30 tools and short results means stay with native tool calling, chains of 3 or more calls or large results means the single code tool, hundreds of operations means search and execute
The same rule of thumb as a chart. The cutoffs are my judgment from four servers, not Cloudflare guidance.
  1. Measure first. Count your tool definitions as JSON and as the generated TypeScript, and count how often a task chains three or more calls. If definitions are small and chains are short, stay native.
  2. Pick the sandbox before the prompt. Deny network access by default, give the code only the bindings it needs, and set CPU and subrequest limits.
  3. Keep credentials in the supervisor. The generated code should never see a key, and each binding should enforce its own allow list.
  4. Declare output schemas. If your server returns structured results, say so. Otherwise the model sees unknown and will probably pay a retry to find the shape.
  5. Log the generated code with every run. When an agent misbehaves, the script it wrote is your audit trail.
  6. Compare on your own tasks. Run the same workflow both ways and compare tokens, latency and failure rate before you commit.

If you're 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, and the context window explains why the definitions count. 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's 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.

Does Code Mode reduce token usage?

Yes, in two cases. A large API drops from over a million tokens of tool definitions to about a thousand with search and execute, and a chained task keeps its intermediate results out of the context. On four small servers I measured the single code tool at 4% to 53% larger than native definitions, depending on how it is counted.

What do the search and execute tools in Cloudflare's MCP server do?

The search tool runs model written JavaScript against Cloudflare's OpenAPI spec and returns only the matching endpoints. The execute tool runs JavaScript that calls the chosen endpoints, handles pagination and chains requests. Together they cover the whole Cloudflare API in roughly 1,000 tokens of definitions.

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 Dynamic Workers are one way to build it, available on the Workers Paid plan.

Where is Cloudflare Code Mode on GitHub?

The client SDK lives in the cloudflare/agents repository under packages/codemode and is published on npm as @cloudflare/codemode. The hosted Cloudflare API server with the search and execute tools is cloudflare/mcp. Cloudflare writes Code Mode in prose and codemode for the package and the object the generated code calls.

Is Code Mode a replacement for MCP?

No. The servers stay ordinary MCP servers with the same tools and authorization. Code Mode changes how the model reaches them: it writes a script against a TypeScript API generated from the MCP schema instead of emitting one tool call per step.

Has Code Mode been adopted?

As a pattern, yes. Cloudflare turned it on by default in MCP server portals on March 26, 2026, Anthropic published a similar approach on November 4, 2025, and the npm package had about 1.15 million downloads in the week to October 29, 2026. Downloads count installs, not production users, and I found no benchmark showing agents finish more tasks with it.

Feed to Claude or ChatGPT

Last updated

November 1, 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.