Cloudflare Code Mode Breakdown
PRASOON.CODES
-99.9%INPUT TOKENS

Is MCP dead?

Cloudflare Code Mode, explained

How Cloudflare gives an AI agent its entire API, 2,500+ endpoints, in about 1,000 tokens. What problem it solves, how it works under the hood, why it's safe, and how you can use it today.

Topic MCP · AI agents · CloudflareBased on Cloudflare's blog (Sept 2025, Feb 2026) and changelog (Mar 2026)Edition October 2026
Contents
  1. TL;DR and key numbers
  2. MCP, from zero
  3. The problem in detail
  4. The insight: code beats tool calls
  5. How Code Mode works
  6. The security model
  7. The Cloudflare MCP server
  8. Code Mode vs the alternatives
  9. Try it yourself
  10. So, is MCP dead?
  11. When to reach for Code Mode
  12. Caveats and limits
  13. FAQ
  14. Glossary and sources
01

TL;DR

2,500+endpoints in the Cloudflare API
1.17Mtokens, equivalent server without Code Mode
~1,000tokens with Code Mode, fixed
99.9%fewer input tokens
2tools: search() and execute()
02

MCP, from zero

The Model Context Protocol (MCP) is an open standard for connecting AI agents to tools and data. A service such as GitHub, a database, email or a payments API runs an MCP server. The server lists its tools, and for each tool it gives a name, a description and the parameters it accepts. An agent that connects to the server can then call those tools.

Any service with an MCP server: one standard plug for all of them.

What a tool definition looks like

Every tool comes with a description written in JSON Schema. A single tool might look like this (simplified example):

tool definition · example
{
  "name": "create_issue",
  "description": "Create a new issue in a GitHub repository",
  "inputSchema": {
    "type": "object",
    "properties": {
      "repo":  { "type": "string", "description": "owner/name" },
      "title": { "type": "string" },
      "body":  { "type": "string" }
    },
    "required": ["repo", "title"]
  }
}

How a normal tool call works

This works well for a handful of tools. The trouble starts when there are many tools, or a task needs many steps.

03

The problem in detail

Problem 1: the context fills up before work starts

A model can only hold a limited amount of text at once, its context window, measured in tokens (roughly word pieces). Tool definitions are loaded up front, so every tool takes some of that space whether the task needs it or not.

Cloudflare's API has over 2,500 endpoints. Cloudflare measured an equivalent MCP server without Code Mode at about 1.17 million tokens, and estimates over 2 million if every endpoint were its own tool.

≈

