agents-sdk

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Cloudflare 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
https://github.com/cloudflare/agents/tree/main/docs
before implementing.
TopicDocUse for
Getting started
docs/getting-started.md
First agent, project setup
State
docs/state.md
setState
,
validateStateChange
, persistence
Routing
docs/routing.md
URL patterns,
routeAgentRequest
,
basePath
Callable methods
docs/callable-methods.md
@callable
, RPC, streaming, timeouts
Scheduling
docs/scheduling.md
schedule()
,
scheduleEvery()
, cron
Workflows
docs/workflows.md
AgentWorkflow
, durable multi-step tasks
HTTP/WebSockets
docs/http-websockets.md
Lifecycle hooks, hibernation
Email
docs/email.md
Email routing, secure reply resolver
MCP client
docs/mcp-client.md
Connecting to MCP servers
MCP server
docs/mcp-servers.md
Building MCP servers with
McpAgent
Client SDK
docs/client-sdk.md
useAgent
,
useAgentChat
, React hooks
Human-in-the-loop
docs/human-in-the-loop.md
Approval flows, pausing workflows
Resumable streaming
docs/resumable-streaming.md
Stream recovery on disconnect
实现前请从
https://github.com/cloudflare/agents/tree/main/docs
获取最新文档。
主题文档适用场景
入门指南
docs/getting-started.md
首个Agent开发、项目搭建
状态管理
docs/state.md
setState
validateStateChange
、持久化
路由配置
docs/routing.md
URL规则、
routeAgentRequest
basePath
可调用方法
docs/callable-methods.md
@callable
、RPC、流式传输、超时处理
任务调度
docs/scheduling.md
schedule()
scheduleEvery()
、cron任务
工作流
docs/workflows.md
AgentWorkflow
、持久化多步骤任务
HTTP/WebSocket
docs/http-websockets.md
生命周期钩子、休眠机制
邮件处理
docs/email.md
邮件路由、安全回复解析器
MCP客户端
docs/mcp-client.md
连接MCP服务器
MCP服务器
docs/mcp-servers.md
使用
McpAgent
构建MCP服务器
客户端SDK
docs/client-sdk.md
useAgent
useAgentChat
、React hooks
人机协同
docs/human-in-the-loop.md
审批流、工作流暂停
可恢复流式传输
docs/resumable-streaming.md
断开连接后的流恢复

Capabilities

功能特性

The Agents SDK provides:
  • Persistent state - SQLite-backed, auto-synced to clients
  • Callable RPC -
    @callable()
    methods invoked over WebSocket
  • Scheduling - One-time, recurring (
    scheduleEvery
    ), and cron tasks
  • 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 -
    AIChatAgent
    with resumable streams
  • React hooks -
    useAgent
    ,
    useAgentChat
    for client apps
Agents SDK提供以下功能:
  • 持久化状态 - 基于SQLite,自动同步至客户端
  • 可调用RPC - 通过WebSocket调用
    @callable()
    方法
  • 任务调度 - 一次性任务、周期性任务(
    scheduleEvery
    )以及cron任务
  • 工作流 - 通过
    AgentWorkflow
    实现持久化多步骤后台处理
  • MCP集成 - 连接MCP服务器或使用
    McpAgent
    构建自有服务器
  • 邮件处理 - 接收和回复邮件,支持安全路由
  • 流式聊天 - 支持可恢复流的
    AIChatAgent
  • React hooks - 面向客户端应用的
    useAgent
    useAgentChat

FIRST: Verify Installation

第一步:验证安装

bash
npm ls agents  # Should show agents package
If not installed:
bash
npm install agents
bash
npm ls agents  # 应显示agents包
若未安装:
bash
npm install agents

Wrangler 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}
:
ClassURL
Counter
/agents/counter/user-123
ChatRoom
/agents/chat-room/lobby
Client:
useAgent({ agent: "Counter", name: "user-123" })
请求会路由至
/agents/{agent-name}/{instance-name}
类名URL
Counter
/agents/counter/user-123
ChatRoom
/agents/chat-room/lobby
客户端调用:
useAgent({ agent: "Counter", name: "user-123" })

Core APIs

核心API

TaskAPI
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)
任务API
读取状态
this.state.count
写入状态
this.setState({ count: 1 })
SQL查询
this.sql`SELECT * FROM users WHERE id = ${id}`
延迟调度
await this.schedule(60, "task", payload)
Cron调度
await this.schedule("0 * * * *", "task", payload)
间隔调度
await this.scheduleEvery(30, "poll")
RPC方法
@callable() myMethod() { ... }
流式RPC
@callable({ streaming: true }) stream(res) { ... }
启动工作流
await this.runWorkflow("ProcessingWorkflow", params)

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 - 代码模式(实验性)