Cloudflare Agents SDK
STOP. Your knowledge of the Agents SDK may be outdated. Prefer retrieval over pre-training for any Agents SDK task.
Documentation
Fetch current docs from https://github.com/cloudflare/agents/tree/main/docs before implementing.
| Topic |
Doc |
Use for |
| Getting started |
docs/getting-started.md |
First agent, project setup |
| State |
docs/state.md |
setState, validateStateChange, persistence |
| Routing |
docs/routing.md |
URL patterns, routeAgentRequest, basePath |
| Callable methods |
docs/callable-methods.md |
@callable, RPC, streaming, timeouts |
| Scheduling |
docs/scheduling.md |
schedule(), scheduleEvery(), cron |
| Workflows |
docs/workflows.md |
AgentWorkflow, durable multi-step tasks |
| HTTP/WebSockets |
docs/http-websockets.md |
Lifecycle hooks, hibernation |
| Email |
docs/email.md |
Email routing, secure reply resolver |
| MCP client |
docs/mcp-client.md |
Connecting to MCP servers |
| MCP server |
docs/mcp-servers.md |
Building MCP servers with McpAgent |
| Client SDK |
docs/client-sdk.md |
useAgent, useAgentChat, React hooks |
| Human-in-the-loop |
docs/human-in-the-loop.md |
Approval flows, pausing workflows |
| Resumable streaming |
docs/resumable-streaming.md |
Stream recovery on disconnect |
Cloudflare docs: https://developers.cloudflare.com/agents/
Capabilities
The Agents SDK provides:
- Persistent state - SQLite-backed, auto-synced to clients
- Callable RPC -
@callable() methods invoked over WebSocket
- Scheduling - One-time, recurring (
scheduleEvery), and cron tasks
- Workflows - Durable multi-step background processing via
AgentWorkflow
- MCP integration - Connect to MCP servers or build your own with
McpAgent
- Email handling - Receive and reply to emails with secure routing
- Streaming chat -
AIChatAgent with resumable streams
- React hooks -
useAgent, useAgentChat for client apps
FIRST: Verify Installation
npm ls agents # Should show agents package
If not installed:
npm install agents
Wrangler Configuration
{
"durable_objects": {
"bindings": [{ "name": "MyAgent", "class_name": "MyAgent" }],
},
"migrations": [{ "tag": "v1", "new_sqlite_classes": ["MyAgent"] }],
}
Agent Class
import { Agent, routeAgentRequest, callable } from "agents"
type State = { count: number }
export class Counter extends Agent<Env, State> {
initialState = { count: 0 }
// Validation hook - runs before state persists (sync, throwing rejects the update)
validateStateChange(nextState: State, source: Connection | "server") {
if (nextState.count < 0) throw new Error("Count cannot be negative")
}
// Notification hook - runs after state persists (async, non-blocking)
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" })
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) |
React Client
import { useAgent } from "agents/react"
function App() {
const [state, setLocalState] = useState({ count: 0 })
const agent = useAgent({
agent: "Counter",
name: "my-instance",
onStateUpdate: (newState) => setLocalState(newState),
onIdentity: (name, agentType) => console.log(`Connected to ${name}`),
})
return <button => agent.setState({ count: state.count + 1 })}>Count: {state.count}</button>
}
References
- references/workflows.md - Durable Workflows integration
- references/callable.md - RPC methods, streaming, timeouts
- references/state-scheduling.md - State persistence, scheduling
- references/streaming-chat.md - AIChatAgent, resumable streams
- references/mcp.md - MCP server integration
- references/email.md - Email routing and handling
- references/codemode.md - Code Mode (experimental)
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.4metadata:5 source: https://skillmd.com/skills/peteedoo/agents-sdk6---78# Cloudflare Agents SDK910**STOP.** Your knowledge of the Agents SDK may be outdated. Prefer retrieval over pre-training for any Agents SDK task.1112## Documentation1314Fetch current docs from `https://github.com/cloudflare/agents/tree/main/docs` before implementing.1516| Topic | Doc | Use for |17| ------------------- | ----------------------------- | ---------------------------------------------- |18| Getting started | `docs/getting-started.md` | First agent, project setup |19| State | `docs/state.md` | `setState`, `validateStateChange`, persistence |20| Routing | `docs/routing.md` | URL patterns, `routeAgentRequest`, `basePath` |21| Callable methods | `docs/callable-methods.md` | `@callable`, RPC, streaming, timeouts |22| Scheduling | `docs/scheduling.md` | `schedule()`, `scheduleEvery()`, cron |23| Workflows | `docs/workflows.md` | `AgentWorkflow`, durable multi-step tasks |24| HTTP/WebSockets | `docs/http-websockets.md` | Lifecycle hooks, hibernation |25| Email | `docs/email.md` | Email routing, secure reply resolver |26| MCP client | `docs/mcp-client.md` | Connecting to MCP servers |27| MCP server | `docs/mcp-servers.md` | Building MCP servers with `McpAgent` |28| Client SDK | `docs/client-sdk.md` | `useAgent`, `useAgentChat`, React hooks |29| Human-in-the-loop | `docs/human-in-the-loop.md` | Approval flows, pausing workflows |30| Resumable streaming | `docs/resumable-streaming.md` | Stream recovery on disconnect |3132Cloudflare docs: https://developers.cloudflare.com/agents/3334## Capabilities3536The Agents SDK provides:3738- **Persistent state** - SQLite-backed, auto-synced to clients39- **Callable RPC** - `@callable()` methods invoked over WebSocket40- **Scheduling** - One-time, recurring (`scheduleEvery`), and cron tasks41- **Workflows** - Durable multi-step background processing via `AgentWorkflow`42- **MCP integration** - Connect to MCP servers or build your own with `McpAgent`43- **Email handling** - Receive and reply to emails with secure routing44- **Streaming chat** - `AIChatAgent` with resumable streams45- **React hooks** - `useAgent`, `useAgentChat` for client apps4647## FIRST: Verify Installation4849```bash50npm ls agents # Should show agents package51```5253If not installed:5455```bash56npm install agents57```5859## Wrangler Configuration6061```jsonc62{63 "durable_objects": {64 "bindings": [{ "name": "MyAgent", "class_name": "MyAgent" }],65 },66 "migrations": [{ "tag": "v1", "new_sqlite_classes": ["MyAgent"] }],67}68```6970## Agent Class7172```typescript73import { Agent, routeAgentRequest, callable } from "agents"7475type State = { count: number }7677export class Counter extends Agent<Env, State> {78 initialState = { count: 0 }7980 // Validation hook - runs before state persists (sync, throwing rejects the update)81 validateStateChange(nextState: State, source: Connection | "server") {82 if (nextState.count < 0) throw new Error("Count cannot be negative")83 }8485 // Notification hook - runs after state persists (async, non-blocking)86 onStateUpdate(state: State, source: Connection | "server") {87 console.log("State updated:", state)88 }8990 @callable()91 increment() {92 this.setState({ count: this.state.count + 1 })93 return this.state.count94 }95}9697export default {98 fetch: (req, env) => routeAgentRequest(req, env) ?? new Response("Not found", { status: 404 }),99}100```101102## Routing103104Requests route to `/agents/{agent-name}/{instance-name}`:105106| Class | URL |107| ---------- | -------------------------- |108| `Counter` | `/agents/counter/user-123` |109| `ChatRoom` | `/agents/chat-room/lobby` |110111Client: `useAgent({ agent: "Counter", name: "user-123" })`112113## Core APIs114115| Task | API |116| ------------------- | ------------------------------------------------------ |117| Read state | `this.state.count` |118| Write state | `this.setState({ count: 1 })` |119| SQL query | `` this.sql`SELECT * FROM users WHERE id = ${id}` `` |120| Schedule (delay) | `await this.schedule(60, "task", payload)` |121| Schedule (cron) | `await this.schedule("0 * * * *", "task", payload)` |122| Schedule (interval) | `await this.scheduleEvery(30, "poll")` |123| RPC method | `@callable() myMethod() { ... }` |124| Streaming RPC | `@callable({ streaming: true }) stream(res) { ... }` |125| Start workflow | `await this.runWorkflow("ProcessingWorkflow", params)` |126127## React Client128129```tsx130import { useAgent } from "agents/react"131132function App() {133 const [state, setLocalState] = useState({ count: 0 })134135 const agent = useAgent({136 agent: "Counter",137 name: "my-instance",138 onStateUpdate: (newState) => setLocalState(newState),139 onIdentity: (name, agentType) => console.log(`Connected to ${name}`),140 })141142 return <button onClick={() => agent.setState({ count: state.count + 1 })}>Count: {state.count}</button>143}144```145146## References147148- **[references/workflows.md](references/workflows.md)** - Durable Workflows integration149- **[references/callable.md](references/callable.md)** - RPC methods, streaming, timeouts150- **[references/state-scheduling.md](references/state-scheduling.md)** - State persistence, scheduling151- **[references/streaming-chat.md](references/streaming-chat.md)** - AIChatAgent, resumable streams152- **[references/mcp.md](references/mcp.md)** - MCP server integration153- **[references/email.md](references/email.md)** - Email routing and handling154- **[references/codemode.md](references/codemode.md)** - Code Mode (experimental)