agents-sdk について
`agents` パッケージでエージェントを開発するための Cloudflare Agents SDK スキルです。最新ドキュメントの参照を促し、状態管理、スケジュール、ワークフロー、チャット、MCP 連携を扱います。
主な機能
- 01最新 SDK ドキュメントの参照案内
- 02SQLite ベースの永続状態
- 03RPC、スケジュール、永続ワークフロー
- 04メール処理とストリーミングチャット
- 05エージェントクライアント向け React フック
活用シーン
- 01実装前に適切な SDK ドキュメントを確認
- 02永続状態とスケジュールタスクを備えたエージェントの構築
- 03永続的な複数ステップ処理とストリーミングチャットの追加
- 04MCP サーバーへの接続や MCP サーバーの構築
MCP 対応
SDK から MCP サーバーに接続する方法と、`McpAgent` で MCP サーバーを構築する方法を扱います。
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ cloudflare/ cloudflare-docs --skill agents-sdkインストール後、Claude Code で/agents-sdkを入力して読み込まれたか確認します。
同梱ファイル
SKILL.md と一緒にインストールされる参考資料やスクリプト。
references/callable.mdcodemode.mdemail.mdmcp.mdstate-scheduling.mdstreaming-chat.mdworkflows.md詳細
Cloudflare Agents SDK
停止してください。 Agents SDK に関する知識は古くなっている可能性があります。Agents SDK に関するタスクでは、事前学習済みの知識よりも検索を優先してください。
ドキュメント
実装前に、最新のドキュメントを https://github.com/cloudflare/agents/tree/main/docs から取得してください。
| トピック | ドキュメント | 用途 |
|---|---|---|
| はじめに | docs/getting-started.md | 最初のエージェント、プロジェクトのセットアップ |
| 状態 | 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 フック |
| Human-in-the-loop | docs/human-in-the-loop.md | 承認フロー、ワークフローの一時停止 |
| 再開可能なストリーミング | docs/resumable-streaming.md | 切断時のストリーム復旧 |
Cloudflare のドキュメント:https://developers.cloudflare.com/agents/
機能
Agents SDK には以下の機能があります。
- 永続的な状態 - SQLite ベースで、クライアントに自動同期されます
- 呼び出し可能な RPC - WebSocket 経由で呼び出す
@callable()メソッド - スケジューリング - 1 回限り、定期的(
scheduleEvery)、cron タスク - ワークフロー -
AgentWorkflowによる永続的な複数ステップのバックグラウンド処理 - MCP 統合 - MCP サーバーへの接続、または
McpAgentを使った独自サーバーの構築 - メール処理 - 安全なルーティングによるメールの受信と返信
- ストリーミングチャット - 再開可能なストリームを備えた
AIChatAgent - React フック - クライアントアプリ向けの
useAgent、useAgentChat
最初に:インストールの確認
npm ls agents # Should show agents package
インストールされていない場合:
npm install agents
Wrangler の設定
{
"durable_objects": {
"bindings": [{ "name": "MyAgent", "class_name": "MyAgent" }]
},
"migrations": [{ "tag": "v1", "new_sqlite_classes": ["MyAgent"] }]
}
Agent クラス
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} にルーティングされます。
| クラス | URL |
|---|---|
Counter | /agents/counter/user-123 |
ChatRoom | /agents/chat-room/lobby |
クライアント:useAgent({ agent: "Counter", name: "user-123" })
コア API
| タスク | 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 クライアント
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/workflows.md - Durable Workflows の統合
- references/callable.md - RPC メソッド、ストリーミング、タイムアウト
- references/state-scheduling.md - 状態の永続化、スケジューリング
- references/streaming-chat.md - AIChatAgent、再開可能なストリーム
- references/mcp.md - MCP サーバーの統合
- references/email.md - メールのルーティングと処理
- references/codemode.md - Code Mode(実験的)
コメント
Markdown 対応