Worked out: 1,170,000 tokens ÷ 2,500 endpoints ≈ 470 tokens per endpoint on average. That is roughly a page of text per endpoint, and the agent would have to carry all of it before typing a single word of its answer. (Our arithmetic from Cloudflare's figures.)

Problem 2: every step goes back through the model

With plain tool calling, each result comes back into the model's context. The model reads it, picks out what it needs, and writes the next tool call. A ten-step task means ten trips through the model, and each trip adds more tokens and more waiting.

Why it matters

04

The insight: code beats tool calls

Cloudflare's argument has two parts.

1 · Training data

Models have read an enormous amount of real-world TypeScript and JavaScript. Tool calls use special formats that models have seen far fewer examples of. Cloudflare compares it to putting Shakespeare through a month-long Mandarin class and then asking him for a play in Mandarin.

2 · Chaining

When an agent strings tool calls together, each result passes through the model only to be copied into the next call. Code can pass values between calls directly and return only the final answer.

→

So instead of teaching the model a format it barely knows, Code Mode describes the tools as an ordinary code API and asks the model to do what it is best at: write code.

05

How Code Mode works

Cloudflare introduced Code Mode in September 2025 as part of its Agents SDK. It works in four steps.

Tools become a TypeScript API

The SDK fetches the MCP server's schema and generates TypeScript interfaces for every tool, with doc comments taken from the schema.

The agent gets one tool: run code

Instead of the full list of tools, the agent gets a single tool that executes TypeScript, plus the generated API as reference.

A fresh sandbox runs the code

Each snippet runs in its own V8 isolate, created on demand with Workers' Worker Loader API. Isolates start in milliseconds and use a few megabytes, so one can be made per snippet and thrown away.

Only results come back

The script reports what matters with console.log(). Those logs go back to the agent; the intermediate data never does.

Step 1 in practice: from schema to TypeScript

The create_issue tool from section 2 becomes a typed function the model already knows how to use. Roughly (illustrative):

generated API · illustrative
declare const codemode: {
  /** Create a new issue in a GitHub repository */
  create_issue(input: { repo: string; title: string; body?: string }): Promise<Issue>;
  /** List issues in a repository */
  list_issues(input: { repo: string; state?: "open" | "closed" }): Promise<Issue[]>;
};

Steps 2–4 in practice: one script instead of many calls

what the agent writes · illustrative
const issues = await codemode.list_issues({ repo: "acme/web", state: "open" });
const stale = issues.filter((i) => i.comments === 0);   // filtering happens here, not in the model
for (const i of stale) {
  await codemode.add_label({ repo: "acme/web", issue: i.number, label: "needs-triage" });
}
console.log(`Labelled ${stale.length} stale issues`);   // the only thing the model reads

The architecture

Calls from the sandbox are RPCs routed back to the agent loop, which dispatches them to the MCP servers.

06

The security model

Letting a model write and run code sounds risky. Code Mode limits what that code can do in several layers.

No internet

Inside the sandbox, fetch() and connect() throw errors, so code can't send data to an arbitrary server. Cloudflare's MCP server can allow specific outbound requests through outbound fetch handlers.

Bindings, not network access

The sandbox can only talk to the MCP servers it was given, through bindings. That is easier to reason about than filtering network traffic.

Keys never reach the code

Bindings are already authorised. A supervisor adds the access tokens on the way out, so the generated code never holds an API key it could leak.

Nothing to steal

The isolate has no file system and no environment variables, which removes common targets for prompt-injection attacks.

✓

Scoped permissions: Cloudflare's MCP server uses OAuth 2.1. When you connect, you choose which permissions the agent gets, and the token is limited to exactly those.

07

The Cloudflare MCP server

In February 2026 Cloudflare applied Code Mode to its own MCP server, which covers the entire Cloudflare API. It exports only two tools. Each takes a single string of code: a JavaScript async arrow function.

search()

Runs code against a spec object holding the full OpenAPI spec, with every $ref already resolved. The agent filters endpoints by product, path, tags or other metadata. The spec itself never enters the model's context.

execute()

Runs code that makes Cloudflare API requests through an authenticated cloudflare.request() client. It can handle pagination, check responses and chain several calls in one run.

search() · illustrative
async () => Object.entries(spec.paths)
  .filter(([path]) => path.includes("/dns_records"))
  .map(([path, ops]) => ({ path, methods: Object.keys(ops) }))
execute() · illustrative
async () => {
  const zones = await cloudflare.request({ method: "GET", path: "/zones" });
  const zone = zones.result[0];
  const dns = await cloudflare.request({ method: "GET", path: `/zones/${zone.id}/dns_records` });
  return dns.result.map((r) => ({ type: r.type, name: r.name }));   // only this returns
}

Code samples in this document are illustrative. The server's own tool descriptions give the exact shape of spec and cloudflare.request().

The numbers, drawn to scale

The Code Mode bar is 0.09% of the other one; what you see is its minimum visible width. Cloudflare's 99.9% figure is measured against the 1.17M baseline, counted with tiktoken.

∞

The ~1,000-token footprint is fixed: it doesn't grow as the API adds endpoints, because the spec is searched by code instead of being read by the model. In Cloudflare's example, an agent searches the spec, inspects a schema, lists rulesets and fetches DDoS and WAF settings in four tool calls.

08

Code Mode vs the alternatives

Cloudflare compares server-side Code Mode with the other common ways of cutting tool overhead:

ApproachHow it worksTrade-off
Plain MCPEvery tool definition loaded into contextContext grows with every tool
Dynamic tool searchA search step picks the relevant tools firstYou maintain the search function, and the matched tools still cost tokens
CLI toolsThe agent runs command-line tools in a shellNeeds a shell, which not every environment has, and widens the attack surface
Client-side Code ModeThe agent writes code that runs on the clientThe agent needs its own secure sandbox
Server-side Code ModeThe MCP server runs the code in its own sandbox: search() + execute()Fixed ~1,000 tokens; no client sandbox needed
09

Try it yourself

Option A · Connect Cloudflare's MCP server to your agent

  1. Add the server to your MCP client's configuration (Claude, Cursor or any MCP-capable client):
mcp config · JSON
{
  "mcpServers": {
    "cloudflare-api": {
      "url": "https://mcp.cloudflare.com/mcp"
    }
  }
}
  1. Your client opens Cloudflare's sign-in page. Approve the permissions you want the agent to have.
  2. Ask the agent for something real, such as "list my zones and show the DNS records for the first one". It will use search() to find the endpoints and execute() to call them.
⚙

For CI/CD or scripts: instead of OAuth you can pass a Cloudflare user or account API token as a bearer token in the Authorization header.

Option B · Turn it on for your own MCP servers (MCP server portals)

Since March 2026, Cloudflare's MCP server portals have Code Mode on by default. The connected agent gets one code tool instead of every tool definition, and its code runs in an isolated Dynamic Worker, so credentials and environment variables stay out of the model's context.

Option C · Build it into your own agent (Agents SDK)

The Cloudflare Agents SDK ships a codemode helper. You give it your system prompt and tools; it returns a new system prompt and a code tool to pass to your model call. In outline (simplified):

agent.ts · simplified
import { codemode } from "agents/codemode/ai";

const { system, tools } = codemode({
  system: "You are a helpful assistant.",
  tools: myTools,           // your MCP tools
  // …sandbox / loader configuration, see the SDK docs
});

const result = streamText({ model, system, tools, messages });

The exact options are in the codemode package. Running your own sandbox uses the Worker Loader API; check its current availability (see section 12).

10
So, is MCP dead?
No. It levelled up.

Code Mode runs on top of MCP. MCP still does the parts that matter most for real systems:

MCP still handles

  • Connecting to services in one standard way
  • Describing what each tool does (the docs the API is generated from)
  • Authorisation and scoped access

What Code Mode changes

  • The agent writes code against the tools instead of calling them one by one
  • Big APIs fit in a fixed, small context
  • Multi-step work runs in one script

Anthropic has explored the same pattern in its "code execution with MCP" work, so this is becoming a common way to use MCP, not a replacement for it.

11

When to reach for Code Mode

A practical guide, based on how the approach works:

Great fit

  • Large APIs with hundreds or thousands of operations
  • Tasks with many dependent steps
  • Workflows that sift through lots of data to return a little
  • Several MCP servers used together

Less needed

  • Two or three small tools, used one at a time
  • Single lookups where the raw result is the answer
  • Setups where you can't run a sandbox and the server doesn't offer Code Mode
12

Caveats and limits

13

FAQ

Does Code Mode replace MCP servers?

No. It consumes MCP servers. The tools, their descriptions and their authorisation all still come from MCP.

Do I need to know TypeScript to use it?

No. The model writes the code. You only connect the server (Option A) or flip the setting on a portal (Option B).

Can the generated code leak my API keys?

It never has them. Calls go through bindings and a supervisor that adds the credentials outside the sandbox.

Is it only for Cloudflare's API?

No. Cloudflare's MCP server is the showcase, but the Agents SDK and MCP server portals apply Code Mode to other MCP servers too.

Why is the footprint fixed at ~1,000 tokens?

The model only sees the two tool descriptions. The spec is explored by code inside the sandbox, so its size doesn't matter to the model.

Does it make answers better, or only cheaper?

Cloudflare reports agents handle more and more complex tools this way, and multi-step tasks use less time and fewer tokens. Quality gains depend on your task, so test it on yours.

14

Glossary

MCP
Model Context Protocol: an open standard for connecting AI agents to tools and data.
Tool call
A structured request from the model to run one tool with given inputs.
Token
The unit models read and bill by, roughly a word piece.
Context window
How many tokens a model can hold at once, instructions and tool definitions included.
OpenAPI spec
A machine-readable description of every endpoint of an API.
V8 isolate
A lightweight, separate JavaScript runtime. Starts in milliseconds and shares nothing with other isolates.
Binding
A pre-authorised object a Worker uses to reach one specific service, without general network access.
OAuth 2.1
The sign-in flow where you approve exactly which permissions an app or agent gets.
Sources
  1. Code Mode: the better way to use MCP. Cloudflare blog, Kenton Varda and Sunil Pai, Sept 2025.
  2. Code Mode: give agents an entire API in 1,000 tokens. Cloudflare blog, Feb 2026.
  3. Code Mode for MCP server portals. Cloudflare changelog, Mar 2026.
  4. github.com/cloudflare/mcp. The open-source Cloudflare MCP server.
  5. github.com/cloudflare/agents · codemode. The Code Mode SDK.