Convert MCP tools into TypeScript APIs that LLMs can orchestrate through generated code instead of direct tool calls. Enables complex workflows with error handling and multi-step operations.
Transform your MCP servers and tools into TypeScript APIs that LLMs can orchestrate through executable code generation. Instead of asking LLMs to call tools directly, Code Mode lets them write code that chains multiple operations naturally.
This skill guides you through implementing Code Mode with the `@cloudflare/codemode` package. Code Mode converts tools (especially MCP servers) into TypeScript APIs, enabling:
**Key Insight:** LLMs are better at writing code than calling tools - they've seen millions of lines of real-world TypeScript but only contrived tool-calling examples.
Install the required packages:
```bash
npm install @cloudflare/codemode agents ai
```
Add the required bindings to your `wrangler.toml`:
```toml
compatibility_flags = ["experimental", "enable_ctx_exports"]
[[worker_loaders]]
binding = "LOADER"
[[services]]
binding = "globalOutbound"
service = "your-service"
entrypoint = "globalOutbound"
[[services]]
binding = "CodeModeProxy"
service = "your-service"
entrypoint = "CodeModeProxy"
```
In your worker file, export the required services:
```typescript
// Network access control
export const globalOutbound = {
fetch: async (input: string | URL | RequestInfo, init?: RequestInit) => {
const url = new URL(typeof input === "string" ? input : input.toString());
// Add your security policies here
if (url.hostname === "blocked-domain.com") {
return new Response("Not allowed", { status: 403 });
}
return fetch(input, init);
}
};
// Tool execution proxy
export { CodeModeProxy } from "@cloudflare/codemode/ai";
```
Define your tools using the standard Vercel AI SDK format:
```typescript
import { tool } from "ai";
import { z } from "zod";
const tools = {
getWeather: tool({
description: "Get weather for a location",
inputSchema: z.object({ location: z.string() }),
execute: async ({ location }) => {
return `Weather in ${location}: 72°F, sunny`;
}
}),
sendEmail: tool({
description: "Send an email",
inputSchema: z.object({
to: z.string(),
subject: z.string(),
body: z.string()
}),
execute: async ({ to, subject, body }) => {
// Send email logic
return `Email sent to ${to}`;
}
})
};
```
Apply Code Mode to your tools:
```typescript
import { experimental_codemode as codemode } from "@cloudflare/codemode/ai";
import { streamText } from "ai";
import { openai } from "@ai-sdk/openai";
const { prompt, tools: wrappedTools } = await codemode({
prompt: "You are a helpful assistant...",
tools,
globalOutbound: env.globalOutbound,
loader: env.LOADER,
proxy: this.ctx.exports.CodeModeProxy({
props: {
binding: "MyAgent",
name: this.name,
callback: "callTool"
}
})
});
const result = streamText({
model: openai("gpt-4o"),
system: prompt,
messages,
tools: wrappedTools // Now a single "codemode" tool
});
```
Create the callback method that Code Mode uses to execute tools:
```typescript
callTool(functionName: string, args: unknown[]) {
return this.tools[functionName]?.execute?.(args, {
abortSignal: new AbortController().signal,
toolCallId: "codemode",
messages: []
});
}
```
If using MCP servers, merge them with your regular tools:
```typescript
const allTools = {
...regularTools,
...this.mcp.getAITools() // Include MCP tools
};
const { prompt, tools: wrappedTools } = await codemode({
prompt: "You are a helpful assistant...",
tools: allTools,
// ... rest of config
});
```
Complete implementation with the `agents` framework:
```typescript
import { Agent } from "agents";
import { experimental_codemode as codemode } from "@cloudflare/codemode/ai";
import { streamText, convertToModelMessages } from "ai";
import { openai } from "@ai-sdk/openai";
export class CodeModeAgent extends Agent<Env> {
async onChatMessage() {
const allTools = {
...regularTools,
...this.mcp.getAITools()
};
const { prompt, tools: wrappedTools } = await codemode({
prompt: "You are a helpful assistant...",
tools: allTools,
globalOutbound: env.globalOutbound,
loader: env.LOADER,
proxy: this.ctx.exports.CodeModeProxy({
props: {
binding: "CodeModeAgent",
name: this.name,
callback: "callTool"
}
})
});
const result = streamText({
model: openai("gpt-4o"),
system: prompt,
messages: await convertToModelMessages(this.messages),
tools: wrappedTools
});
return result.toUIMessageStreamResponse();
}
callTool(functionName: string, args: unknown[]) {
return this.tools[functionName]?.execute?.(args, {
abortSignal: new AbortController().signal,
toolCallId: "codemode",
messages: []
});
}
}
export { CodeModeProxy } from "@cloudflare/codemode/ai";
```
1. **Tool Wrapping**: Code Mode converts your tools into a single "codemode" tool
2. **Code Generation**: The LLM generates executable TypeScript code that orchestrates your tools
3. **Secure Execution**: Code runs in isolated Workers with millisecond startup times
4. **Tool Callbacks**: Generated code calls back to your agent via the proxy to execute actual tools
The LLM might generate code like this to orchestrate multiple operations:
```javascript
async function executeTask() {
const files = await codemode.listFiles({ path: "/projects" });
const recentProject = files
.filter((f) => f.type === "directory")
.sort((a, b) => new Date(b.modified) - new Date(a.modified))[0];
const projectStatus = await codemode.queryDatabase({
query: "SELECT * FROM projects WHERE name = ?",
params: [recentProject.name]
});
if (projectStatus.length === 0 || projectStatus[0].status === "incomplete") {
await codemode.createTask({
title: `Review project: ${recentProject.name}`,
priority: "high"
});
await codemode.sendEmail({
to: "[email protected]",
subject: "Project Review Needed"
});
}
return { success: true, project: recentProject };
}
```
**Simple transformation:**
```bash
"Convert my weather and email tools to use Code Mode"
```
**With MCP integration:**
```bash
"Set up Code Mode for my agent with MCP filesystem tools"
```
**Adding security policies:**
```bash
"Configure Code Mode with network restrictions for production domains"
```
Leave a review
No reviews yet. Be the first to review this skill!
# Download SKILL.md from killerskills.ai/api/skills/code-mode-better-mcp-tool-usage/raw