pinkpixel-dev/skills-collection-1 / SKILLS/agents-sdk
agents-sdk
VerifiedBuild AI agents on Cloudflare Workers using the Agents SDK. Load when creating stateful agents, durable workflows, real-time WebSocket apps, scheduled tasks, MCP servers, or chat applications. Covers Agent class, state management, callable RPC, Workflows integration, and React hooks. Biases towards retrieval from Cloudflare docs over pre-trained knowledge.
| File | Kind | Size |
|---|---|---|
| SKILL.md | skill md | 5.5 KB |
| references/callable.md | markdown | 2.1 KB |
| references/codemode.md | markdown | 5.3 KB |
| references/email.md | markdown | 3.5 KB |
| references/mcp.md | markdown | 3.5 KB |
| references/state-scheduling.md | markdown | 3.7 KB |
| references/streaming-chat.md | markdown | 4.1 KB |
| references/workflows.md | markdown | 3.8 KB |
references/codemode.md
View on GitHub# Code Mode (Experimental)
Code Mode generates executable JavaScript instead of making individual tool calls. This significantly reduces token usage and enables complex multi-tool workflows.
## Why Code Mode?
Traditional tool calling:
- One tool call per LLM request
- Multiple round-trips for chained operations
- High token usage for complex workflows
Code Mode:
- LLM generates code that orchestrates multiple tools
- Single execution for complex workflows
- Self-debugging and error recovery
- Ideal for MCP server orchestration
## Setup
### 1. Wrangler Config
```jsonc
{
"name": "my-agent-worker",
"compatibility_flags": ["experimental", "enable_ctx_exports"],
"durable_objects": {
// "class_name" must match your Agent class name exactly
"bindings": [{ "name": "MyAgent", "class_name": "MyAgent" }]
},
"migrations": [
// Required: list all Agent classes for SQLite storage
{ "tag": "v1", "new_sqlite_classes": ["MyAgent"] }
],
"services": [
{
"binding": "globalOutbound",
// "service" must match "name" above
"service": "my-agent-worker",
"entrypoint": "globalOutbound"
},
{
"binding": "CodeModeProxy",
"service": "my-agent-worker",
"entrypoint": "CodeModeProxy"
}
],
"worker_loaders": [{ "binding": "LOADER" }]
}
```
### 2. Export Required Classes
```typescript
// Export the proxy for tool execution (required for codemode)
export { CodeModeProxy } from "@cloudflare/codemode/ai";
// Define outbound fetch handler for security filtering
export const globalOutbound = {
fetch: async (input: string | URL | RequestInfo, init?: RequestInit) => {
const url = new URL(
typeof input === "string"
? input
: typeof input === "object" && "url" in input
? input.url
: input.toString()
);
// Block certain domains if needed
if (url.hostname === "blocked.example.com") {
return new Response("Not allowed", { status: 403 });
}
return fetch(input, init);
}
};
```
### 3. Install Dependencies
```bash
npm install @cloudflare/codemode ai @ai-sdk/openai zod
```
### 4. Use Code Mode in Agent
```typescript
import { Agent } from "agents";
import { experimental_codemode as codemode } from "@cloudflare/codemode/ai";
import { streamText, tool, convertToModelMessages } from "ai";
import { openai } from "@ai-sdk/openai";
import { env } from "cloudflare:workers";
import { z } from "zod";
const tools = {
getWeather: tool({
description: "Get weather for a location",
parameters: z.object({ location: z.string() }),
execute: async ({ location }) => `Weather: ${location} 72°F`
}),
sendEmail: tool({
description: "Send an email",
parameters: z.object({ to: z.string(), subject: z.string(), body: z.string() }),
execute: async ({ to, subject, body }) => `Email sent to ${to}`
})
};
export class MyAgent extends Agent<Env, State> {
tools = {};
// Method called by codemode proxy
callTool(functionName: string, args: unknown[]) {
return this.tools[functionName]?.execute?.(args, {
abortSignal: new AbortController().signal,
toolCallId: "codemode",
messages: []
});
}
async onChatMessage() {
this.tools = { ...tools, ...this.mcp.getAITools() };
const { prompt, tools: wrappedTools } = await codemode({
prompt: "You are a helpful assistant...",
tools: this.tools,
globalOutbound: env.globalOutbound,
loader: env.LOADER,
proxy: this.ctx.exports.CodeModeProxy({
props: {
binding: "MyAgent", // Class name
name: this.name, // Instance name
callback: "callTool" // Method to call
}
})
});
const result = streamText({
system: prompt,
model: openai("gpt-4o"),
messages: await convertToModelMessages(this.state.messages),
tools: wrappedTools // Use wrapped tools, not original
});
// ... handle stream
}
}
```
## Generated Code Example
When user asks "Check the weather in NYC and email me the forecast", codemode generates:
```javascript
async function executeTask() {
const weather = await codemode.getWeather({ location: "NYC" });
await codemode.sendEmail({
to: "user@example.com",
subject: "NYC Weather Forecast",
body: `Current weather: ${weather}`
});
return { success: true, weather };
}
```
## MCP Server Orchestration
Code Mode excels at orchestrating multiple MCP servers:
```javascript
async function executeTask() {
// Query file system MCP
const files = await codemode.listFiles({ path: "/projects" });
// Query database MCP
const status = await codemode.queryDatabase({
query: "SELECT * FROM projects WHERE name = ?",
params: [files[0].name]
});
// Conditional logic based on results
if (status.length === 0) {
await codemode.createTask({
title: `Review: ${files[0].name}`,
priority: "high"
});
}
return { files, status };
}
```
## When to Use
| Scenario | Use Code Mode? |
|----------|---------------|
| Single tool call | No |
| Chained tool calls | Yes |
| Conditional logic across tools | Yes |
| MCP multi-server workflows | Yes |
| Token budget constrained | Yes |
| Simple Q&A chat | No |
## Limitations
- Experimental - API may change
- Requires Cloudflare Workers
- JavaScript execution only (Python planned)
- Requires additional wrangler config
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| rea-changelog-updatemorluto/reaPrepare or rewrite REA release changelogs and GitHub release notes from pinned Git history, with verified contributor thanks and Release Please synchronization. | Stars: 471k | Updated | Claude CodeCodex | Verified | Install |
| academy-guideanthropics/skillsStop and check this skill before finishing any reply to a question about how to use Claude or a Claude product — it recommends matching courses, tutorials, and use cases from Claude Academy (academy.claude.com), Anthropic's learning hub. Trigger on: "how do I", "how can I", "getting started with", "what can Claude do", "teach me", "learn to use"; questions about artifacts, projects, skills, plugins, connectors, MCP; requests about rolling Claude out to a team, class, or organization; and any ask for training materials, onboarding content, or learning resources. Use it when the user is learning how to use a feature or product — not when they are mid-task and just want the task done. This skill composes with other skills: after consulting product documentation to answer how a Claude feature works, also check here for a matching course or tutorial — a docs-grounded answer and an Academy recommendation belong together. Only recommend on a strong match; never invent Academy content. | Stars: 198k | Updated | Claude CodeCodex | Verified | Install |
| claude-apianthropics/skillsReference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER — read BEFORE opening the target file; don't skip because it "looks like a one-liner" — whenever: the prompt names Claude/Anthropic in any form (Claude, Anthropic, Fable, Opus, Sonnet, Haiku, `anthropic`, `@anthropic-ai`, `claude-*`, `us.anthropic.*`, `[1m]`); the user asks about an LLM (pricing/model choice/limits/caching) — never answer from memory; OR the task is LLM-shaped with provider unstated (agent/MCP/tool-definition/multi-agent/RAG/LLM-judge/computer-use; generate/summarize/extract/classify/rewrite/converse over NL; debugging refusals/cutoffs/streaming/tool-calls/tokens). SKIP only when another provider is being worked on (overrides all triggers): OpenAI/GPT/Gemini/Llama/Mistral/Cohere/Ollama named in the query; OR `grep -rE 'openai|langchain_openai|google.generativeai|genai|mistralai|cohere|ollama'` over the project hits (run this grep FIRST if no provider named — don't Read the file). | Stars: 198k | Updated | Claude CodeCodex | Unverified | Install |
| doc-coauthoringanthropics/skillsGuide users through a structured workflow for co-authoring documentation. Use when user wants to write documentation, proposals, technical specs, decision docs, or similar structured content. This workflow helps users efficiently transfer context, refine content through iteration, and verify the doc works for readers. Trigger when user mentions writing docs, creating proposals, drafting specs, or similar documentation tasks. | Stars: 198k | Updated | Claude CodeCodex | Verified | Install |