# Code Mode MCP: How Cloudflare Lets Models Write Code Instead of Calling Tools

- URL: https://www.dhruvvakharwala.dev/blogs/code-mode-mcp-cloudflare-agents-sdk
- Author: Dhruv Vakharwala (https://www.dhruvvakharwala.dev/about)
- Published: November 24, 2026
- Category: Engineering
- Keywords: code mode mcp, cloudflare code mode, mcp context window, dynamic worker loader, agents sdk codemode, mcp tool calling, llm writes code instead of tool calls, v8 isolate sandbox

> Code Mode MCP, explained: Cloudflare turns MCP tools into a TypeScript API and runs model-written code in a V8 isolate. Real code, real numbers, my ideas.

**TL;DR:** I read Cloudflare's **Code Mode** post and then the open-source code behind it. The idea behind **Code Mode MCP**: do not show the model every MCP tool as a tool call. Convert the tools into a TypeScript API, give the model one tool that runs code, and execute that code in a disposable V8 isolate (a Dynamic Worker) whose only way out is RPC bindings back to the agent. Intermediate tool results never enter the model's context, only what the code logs or returns. Cloudflare's published numbers: the whole Cloudflare API as plain MCP tools would cost **1.17 million tokens**, while Code Mode's `search()` + `execute()` costs **about 1,000** (99.9% fewer input tokens). Anthropic's engineering post describes the same pattern and reports 150,000 tokens down to 2,000 for its own example. In this post I explain why it works, walk through the original code from PR #512 and the current `@cloudflare/codemode` package, check which of my own optimization ideas already exist in the source, and list the ones I am going to try. I have not run Code Mode yet, so there are no benchmark results of mine here.


![Cover card: Cloudflare API as plain MCP tools is 1.17M tokens of definitions, search() plus execute() with Code Mode is about 1,000 tokens, a published 99.9% reduction](https://www.dhruvvakharwala.dev/images/blog/code-mode-mcp-cloudflare-agents-sdk/cover.png)

## What is Code Mode MCP?

Most agents use MCP like this: connect to a server, list its tools, paste every tool's name, description and JSON schema into the model's context, and let the model emit tool calls one at a time. Cloudflare's [Code Mode post](https://blog.cloudflare.com/code-mode/) (by Kenton Varda and Sunil Pai, 2025-09-26) opens with a blunt claim: "It turns out we've all been using MCP wrong."

Their alternative has four moving parts:

1. Take the MCP server's schema and convert it into a **TypeScript API**, with doc comments.
2. Show the model that API and **one** tool that writes and runs code.
3. Run the code in a **sandbox** that has no internet, only calls back into the tools you allowed.
4. Send back only what the code printed with `console.log()` or returned.

The post's own summary is one sentence: "In short, LLMs are better at writing code to call MCP, than at calling MCP directly."

I am writing this as a reader of that post and of the code, not as someone who has shipped it. Everything about what Cloudflare measured is attributed to them. Everything I say about *why* it works, and everything in the optimization section, is my reasoning and is labeled that way.

---

## What does an MCP tool call actually look like?

To see what Code Mode removes, you need the mechanics of a normal tool call. The Cloudflare post explains them well, so I will follow its framing.

A model produces a stream of tokens. A tool call uses a special token that has no text form: the model is trained (usually fine-tuned) to emit a token meaning that what follows is a tool call, then JSON describing the call, then a token that ends it. The post illustrates it with `<|tool_call|>` and `<|end_tool_call|>` and says plainly that these are illustrations, not real text. The harness around the model sees the special token, pauses generation, parses the JSON, calls the tool, and feeds the result back wrapped in another pair of special tokens. The model then continues, reading that result exactly as it would read user input.

```mermaid
sequenceDiagram
    participant U as User
    participant H as Agent harness
    participant M as Model
    participant T as MCP server
    U->>H: "What is the weather in Austin?"
    H->>M: prompt + ALL tool schemas
    M-->>H: tool_call get_current_weather (JSON)
    H->>T: call get_current_weather
    T-->>H: result (JSON)
    H->>M: prompt + schemas + result
    M-->>H: final answer
    H-->>U: answer
```

Two things in that diagram cost tokens, and they are different problems.

**Cost 1: every tool schema sits in context on every request.** The model has to see the definitions before it can call anything. Anthropic's engineering post puts it this way: "In cases where agents are connected to thousands of tools, they'll need to process hundreds of thousands of tokens before reading a request."

**Cost 2: every intermediate result round-trips through the model.** Anthropic's example is "Download my meeting transcript from Google Drive and attach it to the Salesforce lead." The model calls a Drive tool, the whole transcript lands in context, and then the model has to write the whole transcript out again as an argument to the Salesforce tool. In Anthropic's words: "In this example, the full call transcript flows through twice." For a 2-hour sales meeting they estimate "an additional 50,000 tokens". The Cloudflare post makes the same point from the other side: "the output of each tool call must feed into the LLM's neural network, just to be copied over to the inputs of the next call, wasting time, energy, and tokens."

![Left: direct tool calls, the full tool result flows into the model and the model re-writes it into the next call. Right: Code Mode, the code runs in an isolate, results stay inside and only console.log output returns](https://www.dhruvvakharwala.dev/images/blog/code-mode-mcp-cloudflare-agents-sdk/dataflow.png)

The image above is my drawing of that example. The red arrows are the part Code Mode deletes.

---

## Why would writing code beat calling tools?

Cloudflare gives one reason and hedges it. The post says agents handle more and more complex tools when they are shown as a TypeScript API, and then: "Perhaps this is because LLMs have an enormous amount of real-world TypeScript in their training set, but only a small set of contrived examples of tool calls."

Later they state the same thing more firmly: LLMs have seen real-world code from millions of open source projects, while the tool calls they have seen are "probably limited to a contrived training set constructed by the LLM's own developers". Their analogy: "Making an LLM perform tasks with tool calling is like putting Shakespeare through a month-long class in Mandarin and then asking him to write a play in it."

That is a claim about training data, and I cannot verify it from outside. What I can do is lay out the argument for why the design is sensible even if you discount that claim. Here is my reading, which is reasoning and not a measurement:

| Argument | Where it comes from | What it says |
|---|---|---|
| Training distribution | Cloudflare's hedged claim | Real code is plentiful in training data, tool-call JSON is synthetic |
| Context pollution | Cloudflare and Anthropic, both measured or estimated | Schemas and intermediate results are paid for in tokens on every step |
| Chaining | Cloudflare, Anthropic, and the Cloudflare docs | Loops, filters and branches are free in code, but cost a model round trip as tool calls |

The third row is the one I find most convincing on logic alone. A tool-call loop makes the *model* the program counter. Every `if`, every `for each item`, every copy of a value from step 1 to step 2 has to be generated token by token, at model speed and model price, and each one is a place to make a copying mistake. Anthropic says as much: "With large documents or complex data structures, models may be more likely to make mistakes when copying data between tool calls." Code moves that work to a runtime that does it exactly and for free. The Cloudflare docs summarize the same control-flow list: a single plan can "compose several dependent tool calls", "loop over collections of results", "filter and transform returned data" and "branch based on earlier results".

### If code is better, why keep MCP at all?

Cloudflare answers this directly, and I think it is the most underrated part of the post. Almost every MCP server is a wrapper around an existing API, so why not just let the model code against the underlying API? Because MCP "provides a uniform way to connect to and learn about an API":

- one way to **expose** an API,
- the **documentation** the model needs, in the protocol itself,
- **authorization** handled out-of-band.

An agent can use an MCP server neither side had heard of before. That uniformity is what lets a framework build a sandbox that "can only access the tools we give it", handling connectivity and authorization in a standard way, "independent of the AI code". So Code Mode keeps MCP as the *discovery and authorization layer* and changes only the *calling convention* the model sees.

---

## How does Code Mode work end to end?

Here is the pipeline from the 2025 post, which still describes the current design at a high level.

```mermaid
flowchart LR
    A["MCP server<br/>tool schemas"] --> B["Convert to TypeScript<br/>declarations + doc comments"]
    B --> C["ONE tool for the model<br/>write and run code"]
    C --> D["Code runs in a<br/>disposable V8 isolate"]
    D -->|"RPC binding"| E["Agent host<br/>holds tokens, calls MCP"]
    E -->|"result stays in sandbox"| D
    D -->|"console.log or return"| F["Model reads<br/>only the final output"]
```

Step 1 is the type conversion. When the Agents SDK connects to an MCP server in Code Mode it fetches the schema and generates TypeScript "complete with doc comments based on the schema". The post's example is the GitMCP server for `cloudflare/agents`. Trimmed, the generated API looks like this:

```typescript
interface SearchAgentsCodeInput {
  /**
   * The search query to find relevant code files
   */
  query: string;
  /**
   * Page number to retrieve (starting from 1). Each page contains 30
   * results.
   */
  page?: number;
}
interface SearchAgentsCodeOutput {
  [key: string]: any;
}

declare const codemode: {
  /**
   * Search for code within the GitHub repository: "cloudflare/agents"
   * using the GitHub Search API (exact match). Returns matching files
   * for you to query further if relevant.
   */
  search_agents_code: (
    input: SearchAgentsCodeInput
  ) => Promise<SearchAgentsCodeOutput>;
  // ... three more tools
};
```

That is the entire "API" the model learns: types, doc comments, and a single `declare const codemode`. Each MCP tool becomes a method, each input schema becomes an interface, and the schema's `description` fields become comments. The post notes that "Currently, the entire API is loaded" into context, with a hint of what comes next: letting an agent "search and browse the API more dynamically". Hold that thought, because the follow-up post and the current SDK are exactly that.

Step 2 is the one tool. The agent is presented with "just one tool, which simply executes some TypeScript code". Step 3 and 4 are the sandbox, which gets its own section. The result path is the "obvious way": the code calls `console.log()`, and "When the script finishes, all the output logs are passed back to the agent."

### How much does a declaration cost? A worked example

Take the generated GitMCP block from the post (the four Input/Output interface pairs plus the `declare const codemode` block, copied verbatim): it is **2,047 characters** long. The SDK's own truncation code assumes `CHARS_PER_TOKEN = 4` (a comment in `packages/codemode/src/truncate.ts` calls it "a reasonable cross-model estimate"). Under that rule of thumb, 2,047 / 4 is about **512 tokens for four tools, roughly 128 per tool**. A real tokenizer will give a different number, so treat this as an order of magnitude and not a measurement. The point is only that declarations with doc comments are not free, which is why the later work focuses on *not* loading them all.

---

## Why V8 isolates instead of containers?

Running model-written code needs a sandbox. Most people reach for containers. Cloudflare's argument, from the [dynamic-workers post](https://blog.cloudflare.com/dynamic-workers/) (Kenton Varda, Sunil Pai and Ketan Gupta, 2026-03-24): containers are "expensive and slow to start, taking hundreds of milliseconds to boot and hundreds of megabytes of memory to run". An isolate is the same V8 engine Chrome uses: "An isolate takes a few milliseconds to start and uses a few megabytes of memory. That's around 100x faster and 10x-100x more memory efficient than a typical container."

The consequence for design is the interesting part. If starting a sandbox costs almost nothing, you can start a **new one for every piece of code**. The original post says it directly: "There's no need to reuse them. There's no need to prewarm them. Just create it, on demand, run the code, and throw it away." No pooling and no state that leaks from one run to the next.

### The Worker Loader API

The primitive is the Worker Loader. This is the API as shown in the September 2025 post:

```typescript
let worker = env.LOADER.get(id, async () => {
  return {
    compatibilityDate: "2025-06-01",
    mainModule: "foo.js",
    modules: {
      "foo.js":
        "export default {\n" +
        "  fetch(req, env, ctx) { return new Response('Hello'); }\n" +
        "}\n",
    },
    env: {
      SOME_NUMBER: 123,
      // bindings back to the parent worker's exported RPC interfaces,
      // using the new `ctx.exports` loopback bindings API.
      SOME_RPC_BINDING: ctx.exports.MyBindingImpl({props})
    },
    // Redirect fetch() and connect(), or block them completely with null.
    globalOutbound: null,
  };
});
let defaultEntrypoint = worker.getEntrypoint();
```

Four fields matter for Code Mode: `modules` (the code, as strings, so the model's output becomes a module), `env` (what the sandbox can touch), `globalOutbound` (what its `fetch()` can reach, where `null` means nothing) and `getEntrypoint()` (how the host calls into it).

### Why bindings beat network filtering

This is the part of the design I found most convincing. On most platforms, "the way you get access to private resources is, you start with general network access", then you send requests and pass an API key. If you want to sandbox that, you filter the network. Cloudflare's objection: "Limiting access via bindings is much cleaner than doing it via, say, network-level filtering or HTTP proxies." Filtering is hard on both sides: the supervisor cannot tell which traffic is legitimate, and the model cannot guess what will be blocked. With a binding it is well defined: "the binding provides a JavaScript interface, and that interface is allowed to be used."

In Workers, `env` holds live objects (bindings), not just strings. In Code Mode the sandbox gets bindings that represent the MCP servers, and `fetch()` and `connect()` throw. The sandbox can reach exactly the tools you gave it, and nothing else.

A second benefit falls out of the same design: **no API keys to leak**. The binding is "an already-authorized client interface". Calls go to the agent host first, which holds the tokens and adds them on the way to MCP. In the post's words: "the AI cannot possibly write code that leaks any keys". The model's code never has a key in scope to leak, which is a stronger property than telling the model not to print it.

![Architecture: the host holds the model, the executor, one ToolDispatcher per namespace and the MCP clients with tokens. The Dynamic Worker isolate runs the model's JavaScript through a Proxy per namespace. A single RPC path links them, and the Internet path is blocked with globalOutbound null](https://www.dhruvvakharwala.dev/images/blog/code-mode-mcp-cloudflare-agents-sdk/architecture.png)

### What the 2026 dynamic-workers post adds

The March 2026 post is mostly about the primitive, and it states a few things worth recording (I am repeating only what it says):

- Dynamic Worker Loader "is now in open beta, available to all paid Workers users".
- The loader now shows a one-shot `env.LOADER.load({...})` call alongside `get(id, callback)`, and the example passes `globalOutbound: null` to block internet access.
- The runtime sets up a [Cap'n Web RPC](https://blog.cloudflare.com/capnweb-javascript-rpc-library/) bridge between the sandbox and your harness code, "so that the agent can invoke your API across the security boundary without ever realizing that it isn't using a local library".
- If you would rather give the agent HTTP APIs, `globalOutbound` can be a callback that inspects, rewrites or blocks every request, for example to inject credentials so "the agent itself never knows the secret credentials".
- The catch versus containers: "your agent needs to write JavaScript".
- Pricing at publication: "$0.002 per unique Worker loaded per day (as of this post's publication)" plus normal CPU and invocation pricing, waived during the beta, with the post pointing to the pricing page for current numbers.

I did not verify current pricing or beta status beyond that post. The [Dynamic Workers docs page](https://developers.cloudflare.com/dynamic-workers/) I read does not label it beta or quote a price, so check it before you plan around either.

The same post is honest about the weak spot of isolates. "Although all sandboxing mechanisms have bugs, security bugs in V8 are more common than security bugs in typical hypervisors", so isolate sandboxes need defense in depth, which Cloudflare says its platform adds (automatic V8 patches within hours, a second-layer sandbox, and more). If you run Code Mode on your own infrastructure with some other isolate runtime, that hardening is your job.

---

## What did the original Code Mode code look like? (PR #512)

The first implementation landed in [cloudflare/agents PR #512](https://github.com/cloudflare/agents/pull/512), "Codemode", commit `f9f03b44` by Sunil Pai, on 2025-09-26, the same day as the blog post. The core is one 249-line file, `packages/agents/src/codemode/ai.ts`. Some of it differs from how the blog post describes the idea, and that difference is the most instructive thing in the file.

### The outer model never writes code

In the blog post, the agent "is presented with just one tool, which simply executes some TypeScript code". In this first version the tool's input is not code at all, it is a **description**:

```typescript
const codemodeTool = tool({
  description: "codemode: a tool that can generate code to achieve a goal",
  inputSchema: z.object({
    functionDescription: z.string()
  }),
  outputSchema: z.object({
    code: z.string(),
    result: z.any()
  }),
  execute: async ({ functionDescription }) => {
    const response = await generateObject({
      model: openai("gpt-4.1"),
      schema: z.object({ code: z.string() }),
      prompt: `You are a code generating machine.

      In addition to regular javascript, you can also use the following functions:

      ${generatedTypes}

      Respond only with the code, nothing else. Output javascript code.

      Generate an async function that achieves the goal. This async function doesn't accept any arguments.

      Here is user input: ${functionDescription}`
    });
    const evaluator = createEvaluator(response.object.code, {
      proxy: options.proxy,
      loader: options.loader
    });
    const result = await evaluator();
    return { code: response.object.code, result: result };
  }
});
```

So there were **two model calls**. The outer model (in the demo, `gpt-5`) saw only a short prompt built by `getToolDescriptions()`, which lists tool descriptions as bullet points, and called `codemode` with a plain-English `functionDescription`. Then a *second* model, hard-coded to `openai("gpt-4.1")`, received the generated TypeScript declarations through `generateObject` and wrote the code. That code ran in the isolate and the result went back.

```mermaid
flowchart TD
    U["User message"] --> O["Outer model<br/>sees tool descriptions only"]
    O -->|"functionDescription<br/>plain English"| C["codemode tool"]
    C --> G["Second model call<br/>generateObject, gpt-4.1<br/>sees generated TS types"]
    G -->|"code string"| I["createEvaluator<br/>Dynamic Worker isolate"]
    I -->|"RPC to agent"| P["Durable Object runs real tool"]
    P --> I
    I -->|"result"| O
```

It is a design with a clear upside and a clear cost. The upside: the outer model's context stays small and never sees a TypeScript declaration. The cost: an extra model call, a second model to configure, and the outer model describing a plan in prose, then another model re-interpreting that prose. The changelog shows the second model being made configurable first: `0.0.7` notes "Allow configurable model in `experimental_codemode` instead of hardcoded `gpt-4.1`", and later the whole inner call disappears (see the evolution section).

### The isolate and the Proxy trick

The sandbox half is `createEvaluator`. Trimmed:

```typescript
const worker = options.loader.get(`code-${Math.random()}`, () => {
  return {
    compatibilityDate: "2025-06-01",
    compatibilityFlags: ["nodejs_compat"],
    mainModule: "foo.js",
    modules: {
      "foo.js": `
import { env, WorkerEntrypoint } from "cloudflare:workers";

export default class CodeModeWorker extends WorkerEntrypoint {
  async evaluate() {
    try {
      const { CodeModeProxy } = env;
      const codemode = new Proxy({}, {
        get: (target, prop) => {
          return (args) => {
            return CodeModeProxy.callFunction({ functionName: prop, args: args });
          };
        }
      });
      return await ${code}();
    } catch (err) {
      return { err: err.message, stack: err.stack };
    }
  }
}`
    },
    env: { CodeModeProxy: options.proxy },
    globalOutbound: null
  };
});
return await worker.getEntrypoint().evaluate();
```

Reading it line by line:

- `loader.get(\`code-${Math.random()}\`, ...)` gives every run a fresh random id, so every run is a fresh isolate. That is the create-it, run-it, throw-it-away idea in one line.
- `globalOutbound: null` is the "no internet" rule.
- The model's code is spliced into the module text with `${code}()`. The generated code is an async function expression, so `${code}()` calls it immediately.
- The `Proxy` is the cleverest bit. The sandbox has no real `codemode` object. It builds one whose property getter returns a function for *any* name, and that function forwards `{ functionName, args }` over RPC. So `codemode.search_agents_code({ query })` never needs a per-tool stub. The type declarations tell the model which names exist, and the Proxy turns whatever it calls into an RPC.
- `env.CodeModeProxy` is the only binding the sandbox gets.

One detail I noticed: `experimental_codemode()` accepts a `globalOutbound` option, but `createEvaluator` never receives it and hard-codes `null`. In this first version the option was effectively unused.

### The RPC path back to the agent

The other end of that binding is `CodeModeProxy`, a `WorkerEntrypoint`:

```typescript
export class CodeModeProxy extends WorkerEntrypoint<
  Cloudflare.Env,
  { binding: string; name: string; callback: string }
> {
  async callFunction(options: { functionName: string; args: unknown[] }) {
    const stub = (await getAgentByName(
      env[this.ctx.props.binding] as AgentNamespace<T>,
      this.ctx.props.name
    )) as DurableObjectStub;
    return stub[this.ctx.props.callback](options.functionName, options.args);
  }
}
```

The agent builds this entrypoint with `ctx.exports.CodeModeProxy({ props: { binding, name, callback } })`. In the demo (`examples/codemode/src/server.ts`) those props are `binding: "Chat"`, `name: this.name`, `callback: "callTool"`, and the agent's `callTool(functionName, args)` method looks up `this.tools[functionName]` and calls its `execute`. So the chain is: model code -> Proxy getter -> `CodeModeProxy.callFunction` (RPC) -> the agent Durable Object -> the real tool, with its credentials, running on the *host* side of the boundary.

### Generating the TypeScript

`generateTypes()` loops over the tool set. For each tool it turns the input schema into a TypeScript type with `json-schema-to-typescript` (or `zod-to-ts` for Zod), names it with `toCamelCase`, so `fetch_agents_documentation` becomes `FetchAgentsDocumentationInput`, and appends one line to a growing `declare const codemode: {...}` block:

```typescript
availableTools += `\n\t/*\n\t${tool.description?.trim()}\n\t*/`;
availableTools += `\n\t${toolName}: (input: ${toCamelCase(toolName)}Input) => Promise<${toCamelCase(toolName)}Output>;`;
// ...
availableTools = `\ndeclare const codemode: {${availableTools}}`;
```

If a tool has no output schema, the fallback is `interface FooOutput { [key: string]: any }`, which is exactly what you see in the blog post's generated example.

---

## How does the current @cloudflare/codemode package work?

The code moved into its own package, `@cloudflare/codemode`, in commit `0c4275f8` on 2025-12-29 ("feat: split ai-chat and codemode into separate packages (#756)"). The repo snapshot I read is commit `263a5b9` from 2026-11-24, where the package is at version 0.5.6 with its source in `packages/codemode/src/`. It is a different shape from the original, so I will go piece by piece. The docs still carry this warning: "Code Mode is experimental and may introduce breaking changes. Use caution in production."

### One tool, no inner model: `createCodeTool`

The biggest change is that **the inner model call is gone**. Commit `90e54dab` (2026-02-20, PR #879, titled as a modular-SDK refactor that removes the internal LLM and adds an `Executor` interface) replaced `experimental_codemode()` with `createCodeTool()`. The changelog for 0.1.0 says the package "no longer owns an LLM call". The model you already have writes the code directly, which matches what the blog post described all along.

From `src/tool.ts`, trimmed:

```typescript
const codeSchema = z.object({
  code: z.string().describe("JavaScript async arrow function to execute")
});

export function createCodeTool(options: CreateCodeToolOptions): Tool<CodeInput, CodeOutput> {
  const providers = normalizeProviders(options.tools);
  const typeBlocks: string[] = [];
  const resolvedProviders: ResolvedProvider[] = [];

  for (const provider of providers) {
    const name = provider.name ?? "codemode";
    const filtered = filterTools(provider.tools);
    const types = provider.types ?? generateTypes(filtered as ToolDescriptors, name);
    typeBlocks.push(types);
    resolvedProviders.push({ name, fns: extractFns(filtered) });
  }
  const typeBlock = typeBlocks.filter(Boolean).join("\n\n");
  const executor = options.executor;
  const description = (options.description ?? DEFAULT_DESCRIPTION)
    .replace("{{types}}", typeBlock);

  return tool({
    description,
    inputSchema: codeSchema,
    execute: async ({ code }) => runCode({ code, executor, providers: resolvedProviders })
  });
}
```

The input is now `{ code: string }`. The generated type declarations go into the tool's `description`, and `DEFAULT_DESCRIPTION` in `src/shared.ts` wraps them with instructions. The JavaScript wording and the TypeScript ban come from a fix (the source writes a dash after "syntax"; I show it as a hyphen):

```text
Write an async arrow function in JavaScript that returns the result.
Do NOT use TypeScript syntax - no type annotations, interfaces, or generics.
Do NOT define named functions then call them - just write the arrow function body directly.
```

The commit history shows why: `f6aa79f3` (2026-02-23) is titled "explicitly request JavaScript in default tool prompt to prevent TypeScript syntax errors". The model sees TypeScript declarations, so it tends to answer in TypeScript, but the isolate runs JavaScript. That is a small, real cost of showing types and running JavaScript.

Two more details in `tool.ts`: `filterTools` drops any tool with `needsApproval` set, so approval-gated AI SDK tools are never exposed to the sandbox, and `extractFns` wraps each tool's `execute` with schema validation through the AI SDK's `asSchema`, so arguments the model writes are validated before the real tool runs (commit `ef46d68e`, "validate tool arguments against schema before execution").

### Type generation, rewritten

`generateTypes()` in `src/tool-types.ts` is the descendant of the 2025 function, with a few visible changes. It no longer uses `zod-to-ts` (commit `33b92d52`, "remove zod-to-ts") or `json-schema-to-typescript`. A purpose-built converter in `src/json-schema-types.ts` turns JSON Schema into type strings, with a `maxDepth: 20` guard and `$ref` handling. Names go through `sanitizeToolName()` and `toPascalCase()`. And parameter descriptions are now emitted as `@param` lines in the doc comment:

```typescript
const paramDescs = extractParamDescriptions(inputSchema); // "@param input.query - ..."
jsdocLines.push(escapeJsDoc(description.trim().replace(/\r?\n/g, " ")));
// ...
availableTools += `\n\t/**\n${jsdocBody}\n\t */`;
availableTools += `\n\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;
```

The missing-output fallback also changed: it is now `type FooOutput = unknown` rather than an open-ended object. Since 0.5.4, output types describe the value a tool *returns*, not the input side of its schema (a `.default()` field becomes required, a `.transform()` shows as `unknown`).

### The executor: where the isolate lives

`src/executor.ts` defines the interface that makes the whole sandbox replaceable:

```typescript
export interface Executor {
  execute(
    code: string,
    providersOrFns: ResolvedProvider[] | Record<string, (...args: unknown[]) => Promise<unknown>>,
    options?: ExecuteOptions
  ): Promise<ExecuteResult>;
}
interface ExecuteResult { result: unknown; error?: string; logs?: string[]; }
```

The README calls the interface "deliberately minimal", says you can implement it for any sandbox, and sketches a Node VM version. `DynamicWorkerExecutor` is the Cloudflare implementation, and its `execute()` is where the original Proxy trick grew up. It builds the module source as strings. For each namespace (`codemode` by default, plus others like `workspace` or `github`) it emits a Proxy global:

```typescript
`    const ${p.name} = new Proxy({}, {\n` +
`      get: (target, toolName) => {\n` +
`        if (Object.prototype.hasOwnProperty.call(target, toolName)) return target[toolName];\n` +
`        if (typeof toolName !== "string") return undefined;\n` +
`        return async (...args) => {\n` +
`          const resJson = await __dispatchers.${p.name}.call(String(toolName), __stringifyForCodemode(args));\n` +
`          const data = __parseForCodemode(resJson);\n` +
`          if (data.error) throw new Error(data.error);\n` +
`          return data.result;\n` +
`        };\n` +
```

Compared with 2025, several things changed:

- **Dispatch moved from `env` to an argument.** The original passed a `CodeModeProxy` service binding in `env` and needed a `WorkerEntrypoint` export in the host. Now the host creates `ToolDispatcher` objects (`extends RpcTarget`), and passes them as arguments to the isolate's `evaluate()` method. The 0.1.0 changelog says this removes the need for `CodeModeProxy` and "globalOutbound service bindings. Only a WorkerLoader binding is required now." The commit message lists "globalOutbound defaults to null (runtime-enforced fetch/connect blocking)" among the key improvements.
- **Real serialization.** Arguments cross the boundary as JSON strings through a small codec that tags binary values (`Uint8Array`, `ArrayBuffer`) as base64, so tools returning bytes survive the trip (commit `2911bae6`, "preserve binary values across codemode tools").
- **Logs and a timeout.** The module overrides `console.log`, `console.warn` and `console.error` to push into a `__logs` array, runs the code inside `Promise.race` against a `setTimeout` rejection (default `60_000` ms), and returns `{ result, logs }`.
- **One-shot loading.** It calls `this.#loader.load({...})`, not `get(id, callback)`. A code comment explains that every run produces a unique generated module, so there is nothing to cache by id, and that `get` with a random id would only churn the loader's isolate cache.
- **Name hygiene.** Provider names are checked against a `RESERVED_NAMES` set and a valid-identifier regex before being interpolated into module source, and tool names go through `sanitizeToolName()` (so `my-tool` becomes `my_tool`, and `delete` becomes `delete_`).
- **Cleanup.** The worker and entrypoint stubs are disposed after each run, and an `ExecutionGate` exists for a subtle failure: if code returns without awaiting a tool call, that pending RPC would keep the Dynamic Worker counted as in flight. The comment says the Durable Object "runs into the Dynamic Worker concurrency limit after a handful of executions". Once an execution settles, the gate answers any still-pending calls with a "late" error, while the host-side work itself is not cancelled.

### Normalizing what the model writes

Models do not always return exactly an arrow function. `normalizeCode()` in `src/normalize.ts` is the layer that copes. It strips markdown code fences, then parses with **acorn** and handles each shape: an arrow function passes through unchanged, `export default <expr>` is unwrapped, a single named function declaration is wrapped and called, and a trailing expression statement gets a `return` spliced in. If parsing fails, it falls back to wrapping the source in `async () => { ... }`. Commit `9837adc9` (2026-03-17) moved this inside the executor so callers pass raw code.

Note what acorn is used for here: **normalization only**. It is the package's one parser dependency, and nothing else in `src/` imports it. I come back to that in the optimization section.

### Connectors, MCP and OpenAPI

The README's "Tool Providers" and later "Connectors" sections generalize "tools" into integrations. A connector class has `name()`, optional `instructions()` and `tools()`. Two built-in ones matter for MCP:

- `McpConnector` wraps an MCP connection: it lists tools, derives one connector tool per MCP tool (names sanitized into valid JS identifiers), and dispatches through `connection.client.callTool()`.
- `OpenApiConnector` reads an OpenAPI spec **once, host-side** and derives one typed tool per operation, so the model calls something like `stripe.CreatePaymentIntent({ amount, currency })`. The README notes "deriving on the host costs zero prompt tokens".

And for the server side there is `src/mcp.ts`. `codeMcpServer({ server, executor })` wraps an existing MCP server. It links an in-memory transport pair, calls `listTools()`, builds declarations with `generateTypesFromJsonSchema`, and registers a **single** tool called `code`. `openApiMcpServer({ spec, executor, request })` goes further and registers the two-tool `search` and `execute` pair that the follow-up post describes. In the SDK helper, the `search` tool's description tells the model to call `await codemode.spec()`, whereas the blog post's example uses a `spec` object in scope. I only read the SDK helper, not the hosted Cloudflare server, so I cannot say how they differ in production.

### Progressive discovery inside the sandbox

With connectors, the model no longer needs every declaration up front. `src/proxy-tool.ts` builds the tool description with a workflow:

```text
1. `const matches = await codemode.search("short intent phrase");`
2. `const docs = await codemode.describe(matches.results[0].path);`
3. Call the method: `await <connector>.<method>(args);`
```

The package's own docs (`docs/codemode/runtime.md` in the repo) explain the reasoning. Generating types for every tool and putting them in the description "floods the context as the tool count grows", so instead `search` and `describe` "return results into the running code, not into the prompt". Search is a small ranked matcher in `src/connectors/search.ts`: it tokenizes camelCase and snake_case, weights fields (path 12, method 10, connector 8, description 5), and caps results at 50. That is the "search and browse the API more dynamically" idea from the 2025 post, shipped.

### Approvals, replay and durability

The newest layer solves a problem the original did not address: what happens when code wants to do something that needs a human. A connector tool can set `requiresApproval: true` (and an optional `revert` function). The runtime then makes execution **durable by abort-and-replay**. Every tool call is logged. When the code reaches an approval-gated call, the run aborts and the call is recorded as pending. After approval, the *same code re-runs* from the start, every call already in the log is served from the log, and the approved action executes for real.

```mermaid
stateDiagram-v2
    [*] --> running: begin
    running --> completed: code finishes
    running --> error: sandbox error or replay divergence
    running --> paused: approval-gated call
    paused --> running: approve then replay the log
    paused --> rejected: reject
    completed --> rolled_back: rollback via revert
    rejected --> [*]
    rolled_back --> [*]
    completed --> [*]
    error --> [*]
```

Those are the six statuses in `ExecutionStatus` in `src/runtime.ts`. Replay requires determinism, so the docs introduce `codemode.step(name, fn)` to wrap anything nondeterministic or side-effectful, and the runtime detects "replay divergence" if the Nth call differs between runs. Successful or not, outcomes come back as data (`status: "completed" | "paused" | "error"`) instead of exceptions.

The same runtime holds **snippets**: scripts the model wrote that a developer promotes with `runtime.saveSnippet(...)`, which the model can reuse with `codemode.run("name")`.

### Keeping results small: truncation

`src/truncate.ts` exports helpers that cap what comes back. `truncateResult()` leaves a value untouched if its JSON fits the budget, and otherwise shrinks it **structurally**: valid JSON of the same shape, largest values cut first, with `--- TRUNCATED ---` markers. The default budget is `DEFAULT_MAX_TOKENS = 6000`, which is turned into characters with that 4-characters-per-token estimate. Where it is applied matters: the MCP helpers in `src/mcp.ts` use it with a fixed 24,000-character budget (the same 6,000 tokens at 4 characters each), the durable tool's model output truncates the sandbox `logs` with the default, and for the durable runtime's final result you opt in by passing a `transformResult` hook. `createCodeTool` in `src/tool.ts` has no truncation of its own. The structural version came in commit `dcca0896` (2026-09-09), which also keeps the durable call log out of what the model sees.

### And in a browser

For completeness: `src/iframe-executor.ts` implements the same `Executor` interface with a sandboxed iframe and a CSP of `default-src 'none'; script-src 'unsafe-inline' 'unsafe-eval';` (the README's default), so Code Mode can run against browser-owned tools. The README flags that its timeout "cannot preempt tight synchronous browser loops".

---

## How did Code Mode evolve?

Here are the dates, all from `git log` of the Agents SDK repo and the Cloudflare posts.

```mermaid
timeline
    title Code Mode from first commit to durable runtime
    2025-09-26 : PR 512 lands : blog post published : two model calls, gpt-4.1 writes the code
    2025-12-29 : split into @cloudflare/codemode : first version 0.0.1
    2026-02-20 : createCodeTool, Executor interface : inner LLM removed : whole-API post by Matt Carey
    2026-03-17 : MCP helpers codeMcpServer and openApiMcpServer : normalize inside the executor
    2026-03-24 : Dynamic Workers post : Worker Loader in open beta
    2026-05-06 : browser iframe executor
    2026-06-10 : connectors, durable runtime, snippets
    2026-09-09 : structural result truncation
```

| Date | Change | Where |
|---|---|---|
| 2025-09-26 | First implementation, outer model plus a second `generateObject` call | `f9f03b44`, PR #512 |
| 2025-12-29 | Package split out, first version 0.0.1 | `0c4275f8`, PR #756 |
| 2026-02-06 | Inner model made configurable instead of hard-coded | `21a79778`, PR #849 |
| 2026-02-20 | Inner LLM removed, `Executor` interface, `ToolDispatcher`, acorn normalization | `90e54dab`, PR #879 |
| 2026-03-17 | `./mcp` export with `codeMcpServer` and `openApiMcpServer` | `5d88b810`, PR #1114 |
| 2026-05-06 | Browser iframe executor | `186a2a45`, PR #1468 |
| 2026-06-10 | Connector model, durable runtime, snippets | `b2b67623`, PR #1581 |
| 2026-09-09 | Structural truncation, call log out of model context | `dcca0896`, PR #2224 |
| 2026-10-20 | Release tool calls left pending when an execution settles | `d6606fd5`, PR #2614 |

The arc is clear. The September version proved the idea with the least machinery. The February refactor removed the second model and made the sandbox an interface. The following months added the things a real product needs: progressive discovery, approvals, an audit log, and output limits.

---

## What is the 1,000-token follow-up: search() and execute()?

On 2026-02-20, the same day as the refactor, Matt Carey published ["Code Mode: give agents an entire API in 1,000 tokens"](https://blog.cloudflare.com/code-mode-mcp/). It applies Code Mode on the **server side**: instead of one tool per API endpoint, the MCP server exports just two, `search()` and `execute()`, both taking a `code` string. The post prints the full tool surface that enters the context, two JSON tool definitions.

`search()` gives the model a typed representation of the OpenAPI spec to write JavaScript against: filter by product, path or tag and "narrow thousands of endpoints to the handful it needs". The post adds that "The full OpenAPI spec never enters the model context." Then `execute()` runs code that can "make Cloudflare API requests, handle pagination, check responses, and chain operations together in a single execution". Both run in a Dynamic Worker isolate, described as "a lightweight V8 sandbox with no file system, no environment variables to leak through prompt injection and external fetches disabled by default".

The worked example is "protect my origin from DDoS attacks". The agent searches for WAF and ruleset endpoints, inspects the phase enum on zone rulesets, lists existing rulesets, then fetches the DDoS and WAF configuration. The post says that whole operation "took four tool calls".

### The token math, with only published numbers

Here are the published figures and the arithmetic I derived from them. All numbers below come from the sources cited, and the divisions are mine.

| Source | Without Code Mode | With Code Mode | Published reduction | My check |
|---|---|---|---|---|
| Cloudflare, 2026-02-20 (whole Cloudflare API, measured with tiktoken) | 1.17 million tokens | around 1,000 | 99.9% | 1 - 1,000 / 1,170,000 = 99.91% |
| Anthropic, 2025-11-04 (Drive to Salesforce example) | 150,000 | 2,000 | 98.7% | 1 - 2,000 / 150,000 = 98.67% |
| Cloudflare, 2026-04-14 (internal portal, 4 servers) | about 9,400 for 52 tools | roughly 600 for 2 portal tools | 94% | 1 - 600 / 9,400 = 93.6% |

![Log-scale bar chart of three published token reductions: 1,170,000 down to about 1,000, 150,000 down to 2,000, and about 9,400 down to about 600](https://www.dhruvvakharwala.dev/images/blog/code-mode-mcp-cloudflare-agents-sdk/numbers.png)

The three rows come from three different setups, so do not compare them to each other, only within a row. Two more derived figures are worth having. Cloudflare says the API has "over 2,500 endpoints". So 1,170,000 / 2,500 = **468 tokens per endpoint** as an upper bound, since the true endpoint count is above 2,500. The portal numbers give 9,400 / 52 = **about 181 tokens per tool**.

The real story in that table is the *shape*: plain MCP cost grows with the number of tools, while the Code Mode figure "stays fixed, no matter how many API endpoints exist" in the Cloudflare post's words. A back-of-envelope break-even from the portal numbers (my arithmetic, not a published claim): about 600 / 181 = 3.3, so with those per-tool costs Code Mode's fixed overhead is paid back by roughly 4 tools on definitions alone. That ignores the cost of the code the model writes and of retries, and it only holds for the search-and-execute shape: in the `createCodeTool` shape, where all declarations go in the tool description, the cost still scales with tools, just at a lower rate than JSON schemas, as the Dynamic Workers post argues for TypeScript versus OpenAPI.

The enterprise post (Sharon Goldberg, Matt Carey and Ivan Anguiano, 2026-04-14) brings the same pattern to MCP server portals: the portal collapses upstream servers into `portal_codemode_search` and `portal_codemode_execute`, switched on with a `?codemode=search_and_execute` query parameter. I only use its Code Mode section here.

Anthropic's post, which Cloudflare's follow-up points to as an independent exploration, reaches the same idea from the filesystem direction. It generates a file tree of tools (`./servers/google-drive/getDocument.ts` and so on) so "the agent discovers tools by exploring the filesystem" and reads only the files it needs. Two write-ups reaching the same idea is the best evidence I have that this is more than one team's taste, though Anthropic's post cites Cloudflare's, so they are not fully independent.

---

## What does Code Mode cost you? Tradeoffs and risks

Code Mode is not free, and the sources are honest about it. Here is what I take from them, with my own reasoning marked.

- **You need a sandbox.** Anthropic is explicit: "Running agent-generated code requires a secure execution environment with appropriate sandboxing, resource limits, and monitoring", and says these requirements "add operational overhead and security considerations that direct tool calls avoid". Cloudflare's own docs recommend direct tool calls for "simple tasks with a small, fixed tool set".
- **Generated code can be wrong.** The repo shows the scar tissue: `normalizeCode` exists because models wrap code in fences or write named functions, and `f6aa79f3` exists because models answered in TypeScript syntax. A failed run is not free. *My reasoning:* each failure costs a full model round trip plus a fresh isolate, and the error text has to be good enough for the model to repair. The SDK returns errors with the captured console output attached, which helps.
- **Debugging is harder.** A tool-call transcript is a list of calls you can read. A Code Mode run is a program. That is why the durable runtime keeps a tool-call log, so a UI can show what a run actually did.
- **An extra step of latency.** The model has to write a program before anything happens. For a single call with a small payload, it is slower than a direct tool call. The Cloudflare post's benefit claim is for chaining, "The approach really shines when an agent needs to string together multiple calls", and I read the corollary as: do not use it for one-call tasks.
- **Isolate security is not magic.** The Dynamic Workers post says security bugs in V8 are more common than in typical hypervisors, and relies on layered defenses on Cloudflare's side.
- **Prompt injection still exists.** The sandbox bounds what injected instructions can *reach*, since the code has only the bindings you gave it, no network and no keys. It does not stop injected text from steering the model's code. *My reasoning:* if a tool result you `console.log()` contains hostile text, it enters the model's context like any other tool result, and if your bindings include a mutating tool, hostile text can still try to make the model call it. That is the argument for gating mutating tools behind approvals, which the SDK's `requiresApproval` supports. Cloudflare's enterprise post treats prompt injection as a separate risk and fronts public MCP servers with a WAF feature for it, which is a different layer from the sandbox.
- **Output limits matter.** If code returns a huge value, you have rebuilt Cost 2 by hand. This is why `truncateResult` exists.

---

## What I would optimize next

Here is my list. I checked each idea against `packages/codemode` at commit `263a5b9` before writing it down, and I cut or reshaped the ones the source already covers. **Every item below is an untested proposal.** I have not implemented or measured any of them.

### 1. Put the stable declarations first, so prompt caching can hit

The generated TypeScript lives in the tool description, which is the same bytes on every turn as long as the tool list does not change. If a provider caches on a stable prefix (rules differ per provider, so I would read each one before relying on it), a byte-identical description should be cacheable. The source has no cache awareness: I found no cache controls and no mention of prompt caching in `src/`. The README's agent example calls `createCodeTool` inside `onChatMessage`, so the string is rebuilt each turn. `generateTypes` iterates `Object.entries(tools)`, which is deterministic for the same insertion order, so the string should already be stable if the tool order is. My plan: assert byte-identity across turns in a test, keep volatile content such as the date after the declarations, and read cached-token counts from provider usage. The benefit is mostly for the `createCodeTool` shape. The durable-runtime description is short and static, because discovery happens in the sandbox.

### 2. Cache generated declarations by a hash of the tool list

This one is **partly already there**. `OpenApiConnector` memoizes derived operations in a `WeakMap` keyed by spec identity (`operationCache` in `src/connectors/openapi.ts`, with a comment that connectors "are reconstructed per message"), and `McpConnector` caches its connection promise. What does not exist is a persistent cache keyed by a content hash of the MCP tool list, which would survive restarts and let different instances share work. Honestly this is my weakest idea: it saves host CPU, not model tokens. I would first measure how long `generateTypes` takes for a few hundred tools before building anything.

### 3. Check generated code statically before spinning an isolate

`acorn` is already a dependency, but only `normalizeCode` uses it. After parsing, I would walk the AST for member calls such as `codemode.<name>(` and check the names against the known tool list, and perhaps check object-literal arguments for missing required keys. Today a wrong name is caught at runtime: `ToolDispatcher.call` answers `Tool "name" not found`, and argument validation runs through `asSchema` when the call arrives. My reasoning for why this still matters: a script can make several real calls *before* it reaches the typo, so a pre-flight check turns a half-executed script into a run that executes nothing and returns the closest valid name. The limit is that dynamic property access cannot be checked statically, so this would be a fast path and not a guarantee.

### 4. Budget results by tokens, adaptively

`src/truncate.ts` already has a token budget: `maxTokens` defaults to 6000, and callers can pass their own `maxTokens` or `maxChars`. But it converts to characters with the fixed 4-characters-per-token estimate, and nothing in the package derives the budget from the conversation, so in practice it is a constant per deployment. My idea is a budget derived from the model's *remaining* context, measured with a tokenizer for that model, with the truncation marker telling the model how to page (the existing marker already says "Narrow the request to reduce response size."). Gain: fewer cases where a 6,000-token cap is too generous late in a long conversation, or too stingy early. Risk: a tokenizer on the host adds a dependency and CPU.

### 5. Allow `Promise.all` for reads without breaking replay

The README's `ToolProvider` example uses `Promise.all` to fan out `codemode.analyzeFile` calls. That example uses plain providers, not connectors, but the runtime docs say to issue connector calls one at a time in any run that might pause for approval. They explain that `await a(); await b();` is stable across runs while `Promise.all([a(), b()])` is not, because the replay cursor assigns sequence numbers in the order calls arrive at the host. Neither tool description tells the model to parallelize. The idea: identify replayable calls by `(connector, method, stable args, occurrence index)` instead of arrival order, at least for read-only calls, and then hint `Promise.all` for independent reads. This is the riskiest of my proposals, because it touches the replay invariant, and I have only read the documentation and not the whole runtime. The experiment is to write the divergence test first and see whether it can pass.

### 6. Derive approval defaults from MCP tool annotations

The approval and rollback machinery **already exists**: `requiresApproval`, `revert`, `runtime.rollback`, `replay: "reexecute"` for idempotent reads, and `codemode.step` as the side-effect boundary. What I did not find is any use of the MCP tool-annotation hints. (The package has its own connector `ToolAnnotations` type in `src/connectors/types.ts`, but it only carries `requiresApproval` and `replay`, a different thing from the MCP spec's type of the same name.) The MCP schema defines `readOnlyHint`, `destructiveHint` and `idempotentHint`, and I found none of the three anywhere in `packages/codemode/src` outside tests. Today a developer has to override `McpConnector.tool()` by hand to mark `create_issue` as `requiresApproval`. The proposal is a default policy that gates anything not marked read-only. There is a caveat in the spec itself: the annotations are only hints, and "Clients should never make tool use decisions based on ToolAnnotations received from untrusted servers." So the default has to fail closed: unannotated or untrusted tools get gated, and the hints are only trusted for servers I trust.

---

## What I am going to try

I have not run Code Mode. Everything I know about its results is what Cloudflare and Anthropic published, and what I read in the code. The next step is to measure it myself.

Here is the plan. I am going to wire `@cloudflare/codemode` into a small agent that chains several MCP tool calls, and run the same set of tasks twice with the same model: once with plain tool calling, once through Code Mode. For each task I am going to record input tokens, output tokens, wall-clock time, number of model round trips, and whether the answer was right. Then I am going to try the proposals above one at a time, starting with the two cheapest to check, the prompt prefix stability and the pre-flight check, and see whether each moves those numbers. When I have results I will publish the numbers, including the ones that make Code Mode look worse.

---

## FAQ

### What is Code Mode MCP?

It is Cloudflare's technique of converting an MCP server's tools into a TypeScript API and giving the model one tool that runs code, instead of exposing every tool as a separate tool call. The code runs in a sandbox and only its logs or return value come back to the model.

### Why does Code Mode use fewer tokens than normal MCP tool calling?

Two reasons. Tool definitions do not all have to sit in context, and intermediate results stay inside the sandbox instead of passing through the model. Cloudflare reports 1.17 million tokens for the whole Cloudflare API as plain MCP tools versus about 1,000 with `search()` and `execute()`.

### What is the Dynamic Worker Loader?

It is the Workers API that lets a Worker load a new isolate with code supplied at runtime, with its own `env` bindings and a `globalOutbound` setting that can block the network entirely. Cloudflare describes isolates as starting in a few milliseconds with a few megabytes of memory, so a fresh one can be created per piece of generated code.

### How does the generated code call tools if it has no network?

Through bindings. The host passes RPC objects (in the current SDK, `ToolDispatcher` instances) into the isolate, and a JavaScript `Proxy` turns calls like `codemode.someTool(args)` into RPC calls back to the host, which holds the credentials and runs the real tool.

### Does the current Agents SDK still use a second model to write the code?

No. The first version in PR #512 used a second `generateObject` call with `gpt-4.1`, but commit `90e54dab` on 2026-02-20 removed it, and `createCodeTool` now gives the model a single `{ code }` tool.

**Takeaway:** Code Mode keeps MCP for what it is good at, uniform discovery, documentation and authorization, and changes what the model sees: a typed API and one tool that runs code in a disposable isolate whose only exits are RPC bindings. That removes both costs, schemas in context and results round-tripping through the model, and it keeps API keys out of generated code by construction. The price is a sandbox you must trust, code that can be wrong, and a runtime that gets heavier once you add approvals and replay. The code is open source and the package still calls itself experimental. I have the idea and the source read, not the measurements, and those are next.


## References

- Kenton Varda and Sunil Pai, ["Code Mode: The better way to use MCP"](https://blog.cloudflare.com/code-mode/), Cloudflare, 2025-09-26
- Matt Carey, ["Code Mode: give agents an entire API in 1,000 tokens"](https://blog.cloudflare.com/code-mode-mcp/), Cloudflare, 2026-02-20
- Kenton Varda, Sunil Pai and Ketan Gupta, ["Sandboxing AI agents, 100x faster"](https://blog.cloudflare.com/dynamic-workers/), Cloudflare, 2026-03-24
- Sharon Goldberg, Matt Carey and Ivan Anguiano, ["Scaling MCP adoption: Our reference architecture for simpler, safer and cheaper enterprise deployments of MCP"](https://blog.cloudflare.com/enterprise-mcp/), Cloudflare, 2026-04-14 (Code Mode section only)
- Anthropic Engineering, ["Code execution with MCP: Building more efficient agents"](https://www.anthropic.com/engineering/code-execution-with-mcp), 2025-11-04
- Cloudflare docs: [Code Mode](https://developers.cloudflare.com/agents/tools/codemode/), [Code Mode API reference](https://developers.cloudflare.com/agents/tools/codemode/api-reference/), [Dynamic Workers](https://developers.cloudflare.com/dynamic-workers/), [Worker Loader API](https://developers.cloudflare.com/workers/runtime-apis/bindings/worker-loader/)
- Code: [cloudflare/agents PR #512 "Codemode"](https://github.com/cloudflare/agents/pull/512) (commit `f9f03b44`), and [packages/codemode](https://github.com/cloudflare/agents/tree/main/packages/codemode) at commit `263a5b9` (2026-11-24, version 0.5.6)
- [MCP schema, 2025-06-18, `ToolAnnotations`](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/main/schema/2025-06-18/schema.ts)
- Related posts: [Talk to Chart: a model that returns typed ops instead of running a tool-calling loop](https://www.dhruvvakharwala.dev/blogs/talk-to-chart-jev-gpt5-tradingview-pine), [Zero-trust team SSH with Cloudflare WARP](https://www.dhruvvakharwala.dev/blogs/zero-trust-bastion-cloudflare-warp)