Code Mode: MCP agents write scripts, not tool calls
Code Mode lets agents call MCP tools from one script, not call by call. A decode for builders choosing where it runs: in the server, the client or a gateway.
Say you're the one-person platform team at a small web agency. Your agent has Model Context Protocol (MCP) servers connected for DNS, Workers logs, GitHub and your issue tracker. A client asks which of their twenty zones have no managed firewall ruleset turned on. The agent loads every tool definition from every server before it reads the question. Then it calls one tool per turn: list zones, fetch rulesets for zone one, then zone two, then zone three. Each full JSON response lands in the context window, the model reads it and decides the next call. By zone twelve the context is mostly payloads you'll never look at, the token bill keeps climbing, and the answer you wanted is a three-line list.
Code Mode lets the agent do that whole loop as one short script, with only the script's return value going back to the model. Cloudflare's server-side version, published on its blog Feb 20, 2026, puts the entire Cloudflare API behind two tools. The pattern now runs in the MCP server, in the agent client and in the gateway between them. @bibryam on X lists agentgateway, Claude Code and Cloudflare's MCP server as three places it already runs.
What it is
The core move is the same everywhere. Tools stop being a long list of schemas in the prompt and become typed functions. The model writes code that calls them, a sandbox runs the code, and anything the script fetched along the way stays out of the model's context. Speakeasy's explainer traces the name to Cloudflare in September 2025 and notes that Anthropic followed in November 2025. What differs is where the sandbox lives.
In the MCP server (Cloudflare). The Cloudflare MCP server exports only search() and execute(). Both take a JavaScript async arrow function. search() runs code against the full OpenAPI spec, with references pre-resolved, so the agent can filter over 2,500 endpoints down to the few it needs without the spec entering context. execute() gets an authenticated cloudflare.request() client and can paginate, check responses and chain calls in one run. Cloudflare says the tool surface costs about 1,000 tokens however many endpoints exist. It puts an equivalent server without Code Mode at 1.17 million tokens, a 99.9% reduction measured with tiktoken (Cloudflare, Feb 20, 2026). The generated code runs in a Dynamic Worker isolate, a V8 sandbox with no file system and no environment variables, and with external fetches disabled by default. Connections use OAuth 2.1, and the token is downscoped to the permissions the user approves. For the lede's twenty-zone loop, this means one execute() call that walks the zones and returns the short list. Cloudflare's own worked example finds and fetches the DDoS and firewall configuration for a zone in four tool calls. Cloudflare also open-sourced a Code Mode SDK in its Agents SDK for use in your own servers.
In the client (Claude Code and other harnesses). Anthropic's engineering post of Nov 4, 2025 made the same argument from the agent side. It presents MCP servers as a file tree of TypeScript wrappers that the agent opens on demand, as Sulat AI & Tech News explains. On Nov 12, 2026, Claude Code added an experimental Code Mode in which Claude writes JavaScript that makes several tool calls in one step. In the Claude API the equivalent is Programmatic Tool Calling. Philipp Schmid writes that Code Mode is becoming the default in OpenCode 2.0, Claude Code, OpenAI Codex, Pi and Factory Droid. That is his reading, not a list each vendor has confirmed. He adds that it works best when servers declare an outputSchema, so the client can generate typed stubs before the model writes code.
In a gateway (Speakeasy, agentgateway). Speakeasy's gateway Code Mode serves one execute tool that runs short Python scripts. Each upstream call inside a script goes through the same identity checks, permission checks and audit logging as a direct call (Speakeasy). Solo.io's agentgateway has a tool mode setting of Search or Code. In code mode, a tool the caller isn't authorized for simply isn't defined in the program (Solo.io).
Alternatives and placement trade-offs, each from its own source:
- Tool search or deferred tool loading. Definitions stay hidden until the model searches for them. In one benchmark with 206 tools, this cut input from 118k tokens to 11k, while Programmatic Tool Calling still loaded 161k (yeyo11 on DEV Community). The trade-off: once a tool is called, its full result still lands in context.
- CLIs plus Skills, for example MCP servers converted to CLIs with MCPorter. Cloudflare's post names the limit: the agent needs a shell, which not every environment provides and which is a broader attack surface than an isolate.
- Gateway-level code mode. The sandbox cost is paid once for every server behind the gateway. The trade-off is that you need to run that gateway, and Speakeasy's version must be enabled for the organization first.
Who it's for
Pick it up if your agent's real work is chains of dependent calls whose results only need filtering, counting or moving between systems. Anthropic's guidance, quoted by Sulat, names large datasets where you need aggregates, three or more dependent calls, transforms before the model sees results, and parallel operations across many items. Cloudflare users who want one connection for DNS, Zero Trust, Workers and R2 instead of a stack of per-product servers are the clearest fit for the server-side version. Teams already running an MCP gateway for auth and policy get it across every server at once.
Skip it for single lookups and quick reads. In the DEV Community benchmark, a one-call task took 14 seconds with code versus 7 classic, and it cost $0.012 with code versus $0.006 with tool search. Skip it if you run smaller models: Speakeasy relays Pi contributor Armin Ronacher's view that the pattern doesn't work with them yet. And if your problem is hundreds of tool definitions rather than big intermediate results, tool search is the lever. Speakeasy argues that a single MCP server connected to a harness with tool search probably doesn't need its own code mode.
Before and after
Before, for the twenty-zone audit:
- The client loads every tool schema from every connected server.
- The model calls a list tool, and the full zone list enters context.
- It calls a rulesets tool per zone, and each full response enters context.
- The model reads twenty payloads and writes the answer, often re-typing data it already saw.
After, with server-side Code Mode:
- The client loads two tool definitions.
- The model calls
search()with a filter for ruleset endpoints on zones and gets back a short list of paths. - It calls
execute()with a loop over zones that fetches each ruleset entrypoint and returns only the zones that are missing one. - The model reads that short list and answers.
Client-side Code Mode trades turns for tokens. In the DEV Community author's Claude Code test against his real MCP server, Code Mode made 13 model requests versus 5 classic, took the same 21 seconds and cost an estimated 44% less, which the author attributes to the MCP results never reaching the context. The author ran three repetitions per mode.
Try it
Connect the Cloudflare MCP server to your MCP client with this config, from Cloudflare's post:
{
"mcpServers": {
"cloudflare-api": {
"url": "https://mcp.cloudflare.com/mcp"
}
}
}
You'll be redirected to Cloudflare to authorize and pick the permissions the agent gets. For a first run, our suggestion is to grant only the permissions the task needs. For CI or self-managed tokens, Cloudflare says user and account API tokens both work as bearer tokens in the Authorization header. The post gives no price for the server.
Then walk one task through:
- Ask: "List the rulesets on zone with their name, phase and kind."
- Watch the tool calls. In Cloudflare's example, the agent's
search()code filtered spec paths for/zones/andrulesets, then anexecute()call usedcloudflare.request()against/zones/${zoneId}/rulesets. Your agent's code will vary. - Check the result against the dashboard. Cloudflare's example returns objects such as
{ "name": "DDoS L7", "phase": "ddos_l7", "kind": "managed" }.
It worked if your client shows only two tools for this server, and the answer arrived without any endpoint documentation being pasted into the chat.
To try the client-side version, the DEV Community post says you need Claude Code 2.1.323 or later and an interactive session:
CLAUDE_CODE_EXPERIMENTAL_CODE_MODE=1 claude
It asks to enable the mode on first launch and then restart. It doesn't work with claude -p, and press Ctrl+O to see the script Claude writes. Give it a task that spans several calls to an MCP server you already use. If it worked, Ctrl+O shows a script where results sit in a variable and only a count or a filtered list comes back.
Our example of a project instruction (a CLAUDE.md line), based on Anthropic's guidance: "When a task needs three or more dependent MCP calls or a large result filtered down, do it in one script and return only the summary. For a single lookup, call the tool directly."
Where it breaks
- Someone runs the sandbox. Anthropic's post says running agent-generated code needs sandboxing, resource limits and monitoring, which "add operational overhead and security considerations that direct tool calls avoid" (Sulat). Server-side Code Mode moves that burden to Cloudflare; client-side puts it on your harness, and Claude Code's experimental mode runs the script outside Claude Code's sandbox (next point).
- Governance gets coarser. A script with ten calls in a loop is one step from the client's point of view, unless whatever runs it checks each call (Speakeasy). In Claude Code, deny and ask rules and PreToolUse hooks still apply per call. In auto mode, though, the classifier reviews the code, not each call, and the documentation says the JavaScript and its file, web and MCP calls run outside the sandbox (yeyo11). Schmid lists Code Mode sandboxes among the things that widen the prompt-injection surface (Philipp Schmid).
- Nesting hurts. Calling Cloudflare's code-execution tool from inside a client-side Code Mode script means code inside code, which Ronacher calls "double JSON escaping, easy for smaller models to get confused by." Speakeasy also lists binary payloads and resuming long scripts as weak spots.
- Lock-in and cost by placement. agentgateway's search and code tool modes require Solo Enterprise, though federation, auth and guardrails are open source (Solo.io). Speakeasy's mode must be enabled for the organization, and Speakeasy asks you to talk to it to turn it on. This piece describes agentgateway's code mode only from Solo.io's own docs.
- The headline numbers are soft. Cloudflare's 1.17 million-token baseline is, in the DEV Community author's reading, a hypothetical server with one tool per endpoint. Anthropic's 150,000-to-2,000 figure comes from a single example, and the post names no model, tool count, number of runs or counting method, per Sulat. Sulat and the DEV Community author also disagree on what that figure measures: the Drive-to-Salesforce job, or loading tool definitions on demand. The DEV Community benchmark itself used one model, a mock server for its API tests (the Claude Code comparison used the author's real server), and five runs per cell on the API and three per mode in Claude Code, which its author says is enough to show direction, not decimals. The author left Cloudflare's Code Mode out as a different stack that, they write, needs the paid Workers plan to deploy. That is the author's reason for skipping it; for the hosted server in Try it, Cloudflare's post gives no price.
Cloudflare's launch post reports token counts measured with tiktoken, but gives no latency or error-rate figures for the server-side execute() path.
Sources
- Code Mode: give agents an entire API in 1,000 tokens · Cloudflare Blog
- Anthropic’s code execution with MCP, explained · Sulat AI & Tech News
- What is code mode? — Speakeasy · Speakeasy
- What Is an MCP Gateway? | Solo.io · Solo.io
- Why I'm Bullish on MCP for 2027 · Philipp Schmid
- With Code Mode, my agent makes twice the model requests and spends 44% less than without it · DEV Community
- @bibryam: Code Mode is a core agentic pattern. It’s in agentgateway, Claude Code and Cloudflare’s M… · @bibryam