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