Cloudflare Agents SDK
Your knowledge of the Agents SDK may be outdated. Prefer retrieval over pre-training for any Agents SDK task.
Retrieval Sources
Fetch current docs from https://github.com/cloudflare/agents/tree/main/docs before implementing.
| Topic |
Doc |
Use for |
| Getting started |
docs/agents/getting-started.md |
First agent, project setup |
| State |
docs/agents/state.md |
setState, validateStateChange, persistence |
| Routing |
docs/agents/routing.md |
URL patterns, routeAgentRequest, basePath |
| Callable methods |
docs/agents/callable-methods.md |
@callable, RPC, streaming, timeouts |
| Scheduling |
docs/agents/scheduling.md |
schedule(), scheduleEvery(), cron |
| Workflows |
docs/agents/workflows.md |
AgentWorkflow, durable multi-step tasks |
| HTTP/WebSockets |
docs/agents/http-websockets.md |
Lifecycle hooks, hibernation |
| Email |
docs/agents/email.md |
Email routing, secure reply resolver |
| MCP client |
docs/agents/mcp-client.md |
Connecting to MCP servers |
| MCP server |
docs/agents/mcp-servers.md |
Building MCP servers with McpAgent |
| Client SDK |
docs/agents/client-sdk.md |
useAgent, useAgentChat, React hooks |
| Human-in-the-loop |
docs/agents/human-in-the-loop.md |
Approval flows, pausing workflows |
| Resumable streaming |
docs/agents/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. Biases towards retrieval from Cloudflare docs over pre-trained knowledge.4metadata:5 source: https://skillmd.com/skills/stanfish06/agents-sdk6---78# Cloudflare Agents SDK910Your knowledge of the Agents SDK may be outdated. **Prefer retrieval over pre-training** for any Agents SDK task.1112## Retrieval Sources1314Fetch current docs from `https://github.com/cloudflare/agents/tree/main/docs` before implementing.1516| Topic | Doc | Use for |17|-------|-----|---------|18| Getting started | `docs/agents/getting-started.md` | First agent, project setup |19| State | `docs/agents/state.md` | `setState`, `validateStateChange`, persistence |20| Routing | `docs/agents/routing.md` | URL patterns, `routeAgentRequest`, `basePath` |21| Callable methods | `docs/agents/callable-methods.md` | `@callable`, RPC, streaming, timeouts |22| Scheduling | `docs/agents/scheduling.md` | `schedule()`, `scheduleEvery()`, cron |23| Workflows | `docs/agents/workflows.md` | `AgentWorkflow`, durable multi-step tasks |24| HTTP/WebSockets | `docs/agents/http-websockets.md` | Lifecycle hooks, hibernation |25| Email | `docs/agents/email.md` | Email routing, secure reply resolver |26| MCP client | `docs/agents/mcp-client.md` | Connecting to MCP servers |27| MCP server | `docs/agents/mcp-servers.md` | Building MCP servers with `McpAgent` |28| Client SDK | `docs/agents/client-sdk.md` | `useAgent`, `useAgentChat`, React hooks |29| Human-in-the-loop | `docs/agents/human-in-the-loop.md` | Approval flows, pausing workflows |30| Resumable streaming | `docs/agents/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:54```bash55npm install agents56```5758## Wrangler Configuration5960```jsonc61{62 "durable_objects": {63 "bindings": [{ "name": "MyAgent", "class_name": "MyAgent" }]64 },65 "migrations": [{ "tag": "v1", "new_sqlite_classes": ["MyAgent"] }]66}67```6869## Agent Class7071```typescript72import { Agent, routeAgentRequest, callable } from "agents";7374type State = { count: number };7576export class Counter extends Agent<Env, State> {77 initialState = { count: 0 };7879 // Validation hook - runs before state persists (sync, throwing rejects the update)80 validateStateChange(nextState: State, source: Connection | "server") {81 if (nextState.count < 0) throw new Error("Count cannot be negative");82 }8384 // Notification hook - runs after state persists (async, non-blocking)85 onStateUpdate(state: State, source: Connection | "server") {86 console.log("State updated:", state);87 }8889 @callable()90 increment() {91 this.setState({ count: this.state.count + 1 });92 return this.state.count;93 }94}9596export default {97 fetch: (req, env) => routeAgentRequest(req, env) ?? new Response("Not found", { status: 404 })98};99```100101## Routing102103Requests route to `/agents/{agent-name}/{instance-name}`:104105| Class | URL |106|-------|-----|107| `Counter` | `/agents/counter/user-123` |108| `ChatRoom` | `/agents/chat-room/lobby` |109110Client: `useAgent({ agent: "Counter", name: "user-123" })`111112## Core APIs113114| Task | API |115|------|-----|116| Read state | `this.state.count` |117| Write state | `this.setState({ count: 1 })` |118| SQL query | `` this.sql`SELECT * FROM users WHERE id = ${id}` `` |119| Schedule (delay) | `await this.schedule(60, "task", payload)` |120| Schedule (cron) | `await this.schedule("0 * * * *", "task", payload)` |121| Schedule (interval) | `await this.scheduleEvery(30, "poll")` |122| RPC method | `@callable() myMethod() { ... }` |123| Streaming RPC | `@callable({ streaming: true }) stream(res) { ... }` |124| Start workflow | `await this.runWorkflow("ProcessingWorkflow", params)` |125126## React Client127128```tsx129import { useAgent } from "agents/react";130131function App() {132 const [state, setLocalState] = useState({ count: 0 });133134 const agent = useAgent({135 agent: "Counter",136 name: "my-instance",137 onStateUpdate: (newState) => setLocalState(newState),138 onIdentity: (name, agentType) => console.log(`Connected to ${name}`)139 });140141 return (142 <button onClick={() => agent.setState({ count: state.count + 1 })}>143 Count: {state.count}144 </button>145 );146}147```148149## References150151- **[references/workflows.md](references/workflows.md)** - Durable Workflows integration152- **[references/callable.md](references/callable.md)** - RPC methods, streaming, timeouts153- **[references/state-scheduling.md](references/state-scheduling.md)** - State persistence, scheduling154- **[references/streaming-chat.md](references/streaming-chat.md)** - AIChatAgent, resumable streams155- **[references/mcp.md](references/mcp.md)** - MCP server integration156- **[references/email.md](references/email.md)** - Email routing and handling157- **[references/codemode.md](references/codemode.md)** - Code Mode (experimental)