agents-sdk
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseCloudflare Agents SDK
Cloudflare Agents SDK
STOP. Your knowledge of the Agents SDK may be outdated. Prefer retrieval over pre-training for any Agents SDK task.
注意:你所了解的Agents SDK知识可能已过时。在处理任何Agents SDK相关任务时,优先使用检索而非预训练内容。
Documentation
文档
Fetch current docs from before implementing.
https://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 |
Cloudflare docs: https://developers.cloudflare.com/agents/
实现前请从获取最新文档。
https://github.com/cloudflare/agents/tree/main/docs| 主题 | 文档 | 适用场景 |
|---|---|---|
| 入门指南 | | 首个Agent开发、项目搭建 |
| 状态管理 | | |
| 路由配置 | | URL规则、 |
| 可调用方法 | | |
| 任务调度 | | |
| 工作流 | | |
| HTTP/WebSocket | | 生命周期钩子、休眠机制 |
| 邮件处理 | | 邮件路由、安全回复解析器 |
| MCP客户端 | | 连接MCP服务器 |
| MCP服务器 | | 使用 |
| 客户端SDK | | |
| 人机协同 | | 审批流、工作流暂停 |
| 可恢复流式传输 | | 断开连接后的流恢复 |
Cloudflare官方文档:https://developers.cloudflare.com/agents/
Capabilities
功能特性
The Agents SDK provides:
- Persistent state - SQLite-backed, auto-synced to clients
- Callable RPC - methods invoked over WebSocket
@callable() - Scheduling - One-time, recurring (), and cron tasks
scheduleEvery - Workflows - Durable multi-step background processing via
AgentWorkflow - MCP integration - Connect to MCP servers or build your own with
McpAgent - Email handling - Receive and reply to emails with secure routing
- Streaming chat - with resumable streams
AIChatAgent - React hooks - ,
useAgentfor client appsuseAgentChat
Agents SDK提供以下功能:
- 持久化状态 - 基于SQLite,自动同步至客户端
- 可调用RPC - 通过WebSocket调用方法
@callable() - 任务调度 - 一次性任务、周期性任务()以及cron任务
scheduleEvery - 工作流 - 通过实现持久化多步骤后台处理
AgentWorkflow - MCP集成 - 连接MCP服务器或使用构建自有服务器
McpAgent - 邮件处理 - 接收和回复邮件,支持安全路由
- 流式聊天 - 支持可恢复流的
AIChatAgent - React hooks - 面向客户端应用的、
useAgentuseAgentChat
FIRST: Verify Installation
第一步:验证安装
bash
npm ls agents # Should show agents packageIf not installed:
bash
npm install agentsbash
npm ls agents # 应显示agents包若未安装:
bash
npm install agentsWrangler Configuration
Wrangler配置
jsonc
{
"durable_objects": {
"bindings": [{ "name": "MyAgent", "class_name": "MyAgent" }]
},
"migrations": [{ "tag": "v1", "new_sqlite_classes": ["MyAgent"] }]
}jsonc
{
"durable_objects": {
"bindings": [{ "name": "MyAgent", "class_name": "MyAgent" }]
},
"migrations": [{ "tag": "v1", "new_sqlite_classes": ["MyAgent"] }]
}Agent Class
Agent类
typescript
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 })
};typescript
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}| Class | URL |
|---|---|
| |
| |
Client:
useAgent({ agent: "Counter", name: "user-123" })请求会路由至:
/agents/{agent-name}/{instance-name}| 类名 | URL |
|---|---|
| |
| |
客户端调用:
useAgent({ agent: "Counter", name: "user-123" })Core APIs
核心API
| Task | API |
|---|---|
| Read state | |
| Write state | |
| SQL query | |
| Schedule (delay) | |
| Schedule (cron) | |
| Schedule (interval) | |
| RPC method | |
| Streaming RPC | |
| Start workflow | |
| 任务 | API |
|---|---|
| 读取状态 | |
| 写入状态 | |
| SQL查询 | |
| 延迟调度 | |
| Cron调度 | |
| 间隔调度 | |
| RPC方法 | |
| 流式RPC | |
| 启动工作流 | |
React Client
React客户端示例
tsx
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>
);
}tsx
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
参考资料
- references/workflows.md - Durable Workflows integration
- references/callable.md - RPC methods, streaming, timeouts
- references/state-scheduling.md - State persistence, scheduling
- references/streaming-chat.md - AIChatAgent, resumable streams
- references/mcp.md - MCP server integration
- references/email.md - Email routing and handling
- references/codemode.md - Code Mode (experimental)
- references/workflows.md - 持久化Workflows集成
- references/callable.md - RPC方法、流式传输、超时处理
- references/state-scheduling.md - 状态持久化、任务调度
- references/streaming-chat.md - AIChatAgent、可恢复流
- references/mcp.md - MCP服务器集成
- references/email.md - 邮件路由与处理
- references/codemode.md - 代码模式(实验性)