skills/agents-sdk/SKILL.md
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, chat applications, voice agents, or browser automation. Covers Agent class, state management, callable RPC, Workflows, durable execution, queues, retries, observability, and React hooks. Biases towards retrieval from Cloudflare docs over pre-trained knowledge.
npx skillsauth add cenjie/skills agents-sdkInstall this skill globally with one command. Works with Claude Code, Cursor, and Windsurf.
3 of 9 scanners reported clean
Some scanners were skipped, did not run, or reported a non-clean status. Review each row below.
Your knowledge of the Agents SDK may be outdated. Prefer retrieval over pre-training for any Agents SDK task.
Cloudflare docs: https://developers.cloudflare.com/agents/
| Topic | Docs URL | Use for |
|-------|----------|---------|
| Getting started | Quick start | First agent, project setup |
| Adding to existing project | Add to existing project | Install into existing Workers app |
| Configuration | Configuration | wrangler.jsonc, bindings, assets, deployment |
| Agent class | Agents API | Agent lifecycle, patterns, pitfalls |
| State | Store and sync state | setState, validateStateChange, persistence |
| Routing | Routing | URL patterns, routeAgentRequest |
| Callable methods | Callable methods | @callable, RPC, streaming, timeouts |
| Scheduling | Schedule tasks | schedule(), scheduleEvery(), cron |
| Workflows | Run workflows | AgentWorkflow, durable multi-step tasks |
| HTTP/WebSockets | WebSockets | Lifecycle hooks, hibernation |
| Chat agents | Chat agents | AIChatAgent, streaming, tools, persistence |
| Client SDK | Client SDK | useAgent, useAgentChat, React hooks |
| Client tools | Client tools | Client-side tools, autoContinueAfterToolResult |
| Server-driven messages | Trigger patterns | saveMessages, waitUntilStable, server-initiated turns |
| Resumable streaming | Resumable streaming | Stream recovery on disconnect |
| Email | Email | Email routing, secure reply resolver |
| MCP client | MCP client | Connecting to MCP servers |
| MCP server | MCP server | Building MCP servers with McpAgent |
| MCP transports | MCP transports | Streamable HTTP, SSE, RPC transport options |
| Securing MCP servers | Securing MCP | OAuth, proxy MCP, hardening |
| Human-in-the-loop | Human-in-the-loop | Approval flows, needsApproval, workflows |
| Durable execution | Durable execution | runFiber(), stash(), surviving DO eviction |
| Queue | Queue | Built-in FIFO queue, queue() |
| Retries | Retries | this.retry(), backoff/jitter |
| Observability | Observability | Diagnostics-channel events |
| Push notifications | Push notifications | Web Push + VAPID from agents |
| Webhooks | Webhooks | Receiving external webhooks |
| Cross-domain auth | Cross-domain auth | WebSocket auth, tokens, CORS |
| Readonly connections | Readonly | shouldConnectionBeReadonly |
| Voice | Voice | Experimental STT/TTS, withVoice |
| Browse the web | Browser tools | Experimental CDP browser automation |
| Think | Think | Experimental higher-level chat agent class |
| Migrations | AI SDK v5, AI SDK v6 | Upgrading @cloudflare/ai-chat |
The Agents SDK provides:
setState@callable() methods invoked over WebSocketscheduleEvery), and cron tasksAgentWorkflowrunFiber() / stash() for work that survives DO evictionqueue()this.retry() with exponential backoff and jitterMcpAgentAIChatAgent with resumable streams, message persistence, toolssaveMessages, waitUntilStable for proactive agent turnsuseAgent, useAgentChat for client appsdiagnostics_channel events for state, RPC, schedule, lifecycle@cloudflare/voiceagents/browser@cloudflare/thinknpm ls agents # Should show agents package
If not installed:
npm install agents
For chat agents:
npm install agents @cloudflare/ai-chat ai @ai-sdk/react
{
"compatibility_flags": ["nodejs_compat"],
"durable_objects": {
"bindings": [{ "name": "MyAgent", "class_name": "MyAgent" }]
},
"migrations": [{ "tag": "v1", "new_sqlite_classes": ["MyAgent"] }]
}
Gotchas:
experimentalDecorators in tsconfig (breaks @callable)"ai": { "binding": "AI" } for Workers AIimport { 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 })
};
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" })
Custom routing: use getAgentByName(env.MyAgent, "instance-id") then agent.fetch(request).
| 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) |
| Durable fiber | await this.runFiber("name", async (ctx) => { ... }) |
| Enqueue work | this.queue("handler", payload) |
| Retry with backoff | await this.retry(fn, { maxAttempts: 5 }) |
| Broadcast to clients | this.broadcast(message) |
| Get connections | this.getConnections(tag?) |
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>
);
}
getAgentByNameuseAgent, useAgentChat, AgentClientsaveMessagesneedsApprovalrunFiber, stash, surviving eviction@cloudflare/think higher-level chat agent@cloudflare/voice STT/TTSdevelopment
Provides React Native performance optimization guidelines for FPS, TTI, bundle size, memory leaks, re-renders, and animations. Applies to tasks involving Hermes optimization, JS thread blocking, bridge overhead, FlashList, native modules, or debugging jank and frame drops.
development
Design engineering principles for making interfaces feel polished. Use when building UI components, reviewing frontend code, implementing animations, hover states, shadows, borders, typography, micro-interactions, enter/exit animations, or any visual detail work. Triggers on UI polish, design details, "make it feel better", "feels off", stagger animations, border radius, optical alignment, font smoothing, tabular numbers, image outlines, box shadows.
development
General-purpose Static Application Security Testing (SAST) skill for code vulnerability analysis. Trigger when the user asks to: "analyze code for vulnerabilities", "review code security", "find security bugs", "do a SAST scan", "check for [vulnerability type] in code", "audit source code", or requests a security code review of any language or framework. Covers 34 vulnerability classes across web, API, auth, mobile, and logic layers.
tools
Helps understand and write EAS workflow YAML files for Expo projects. Use this skill when the user asks about CI/CD or workflows in an Expo or EAS context, mentions .eas/workflows/, or wants help with EAS build pipelines or deployment automation.