Build stateful AI agents using the Cloudflare Agents SDK. Load when creating agents with persistent state, scheduling, RPC, MCP servers, email handling, or streaming chat. Covers Agent class, AIChatAgent, state management, and Code Mode for reduced token usage.
View on GitHubSelect agents to install to:
npx add-skill https://github.com/cloudflare/skills/blob/main/skills/agents-sdk/SKILL.md -a claude-code --skill agents-sdkInstallation paths:
.claude/skills/agents-sdk/# Cloudflare Agents SDK
Build persistent, stateful AI agents on Cloudflare Workers using the `agents` npm package.
## FIRST: Verify Installation
```bash
npm install agents
```
Agents require a binding in `wrangler.jsonc`:
```jsonc
{
"durable_objects": {
// "class_name" must match your Agent class name exactly
"bindings": [{ "name": "Counter", "class_name": "Counter" }]
},
"migrations": [
// Required: list all Agent classes for SQLite storage
{ "tag": "v1", "new_sqlite_classes": ["Counter"] }
]
}
```
## Choosing an Agent Type
| Use Case | Base Class | Package |
|----------|------------|---------|
| Custom state + RPC, no chat | `Agent` | `agents` |
| Chat with message persistence | `AIChatAgent` | `@cloudflare/ai-chat` |
| Building an MCP server | `McpAgent` | `agents/mcp` |
## Key Concepts
- **Agent** base class provides state, scheduling, RPC, MCP, and email capabilities
- **AIChatAgent** adds streaming chat with automatic message persistence and resumable streams
- **Code Mode** generates executable code instead of tool calls—reduces token usage significantly
- **this.state / this.setState()** - automatic persistence to SQLite, broadcasts to clients
- **this.schedule()** - schedule tasks at Date, delay (seconds), or cron expression
- **@callable** decorator - expose methods to clients via WebSocket RPC
## Quick Reference
| Task | API |
|------|-----|
| Persist state | `this.setState({ count: 1 })` |
| Read state | `this.state.count` |
| Schedule task | `this.schedule(60, "taskMethod", payload)` |
| Schedule cron | `this.schedule("0 * * * *", "hourlyTask")` |
| Cancel schedule | `this.cancelSchedule(id)` |
| Queue task | `this.queue("processItem", payload)` |
| SQL query | `` this.sql`SELECT * FROM users WHERE id = ${id}` `` |
| RPC method | `@callable() async myMethod() { ... }` |
| Streaming RPC | `@callable({ streaming: true }) async stream(res) { ... }` |
## Minimal Agent
```typescript
import { Agent, routeAgentRequest, call