Dev Blog

Cloudflare Code Mode: When AI Agents Should Write Code

By · · 13 min read

Cloudflare Code Mode: When AI Agents Should Write Code

Short answer: Code Mode is a Cloudflare feature that lets an AI agent write a small JavaScript function that calls your tools, instead of calling each tool one at a time. The code runs in an isolated sandbox, and only the final result goes back to the model. That saves round trips and keeps bulky intermediate data out of the model's context. It's experimental, and its main executor runs on Dynamic Workers, which need the Workers Paid plan.

I'm Royette B. Millares, an AI automation engineer in the Philippines who builds agent and workflow automations with n8n, Zapier and the OpenAI and Claude APIs. I haven't built with Code Mode yet, so this post explains it from Cloudflare's documentation and engineering posts, checked on November 21, 2026, plus Anthropic's write-up of the same idea. My own views are labelled as such.

Key Takeaways

  • With createCodeTool(), the model gets one tool, codemode, whose only input is code. The code calls your tools as typed methods (Cloudflare docs).
  • It suits agents that chain calls, loop, filter results or work with large tool catalogs; for a few simple calls, Cloudflare recommends normal tool calling.
  • The sandbox has no network access by default and never receives your API keys; risky actions can pause for human approval (with the durable runtime).
  • Cloudflare reports one API's tool definitions dropping from 1.17 million tokens to about 1,000 with Code Mode. That's a vendor figure for one catalog, not a general benchmark.
  • Code Mode is labelled experimental, and Dynamic Workers are in open beta on the Workers Paid plan, with a per-day charge for each unique Dynamic Worker beyond 1,000 a day, plus request and CPU charges.

What is Cloudflare Code Mode?

Code Mode is a way of giving tools to an AI agent where the model writes code instead of issuing tool calls. The model gets a single code-execution tool. Inside the code it writes, your tools appear as typed methods it can call, loop over and combine, and it returns only what it needs (Cloudflare docs).

The code runs on Dynamic Workers: Workers that Cloudflare creates at run time from code another Worker supplies (Dynamic Workers docs). Code Mode works with MCP (Model Context Protocol, a standard way to plug tools into AI models) and other tool sources, and it ships as the @cloudflare/codemode package in Cloudflare's Agents tooling. The docs describe three parts: an executor that runs the code, connectors that provide the tools, and an optional durable runtime that keeps history and approvals (How Code Mode works).

Why tool calling wastes tokens, and what Code Mode changes

With normal tool calling, each result goes back to the model before it decides the next step. Every operation can cost another round trip, and every intermediate result takes up room in the model's context (Cloudflare docs). Code Mode moves the chaining, filtering and reshaping into one sandboxed run.

Cloudflare's argument is that models have seen far more real code than tool-call syntax, and most tool-call examples they learned from are synthetic, so they're better at writing code. Its launch post compares tool calling to asking Shakespeare to write in a language he studied for a month (Cloudflare blog, Kenton Varda and Sunil Pai, September 26, 2025). Anthropic made the same case in its own post about six weeks later, and credits Cloudflare with the name "Code Mode" (Anthropic, Adam Jones and Conor Kelly, November 4, 2025).

Diagram: with direct tool calls the model makes a round trip for every tool; with Code Mode the model writes code, a sandbox runs it, tool calls go to your own Worker that holds the API keys, and only the final result comes back
Direct tool calls vs Code Mode. Diagram by the author, based on Cloudflare's Code Mode docs.

Both companies publish token numbers. They measure different things, so don't add them up or average them:

