agents-sdk

作者: Cloudflare

在Cloudflare Workers上使用Agents SDK构建AI代理。创建有状态代理、持久化工作流、实时WebSocket应用、定时任务、MCP服务器或聊天应用时加载。涵盖Agent类、状态管理、可调用RPC、Workflows集成及React钩子。

npx skills add https://github.com/cloudflare/skills --skill agents-sdk

Cloudflare Agents SDK

Your knowledge of the Agents SDK may be outdated. Prefer retrieval over pre-training for any Agents SDK task.

Retrieval Sources

Cloudflare docs: https://developers.cloudflare.com/agents/

TopicDocs URLUse for
Getting startedQuick startFirst agent, project setup
Adding to existing projectAdd to existing projectInstall into existing Workers app
ConfigurationConfigurationwrangler.jsonc, bindings, assets, deployment
Agent classAgents APIAgent lifecycle, patterns, pitfalls
StateStore and sync statesetState, validateStateChange, persistence
RoutingRoutingURL patterns, routeAgentRequest
Callable methodsCallable methods@callable, RPC, streaming, timeouts
SchedulingSchedule tasksschedule(), scheduleEvery(), cron
WorkflowsRun workflowsAgentWorkflow, durable multi-step tasks
HTTP/WebSocketsWebSocketsLifecycle hooks, hibernation
Chat agentsChat agentsAIChatAgent, streaming, tools, persistence
Client SDKClient SDKuseAgent, useAgentChat, React hooks
Client toolsClient toolsClient-side tools, autoContinueAfterToolResult
Server-driven messagesTrigger patternssaveMessages, waitUntilStable, server-initiated turns
Resumable streamingResumable streamingStream recovery on disconnect
EmailEmailEmail routing, secure reply resolver
MCP clientMCP clientConnecting to MCP servers
MCP serverMCP serverBuilding MCP servers with McpAgent
MCP transportsMCP transportsStreamable HTTP, SSE, RPC transport options
Securing MCP serversSecuring MCPOAuth, proxy MCP, hardening
Human-in-the-loopHuman-in-the-loopApproval flows, needsApproval, workflows
Durable executionDurable executionrunFiber(), stash(), surviving DO eviction
QueueQueueBuilt-in FIFO queue, queue()
RetriesRetriesthis.retry(), backoff/jitter
ObservabilityObservabilityDiagnostics-channel events
Push notificationsPush notificationsWeb Push + VAPID from agents
WebhooksWebhooksReceiving external webhooks
Cross-domain authCross-domain authWebSocket auth, tokens, CORS
Readonly connectionsReadonlyshouldConnectionBeReadonly
VoiceVoiceExperimental STT/TTS, withVoice
Browse the webBrowser toolsExperimental CDP browser automation
ThinkThinkExperimental higher-level chat agent class
MigrationsAI SDK v5, AI SDK v6Upgrading @cloudflare/ai-chat

Capabilities

The Agents SDK provides:

  • Persistent state — SQLite-backed, auto-synced to clients via setState
  • Callable RPC@callable() methods invoked over WebSocket
  • Scheduling — One-time, recurring (scheduleEvery), and cron tasks
  • Workflows — Durable multi-step background processing via AgentWorkflow
  • Durable executionrunFiber() / stash() for work that survives DO eviction
  • Queue — Built-in FIFO queue with retries via queue()
  • Retriesthis.retry() with exponential backoff and jitter
  • MCP integration — Connect to MCP servers or build your own with McpAgent
  • Email handling — Receive and reply to emails with secure routing
  • Streaming chatAIChatAgent with resumable streams, message persistence, tools
  • Server-driven messagessaveMessages, waitUntilStable for proactive agent turns
  • React hooksuseAgent, useAgentChat for client apps
  • Observabilitydiagnostics_channel events for state, RPC, schedule, lifecycle
  • Push notifications — Web Push + VAPID delivery from agents
  • Webhooks — Receive and verify external webhooks
  • Voice (experimental) — STT/TTS via @cloudflare/voice
  • Browser tools (experimental) — CDP-powered browsing via agents/browser
  • Think (experimental) — Higher-level chat agent via @cloudflare/think

FIRST: Verify Installation

npm 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

Wrangler Configuration

