Key Takeaway
Cloudflare's MCP server covers its 2,500-plus API endpoints with two tools, search and execute, costing about 1,000 tokens instead of the 1.17 million the company measured for an equivalent tool-per-endpoint server. The model writes JavaScript that runs in a Dynamic Worker V8 isolate with no filesystem, and outbound fetch is disabled by default.
The number that made me stop and read the whole announcement was 1.17 million. That is how many tokens Cloudflare says an MCP server would need if every one of its API endpoints were described to the model as its own tool, and it is more than the context window of the most advanced models. The server they shipped instead spends about 1,000.
This post is a close reading of Cloudflare's two engineering posts, the cloudflare/mcp README, Anthropic's code-execution write-up and the Dynamic Workers documentation, all fetched on 2026-10-17. I have not benchmarked the server myself, so every figure below is attributed to the page it came from, and where two pages disagree I say so rather than reconcile them.
The arithmetic: why per-endpoint tools cannot work here
The Cloudflare API has over 2,500 endpoints. Cloudflare's post says that exposing each as an MCP tool would consume over 2 million tokens, and that an equivalent server without Code Mode would use 1.17 million tokens. The Code Mode server loads about 1,000 tokens of tool definitions, and the post says that footprint stays fixed however many endpoints the API grows to. The README for the server gives a fourth number for the opt-out mode. Four figures, four different sources:
| What is measured | Tokens | Where it comes from |
|---|---|---|
| One tool per endpoint, as described in the post metadata | over 2 million | Cloudflare blog, Code Mode for the Cloudflare API |
| Equivalent MCP server without Code Mode | 1.17 million | Same post, counted with tiktoken |
| Server with ?codemode=false, about 2,500 tools | about 244k | cloudflare/mcp README |
| Server in Code Mode, fixed footprint | about 1,000 | Blog post and README agree |
I could not make the first three numbers agree, and I do not think they are meant to. They are different counting methods over different serialisations of the same idea. What the sources do agree on is the order of magnitude: the per-endpoint design is hundreds of thousands to millions of tokens, and Code Mode is a thousand. The post reports the saving as a 99.9% reduction in input tokens, and 1,000 against 1.17 million is about 0.09%, so that arithmetic holds.
What search and execute actually are
Each tool takes a single required code string: a JavaScript async arrow function. The search tool is described as searching the Cloudflare OpenAPI spec with all references pre-resolved inline, and the model writes code against a spec object that holds the entire document. The execute tool runs code against the real API through a cloudflare.request client inside the sandbox. The two sketches below show the shape. The spec.paths access comes from the README; the request argument shape is my sketch and is flagged as such in the comment.
// Tool 1: search. The model writes this; "spec" is the whole OpenAPI
// document, resolved server-side. Only what the function RETURNS reaches
// the model's context, so a 2,500-endpoint spec costs a few lines of output.
async () => {
const hits = [];
for (const [path, methods] of Object.entries(spec.paths)) {
if (!/rulesets/.test(path)) continue;
for (const [method, op] of Object.entries(methods)) {
hits.push(method.toUpperCase() + " " + path + " " + (op.summary ?? ""));
}
}
return hits.slice(0, 20);
}
// Tool 2: execute. Same shape, but it can call the API. Pagination, retries
// and chaining happen inside one tool call instead of one round trip each.
// The request argument shape below is a sketch: confirm the exact signature
// in the cloudflare/mcp README before you rely on it.
async () => {
const ZONE_ID = "<your zone id>";
const res = await cloudflare.request({
method: "GET",
path: "/zones/" + ZONE_ID + "/rulesets",
});
// Return a summary, not the payload. This is the whole token-saving trick.
return res.result.map((r) => r.phase + " " + r.name);
}The worked example in the post is a DDoS and WAF question. The agent filtered spec paths for WAF and ruleset endpoints, read the phase enum out of the zone rulesets schema, chose ddos_l7 and http_request_firewall_managed, then listed the existing rulesets and fetched both entrypoint rulesets in a single execute run. Cloudflare counts the whole task as four tool calls. With per-endpoint tools the model would have had to scan thousands of definitions up front and paste each response into the next call by hand.
One correction to the headline. The post describes two tools, and the README today lists four: docs, search, execute and whoami. The extra two are small. The docs tool searches Cloudflare developer documentation, and whoami takes no arguments and returns the identity behind the credential. They do not change the cost argument, but if you count tools in your client you will see four, not two.
Why code beats tool calls: the argument underneath
The earlier Cloudflare post makes the claim that LLMs are better at writing code to call MCP than at calling MCP directly, because models have seen vast amounts of real-world code and relatively few tool-call examples. The second argument is mechanical. With direct tool calls, every result passes through the model just to be copied into the next call. With code, the model chains the calls itself and reads back only the final result. Anthropic's own write-up of the same pattern gives the proportion: a Google Drive to Salesforce example fell from about 150,000 tokens to 2,000, and filtering a 10,000-row spreadsheet in code means the model sees five rows.
Anthropic also names a side benefit that matters for privacy. Intermediate results stay in the execution environment by default, so the model sees only what the code logs or returns. That is the same property that makes the return a summary, not the payload line in the sketch above the important one. It is easy to write an execute call that returns the whole response and throws the saving away.
Treat the return statement as the budget. When you read the code an agent wrote, look at what it returns. A script that fetches 500 rulesets and returns all of them has moved the cost from tool definitions into tool output, which the README separately caps at about 6,000 tokens per result.
The sandbox: a V8 isolate with nothing in it
Agent-written code is untrusted by definition, so the sandbox carries the safety argument. The code runs in a Dynamic Worker, which Cloudflare describes as a lightweight V8 sandbox with no filesystem and no environment variables, and with external fetches disabled by default. The earlier post adds that a fresh isolate is created per code snippet and discarded afterwards, with no pooling or prewarming, and that an isolate can start in a handful of milliseconds using a few megabytes of memory. The Dynamic Workers docs position it as a lightweight alternative to containers for code you do not trust. The config below is lifted from those docs and trimmed, so you can run the same idea against your own API.
# wrangler.toml: the Worker Loader binding. It points at no external
# resource; it just exposes env.LOADER to your loader Worker.
[[worker_loaders]]
binding = "LOADER"
// Loader Worker. Option 1: no network at all. fetch() and connect() throw.
return {
mainModule: "index.js",
modules: { "index.js": code },
globalOutbound: null,
};
// Option 2: route every outbound call through a gateway you own, and attach
// the secret there so the generated code never holds it.
import { WorkerEntrypoint } from "cloudflare:workers";
export class HttpGateway extends WorkerEntrypoint {
async fetch(request) {
const url = new URL(request.url);
const headers = new Headers(request.headers);
if (url.hostname === "api.example.com") {
headers.set("Authorization", "Bearer " + this.env.API_TOKEN);
}
return fetch(request, { headers });
}
}
// ...and in the loader: globalOutbound: ctx.exports.HttpGateway({ props: {} })The design choice I found most useful is how credentials are handled. In the Code Mode SDK, the sandbox receives bindings rather than strings: live, already-authorised objects. The generated code calls a binding, the call goes back to a supervisor that holds the tokens and adds them before forwarding, and so the generated code never sees a credential and cannot leak one. The Dynamic Workers egress documentation shows the same idea for HTTP: a gateway class attaches the Authorization header to matching requests so the dynamic Worker calls fetch with no secret.
Cloudflare argues this is cleaner than network-level filtering, because filtering leaves unclear boundaries for both the supervisor and the model, while a binding exposes a defined JavaScript interface. One caveat from the docs: if the sandboxed code depends on an HTTP client library that needs fetch, blocking outright may not work, and you should intercept instead of setting globalOutbound to null.
Where it sits among the other ways to cut MCP context
Code Mode is one of several answers to the same problem, and the Cloudflare post compares itself to the neighbours. The table below collects what the sources say about each, so you can see what each approach costs you rather than only what it saves.
| Approach | What the model sees up front | Sandbox needed | Cost named in the sources |
|---|---|---|---|
| One tool per endpoint | Every definition, about 2,500 tools | No | About 244k tokens against about 1k, per the README |
| Dynamic tool search, as in Claude Code | Names first, matched tools on demand | No | Cloudflare notes you maintain a search function and matched tools still consume tokens |
| Client-side code execution, per Anthropic | A directory of tool files, read as needed | Yes, yours | Anthropic cites operational overhead, resource limits and monitoring |
| Server-side Code Mode, per Cloudflare | Two to four fixed tools | Yes, the provider's | Solves context for one API; several servers still add up |
I wrote about the second row separately in the Claude Code tool search post: that is the client deferring definitions it already received. Code Mode is a different layer, because the server never publishes the big surface in the first place. The two compose, but neither replaces the other. Cloudflare also lists CLI-based approaches that need a shell, and calls that a much broader attack surface than a sandboxed isolate.
Authorisation: what the agent is actually allowed to do
The server is described as OAuth 2.1 compliant and uses the Workers OAuth Provider to downscope tokens to the permissions you approve when you connect. The agent gets only what you explicitly grant. For CI and automation you create a Cloudflare API token, user or account, and send it as a bearer token. The README adds three practical details: an account token needs the Account Resources Read permission so the server can detect the account ID, API tokens with Client IP Address Filtering enabled are not currently supported, and with a user token you pass account_id to execute.
// Interactive: OAuth. Connect, get redirected to Cloudflare, tick the
// permissions you are willing to hand over. Nothing else is granted.
{
"mcpServers": {
"cloudflare-api": {
"type": "http",
"url": "https://mcp.cloudflare.com/mcp"
}
}
}
# Non-interactive (CI): a Cloudflare API token as a bearer token.
# An account token needs "Account Resources : Read" so the server can
# detect the account ID. Tokens with Client IP Address Filtering are
# not currently supported.
claude mcp add --transport http cloudflare-api https://mcp.cloudflare.com/mcp \
--header "Authorization: Bearer $CLOUDFLARE_API_TOKEN"The README also documents the two query parameters worth knowing. Results are truncated at about 6,000 tokens each by default, marked with a TRUNCATED line, and truncateToolResult=false turns the cap off, which it advises only when your client bounds what reaches the model. GraphQL Analytics requests go through execute as well.
The sandbox protects Cloudflare's host from the agent's code. It does not protect your account from the agent's intent. Those are different threats, and this is my inference from the design rather than a claim in the sources: if you approve write permissions in the OAuth screen, code the model wrote can use them. Approve the narrowest scopes the task needs, and prefer a read-only token for any exploratory session.
Trade-offs and what can go wrong
None of the sources claim Code Mode is free. These are the costs I found by reading, in the order I would worry about them.
- You review code, not a tool call. A named tool with typed arguments is easy to approve at a glance. A generated function with loops and chained requests is harder to audit, so approval prompts carry more weight.
- It fixes one API, not your whole toolbelt. Cloudflare says so directly: an agent that also talks to GitHub and a database still sees context pressure from each extra MCP server. Its answer, MCP Server Portals with a first-class Code Mode integration, is described as in development.
- The model has to write correct JavaScript. Failures move from schema errors to runtime errors inside the sandbox, and the agent spends extra calls reading them. The four-call DDoS example is the success case.
- Output can still be large. The default cap of about 6,000 tokens per result exists because a careless execute call can return a lot, and truncated output hides data from the agent.
- Running your own version has overhead. Anthropic states that running agent-generated code requires a secure execution environment and that this adds operational overhead and security considerations that direct tool calls avoid. Using Cloudflare's hosted server shifts that burden onto them, which is a trust decision.
My read: the sandbox is the strong part of the design, and the open question is human review of generated code at scale. Nothing in the pages I read measures how often agents write wrong or over-broad code, so I would not put a number on it.
What to do on Monday
You do not need to adopt anything to learn from this. Five steps, cheapest first.
- Count your own tool surface. List every connected MCP server and how many tools each exposes. If one server alone exposes dozens of tools, that is your Code Mode candidate.
- Try the Cloudflare server over OAuth on a read-only task and approve the narrowest permissions that task needs.
- Read the generated search and execute code before trusting the result. Check what each function returns.
- Use an API token with a bearer header for CI, scoped to one account, and remember Client IP filtering tokens are not supported.
- If you own a large API, steal the shape: publish an OpenAPI spec to a search tool, one execute tool, and run the code in an isolate with outbound blocked and credentials added by a gateway.
# 1. Measure your own baseline before changing anything. How many tool
# definitions does each connected server contribute? Ask your client.
claude mcp list
# 2. Add the server over OAuth and approve only the scopes the task needs.
claude mcp add --transport http cloudflare-api https://mcp.cloudflare.com/mcp
# 3. Ask for a read-only task first and read the code the agent wrote.
# "Which zones do I have, and which have no WAF managed ruleset?"
# 4. Only if you must see 2,500 individual tools (for example to compose with
# another code-mode system), opt out. The README says this costs about
# 244k tokens against about 1k, so treat it as an escape hatch.
# https://mcp.cloudflare.com/mcp?codemode=falseLeave ?codemode=false alone unless you are composing with another code-mode system. The README itself says it raises the cost from about 1k to about 244k tokens.
The lesson I am keeping: when an API is too big to describe, stop describing it and give the model a way to look it up. Two tools, a fixed footprint of about 1,000 tokens, and a sandbox with no filesystem and no outbound network turn 2,500 endpoints into a search problem. What Code Mode does not solve is review and scope: the code is still written by a model, and it runs with every permission you approved.
Sources and further reading
- Cloudflare blog: Code Mode for the Cloudflare API (2026-02-20)
- Cloudflare blog: Code Mode, the better way to use MCP
- GitHub: cloudflare/mcp README, the token-efficient MCP server
- Anthropic Engineering: Code execution with MCP
- Cloudflare docs: Dynamic Workers egress control
- Cloudflare docs: Dynamic Workers getting started

