AI Agents 9 min read 30 November 2026

Cloudflare Code Mode: what needs to change in your current MCP server

Cloudflare's Code Mode turns your MCP tools into a typed API that agents call with code. Here are 12 concrete changes to make to your MCP server so it works well under it.

Cloudflare Code Mode: what needs to change in your current MCP server
Part of the Implementing AI Agents guideHow to Implement AI Agents in Your Business

Most MCP servers in production today were built for one style of agent: the model reads a list of tools, picks one, waits for the result, then picks the next. Every tool's schema sits in the context window on every turn, and every step is a round trip through the model.

Cloudflare's Code Mode changes that contract. Instead of calling your tools one at a time, the agent gets a TypeScript API generated from them and writes a short program that calls that API. The program runs in a locked-down sandbox, and only the result goes back to the model.

Cloudflare's own numbers show why this matters: for its API of over 2,500 endpoints, Code Mode cut the context needed from about 1.17 million tokens to roughly 1,000.

If you own an MCP server, for an internal system, a SaaS product or a client integration, this is not a rewrite. It is a set of design changes that make your server a good API for code, not just a good menu for a model. Here is what Code Mode does, and the twelve changes we would make.

Why Code Mode is needed

Classic MCP tool calling has three costs, and they grow with every tool you add and every step a task takes.

1. Every tool definition costs context, on every turn. To choose between tools, the model needs each tool's name, description and schema in its context window. In Cloudflare's words, "every tool added fills the model's context window, leaving less room for the actual task." A server that exposes a large API pays that bill before the user has asked anything.

2. Every intermediate result goes through the model. When a task needs several calls, the output of each one is sent back to the model, which reads it and copies what it needs into the next call. Cloudflare's 2025 post calls this "wasting time, energy, and tokens." With Code Mode, the code passes results from one call to the next, and the model reads only the final answer: "When the LLM can write code, it can skip all that, and only read back the final results it needs."

3. Models are better at writing code than at calling tools. Cloudflare's Kenton Varda and Sunil Pai put it simply: "LLMs have seen a lot of code. They have not seen a lot of "tool calls"." The special tokens used for tool calls are "things LLMs have never seen in the wild." Their conclusion: "LLMs are better at writing code to call MCP, than at calling MCP directly." Today's workaround is to shrink the API, and they note that MCP server designers "are encouraged to present greatly simplified APIs."

The numbers from Cloudflare's own API make the first cost concrete:

Cloudflare API (over 2,500 endpoints)Context tokens
Classic MCP server, one tool per endpointabout 1.17 million
Code Mode, two tools (search and execute)about 1,000

Cloudflare reports this as a 99.9% cut in input tokens, measured with tiktoken, and adds that "the footprint stays fixed, no matter how many API endpoints exist." The post's summary line quotes "over 2 million tokens" for the classic server; we use the figure in its body.

For a business, those tokens are cost and response time on every agent run. The saving is largest for big tool catalogues and for tasks that chain several calls. For a small, fixed set of tools, Cloudflare's own docs say direct tool calls are still fine.

How Code Mode treats your server

Four things are worth knowing before you change anything.

  • Your tools become typed methods. Code Mode reads your MCP tool schemas and generates TypeScript declarations from them. Your descriptions become doc comments. Tool names are turned into valid JavaScript identifiers, so list-pull.requests becomes list_pull_requests, 3d-render becomes _3d_render, and delete becomes delete_.
  • The model writes code against them. A single snippet can call codemode.list_projects({ status: "active" }), loop over the results and call codemode.list_tasks({ projectId: project.id }) for each, all in one pass.
  • The code runs in an isolated Worker. Each run gets a fresh Dynamic Worker with no Node APIs, no host credentials and, by default, no outbound network access. Calls back to your tools cross a controlled bridge.
  • There are two server patterns. A single code tool (codeMcpServer()) suits servers whose type declarations fit inside one tool description. Search and execute (openApiMcpServer()) suits large APIs: the model searches your OpenAPI spec with code, then executes requests, and the spec never enters its context.

Code Mode is also arriving whether or not you adopt it yourself. Since March 2026 it is on by default for Cloudflare's MCP server portals, which present one code tool in place of every upstream tool. If your server sits behind a portal, agents may already be reaching it this way.

One caution up front: Cloudflare labels Code Mode experimental and says it may introduce breaking changes. Plan accordingly.

The 12 changes

1. Pick the pattern that fits your server

Count your tools and look at how large their combined type declarations would be.

  • A small, focused server (a few to a few dozen tools): wrap it with codeMcpServer(). Your existing tools stay as they are underneath.
  • A large REST API with an OpenAPI spec: use openApiMcpServer() and expose search and execute instead of hundreds of tools.
  • A small fixed tool set that never chains calls: Cloudflare's docs say direct tool calls are still fine. Code Mode pays off for composition and large catalogs.

2. Rename tools to clean identifiers

Names now become method names in code. Avoid hyphens, dots, leading digits and reserved words, and make sure no two tools reduce to the same identifier: Cloudflare's connector throws on collisions. A consistent verb_noun scheme in snake_case (get_invoice, list_invoices, void_invoice) reads well to both the model and your team.

3. Type and describe every input field

The generated declarations are only as good as your input schemas. Give every field a precise type and a description, as in Cloudflare's example z.string().describe("Order ID"). Keep to plain JSON Schema that converts cleanly. Anything the generator cannot convert is typed as unknown, and the model has to guess.

