Cloudflare Agents SDK
Prefer retrieval over pre-training for any Agents SDK task. 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/
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 };
validateStateChange(nextState: State, source: Connection | "server") {
if (nextState.count < 0) throw new Error("Count cannot be negative");
}
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.4---56# Cloudflare Agents SDK78Prefer retrieval over pre-training for any Agents SDK task. Fetch current docs from `https://github.com/cloudflare/agents/tree/main/docs` before implementing.910| Topic | Doc | Use for |11|-------|-----|---------|12| Getting started | `docs/getting-started.md` | First agent, project setup |13| State | `docs/state.md` | `setState`, `validateStateChange`, persistence |14| Routing | `docs/routing.md` | URL patterns, `routeAgentRequest`, `basePath` |15| Callable methods | `docs/callable-methods.md` | `@callable`, RPC, streaming, timeouts |16| Scheduling | `docs/scheduling.md` | `schedule()`, `scheduleEvery()`, cron |17| Workflows | `docs/workflows.md` | `AgentWorkflow`, durable multi-step tasks |18| HTTP/WebSockets | `docs/http-websockets.md` | Lifecycle hooks, hibernation |19| Email | `docs/email.md` | Email routing, secure reply resolver |20| MCP client | `docs/mcp-client.md` | Connecting to MCP servers |21| MCP server | `docs/mcp-servers.md` | Building MCP servers with `McpAgent` |22| Client SDK | `docs/client-sdk.md` | `useAgent`, `useAgentChat`, React hooks |23| Human-in-the-loop | `docs/human-in-the-loop.md` | Approval flows, pausing workflows |24| Resumable streaming | `docs/resumable-streaming.md` | Stream recovery on disconnect |2526Cloudflare docs: https://developers.cloudflare.com/agents/2728## Wrangler Configuration2930```jsonc31{32 "durable_objects": {33 "bindings": [{ "name": "MyAgent", "class_name": "MyAgent" }]34 },35 "migrations": [{ "tag": "v1", "new_sqlite_classes": ["MyAgent"] }]36}37```3839## Agent Class4041```typescript42import { Agent, routeAgentRequest, callable } from "agents";4344type State = { count: number };4546export class Counter extends Agent<Env, State> {47 initialState = { count: 0 };4849 validateStateChange(nextState: State, source: Connection | "server") {50 if (nextState.count < 0) throw new Error("Count cannot be negative");51 }5253 onStateUpdate(state: State, source: Connection | "server") {54 console.log("State updated:", state);55 }5657 @callable()58 increment() {59 this.setState({ count: this.state.count + 1 });60 return this.state.count;61 }62}6364export default {65 fetch: (req, env) => routeAgentRequest(req, env) ?? new Response("Not found", { status: 404 })66};67```6869## Routing7071Requests route to `/agents/{agent-name}/{instance-name}`:7273| Class | URL |74|-------|-----|75| `Counter` | `/agents/counter/user-123` |76| `ChatRoom` | `/agents/chat-room/lobby` |7778Client: `useAgent({ agent: "Counter", name: "user-123" })`7980## Core APIs8182| Task | API |83|------|-----|84| Read state | `this.state.count` |85| Write state | `this.setState({ count: 1 })` |86| SQL query | `` this.sql`SELECT * FROM users WHERE id = ${id}` `` |87| Schedule (delay) | `await this.schedule(60, "task", payload)` |88| Schedule (cron) | `await this.schedule("0 * * * *", "task", payload)` |89| Schedule (interval) | `await this.scheduleEvery(30, "poll")` |90| RPC method | `@callable() myMethod() { ... }` |91| Streaming RPC | `@callable({ streaming: true }) stream(res) { ... }` |92| Start workflow | `await this.runWorkflow("ProcessingWorkflow", params)` |9394## React Client9596```tsx97import { useAgent } from "agents/react";9899function App() {100 const [state, setLocalState] = useState({ count: 0 });101102 const agent = useAgent({103 agent: "Counter",104 name: "my-instance",105 onStateUpdate: (newState) => setLocalState(newState),106 onIdentity: (name, agentType) => console.log(`Connected to ${name}`)107 });108109 return (110 <button onClick={() => agent.setState({ count: state.count + 1 })}>111 Count: {state.count}112 </button>113 );114}115```116117## References118119- **[references/workflows.md](references/workflows.md)** - Durable Workflows integration120- **[references/callable.md](references/callable.md)** - RPC methods, streaming, timeouts121- **[references/state-scheduling.md](references/state-scheduling.md)** - State persistence, scheduling122- **[references/streaming-chat.md](references/streaming-chat.md)** - AIChatAgent, resumable streams123- **[references/mcp.md](references/mcp.md)** - MCP server integration124- **[references/email.md](references/email.md)** - Email routing and handling125- **[references/codemode.md](references/codemode.md)** - Code Mode (experimental)