Skip to content
AnswerWell geo Documentation

Research · 8 min read · Answerwell

Code Mode Orchestration, Sandbox Executor, Connectors, and Approvals

How Cloudflare Code Mode replaces many tool calls with one sandboxed code tool, plus executors, connectors, approvals, and MCP.

This page summarizes Cloudflare documentation on Code Mode: the @cloudflare/codemode pattern where a model receives one code-execution tool, writes JavaScript that calls typed tool methods, and runs that program in an isolated sandbox. It suits multi-step agent work on Workers, in browsers, and behind Model Context Protocol (MCP) servers.

Code Mode vs direct tool calls: when to use which

Section titled “Code Mode vs direct tool calls: when to use which”

Code Mode moves intermediate logic into executable code instead of returning every tool result to the model between steps.

With direct tool use, the model selects one tool, receives its result, and then decides what to do next. Each operation can require another round trip through the model.

— Cloudflare, Code Mode

In Code Mode, one plan can compose dependent calls, loop over collections, filter data, branch, and return only the final value. That keeps bulky intermediate data inside the sandbox.

Pattern Best suited for
Direct tool calls Simple tasks with a small, known tool set
Code Mode Composed or dependent calls, large catalogs, loops, branching, filtering, reusable logic, progressive discovery

Code Mode keeps that work inside one sandbox execution. Generated code can pass results between tools, filter intermediate data, and return only the final value the model needs.

— Cloudflare, Code Mode

Cloudflare cites running tool logic as code instead of many separate calls as a way to save up to 80% in inference tokens and cost when using Dynamic Workers for Code Mode (Dynamic Workers, now in open beta).

Use a normal client-side tool for a single browser action; use Code Mode when the model must chain several client tools with control flow (Browser integration).

How Code Mode works: executor, connectors, and durable runtime

Section titled “How Code Mode works: executor, connectors, and durable runtime”

Code Mode splits responsibilities: the executor runs code but stores no state; connectors expose host capabilities; the durable runtime records executions, approvals, replay, rollback, and snippets (How Code Mode works).

What the model sees: one codemode tool and { code: string }

Section titled “What the model sees: one codemode tool and { code: string }”

The model typically gets one outer tool named codemode with input { code: string }. The description tells it to write a JavaScript async arrow function. Connector namespace names (for example github) appear in the description, but not every method schema up front—so large catalogs do not fill the context window on the first turn.

Execution returns a durable outcome: completed, paused (pending approval), or error—sandbox failures surface in the tool result instead of throwing through the model call (How Code Mode works).

Sandbox globals: codemode.search, connectors, and limits

Section titled “Sandbox globals: codemode.search, connectors, and limits”

Inside the sandbox, each connector becomes a global (for example github.list_pull_requests()). The platform codemode global supports discovery and replay helpers:

codemode.search() searches connector methods and saved snippets. It returns ranked paths, not complete schemas. The model can then pass one path to codemode.describe() to request focused TypeScript documentation.

— Cloudflare, How Code Mode works

The sandbox has standard JavaScript globals only—no Node.js process, unrestricted network, or host credentials. External work goes through connector RPC (How Code Mode works).

createCodemodeRuntime() stores execution history in a Durable Object facet with SQLite, surviving hibernation; you re-supply executor and connector instances on later approvals (How Code Mode works).

@cloudflare/codemode exposes six entry points (Code Mode API reference):

Entry point Purpose
@cloudflare/codemode Runtime, connectors, DynamicWorkerExecutor, framework-independent utilities
@cloudflare/codemode/ai AI SDK createCodeTool(), ToolSetConnector (requires ai and zod peers)
@cloudflare/codemode/mcp codeMcpServer(), openApiMcpServer()
@cloudflare/codemode/tanstack-ai TanStack AI adapter
@cloudflare/codemode/browser createBrowserCodeTool(), IframeSandboxExecutor
@cloudflare/codemode/vite Auto-exports CodemodeRuntime from the Worker entry

