Build 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.
Add this skill
npx mdskills install cloudflare/agents-sdkComprehensive SDK guide with clear routing, state management, and integration examples
1---2name: agents-sdk3description: Build 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.4---56# Cloudflare Agents SDK78**STOP.** Your knowledge of the Agents SDK may be outdated. Prefer retrieval over pre-training for any Agents SDK task.910## Documentation1112Fetch current docs from `https://github.com/cloudflare/agents/tree/main/docs` before implementing.1314| Topic | Doc | Use for |15|-------|-----|---------|16| Getting started | `docs/getting-started.md` | First agent, project setup |17| State | `docs/state.md` | `setState`, `validateStateChange`, persistence |18| Routing | `docs/routing.md` | URL patterns, `routeAgentRequest`, `basePath` |19| Callable methods | `docs/callable-methods.md` | `@callable`, RPC, streaming, timeouts |20| Scheduling | `docs/scheduling.md` | `schedule()`, `scheduleEvery()`, cron |21| Workflows | `docs/workflows.md` | `AgentWorkflow`, durable multi-step tasks |22| HTTP/WebSockets | `docs/http-websockets.md` | Lifecycle hooks, hibernation |23| Email | `docs/email.md` | Email routing, secure reply resolver |24| MCP client | `docs/mcp-client.md` | Connecting to MCP servers |25| MCP server | `docs/mcp-servers.md` | Building MCP servers with `McpAgent` |26| Client SDK | `docs/client-sdk.md` | `useAgent`, `useAgentChat`, React hooks |27| Human-in-the-loop | `docs/human-in-the-loop.md` | Approval flows, pausing workflows |28| Resumable streaming | `docs/resumable-streaming.md` | Stream recovery on disconnect |2930Cloudflare docs: https://developers.cloudflare.com/agents/3132## Capabilities3334The Agents SDK provides:3536- **Persistent state** - SQLite-backed, auto-synced to clients37- **Callable RPC** - `@callable()` methods invoked over WebSocket38- **Scheduling** - One-time, recurring (`scheduleEvery`), and cron tasks39- **Workflows** - Durable multi-step background processing via `AgentWorkflow`40- **MCP integration** - Connect to MCP servers or build your own with `McpAgent`41- **Email handling** - Receive and reply to emails with secure routing42- **Streaming chat** - `AIChatAgent` with resumable streams43- **React hooks** - `useAgent`, `useAgentChat` for client apps4445## FIRST: Verify Installation4647```bash48npm ls agents # Should show agents package49```5051If not installed:52```bash53npm install agents54```5556## Wrangler Configuration5758```jsonc59{60 "durable_objects": {61 "bindings": [{ "name": "MyAgent", "class_name": "MyAgent" }]62 },63 "migrations": [{ "tag": "v1", "new_sqlite_classes": ["MyAgent"] }]64}65```6667## Agent Class6869```typescript70import { Agent, routeAgentRequest, callable } from "agents";7172type State = { count: number };7374export class Counter extends Agent<Env, State> {75 initialState = { count: 0 };7677 // Validation hook - runs before state persists (sync, throwing rejects the update)78 validateStateChange(nextState: State, source: Connection | "server") {79 if (nextState.count < 0) throw new Error("Count cannot be negative");80 }8182 // Notification hook - runs after state persists (async, non-blocking)83 onStateUpdate(state: State, source: Connection | "server") {84 console.log("State updated:", state);85 }8687 @callable()88 increment() {89 this.setState({ count: this.state.count + 1 });90 return this.state.count;91 }92}9394export default {95 fetch: (req, env) => routeAgentRequest(req, env) ?? new Response("Not found", { status: 404 })96};97```9899## Routing100101Requests route to `/agents/{agent-name}/{instance-name}`:102103| Class | URL |104|-------|-----|105| `Counter` | `/agents/counter/user-123` |106| `ChatRoom` | `/agents/chat-room/lobby` |107108Client: `useAgent({ agent: "Counter", name: "user-123" })`109110## Core APIs111112| Task | API |113|------|-----|114| Read state | `this.state.count` |115| Write state | `this.setState({ count: 1 })` |116| SQL query | `` this.sql`SELECT * FROM users WHERE id = ${id}` `` |117| Schedule (delay) | `await this.schedule(60, "task", payload)` |118| Schedule (cron) | `await this.schedule("0 * * * *", "task", payload)` |119| Schedule (interval) | `await this.scheduleEvery(30, "poll")` |120| RPC method | `@callable() myMethod() { ... }` |121| Streaming RPC | `@callable({ streaming: true }) stream(res) { ... }` |122| Start workflow | `await this.runWorkflow("ProcessingWorkflow", params)` |123124## React Client125126```tsx127import { useAgent } from "agents/react";128129function App() {130 const [state, setLocalState] = useState({ count: 0 });131132 const agent = useAgent({133 agent: "Counter",134 name: "my-instance",135 onStateUpdate: (newState) => setLocalState(newState),136 onIdentity: (name, agentType) => console.log(`Connected to ${name}`)137 });138139 return (140 <button onClick={() => agent.setState({ count: state.count + 1 })}>141 Count: {state.count}142 </button>143 );144}145```146147## References148149- **[references/workflows.md](references/workflows.md)** - Durable Workflows integration150- **[references/callable.md](references/callable.md)** - RPC methods, streaming, timeouts151- **[references/state-scheduling.md](references/state-scheduling.md)** - State persistence, scheduling152- **[references/streaming-chat.md](references/streaming-chat.md)** - AIChatAgent, resumable streams153- **[references/mcp.md](references/mcp.md)** - MCP server integration154- **[references/email.md](references/email.md)** - Email routing and handling155- **[references/codemode.md](references/codemode.md)** - Code Mode (experimental)156
Full transparency — inspect the skill content before installing.