Code Mode API reference·续
revert provides compensation for runtime.rollback(). It can apply to any tool, whether or not the tool requires approval.
McpConnector
abstract class McpConnector<
Env = unknown,
Props = unknown,
> extends CodemodeConnector<Env, Props> {
protected abstract createConnection():
| McpConnectionLike
| Promise<McpConnectionLike>;
protected toolName(tool: McpTool): string;
}
McpConnector converts each MCP tool into a connector method. toolName() defaults to sanitizeToolName(tool.name). Override it to resolve naming collisions.
interface McpConnectionLike {
name?: string;
client: Pick<Client, "callTool">;
instructions?: string;
tools?: McpTool[];
fetchTools?: () => Promise<McpTool[]>;
}
The connector uses tools when that array is non-empty. Otherwise, it calls fetchTools() when provided. MCP error results become thrown connector errors. Structured content is returned before text content.
OpenApiConnector
abstract class OpenApiConnector<
Env = unknown,
Props = unknown,
> extends CodemodeConnector<Env, Props> {
protected abstract spec():
| Record<string, unknown>
| Promise<Record<string, unknown>>;
protected abstract request(options: OpenApiRequestOptions): Promise<unknown>;
protected exposeSpec(): boolean;
}
OpenApiConnector creates one method per OpenAPI operation. It uses a sanitized operationId when present, then falls back to a name based on the HTTP method and path. Duplicate operations and names reserved for request or spec are skipped.
Every OpenAPI connector exposes a low-level request method. exposeSpec() defaults to false. Return true to also expose spec.
type OpenApiRequestOptions = {
path: string;
method?: string;
params?: Record<string, unknown>;
body?: unknown;
headers?: Record<string, string>;
};
Derived operation tools substitute path parameters. They pass query values as params, header values as headers, and JSON request data as body.
Connector lifecycle and description types
type ExecutionEndStatus = "completed" | "error" | "rejected" | "rolled_back";
type PassEndStatus = ExecutionEndStatus | "paused";
type ToolAnnotations = {
requiresApproval?: boolean;
replay?: "log" | "reexecute";
};
type ConnectorDescription = {
name: string;
instructions?: string;
descriptors: JsonSchemaToolDescriptors;
annotations?: Record<string, ToolAnnotations>;
};
JSON Schema utilities
interface JsonSchemaToolDescriptor {
description?: string;
inputSchema: JSONSchema7;
outputSchema?: JSONSchema7;
}
type JsonSchemaToolDescriptors = Record<string, JsonSchemaToolDescriptor>;
function generateTypesFromJsonSchema(tools: JsonSchemaToolDescriptors): string;
function jsonSchemaToType(schema: JSONSchema7, typeName: string): string;
generateTypesFromJsonSchema() returns declarations for a codemode namespace. Tool names are sanitized before declarations are generated. Unsupported schemas degrade to unknown instead of causing generation to fail.
Code and output utilities
The main entry point provides these code and result utilities:
| Function | Signature | Behavior |
|---|---|---|
sanitizeToolName |
(name: string) => string |
Replaces common separators, removes invalid characters, prefixes digit-leading names, and suffixes JavaScript reserved words. |
normalizeCode |
(code: string) => string |
Converts common model output forms into an async arrow function. It also removes supported Markdown fences. |
truncateResponse |
(text: string, options?: TruncateOptions) => string |
Truncates text to a character budget and appends a size marker. |
truncateResult |
(value: unknown, options?: TruncateOptions) => unknown |
Preserves small structured values. Oversized serializable values become truncated JSON text. |
type TruncateOptions = {
maxChars?: number;
maxTokens?: number;
};
The default budget is 6000 estimated tokens at four characters per token. maxChars overrides the derived character budget.
@cloudflare/codemode/ai
This entry point requires the ai and zod peer dependencies.
createCodeTool()
function createCodeTool(
options: CreateCodeToolOptions,
): Tool<CodeInput, CodeOutput>;
interface CreateCodeToolOptions {
tools: ToolProviderTools | ToolProvider[];
executor: Executor;
description?: string;
}
type CodeInput = { code: string };
type CodeOutput = { result: unknown; logs?: string[] };
description can contain {{types}}. Code Mode replaces that token with generated declarations. A raw tool record becomes one provider named codemode. An array accepts multiple provider namespaces.
Tools whose needsApproval is true or a function are excluded. This API does not pause. Use createCodemodeRuntime() and connectors for durable approval handling.
AI SDK provider utilities
The AI SDK entry point provides these tool-provider utilities:
| Export | Signature | Description |
|---|---|---|
aiTools |
(tools: ToolDescriptors \| ToolSet) => ToolProvider |
Wraps AI SDK tools in the default provider. |
generateTypes |
(tools: ToolDescriptors \| ToolSet, namespace?: string) => string |
Generates declarations from AI SDK or Zod schemas. The namespace defaults to codemode. |
resolveProvider |
(provider: ToolProvider) => ResolvedProvider |
Filters approval-gated tools, validates input with AI SDK asSchema() when available, and extracts executable functions. |
interface ToolDescriptor {
description?: string;
inputSchema: ZodType;
outputSchema?: ZodType;
execute?: (args: unknown) => Promise<unknown>;
}
type ToolDescriptors = Record<string, ToolDescriptor>;
ToolSetConnector
class ToolSetConnector extends CodemodeConnector {
constructor(
ctx: DurableObjectState | ExecutionContext,
options: ToolSetConnectorOptions,
);
}
function toolSetConnector(
ctx: DurableObjectState | ExecutionContext,
options: ToolSetConnectorOptions,
): ToolSetConnector;
interface ToolSetConnectorOptions {
name?: string;
instructions?: string;
tools: ToolSet;
}
The namespace defaults to tools. The connector excludes tools without an execute function. needsApproval: true and function-valued needsApproval map to durable connector approval. needsApproval: false executes without approval. AI SDK schemas validate input before execution.
@cloudflare/codemode/mcp
This entry point requires the MCP SDK and Zod peer dependencies.
codeMcpServer()
interface CodeMcpServerOptions {
server: McpServer;
executor: Executor;
description?: string;
}
function codeMcpServer(options: CodeMcpServerOptions): Promise<McpServer>;
Wraps an existing MCP server with one code tool. The wrapper connects to the source server through an in-memory transport, discovers its tools, and exposes those tools as methods on codemode inside the executor.
A custom description can contain {{types}}, which the wrapper replaces with generated TypeScript declarations. It can also contain {{example}}, which the wrapper replaces with an example call based on the first upstream MCP tool. Returned MCP values are unwrapped in this order: compatibility toolResult, MCP errors, structuredContent, all-text content, then the original mixed-content result.
openApiMcpServer()
interface OpenApiMcpServerOptions {
spec: Record<string, unknown>;
executor: Executor;
request: (options: RequestOptions) => Promise<unknown>;
name?: string;
version?: string;
description?: string;
}
interface RequestOptions {
method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
path: string;
query?: Record<string, string | number | boolean | undefined>;
body?: unknown;
contentType?: string;
rawBody?: boolean;
}
function openApiMcpServer(options: OpenApiMcpServerOptions): McpServer;
Creates an MCP server with two tools:
| MCP tool | Sandbox API | Purpose |
|---|---|---|
search |
codemode.spec() |
Runs code against the OpenAPI document. Local $ref values are resolved before the code receives the document. |
execute |
codemode.spec() and codemode.request(options) |
Runs code that can inspect the document and call the host-provided request function. |
name defaults to openapi. version defaults to 1.0.0. The host request function keeps credentials outside the sandbox. Text responses are limited to approximately 6,000 tokens and include a truncation marker when clipped.
The search and execute tool descriptions use fixed example snippets. Unlike codeMcpServer(), this function does not support {{types}} or {{example}} placeholders. An optional description is appended to the execute tool description.
@cloudflare/codemode/tanstack-ai
This entry point requires the @tanstack/ai and zod peer dependencies.
createCodeTool()
function createCodeTool(options: CreateCodeToolOptions): ServerTool;
The options, CodeInput, and CodeOutput match the /ai entry point. The returned ServerTool can be passed to TanStack AI chat().
TanStack AI provider utilities
The TanStack AI entry point provides these tool-provider utilities:
| Export | Signature | Description |
|---|---|---|
tanstackTools |
(tools: TanStackTool[], name?: string) => ToolProvider |
Wraps TanStack AI tools in a provider. Only tools with an execute function are callable. The namespace defaults to codemode. |
generateTypes |
(tools: TanStackTool[], namespace?: string) => string |
Converts supported TanStack AI schemas to JSON Schema, then generates declarations. |
resolveProvider |
(provider: ToolProvider) => ResolvedProvider |
Resolves a framework-independent provider without schema validation. |
normalizeProviders |
(tools: ToolProviderTools \| ToolProvider[]) => ToolProvider[] |
Converts raw tools into a one-element provider array. |
This entry point also exports DEFAULT_DESCRIPTION. tanstackTools() excludes tools with needsApproval: true or a function-valued needsApproval. Tools with needsApproval: false remain callable.
@cloudflare/codemode/browser
The browser entry point uses browser APIs and plain JSON Schema. It does not require the AI SDK or Zod.
createBrowserCodeTool()
function createBrowserCodeTool(
options: CreateBrowserCodeToolOptions,
): BrowserCodeToolDescriptor;
interface CreateBrowserCodeToolOptions {
tools:
| JsonSchemaExecutableToolDescriptor[]
| JsonSchemaExecutableToolDescriptors;
executor?: Executor;
description?: string;
}
Array-form tools must include name. Object-form tools use each record key as the name. The executor defaults to a new IframeSandboxExecutor.
The tools option also accepts descriptors with needsApproval?: boolean | ((...args: unknown[]) => unknown). Tools with needsApproval: true or a function-valued needsApproval are excluded. Tools with needsApproval: false remain callable. JSON Schema contributes model-facing declarations but does not perform runtime validation.
interface JsonSchemaExecutableToolDescriptor extends JsonSchemaToolDescriptor {
name?: string;
execute: (args: Record<string, unknown>) => Promise<unknown>;
}
type JsonSchemaExecutableToolDescriptors = Record<
string,
JsonSchemaExecutableToolDescriptor
>;
The returned descriptor has this shape:
interface BrowserCodeToolDescriptor {
name: string;
description: string;
inputSchema: {
type: "object";
properties: {
code: { type: "string"; description: string };
};
required: ["code"];
};
outputSchema: {
type: "object";
properties: {
result: { description: string };
logs: {
type: "array";
items: { type: "string" };
description: string;
};
};
required: ["result"];
};
execute(args: CodeInput): Promise<CodeOutput>;
}
IframeSandboxExecutor
class IframeSandboxExecutor implements Executor {
constructor(options?: IframeSandboxExecutorOptions);
execute(
code: string,
providersOrFns:
| ResolvedProvider[]
| Record<string, (...args: unknown[]) => Promise<unknown>>,
): Promise<ExecuteResult>;
}
interface IframeSandboxExecutorOptions {
timeout?: number;
csp?: string;
}
The iframe executor accepts these options:
| Field | Default | Description |
|---|---|---|
timeout |
30000 |
Maximum execution time in milliseconds. It cannot preempt a synchronous loop that blocks the browser event loop. |
csp |
default-src 'none'; script-src 'unsafe-inline' 'unsafe-eval'; |
Content Security Policy applied to the sandbox iframe document. |
Each execution creates a hidden iframe with sandbox="allow-scripts". Tool calls cross the iframe boundary through nonce-scoped postMessage messages. The iframe is removed after success, error, or timeout.
This entry point also exports the framework-independent Executor, ExecuteResult, and ResolvedProvider types. It re-exports JsonSchemaToolDescriptor and JsonSchemaToolDescriptors.
@cloudflare/codemode/vite
The Vite entry point has one default export:
function codemodeVitePlugin(): Plugin;
The plugin appends export { CodemodeRuntime } from "@cloudflare/codemode" to the Worker entry module (src/server.ts, src/index.ts, or src/worker.ts). This makes the runtime facet available as ctx.exports.CodemodeRuntime, which createCodemodeRuntime() requires.
The plugin leaves the entry module unchanged if it already exports CodemodeRuntime. Connector classes need no special file name or import syntax — import them normally and pass instances to the runtime.
Without the plugin, add the export manually:
export { CodemodeRuntime } from "@cloudflare/codemode";
A connector import can target one connector file or a directory. A directory import re-exports every matching connector file under that directory.
Was this helpful?
YesNo
On this page
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/agents/tools/codemode/api-reference/#page","headline":"Code Mode API reference","description":"Reference the public classes, functions, options, runtime methods, connector hooks, and result types exported by Code Mode.","url":"https://developers.cloudflare.com/agents/tools/codemode/api-reference/","inLanguage":"en","image":"https://developers.cloudflare.com/agents/tools/codemode/api-reference/og.png?v=636a8f8bcc67342b","dateModified":"2026-07-22","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
description: Run model-generated code against browser-owned tools with the Code Mode iframe executor and an Agent chat UI. title: Browser integration image: https://developers.cloudflare.com/agents/tools/codemode/browser/og.png?v=19a85b03212792d4
Documentation Index
Fetch the complete documentation index at: https://developers.cloudflare.com/agents/llms.txt
Use this file to discover all available pages before exploring further.
Docs