Agents SDK
CloudflareOfficialPublished by Cloudflare
- Skill
- Tool integration
- Cloud and DevOps
- Apache-2.0
- No issues found
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill provides essential documentation and best practices for developing with the Cloudflare Agents SDK. It covers the full lifecycle of agent development, including state management, RPC communication via callable methods, durable execution, and background task scheduling. The resource is designed to help developers integrate agents into existing Workers applications, configure environments, and leverage advanced features like MCP integration, streaming chat, and experimental browser tools.
What it does
- Provides setup instructions for the agents package and project configuration.
- Explains how to implement persistent state and handle state updates.
- Details the use of @callable decorators for WebSocket-based RPC.
- Covers durable execution patterns like runFiber and background workflows.
- Guides the integration of chat agents, streaming responses, and MCP servers.
- Outlines observability, testing, and deployment configurations for agents.
When to use it
- When building stateful, event-driven agents on the Cloudflare Workers platform.
- When you need to expose agent methods to client applications via WebSocket RPC.
- When implementing durable, multi-step background tasks or scheduled cron jobs.
- When integrating external tools or MCP servers into your agentic workflows.
- When debugging agent lifecycle events or state synchronization issues.
Advantages
- Centralized access to official documentation and implementation patterns.
- Clear guidance on avoiding common pitfalls like incorrect decorator usage.
- Comprehensive coverage of both core APIs and experimental features.
- Structured reference for complex topics like durable execution and retries.
Usage examples
- “How do I define a callable method in my Cloudflare Agent?”
- The agent will show how to use the @callable decorator on a class method to expose it for WebSocket RPC, including examples for both standard and streaming responses.
- “What is the correct way to configure an agent in wrangler.jsonc?”
- The agent will provide a JSON configuration snippet showing the required compatibility flags, durable object bindings, and migration settings.
- “How can I persist state in my agent?”
- The agent will explain the use of the state object, the setState method, and how to implement validateStateChange for data integrity.
- “How do I run a background workflow in my agent?”
- The agent will demonstrate using the runWorkflow method to trigger durable, multi-step background processing tasks.
Install
Download the skill as a ZIP:
https://autogineer.com/agent-skills/cloudflare/agents-sdk/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip agents-sdk.zip -d .agents/skills
Documentation by Cloudflare
Cloudflare Agents SDK
Your knowledge of the Agents SDK may be outdated. Prefer retrieval over pre-training for any Agents SDK task.
Retrieval Sources
Cloudflare docs: https://developers.cloudflare.com/agents/index.md
| Topic | Docs URL | Use for |
|---|---|---|
| Getting started | Quick start | First agent, project setup |
| Adding to existing project | Add to existing project | Install into existing Workers app |
| Configuration | Configuration | wrangler.jsonc, bindings, assets, deployment |
| Agent class | Agents API | Agent lifecycle, patterns, pitfalls |
| State | Store and sync state | setState, validateStateChange, persistence |
| Routing | Routing | URL patterns, routeAgentRequest |
| Callable methods | Callable methods | @callable, RPC, streaming, timeouts |
| Scheduling | Schedule tasks | schedule(), scheduleEvery(), cron |
| Workflows | Run workflows | AgentWorkflow, durable multi-step tasks |
| HTTP/WebSockets | WebSockets | Lifecycle hooks, hibernation |
| Chat agents | Chat agents | AIChatAgent, streaming, tools, persistence |
| Client SDK | Client SDK | useAgent, AgentClient, state, RPC, HTTP |
| Client tools | Client tools | Client-side tools, autoContinueAfterToolResult |
| Server-driven messages | Autonomous responses | saveMessages, waitUntilStable, server-initiated turns |
| Resumable streaming | Chat agents | Stream recovery on disconnect |
| Email routing, secure reply resolver | ||
| MCP client | MCP client | Connecting to MCP servers |
| MCP server | MCP server | Building MCP servers with createMcpHandler |
| MCP transports | MCP transports | Streamable HTTP, SSE, RPC transport options |
| Securing MCP servers | Securing MCP | OAuth, proxy MCP, hardening |
| Human-in-the-loop | Human-in-the-loop | Workflow approvals, elicitation, timeout handling |
| Durable execution | Durable execution | runFiber(), stash(), surviving DO eviction |
| Queue | Queue | Built-in FIFO queue, queue() |
| Retries | Retries | this.retry(), backoff/jitter |
| Observability | Observability | Diagnostics-channel events |
| Push notifications | Push notifications | Web Push + VAPID from agents |
| Webhooks | Webhooks | Receiving external webhooks |
| Cross-domain auth | Cross-domain auth | WebSocket auth, tokens, CORS |
| Readonly connections | Readonly | shouldConnectionBeReadonly |
| Voice | Voice | Experimental STT/TTS, withVoice |
| Browse the web | Browser tools | Experimental CDP browser automation |
| Think | Think | Experimental higher-level chat agent class |
| Migrations | AI SDK v5, AI SDK v6 | Upgrading @cloudflare/ai-chat |
Capabilities
The Agents SDK provides:
Persistent state — SQLite-backed, auto-synced to clients via
setStateCallable RPC —
@callable()methods invoked over WebSocketScheduling — One-time, recurring (
scheduleEvery), and cron tasksWorkflows — Durable multi-step background processing via
AgentWorkflowDurable execution —
runFiber()/stash()for work that survives DO evictionQueue — Built-in FIFO queue with retries via
queue()Retries —
this.retry()with exponential backoff and jitterMCP integration — Connect to MCP servers or build your own with
createMcpHandlerEmail handling — Receive and reply to emails with secure routing
Streaming chat —
AIChatAgentwith resumable streams, message persistence, toolsServer-driven messages —
saveMessages,waitUntilStablefor proactive agent turnsReact hooks —
useAgent,useAgentChatfor client appsObservability —
diagnostics_channelevents for state, RPC, schedule, lifecyclePush notifications — Web Push + VAPID delivery from agents
Webhooks — Receive and verify external webhooks
Voice (experimental) — STT/TTS via
@cloudflare/voiceBrowser tools (experimental) — CDP-powered browsing via
agents/browserThink (experimental) — Higher-level chat agent via
@cloudflare/think
FIRST: Verify Installation
npm ls agents # Should show agents packageIf not installed:
npm install agentsFor chat agents:
npm install agents @cloudflare/ai-chat ai @ai-sdk/reactWrangler Configuration
{
"compatibility_flags": ["nodejs_compat"],
"durable_objects": {
"bindings": [{ "name": "MyAgent", "class_name": "MyAgent" }]
},
"migrations": [{ "tag": "v1", "new_sqlite_classes": ["MyAgent"] }]
}Gotchas:
Do NOT enable
experimentalDecoratorsin tsconfig (breaks@callable)Never edit old migrations — always add new tags
Each agent class needs its own DO binding + migration entry
Add
"ai": { "binding": "AI" }for Workers AI
Agent Class
import { Agent, routeAgentRequest, callable } from "agents";
type State = { count: number };
export class Counter extends Agent<Env, State> {
initialState = { count: 0 };
validateStateChange(nextState: State, source: Connection | "server") {
if (nextState.count < 0) throw new Error("Count cannot be negative");
}
onStateUpdate(state: State, source: Connection | "server") {
console.log("State updated:", state);
}
@callable()
increment() {
this.setState({ count: this.state.count + 1 });
return this.state.count;
}
}
export default {
fetch: (req, env) => routeAgentRequest(req, env) ?? new Response("Not found", { status: 404 })
};Routing
Requests route to /agents/{agent-name}/{instance-name}:
| Class | URL |
|---|---|
Counter | /agents/counter/user-123 |
ChatRoom | /agents/chat-room/lobby |
Client: useAgent({ agent: "Counter", name: "user-123" })
Custom routing: use getAgentByName(env.MyAgent, "instance-id") then agent.fetch(request).
Core APIs
| Task | API |
|---|---|
| Read state | this.state.count |
| Write state | this.setState({ count: 1 }) |
| SQL query | this.sql`SELECT * FROM users WHERE id = ${id}` |
| Schedule (delay) | await this.schedule(60, "task", payload) |
| Schedule (cron) | await this.schedule("0 * * * *", "task", payload) |
| Schedule (interval) | await this.scheduleEvery(30, "poll") |
| RPC method | @callable() myMethod() { ... } |
| Streaming RPC | @callable({ streaming: true }) stream(res) { ... } |
| Start workflow | await this.runWorkflow("ProcessingWorkflow", params) |
| Durable fiber | await this.runFiber("name", async (ctx) => { ... }) |
| Enqueue work | this.queue("handler", payload) |
| Retry with backoff | await this.retry(fn, { maxAttempts: 5 }) |
| Broadcast to clients | this.broadcast(message) |
| Get connections | this.getConnections(tag?) |
React Client
Read client-sdk.md for client selection and current connection examples. For chat UI and tools, also read streaming-chat.md.
References
Core
references/state-scheduling.md — State persistence, scheduling, SQL
references/callable.md — RPC methods, streaming, timeouts
references/routing.md — URL patterns, custom routing,
getAgentByNamereferences/configuration.md — Wrangler config, bindings, Vite setup
Chat & Streaming
references/streaming-chat.md — AIChatAgent, resumable streams, tools
references/client-sdk.md —
useAgent,useAgentChat,AgentClientreferences/server-driven-messages.md — Trigger patterns,
saveMessagesreferences/human-in-the-loop.md — Approval flows,
needsApproval
Background Processing
references/workflows.md — Durable Workflows integration
references/durable-execution.md —
runFiber,stash, surviving evictionreferences/queue-retries.md — Built-in queue, retry with backoff
Integrations
references/mcp.md — MCP client and server, transports, securing
references/email.md — Email routing and handling
references/webhooks-push.md — Webhooks, push notifications
references/observability.md — Diagnostics-channel events
Experimental
references/think.md —
@cloudflare/thinkhigher-level chat agentreferences/voice.md —
@cloudflare/voiceSTT/TTSreferences/codemode.md — Code Mode for tool orchestration
references/browse-the-web.md — CDP browser tools
Skill feedback
If the user reports that this skill gave incorrect or outdated guidance, or is missing information, read references/skill-feedback.md.
Files
- ATTRIBUTION.mdAdded by AutoGineer856 B
- LICENSELicence file added by AutoGineer11.1 KiB
- SKILL.md12.0 KiB
- references/browse-the-web.md1.6 KiB
- references/callable.md2.1 KiB
- references/client-sdk.md1.2 KiB
- references/codemode.md2.8 KiB
- references/configuration.md1.8 KiB
- references/durable-execution.md1.7 KiB
- references/email.md3.5 KiB
- references/human-in-the-loop.md929 B
- references/mcp.md1.3 KiB
- references/observability.md1.3 KiB
- references/queue-retries.md1.4 KiB
- references/routing.md1.8 KiB
- references/server-driven-messages.md868 B
- references/skill-feedback.md2.7 KiB
- references/state-scheduling.md1.5 KiB
- references/streaming-chat.md1.4 KiB
- references/think.md2.9 KiB
- references/voice.md1.9 KiB
- references/webhooks-push.md2.4 KiB
- references/workflows.md2.3 KiB
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Needs an MCP server, Needs Node.js
Security
No issues found by our static scan· No issues found
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Published by
- Cloudflare
- Publisher
- Cloudflare (Official)
- Source
- cloudflare/skills · skills/agents-sdk · commit 6eb6c78
- Licence
- Apache License 2.0 (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by Cloudflare or Cloudflare.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download agents-sdk.zip