Loading...
Loading...
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.
npx skill4agent add cloudflare/skills agents-sdkhttps://github.com/cloudflare/agents/tree/main/docs| Topic | Doc | Use for |
|---|---|---|
| Getting started | | First agent, project setup |
| State | | |
| Routing | | URL patterns, |
| Callable methods | | |
| Scheduling | | |
| Workflows | | |
| HTTP/WebSockets | | Lifecycle hooks, hibernation |
| Email routing, secure reply resolver | |
| MCP client | | Connecting to MCP servers |
| MCP server | | Building MCP servers with |
| Client SDK | | |
| Human-in-the-loop | | Approval flows, pausing workflows |
| Resumable streaming | | Stream recovery on disconnect |
@callable()scheduleEveryAgentWorkflowMcpAgentAIChatAgentuseAgentuseAgentChatnpm ls agents # Should show agents packagenpm install agents{
"durable_objects": {
"bindings": [{ "name": "MyAgent", "class_name": "MyAgent" }]
},
"migrations": [{ "tag": "v1", "new_sqlite_classes": ["MyAgent"] }]
}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 })
};/agents/{agent-name}/{instance-name}| Class | URL |
|---|---|
| |
| |
useAgent({ agent: "Counter", name: "user-123" })| Task | API |
|---|---|
| Read state | |
| Write state | |
| SQL query | |
| Schedule (delay) | |
| Schedule (cron) | |
| Schedule (interval) | |
| RPC method | |
| Streaming RPC | |
| Start workflow | |
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>
);
}