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.
Explore with AI

Table of Contents
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.
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.

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.
| What | Where | Notes |
|---|---|---|
| The SDK package | @cloudflare/codemode on npm | Version 0.5.6 as of October 29, 2026 |
| Its source on GitHub | cloudflare/agents, packages/codemode | MIT license. The Agents SDK repository had 5,928 stars on November 1, 2026 |
| The hosted Cloudflare API server | cloudflare/mcp | Apache 2.0 license, 1,032 stars on November 1, 2026. The search and execute server |
| The original blog post | blog.cloudflare.com/code-mode | Kenton Varda and Sunil Pai, September 26, 2025 |
| The server blog post | Code Mode: give agents an entire API in 1,000 tokens | Matt Carey, February 20, 2026 |
| The docs | Cloudflare Agents docs | Names the two patterns, single code tool and search and execute |
| Sandbox pricing and limits | Dynamic Workers docs | Covered under Inside the sandbox |
Why Cloudflare says tool calling is the weak link
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:
- 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.
- The sandbox has no internet. The only way out is the generated API, which calls back to the agent loop over RPC.
- Output comes back through
console.log(). Logs are collected and returned to the model when the script ends. - A loader API starts isolates on demand. Cloudflare added the Worker Loader API for this, and setting
globalOutboundto 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."

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.

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:

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"
}
}
}
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.

| Server | Native JSON | Types only | Code tool as text | Code tool as JSON string |
|---|---|---|---|---|
| memory (9 tools) | 949 | 872 | 988 | 1,171 |
| filesystem (14 tools) | 1,680 | 1,722 | 1,846 | 2,081 |
| everything (13 tools) | 1,077 | 1,322 | 1,437 | 1,652 |
| github (26 tools) | 3,548 | 4,091 | 4,233 | 4,895 |
| All four (62 tools) | 7,254 | 8,007 | 8,504 | 9,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.

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.

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.

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.
| Point | Native tool calling | Code Mode |
|---|---|---|
| What the model is given | Every tool definition as a tool | One code tool plus a TypeScript API, or search and execute |
| Definition size on a small server | Baseline | 4% to 53% larger in my test |
| Chained calls | Each result passes through the model | Intermediate results stay in the script |
| Large outputs | Enter the context in full | Can be filtered in code first |
| Credentials | Held by your framework | Held by the supervisor, never in the code |
| What you must run | Nothing extra | A 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:
| Signal | Number or event | When |
|---|---|---|
| npm downloads of @cloudflare/codemode, last week | 1,153,535 | October 23 to 29, 2026 |
| npm downloads, last 30 days | 2,878,812 | September 30 to October 29, 2026 |
| GitHub stars, cloudflare/agents | 5,928 | November 1, 2026 |
| GitHub stars, cloudflare/mcp | 1,032 | November 1, 2026 |
| Cloudflare MCP server portals turn Code Mode on by default | Changelog entry | March 26, 2026 |
| Anthropic publishes Code execution with MCP | Engineering article | November 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.

- 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.
- 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.
- Keep credentials in the supervisor. The generated code should never see a key, and each binding should enforce its own allow list.
- Declare output schemas. If your server returns structured results, say so. Otherwise the model sees
unknownand will probably pay a retry to find the shape. - Log the generated code with every run. When an agent misbehaves, the script it wrote is your audit trail.
- 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.
Related reading
- How I build MCP servers that run in production: the server side of what Code Mode wraps.
- How to add MCP servers to Claude Code: the native route, with the commands.
- How to add a custom MCP connector to Claude: connecting your own server to Claude.
- How to remove an MCP server from Claude Code: audit what an agent can reach.
- How to use MCP servers in LangGraph: the same servers from a graph.
- How to set up the Playwright MCP server: a server that holds real logins.
- How to connect Claude to n8n's MCP server: limiting what a connected agent can run.
- The Google Harness2 setup guide: what an agent with a shell can reach when nothing blocks the network.
- MCP in the glossary, in plain words.
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.
Last updated
November 1, 2026
Category
AI Agents
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.
Related articles

MCP Just Hit 97 Million Installs. The Dev Summit Showed What Comes Next for AI Agents.
The Model Context Protocol crossed 97 million monthly installs in March 2026. Two weeks later, hundreds of engineers gathered in New York for the first ever MCP Dev Summit. Here is what I took away from both events and what it means if you are building AI agents right now.
GuideTrends & InsightsMCP
Model Context Protocol: How I Build MCP Servers That Run in Production (and What Most Guides Skip)
A practitioner's guide to building Model Context Protocol servers that actually work in production, covering authentication, error handling, transport options, deployment, and real ROI numbers from 23 client deployments.
GuideImplementationMCP
How to Evaluate the Manus AI Agent in October 2026: Owner, Cost and Risks
Who owns the Manus AI agent after the Meta deal was unwound, what its credits cost in October 2026, how its sandbox and security record look, and when to pick OpenClaw, Hermes Agent, Claude, OpenAI or n8n.
How toAI AgentsManus
