Preface¶
When using an AI programming assistant to build an Agent that can track state, run scheduled tasks, and expose external tools, the most common pitfall is not the model calls themselves, but the runtime conventions: how to persist state, how to connect WebSockets, how to expose RPC methods, and how to configure Durable Object bindings / migrations. Cloudflare Agents SDK packs these capabilities onto Workers and Durable Objects, with a wide API surface and fast documentation updates. If an assistant only relies on outdated knowledge from its training data, it will easily generate outdated decorator configurations, incorrect routes, or treat experimental features as stable APIs.
The official Cloudflare repository cloudflare/skills provides an Agent Skill named agents-sdk. It does not replace the agents npm package, but rather a set of operational guidelines that automatically load when building stateful Agents, scheduling tasks, MCP services, streaming chats, and similar scenarios: it requires the assistant to prioritize retrieving the Cloudflare Agents documentation before writing code and wrangler.jsonc using the current API.
What is this¶
agents-sdk is an Agent Skill maintained by Cloudflare (in the universal SKILL.md format), targeted at development tasks using the Agents SDK on Cloudflare Workers. The official described trigger scenarios include: stateful Agents, durable workflows, real-time WebSockets, scheduled tasks, MCP servers, chat applications, voice Agents, browser automation, etc. It covers the Agent class, state management, @callable RPC, Workflows, durable execution, queues, retries, observability, and React hooks.
This Skill has a clear core principle: Prefer retrieval over pre-training. That is, when writing code related to the Agents SDK, you should prioritize fetching the latest information from the Cloudflare Agents documentation instead of relying on the model’s built-in memory. The Skill also includes a topic-based documentation index table (Quick Start, Configuration, State, Routing, Scheduling, MCP, Client SDK, etc.) to help assistants jump directly to relevant content based on their tasks.
It follows the open Agent Skills standard and can be used in tools that support this standard, such as Claude Code, Cursor, OpenCode, OpenAI Codex, Pi, etc.
Core Features and Highlights¶
According to the official SKILL.md, the Agents SDK (and the capabilities this Skill guides assistants to use correctly) mainly include:
- Persistent State: Based on SQLite, written via
setStateand automatically synced to connected clients; you can also usethis.sqlfor in-instance queries. - Callable RPC: Expose methods to clients via
@callable(), called over WebSocket; supports streaming RPC. - Scheduling: One-off delayed tasks (
schedule), cron jobs, and recurring tasks (scheduleEvery). - Workflows and durable execution: Use
AgentWorkflowfor multi-step background tasks;runFiber()/stash()for long-running tasks that can survive Durable Object evictions. - Queues and Retries: Built-in FIFO
queue();this.retry()with exponential backoff and jitter. - MCP: Can act as an MCP client to connect to external servers, or use
McpAgentto build your own MCP server (including links to transport and security-related documentation). - Chat and Frontend:
AIChatAgent(resumable streams, message persistence, tools); React-sideuseAgent,useAgentChat. - Other Integrations: Email sending/receiving, Webhooks, Web Push, observability (
diagnostics_channel); voice, browser tools, and Think are marked as experimental, and you should refer to the documentation before using them.
The Skill also helps assistants avoid common pitfalls, such as: do not enable experimentalDecorators in tsconfig (it will break @callable); do not modify old migrations, only append new tags; each Agent class needs a separate DO binding and migration entry.
Installation and Activation¶
The Skill itself is an instruction file; to actually run an Agent, you still need the agents package installed in your project, and correct Wrangler / Durable Objects configuration.
1. Install Cloudflare Skills (including agents-sdk)¶
The official README offers multiple installation methods, choose any one:
Use npx skills to install the entire repository (you can also install only agents-sdk):
npx skills add https://github.com/cloudflare/skills
# To install only agents-sdk:
# npx skills add https://github.com/cloudflare/skills --skill agents-sdk
Claude Code (Plugin Marketplace):
/plugin marketplace add cloudflare/skills
/plugin install cloudflare@cloudflare
Cursor: You can install it from the Cursor Marketplace, or add cloudflare/skills in Settings > Rules > Add Rule > Remote Rule (Github).
Manual Copy (official directory mapping):
| Tool | Skill Directory |
|------|------------|
| Claude Code | ~/.claude/skills/ |
| Cursor | ~/.cursor/skills/ |
| OpenCode | ~/.config/opencode/skills/ |
| OpenAI Codex | ~/.codex/skills/ |
| Pi | ~/.pi/agent/skills/ |
For example:
git clone https://github.com/cloudflare/skills.git
cp -r skills/skills/agents-sdk ~/.cursor/skills/
After installation, it will automatically load when the assistant matches trigger conditions such as “write a stateful Agent”, “add @callable”, “build an MCP server”, “configure a schedule”, etc. You can also explicitly ask to use the agents-sdk skill in a conversation. The repository also provides slash commands /cloudflare:build-agent and /cloudflare:build-mcp for scaffolding.
2. Verify Agents SDK Dependencies¶
The Skill requires you to first check if the npm package is installed:
npm ls agents # You should see the agents package
# If not installed:
npm install agents
If you are building a chat Agent, the official example also depends on:
npm install agents @cloudflare/ai-chat ai @ai-sdk/react
Typical Usage Examples¶
All examples below are from the official Skill documentation and can be directly reproduced in a Workers project.
Minimal Wrangler Configuration¶
{
"compatibility_flags": ["nodejs_compat"],
"durable_objects": {
"bindings": [{ "name": "MyAgent", "class_name": "MyAgent" }]
},
"migrations": [{ "tag": "v1", "new_sqlite_classes": ["MyAgent"] }]
}
You can add "ai": { "binding": "AI" } if you need Workers AI. Each Agent class needs its own binding and migration; historical migrations should only be appended, not modified retroactively.
Minimal Agent: State + RPC + Routing¶
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 })
};
The default routing format is /agents/{agent-name}/{instance-name}, for example, the Counter class corresponds to /agents/counter/user-123. You can also use getAgentByName(env.MyAgent, "instance-id") on the server side and then agent.fetch(request) to create a custom entry point.
Quick Reference of Core APIs¶
| Task | API |
|---|---|
| Read State | this.state.count |
| Write State | this.setState({ count: 1 }) |
| SQL | this.sql`SELECT * FROM users WHERE id = ${id}` |
| Delayed Scheduling | await this.schedule(60, "task", payload) |
| Cron Job | await this.schedule("0 * * * *", "task", payload) |
| Recurring Scheduling | await this.scheduleEvery(30, "poll") |
| RPC | @callable() myMethod() { ... } |
| Streaming RPC | @callable({ streaming: true }) stream(res) { ... } |
| Workflow | await this.runWorkflow("ProcessingWorkflow", params) |
| Durable Fiber | await this.runFiber("name", async (ctx) => { ... }) |
| Enqueue | this.queue("handler", payload) |
| Retry | await this.retry(fn, { maxAttempts: 5 }) |
| Broadcast | this.broadcast(message) |
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 onClick={() => agent.setState({ count: state.count + 1 })}>
Count: {state.count}
</button>
);
}
For more complete examples of chat, MCP, Workflows, human-in-the-loop, etc., the Skill guides assistants to continue retrieving official instructions through topic-specific documents under the references/ folder (such as mcp.md, workflows.md, streaming-chat.md), instead of piecing together APIs from memory.
Applicable Scenarios and Notes¶
Applicable Scenarios:
- Building or refactoring stateful Agents (counters, sessions, collaboration rooms, etc.) on Cloudflare Workers using an AI assistant
- Needing scheduling, queues, recoverable long-running tasks, or turning an Agent into an MCP tool provider/consumer
- Using useAgent / useAgentChat on the frontend for real-time state synchronization and streaming chats
- Wanting the assistant to align with official documentation and current agents package conventions before writing code, instead of relying on memorized old examples
Notes:
- The Skill guides you on how to use the Agents SDK correctly; account, billing, quotas, and Durable Object restrictions still follow the Cloudflare Console and official documentation.
- Do not enable TypeScript experimentalDecorators; @callable relies on correct decorator transformation (the official Quick Start also emphasizes that Vite needs to handle decorators correctly).
- Migrations should only be appended, not modified; Agent classes and DO bindings have a one-to-one correspondence.
- Features marked as experimental in the Skill, such as voice, browser automation, and Think, should be checked against their respective documentation pages before integration.
- The Agents SDK differs from “model orchestration frameworks”: it focuses on persistent runtime, state, and edge infrastructure; you can still choose Workers AI or other model providers for specific inference loops based on your project.
- If installation commands on third-party mirrors differ from the official README, refer to the cloudflare/skills repository as the source of truth.
Summary¶
agents-sdk固化了Cloudflare Agents SDK的文档索引、安装校验、Wrangler/DO配置约定,以及状态、RPC、调度、MCP、React客户端等可复现示例,将其转化为Agent可加载的操作手册:先检索、再编写代码,避免用过时知识硬写边缘Agent。对于已经在使用或准备部署Cloudflare有状态Agent的开发者来说,将其安装到Cursor/Claude Code/Codex等工具中,可以显著减少配置和API使用方面的低级错误。
Official links:
- Skill directory: https://github.com/cloudflare/skills/tree/main/skills/agents-sdk
- Repository description and installation: https://github.com/cloudflare/skills
- Agents documentation: https://developers.cloudflare.com/agents/
- Agents SDK code repository: https://github.com/cloudflare/agents