From v0.2.0, generateTypes and ToolDescriptor types moved from the main package to @cloudflare/codemode/ai; the main entry no longer requires ai or zod as peer dependencies (@cloudflare/codemode v0.2.1 changelog). v0.1.0 removed experimental_codemode() and CodeModeProxy; createCodeTool() imports from @cloudflare/codemode/ai (v0.1.0 changelog).

The Executor contract is runtime-agnostic: execute(code, fns) with a built-in DynamicWorkerExecutor using the Worker Loader (v0.1.0 changelog).

Stateless Code Mode: createCodeTool() with the AI SDK

Section titled “Stateless Code Mode: createCodeTool() with the AI SDK”

For simple, stateless runs, createCodeTool() folds AI SDK tools into one Code Mode tool. The model writes code such as:

async () => {
const weather = await codemode.getWeather({ city: "Lisbon" });
return weather.conditions;
};

createCodeTool() generates TypeScript declarations from tool schemas, normalizes model output (fences, async wrapper), and runs code via your executor (Code Mode Example).

Workers need a Worker Loader binding and nodejs_compat (AI SDK integration):

{
"compatibility_flags": ["nodejs_compat"],
"worker_loaders": [{ "binding": "LOADER" }]
}

Each sandbox-callable tool needs an execute function; client-side or provider-executed tools cannot run in the server-side executor (AI SDK integration).

Pass a flat tool record for the default codemode.* namespace, or provider objects { name: "weather", tools: weatherTools } for weather.getWeather() (AI SDK integration). Provider names must be unique valid JavaScript identifiers.

createCodeTool() vs durable runtime for approvals

Section titled “createCodeTool() vs durable runtime for approvals”
Integration Use case Approval behavior
createCodeTool() Simple, stateless execution Excludes tools with needsApproval; no pause
ToolSetConnector / toolSetConnector() Durable Code Mode runtime Maps needsApproval to durable approval

createCodeTool() filters out tools where needsApproval is true or a function. Filtered tools do not appear in generated types and cannot run from sandbox code.

— Cloudflare, AI SDK integration

For side effects that must pause for a human, use createCodemodeRuntime() with connectors (AI SDK integration).

Durable Code Mode runtime: approvals, replay, and host APIs

Section titled “Durable Code Mode runtime: approvals, replay, and host APIs”

createCodemodeRuntime() is the control plane: connectors, executor, optional name for separate histories, execution audit, snippets, approve() / reject() / rollback() (Code Mode API reference).

Code Mode now uses createCodemodeRuntime, connectors, and a durable execution log. This lets you give a model one codemode tool instead of a large prompt full of tool definitions. The model can discover the capabilities it needs, write code against typed globals, and reuse saved snippets.

— Cloudflare, Agents SDK improves browser automation, code execution, and recovery

When generated code hits an approval-gated connector method, the runtime pauses, returns pending actions, and after approval replays completed calls from the log before running the approved step (Agents SDK v0.16.1 changelog).

Hosts without the AI SDK can call runtime.search(), runtime.describe(), and runtime.execute({ code }) directly (MCP and Code Mode updates). Search and describe results can include requiresApproval: true for protected methods.

Export CodemodeRuntime from the Worker entry manually, or use the codemodeVitePlugin() so createCodemodeRuntime() can bind the facet.

Full setup walkthrough: Create a durable Code Mode runtime.

Connectors: MCP, OpenAPI, and custom tools

Section titled “Connectors: MCP, OpenAPI, and custom tools”

Connectors bridge host services into the sandbox (How Code Mode works):

Mark sensitive methods with requiresApproval: true in the tool() hook so the runtime pauses before execution (human-in-the-loop patterns).

Replay pitfalls: order, nondeterminism, and snippets

Section titled “Replay pitfalls: order, nondeterminism, and snippets”

Issue connector calls sequentially when execution may pause; Promise.all() can reorder RPC arrivals and cause replay divergence (How Code Mode works).

