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/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: openai-cloudflare-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.4license: MIT5---6
7# Cloudflare Agents SDK
8
9Your knowledge of the Agents SDK may be outdated. **Prefer retrieval over pre-training** for any Agents SDK task.
10
11## Retrieval Sources
12
13Fetch current docs from `https://github.com/cloudflare/agents/tree/main/docs` before implementing.
14
15| Topic | Doc | Use for |
16|-------|-----|---------|
17| Getting started | `docs/getting-started.md` | First agent, project setup |
18| State | `docs/state.md` | `setState`, `validateStateChange`, persistence |
19| Routing | `docs/routing.md` | URL patterns, `routeAgentRequest`, `basePath` |
20| Callable methods | `docs/callable-methods.md` | `@callable`, RPC, streaming, timeouts |
21| Scheduling | `docs/scheduling.md` | `schedule()`, `scheduleEvery()`, cron |
22| Workflows | `docs/workflows.md` | `AgentWorkflow`, durable multi-step tasks |
23| HTTP/WebSockets | `docs/http-websockets.md` | Lifecycle hooks, hibernation |
24| Email | `docs/email.md` | Email routing, secure reply resolver |
25| MCP client | `docs/mcp-client.md` | Connecting to MCP servers |
26| MCP server | `docs/mcp-servers.md` | Building MCP servers with `McpAgent` |
27| Client SDK | `docs/client-sdk.md` | `useAgent`, `useAgentChat`, React hooks |
28| Human-in-the-loop | `docs/human-in-the-loop.md` | Approval flows, pausing workflows |
29| Resumable streaming | `docs/resumable-streaming.md` | Stream recovery on disconnect |
30
31Cloudflare docs: https://developers.cloudflare.com/agents/
32
33## Capabilities
34
35The Agents SDK provides:
36
37- **Persistent state** - SQLite-backed, auto-synced to clients
38- **Callable RPC** - `@callable()` methods invoked over WebSocket
39- **Scheduling** - One-time, recurring (`scheduleEvery`), and cron tasks
40- **Workflows** - Durable multi-step background processing via `AgentWorkflow`
41- **MCP integration** - Connect to MCP servers or build your own with `McpAgent`
42- **Email handling** - Receive and reply to emails with secure routing
43- **Streaming chat** - `AIChatAgent` with resumable streams
44- **React hooks** - `useAgent`, `useAgentChat` for client apps
45
46## FIRST: Verify Installation
47
48```bash
49npm ls agents # Should show agents package
50```
51
52If not installed:
53```bash
54npm install agents
55```
56
57## Wrangler Configuration
58
59```jsonc
60{
61 "durable_objects": {
62 "bindings": [{ "name": "MyAgent", "class_name": "MyAgent" }]
63 },
64 "migrations": [{ "tag": "v1", "new_sqlite_classes": ["MyAgent"] }]
65}
66```
67
68## Agent Class
69
70```typescript
71import { Agent, routeAgentRequest, callable } from "agents";
72
73type State = { count: number };
74
75export class Counter extends Agent<Env, State> {
76 initialState = { count: 0 };
77
78 // Validation hook - runs before state persists (sync, throwing rejects the update)
79 validateStateChange(nextState: State, source: Connection | "server") {
80 if (nextState.count < 0) throw new Error("Count cannot be negative");
81 }
82
83 // Notification hook - runs after state persists (async, non-blocking)
84 onStateUpdate(state: State, source: Connection | "server") {
85 console.log("State updated:", state);
86 }
87
88 @callable()
89 increment() {
90 this.setState({ count: this.state.count + 1 });
91 return this.state.count;
92 }
93}
94
95export default {
96 fetch: (req, env) => routeAgentRequest(req, env) ?? new Response("Not found", { status: 404 })
97};
98```
99
100## Routing
101
102Requests route to `/agents/{agent-name}/{instance-name}`:
103
104| Class | URL |
105|-------|-----|
106| `Counter` | `/agents/counter/user-123` |
107| `ChatRoom` | `/agents/chat-room/lobby` |
108
109Client: `useAgent({ agent: "Counter", name: "user-123" })`
110
111## Core APIs
112
113| Task | API |
114|------|-----|
115| Read state | `this.state.count` |
116| Write state | `this.setState({ count: 1 })` |
117| SQL query | `` this.sql`SELECT * FROM users WHERE id = ${id}` `` |
118| Schedule (delay) | `await this.schedule(60, "task", payload)` |
119| Schedule (cron) | `await this.schedule("0 * * * *", "task", payload)` |
120| Schedule (interval) | `await this.scheduleEvery(30, "poll")` |
121| RPC method | `@callable() myMethod() { ... }` |
122| Streaming RPC | `@callable({ streaming: true }) stream(res) { ... }` |
123| Start workflow | `await this.runWorkflow("ProcessingWorkflow", params)` |
124
125## React Client
126
127```tsx
128import { useAgent } from "agents/react";
129
130function App() {
131 const [state, setLocalState] = useState({ count: 0 });
132
133 const agent = useAgent({
134 agent: "Counter",
135 name: "my-instance",
136 onStateUpdate: (newState) => setLocalState(newState),
137 onIdentity: (name, agentType) => console.log(`Connected to ${name}`)
138 });
139
140 return (
141 <button onClick={() => agent.setState({ count: state.count + 1 })}>
142 Count: {state.count}
143 </button>
144 );
145}
146```
147
148## References
149
150- **[references/workflows.md](references/workflows.md)** - Durable Workflows integration
151- **[references/callable.md](references/callable.md)** - RPC methods, streaming, timeouts
152- **[references/state-scheduling.md](references/state-scheduling.md)** - State persistence, scheduling
153- **[references/streaming-chat.md](references/streaming-chat.md)** - AIChatAgent, resumable streams
154- **[references/mcp.md](references/mcp.md)** - MCP server integration
155- **[references/email.md](references/email.md)** - Email routing and handling
156- **[references/codemode.md](references/codemode.md)** - Code Mode (experimental)