4. Declare output schemas and return structured content

This is the change most servers need. In direct calling, the model reads your output as text. In Code Mode, the next line of code uses it, so its shape matters.

  • Add an output schema to every tool, so the generated output type is real rather than unknown.
  • Return structuredContent. Code Mode exposes it directly to the generated code.
  • If you return text, return JSON. Text-only content is parsed as JSON where possible, and prose summaries are not.

5. Fail with real errors

Upstream MCP errors become exceptions that the generated code can catch. A tool that returns "Error: not found" as a successful text result looks like data to the code, which carries on with it. Throw proper MCP errors with clear messages, so the model's try/catch can handle a missing record or a permission failure.

6. Write descriptions as API documentation

Your descriptions are now doc comments that a programmer reads, so write them that way. Say what the tool returns, the units and formats of fields, how pagination works and what side effects it has. If you write a custom description for the code tool, Cloudflare supports {{types}} and {{example}} placeholders. Use the example slot for one realistic snippet that chains two of your tools.

7. Design for composition and small results

Code Mode lets the model filter, join and loop in code. Help it.

  • Add filter and pagination parameters, so the code can ask for exactly what it needs.
  • Return stable IDs that feed straight into your other tools.
  • Keep responses lean. In Cloudflare's MCP server helpers, results are capped at about 6,000 estimated tokens and marked --- TRUNCATED --- beyond that.

8. Keep credentials and authorization in the host

Generated code never receives your credentials. With openApiMcpServer(), a host-side request callback adds the bearer token, and the token never enters the sandbox. Cloudflare is explicit that "code execution does not replace authorization."

  • Enforce permissions in each tool handler or in the request callback, not in the prompt.
  • Keep secrets out of tool results and out of the OpenAPI document.
  • In the request callback, validate the path and never accept an arbitrary origin.

9. Lock down the sandbox

Run generated code with the DynamicWorkerExecutor and a Worker Loader binding. In your Wrangler config:

TOML
compatibility_flags = ["nodejs_compat"]

[[worker_loaders]]
binding = "LOADER"

The executor's globalOutbound defaults to null, which blocks direct network access. Leave it that way unless you have a reason. If code genuinely needs to reach out, pass a Fetcher that allows only the hosts you name. The default timeout is 60 seconds; set your own to match your slowest legitimate run.

10. Gate side effects deliberately

codeMcpServer() and openApiMcpServer() do not provide durable approval for each operation. Until you add it, a single snippet can call a destructive tool as easily as a read.

  • Put approval and limits for writes, deletes and payments inside the handlers themselves.
  • If you build the agent too, Cloudflare's durable runtime (createCodemodeRuntime) lets you mark tools requiresApproval and add a revert for each. Treat revert as compensation, not a transaction.
  • In runs that can pause for approval, Cloudflare advises calling tools one after another rather than with Promise.all(), which can break replay.

11. Test with code, not just tool calls

Your existing tests check single calls. Add tests that look like what the model will write.

  1. 1Generate the TypeScript declarations for your server and read them. Anything typed unknown is a gap.
  2. 2Run a few multi-step snippets end to end: list, filter, then act on one result.
  3. 3Force an error and confirm the snippet can catch it.
  4. 4Return a large result and confirm the truncation is acceptable.
  5. 5If your server is behind a Cloudflare MCP server portal, test through the portal too. Adding ?codemode=search_and_execute to the portal URL switches it to two-tool mode, and Code Mode can be turned off in the portal's settings if you need to compare.

12. Pin versions and watch the changelog

Code Mode is moving quickly. In July 2026 Cloudflare added direct execute(), search() and describe() methods for hosts outside the AI SDK, and the current MCP server helpers return an MCP SDK v1 server served through createLegacyMcpHandler. Pin @cloudflare/codemode and agents to known versions, and read the changelog before upgrading.

A starting point

For a small server, the wrap is short. This sketch shows the shape; Cloudflare's "Build a Code Mode MCP server" guide has the complete Worker.

TypeScript
import { DynamicWorkerExecutor } from "@cloudflare/codemode";
import { codeMcpServer } from "@cloudflare/codemode/mcp";
import { createLegacyMcpHandler } from "agents/mcp";

// upstream: your existing MCP server with its tools registered
const executor = new DynamicWorkerExecutor({ loader: env.LOADER });
const server = codeMcpServer({ server: upstream, executor });
// serve `server` with createLegacyMcpHandler, as in Cloudflare's guide

The real work is not these lines. It is steps 2 to 8: clean names, real types, structured outputs, honest errors and authorization that lives on the server.

The one-page checklist

  • Pattern chosen: single code tool, or search and execute
  • Tool names are clean, unique JavaScript identifiers
  • Every input field typed and described
  • Every tool has an output schema and returns structuredContent
  • Failures throw MCP errors
  • Descriptions read like API docs, with one chained example
  • Filters, pagination and lean responses
  • Credentials and authorization in the host, paths validated
  • Sandbox outbound access off, or allow-listed
  • Writes and deletes gated in the handlers
  • Code-style tests, including errors and large results
  • Versions pinned

None of this is wasted if you never adopt Code Mode. A server with clean names, real types and structured outputs is simply a better API, for agents and for people.

If your team runs MCP servers for internal systems or client integrations and wants a second pair of eyes on them, WizeB can review one against this list and tell you what to fix first. Send an enquiry.

Sources

Ready to act on this?

We build exactly what this article is about.

Tell us about your situation — we'll come back with a realistic assessment.