ClaimWhat was measuredSource
1.17 million tokens down to about 1,000 (99.9% fewer input tokens)Tool definitions for the whole Cloudflare API (2,500+ endpoints) as a normal MCP server vs a two-tool Code Mode server, counted with tiktoken (OpenAI's token counter)Cloudflare blog, February 20, 2026
About 150,000 tokens down to about 2,000 (98.7%)Loading tool definitions on demand instead of all up front, in an illustrative exampleAnthropic, November 4, 2025
About 50,000 extra tokens avoidedA 2-hour meeting transcript that would otherwise pass through the model twiceAnthropic, November 4, 2025

These are vendor-reported illustrations, not independent benchmarks. Your savings depend on how many tools you have and how much data flows between them.

How Code Mode works

With createCodeTool(), the model sees one tool named codemode, and its only input is { code: string }: a JavaScript async arrow function. The full tool catalog isn't loaded into the model's context up front (How Code Mode works).

  • The sandbox. Each run gets a fresh, isolated Worker created by Dynamic Worker Loader. By default it can't make network requests (fetch() and connect() are blocked), and it has no Node.js APIs, process, require or host credentials.
  • Connectors. Tools come from an MCP server, an OpenAPI document, an AI SDK tool set or your own code. Each connector appears in the sandbox as a global, so the model can write github.list_pull_requests(). Calls cross back to your own Worker over Workers RPC (Cloudflare's internal remote calls), and the generated code never sees connector credentials.
  • Discovery. Inside the sandbox, codemode.search() returns up to 50 matching tool paths and codemode.describe() returns TypeScript docs for one tool, so the model looks up what it needs instead of reading everything.
  • Results. Every run ends as completed (with the result), paused (waiting for approval) or error. Errors come back as data, not crashes.

Here is the kind of code the model writes. This is my illustration, not an example from Cloudflare's docs, and the tool's parameters and return shape depend on your connector:

// Illustrative only: find open pull requests untouched for a week
async () => {
  const prs = await github.list_pull_requests({ state: "open" });
  const weekAgo = Date.now() - 7 * 24 * 60 * 60 * 1000;
  const stale = prs.filter((pr) => Date.parse(pr.updated_at) < weekAgo);
  return stale.map((pr) => ({ title: pr.title, url: pr.html_url }));
}

With normal tool calling, the full list of pull requests would go back to the model before it could filter it. Here only the short list of stale ones does.

The durable runtime: approvals, replay and rollback

The optional durable runtime adds memory and control. It stores runs, connector-call logs, pending approvals and saved snippets in SQLite inside a Durable Object (Cloudflare's stateful storage unit). When a call needs approval, the run pauses; after approval, it replays with the recorded results and then performs the approved action. Because of that replay, a run that may pause should make its calls in a fixed order; Cloudflare advises against Promise.all there. Rollback runs each call's revert in reverse order, which the docs describe as compensation, not a database transaction. Only your application can save a run as a reusable snippet; the model can't promote its own code (API reference).

The documented defaults include a 60-second execution timeout, a maxExecutions of 50 (finished run records kept), and paused runs expiring after 24 hours (API reference).

How to set up Code Mode with the AI SDK

Cloudflare's AI SDK guide shows the stateless path, using the Vercel AI SDK. Install the packages (AI SDK guide):

npm i @cloudflare/codemode agents ai zod

Add a Worker Loader binding to your Wrangler config (Cloudflare's CLI configuration). This is the Worker Loader part of the config in Cloudflare's durable runtime guide:

{
  "$schema": "./node_modules/wrangler/config-schema.json",
  // Set this to today's date
  "compatibility_date": "2026-11-20",
  "compatibility_flags": [
    "nodejs_compat"
  ],
  "worker_loaders": [
    {
      "binding": "LOADER"
    }
  ]
}

Then wrap your tools in a Code Mode tool and pass it to the model. This is Cloudflare's stateless example, where weatherTools is an AI SDK tool set (a getWeather tool) and ./model is your own model setup (AI SDK guide):

import { DynamicWorkerExecutor } from "@cloudflare/codemode";
import { createCodeTool } from "@cloudflare/codemode/ai";
import { generateText, stepCountIs } from "ai";
import { model } from "./model";
import { weatherTools } from "./tools";

export default {
  async fetch(request, env): Promise<Response> {
    const executor = new DynamicWorkerExecutor({ loader: env.LOADER });
    const codemode = createCodeTool({ tools: weatherTools, executor });

    const response = await generateText({
      model,
      prompt: await request.text(),
      tools: { codemode },
      stopWhen: stepCountIs(5),
    });

    return new Response(response.text);
  },
} satisfies ExportedHandler<Env>;

One catch: the stateless createCodeTool() can't pause for approval, and it leaves out any tool marked as needing approval. For tools that change things, Cloudflare points you to the durable runtime with an MCP connector instead (MCP guide). That setup adds the agents(), codemode() and cloudflare() Vite plugins, a connector class, and createCodemodeRuntime() running inside an Agent with ctx, an executor and your connectors, then passes runtime.tool() to the model as codemode; the durable runtime guide walks through it.

When to use Code Mode, and when not to

Use normal tool calling for simple tasks with a small, known set of tools. Use Code Mode when calls depend on each other, when you have a large tool catalog, or when the agent needs loops, branching, filtering or reusable logic (Cloudflare docs).

SituationOptionWhy
A few simple, independent callsNormal tool callingCloudflare's recommendation; no sandbox needed
Quick agent, no approvals neededcreateCodeTool()Simplest setup; can't pause for approval
Tools with side effects, or the model should discover tools as it goesDurable runtime with McpConnectorApprovals, logs and replay
Expose your tools to MCP clients as one code toolcodeMcpServer()Exposes one code tool
Expose an OpenAPI API to MCP clientsopenApiMcpServer()Exposes search and execute tools

The last two come from Cloudflare's guide to building a Code Mode MCP server. Cloudflare also turned on a single code tool by default for its MCP server portals on March 26, 2026 (changelog).

Is Code Mode secure? What business owners should know

The design keeps the riskiest things out of the model's reach, but it isn't a permission system on its own.

  • Your API keys stay with you. Credentials live in your Worker or connector and never enter the sandbox. In Cloudflare's OpenAPI example, the authorization header is added on the host side (OpenAPI guide).
  • No network by default. The sandbox can't call the internet unless you route requests through a service you control, which limits what a prompt injection could leak (Cloudflare blog).
  • Human approval for risky actions (durable runtime). With the durable runtime, tools marked as requiring approval pause the run before that tool's action runs; the stateless setup above can't pause. Calls earlier in the run have already happened, rejecting doesn't undo them, and rollback only works where you wrote a revert (API reference).
  • An audit trail (durable runtime). The durable runtime logs every connector call (API reference).
  • You still need authorization. Cloudflare's MCP server guide says to enforce permissions in your own handlers, and never to put secrets in tool results or OpenAPI documents, because the model's code can read both (MCP server guide).

Anthropic adds a fair counterweight: running agent-written code needs sandboxing, resource limits and monitoring, and that overhead has to be weighed against the token savings (Anthropic).

What Code Mode costs, and is it production-ready?

Running Code Mode with Cloudflare's Dynamic Worker executor needs the Workers Paid plan, and use beyond the included allowances is billed per Dynamic Worker, request and CPU time (table below). Cloudflare also documents a browser iframe executor; this post covers the Dynamic Worker one. As for production, Cloudflare labels it experimental: every Code Mode page says it "is experimental and may introduce breaking changes" (Cloudflare docs).

The sandbox runs on Dynamic Workers, which are "currently only available on the Workers Paid plan" and have been in open beta for paid users since March 24, 2026 (Dynamic Workers pricing; changelog). I found no general-availability announcement.

Dynamic Workers usageIncludedBeyond that
Unique Dynamic Workers1,000 per day$0.002 per Dynamic Worker per day
Requests10 million per month$0.30 per million
CPU time30 million CPU-ms per month$0.02 per million CPU-ms

Per-day billing for Dynamic Workers started on May 26, 2026, and changing a Worker's ID or code counts as a new Dynamic Worker (Dynamic Workers pricing). Dynamic Workers also have concurrency limits: at most 4 Dynamic Workers with in-flight requests per Worker request, and 10 per Durable Object (limits).

My reading, not Cloudflare's statement: since each run gets a fresh Worker and new code counts as a new Dynamic Worker, a busy agent could pass the daily allowance. Assuming each run's code is different, 5,000 runs a day would mean about 4,000 extra Dynamic Workers: $8 a day at $0.002 each, or about $240 over 30 days, before request and CPU charges. Check with Cloudflare before you budget. These are Cloudflare's charges only, on top of the Workers Paid subscription itself. The model is whatever provider you plug in, and that provider bills its own token usage.

What this means for business automation (my take)

This section is my opinion, not Cloudflare's. Most business automations I build are fixed workflows: a form comes in, data goes to a CRM, someone gets a message. Tools like n8n and Zapier already run those without a model in the loop, and I'd keep them there (my n8n vs Make vs Zapier comparison).

Code Mode matters when an AI agent decides what to do at run time and has many tools to choose from: an assistant that searches orders, checks stock, drafts a reply and logs the result in one go. That's where round trips and context bloat add up. If I were trying it on a client project, I'd start with the durable runtime and approvals on anything that writes data, and keep the experimental label in mind before relying on it. If you want help deciding where an AI agent fits in your business, or building one, let's talk.

Frequently asked questions

What is Cloudflare Code Mode in simple terms?

It's a way to give an AI agent tools where the model writes a short JavaScript function that calls them, instead of calling each tool separately. Cloudflare runs that code in an isolated sandbox and returns only the final result to the model.

Is Cloudflare Code Mode free?

Not with its main executor. DynamicWorkerExecutor runs code on Dynamic Workers, which are "currently only available on the Workers Paid plan" (Cloudflare also documents a browser iframe executor, which this post doesn't cover). Within that plan, 1,000 unique Dynamic Workers a day, 10 million requests and 30 million CPU-ms a month are included; beyond that Cloudflare charges $0.002 per extra Dynamic Worker per day, $0.30 per million requests and $0.02 per million CPU-ms. Your AI model provider bills its own token usage on top.

Is Code Mode production-ready?

Cloudflare labels Code Mode experimental and says it may introduce breaking changes, and Dynamic Workers have been in open beta since March 24, 2026. Treat it as early technology and test it before relying on it.

Do I need MCP to use Code Mode?

No. Code Mode can wrap an MCP server, but it also works with an OpenAPI document, an AI SDK tool set or your own code. Cloudflare's AI SDK example uses AI SDK tools.

How is Code Mode different from Anthropic's code execution with MCP?

Same idea, different form. Cloudflare's Code Mode is a package you install, and its main executor runs the code on Dynamic Workers. Anthropic's November 2025 post makes the same argument, presents MCP servers to agents as code APIs, credits Cloudflare with the name, and notes that running agent-written code needs your own sandboxing, resource limits and monitoring.

Sources

Checked on November 21, 2026. Research and drafting were AI-assisted, and every factual claim was checked against the pages below; the illustration, cost estimate and opinions are mine.