{
  "compatibility_flags": ["nodejs_compat"],
  "durable_objects": {
    "bindings": [{ "name": "MyAgent", "class_name": "MyAgent" }]
  },
  "migrations": [{ "tag": "v1", "new_sqlite_classes": ["MyAgent"] }]
}

Gotchas:

  • Do NOT enable experimentalDecorators in tsconfig (breaks @callable)
  • Never edit old migrations — always add new tags
  • Each agent class needs its own DO binding + migration entry
  • Add "ai": { "binding": "AI" } for Workers AI

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}:

ClassURL
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).

Core APIs

TaskAPI
Read statethis.state.count
Write statethis.setState({ count: 1 })
SQL querythis.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 workflowawait this.runWorkflow("ProcessingWorkflow", params)
Durable fiberawait this.runFiber("name", async (ctx) => { ... })
Enqueue workthis.queue("handler", payload)
Retry with backoffawait this.retry(fn, { maxAttempts: 5 })
Broadcast to clientsthis.broadcast(message)
Get connectionsthis.getConnections(tag?)

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>
  );
}

References

Core

Chat & Streaming

Background Processing

Integrations

Experimental

来自 Cloudflare 的更多技能

building-ai-agent-on-cloudflare
Cloudflare
基于Cloudflare构建AI智能体,使用Agents SDK实现状态管理、实时WebSocket、定时任务、工具集成及聊天功能。生成可直接部署到Workers的生产级智能体代码。 适用场景:用户需要“构建智能体”、“AI智能体”、“聊天智能体”、“有状态智能体”,提及“Agents SDK”,需要“实时AI”、“WebSocket AI”,或询问智能体“状态管理”、“定时任务”、“工具调用”。
developmentofficial
building-mcp-server-on-cloudflare
Cloudflare
在 Cloudflare Workers 上构建远程 MCP(模型上下文协议)服务器,支持工具、OAuth 认证和生产部署。生成服务器代码、配置认证提供者并部署到 Workers。 使用场景:用户想要“构建 MCP 服务器”、“创建 MCP 工具”、“远程 MCP”、“部署 MCP”、添加“MCP 的 OAuth”,或提及 Cloudflare 上的模型上下文协议。也会在“MCP 认证”或“MCP 部署”时触发。
developmentofficial
cloudflare
Cloudflare
全面的Cloudflare平台技能,涵盖Workers、Pages、存储(KV、D1、R2)、AI(Workers AI、Vectorize、Agents SDK)、网络(Tunnel、Spectrum)、安全(WAF、DDoS)以及基础设施即代码(Terraform、Pulumi)。适用于任何Cloudflare开发任务。
official
durable-objects
Cloudflare
创建和审查Cloudflare Durable Objects。用于构建有状态协调(聊天室、多玩家游戏、预订系统)、实现RPC方法、SQLite存储、警报、WebSocket,或审查DO代码以遵循最佳实践。涵盖Workers集成、wrangler配置以及使用Vitest进行测试。
official
sandbox-sdk
Cloudflare
构建沙盒化应用程序以实现安全代码执行。在构建AI代码执行、代码解释器、CI/CD系统、交互式开发环境或执行不受信任的代码时加载。涵盖Sandbox SDK生命周期、命令、文件、代码解释器和预览URL。
official
web-perf
Cloudflare
使用Chrome DevTools MCP分析网页性能。测量核心网页指标(FCP、LCP、TBT、CLS、速度指数),识别渲染阻塞资源、网络依赖链、布局偏移、缓存问题及可访问性差距。当被要求审计、分析、调试或优化页面加载性能、Lighthouse评分或网站速度时使用。
official
workers-best-practices
Cloudflare
审查并根据生产最佳实践对Cloudflare Workers代码进行审核。在编写新的Workers、审查Worker代码、配置wrangler.jsonc或检查常见的Workers反模式(流式处理、浮动Promise、全局状态、机密、绑定、可观测性)时加载。倾向于从Cloudflare文档中检索信息,而非依赖预训练知识。
official
wrangler
Cloudflare
Cloudflare Workers CLI,用于部署、开发和管理 Workers、KV、R2、D1、Vectorize、Hyperdrive、Workers AI、Containers、Queues、Workflows、Pipelines 及 Secrets Store。在运行 wrangler 命令前加载,以确保正确的语法和最佳实践。
official