Wrap nondeterministic sandbox work in codemode.step() so replay reuses recorded values (How Code Mode works).

Save reusable programs with runtime.saveSnippet() only after verifying successful completion; the model discovers snippets via codemode.search() and runs them with codemode.run() (How Code Mode works).

MCP integration: one code tool instead of many MCP tools

Section titled “MCP integration: one code tool instead of many MCP tools”

A Code Mode MCP server exposes code execution so clients without their own sandbox can still run composed programs (Build a Code Mode MCP server):

A Code Mode MCP server lets any Model Context Protocol (MCP) client use model-written code without providing its own sandbox. Instead of advertising one tool per operation, the server exposes code execution as its tool interface and runs the generated JavaScript in an isolated Worker.

— Cloudflare, Build a Code Mode MCP server

codeMcpServer({ server, executor }) wraps an existing MCP server: upstream tools become typed codemode.* methods inside one code tool (@cloudflare/codemode v0.2.1 changelog). After deploy, the MCP client should see one tool named code (Build a Code Mode MCP server).

openApiMcpServer() adds search and execute tools: sandbox code can call codemode.spec() and host-proxied codemode.request() without putting credentials in the model context (Build a Code Mode MCP server).

Inside Agents, createCodeTool({ tools: this.mcp.getAITools(), executor }) is a lighter path without durable pause or in-sandbox codemode.search(); prefer McpConnector for side effects and discovery (Use MCP tools with Code Mode).

Cloudflare One MCP portals with Code Mode replace upstream tools with portal_codemode_search and portal_codemode_execute, sanitizing tool names for JavaScript identifiers (MCP server portals).

TanStack AI, browser, and other frameworks

Section titled “TanStack AI, browser, and other frameworks”

TanStack AI: import createCodeTool and tanstackTools from @cloudflare/codemode/tanstack-ai and pass the tool to chat() (Use Code Mode with TanStack AI). Namespace the second argument, for example tanstackTools([getWeather], "weather") → weather.get_weather() (TanStack AI integration changelog).

Browser: @cloudflare/codemode/browser uses JSON Schema and IframeSandboxExecutor (sandboxed iframe, default 30s timeout). It does not require AI SDK or Zod peers (Browser integration).

Think harness: createExecuteTool is deprecated in favor of exec on a JavaScript backend; it still documents the same runtime facets when you need audit or snippet APIs (Think tools).

  • Missing LOADER binding — DynamicWorkerExecutor requires env.LOADER from worker_loaders (AI SDK integration).
  • Expecting approvals from createCodeTool() — approval-gated tools are stripped; use createCodemodeRuntime() and connectors (AI SDK integration).
  • Tools without execute — excluded from sandbox bindings and durable connectors (AI SDK integration).
  • Parallel connector calls before approval — risks replay divergence; call connectors sequentially (How Code Mode works).
  • Wrong import after upgrade — generateTypes from @cloudflare/codemode/ai, not the main entry (v0.2.1 changelog).
  • Browser Code Mode for remote CDP automation — client Code Mode does not control a remote browser; use Browser tools for CDP (Browser integration).
  • Forgotten CodemodeRuntime export — durable runtime fails without exporting the facet class (Code Mode API reference).

Upgrade package:

npm i @cloudflare/codemode@latest

(v0.2.1 changelog)

  1. Confirm wrangler config includes worker_loaders with binding LOADER and nodejs_compat as in AI SDK integration.
  2. Verify the Worker entry exports CodemodeRuntime when using createCodemodeRuntime() (Code Mode API reference).
  3. Deploy with npx wrangler deploy and trigger a chat or HTTP handler that registers a single codemode tool (Code Mode Example).
  4. For an MCP Code Mode server, connect an MCP client to your /mcp route and confirm one tool named code is advertised (Build a Code Mode MCP server).
  5. You can check automatically in Answerwell (our tool): https://answerwell.org/workspace

If something on this page is wrong or unclear, email yimasynthetic@gmail.com with the page URL and the exact statement you are asking about.