getCurrentAgent() を使うと、外部ユーティリティ関数やライブラリを含む、コードのどこからでも現在のエージェントコンテキストにアクセスできます。this に直接アクセスできない関数で、エージェント情報が必要なときに便利です。
フレームワークは初期化時にカスタム Agent メソッドを検出してラップします。そのため、そのメソッド内と、そこから呼ぶ関数内で getCurrentAgent() がアクティブなエージェントを解決できます。
import { AIChatAgent } from "@cloudflare/ai-chat";
import { getCurrentAgent } from "agents";
export class MyAgent extends AIChatAgent {
async customMethod() {
const { agent } = getCurrentAgent();
// agent is automatically available
console.log(agent.name);
}
async anotherMethod() {
// This works too - no setup needed
const { agent } = getCurrentAgent();
return agent.state;
}
}import { AIChatAgent } from "@cloudflare/ai-chat";
import { getCurrentAgent } from "agents";
export class MyAgent extends AIChatAgent {
async customMethod() {
const { agent } = getCurrentAgent();
// agent is automatically available
console.log(agent.name);
}
async anotherMethod() {
// This works too - no setup needed
const { agent } = getCurrentAgent();
return agent.state;
}
}設定は不要です。フレームワークは自動で次を行います。
- エージェントクラスのカスタムメソッドをスキャンします。
- 初期化時に、それらをエージェントコンテキストでラップします。
- メソッドから呼ぶすべての外部関数で、
getCurrentAgent()が動くようにします。
import { AIChatAgent } from "@cloudflare/ai-chat";
import { getCurrentAgent } from "agents";
import { generateText } from "ai";
import { openai } from "@ai-sdk/openai";
// External utility function that needs agent context
async function processWithAI(prompt) {
const { agent } = getCurrentAgent();
// External functions can access the current agent
return await generateText({
model: openai("gpt-4"),
prompt: `Agent ${agent?.name}: ${prompt}`,
});
}
export class MyAgent extends AIChatAgent {
async customMethod(message) {
// Use this.* to access agent properties directly
console.log("Agent name:", this.name);
console.log("Agent state:", this.state);
// External functions automatically work
const result = await processWithAI(message);
return result.text;
}
}import { AIChatAgent } from "@cloudflare/ai-chat";
import { getCurrentAgent } from "agents";
import { generateText } from "ai";
import { openai } from "@ai-sdk/openai";
// External utility function that needs agent context
async function processWithAI(prompt: string) {
const { agent } = getCurrentAgent();
// External functions can access the current agent
return await generateText({
model: openai("gpt-4"),
prompt: `Agent ${agent?.name}: ${prompt}`,
});
}
export class MyAgent extends AIChatAgent {
async customMethod(message: string) {
// Use this.* to access agent properties directly
console.log("Agent name:", this.name);
console.log("Agent state:", this.state);
// External functions automatically work
const result = await processWithAI(message);
return result.text;
}
}- 組み込みメソッド(
onRequest、onEmail、onStateChanged): すでにコンテキストがあります。 - カスタムメソッド(自分で定義したメソッド): 初期化時に自動でラップされます。
- 外部関数:
getCurrentAgent()でコンテキストにアクセスします。
// When you call a custom method:
agent.customMethod();
// → automatically wrapped with agentContext.run()
// → your method executes with full context
// → external functions can use getCurrentAgent()// When you call a custom method:
agent.customMethod();
// → automatically wrapped with agentContext.run()
// → your method executes with full context
// → external functions can use getCurrentAgent()import { AIChatAgent } from "@cloudflare/ai-chat";
import { generateText } from "ai";
import { openai } from "@ai-sdk/openai";
export class MyAgent extends AIChatAgent {
async generateResponse(prompt) {
// AI SDK tools automatically work
const response = await generateText({
model: openai("gpt-4"),
prompt,
tools: {
// Tools that use getCurrentAgent() work perfectly
},
});
return response.text;
}
}import { AIChatAgent } from "@cloudflare/ai-chat";
import { generateText } from "ai";
import { openai } from "@ai-sdk/openai";
export class MyAgent extends AIChatAgent {
async generateResponse(prompt: string) {
// AI SDK tools automatically work
const response = await generateText({
model: openai("gpt-4"),
prompt,
tools: {
// Tools that use getCurrentAgent() work perfectly
},
});
return response.text;
}
}import { AIChatAgent } from "@cloudflare/ai-chat";
import { getCurrentAgent } from "agents";
async function saveToDatabase(data) {
const { agent } = getCurrentAgent();
// Can access agent info for logging, context, etc.
console.log(`Saving data for agent: ${agent?.name}`);
}
export class MyAgent extends AIChatAgent {
async processData(data) {
// External functions automatically have context
await saveToDatabase(data);
}
}import { AIChatAgent } from "@cloudflare/ai-chat";
import { getCurrentAgent } from "agents";
async function saveToDatabase(data: any) {
const { agent } = getCurrentAgent();
// Can access agent info for logging, context, etc.
console.log(`Saving data for agent: ${agent?.name}`);
}
export class MyAgent extends AIChatAgent {
async processData(data: any) {
// External functions automatically have context
await saveToDatabase(data);
}
}import { getCurrentAgent } from "agents";
function logRequestInfo() {
const { agent, connection, request } = getCurrentAgent();
if (request) {
console.log("Request URL:", request.url);
console.log("Request method:", request.method);
}
if (connection) {
console.log("Connection ID:", connection.id);
}
}import { getCurrentAgent } from "agents";
function logRequestInfo() {
const { agent, connection, request } = getCurrentAgent();
if (request) {
console.log("Request URL:", request.url);
console.log("Request method:", request.method);
}
if (connection) {
console.log("Connection ID:", connection.id);
}
}エージェントコンテキストは、元の呼び出しのコールツリーに沿ってだけ伝播します。そのコールツリーの外に到達したコードは空のコンテキストで始まるため、getCurrentAgent() は各フィールドが undefined のオブジェクトを返します。よくあるケースは次です。
- Worker Loader の子 isolate から RPC で呼ばれるホストコールバック(サンドボックス化された Codemode 実行など)
- service binding または Durable Object の RPC エントリポイント
- エージェント参照を保持する queue consumer や、その他のエントリポイント
コールバックはエージェントの公開メソッド経由にします。カスタムメソッドは自動でラップされるため、agent.someMethod() を呼べば、そのエージェントのコンテキストに再入場します。
import { RpcTarget } from "cloudflare:workers";
class HostCallbackBridge extends RpcTarget {
agent;
constructor(agent) {
super();
this.agent = agent;
}
// Invoked through RPC from a Worker Loader child isolate. There is no context
// ancestry. Calling a public agent method restores it automatically.
async invoke() {
return this.agent.handleSandboxCallback();
}
}
export class MyMcpAgent extends McpAgent {
async handleSandboxCallback() {
const { agent } = getCurrentAgent();
// `agent` is available again.
}
}import { RpcTarget } from "cloudflare:workers";
class HostCallbackBridge extends RpcTarget {
agent: MyMcpAgent;
constructor(agent: MyMcpAgent) {
super();
this.agent = agent;
}
// Invoked through RPC from a Worker Loader child isolate. There is no context
// ancestry. Calling a public agent method restores it automatically.
async invoke() {
return this.agent.handleSandboxCallback();
}
}
export class MyMcpAgent extends McpAgent {
async handleSandboxCallback() {
const { agent } = getCurrentAgent<MyMcpAgent>();
// `agent` is available again.
}
}この方法で復元したコンテキストでは、connection、request、email は未設定です。ライブなクライアント I/O には結び付きません。
McpAgent 上のサーバー起点 MCP リクエスト(elicitInput、createMessage、listRoots)では、この迂回は不要です。MCP トランスポートが所有エージェントを保持するためです。
利用可能な任意のコンテキストから、現在のエージェントを取得します。
import { getCurrentAgent } from "agents";import { getCurrentAgent } from "agents";
function getCurrentAgent<T extends Agent>(): {
agent: T | undefined;
connection: Connection | undefined;
request: Request | undefined;
email: AgentEmail | undefined;
};| プロパティ | 型 | 説明 |
|---|---|---|
agent |
T | undefined |
現在のエージェントインスタンス |
connection |
Connection | undefined |
WebSocket 接続(WebSocket ハンドラーから呼ばれた場合) |
request |
Request | undefined |
HTTP リクエスト(リクエストハンドラーから呼ばれた場合) |
email |
AgentEmail | undefined |
メール(メールハンドラーから呼ばれた場合) |
import { AIChatAgent } from "@cloudflare/ai-chat";
import { getCurrentAgent } from "agents";
export class MyAgent extends AIChatAgent {
async customMethod() {
const { agent, connection, request } = getCurrentAgent();
// agent is properly typed as MyAgent
// connection and request available if called from a request handler
}
}import { AIChatAgent } from "@cloudflare/ai-chat";
import { getCurrentAgent } from "agents";
export class MyAgent extends AIChatAgent {
async customMethod() {
const { agent, connection, request } = getCurrentAgent<MyAgent>();
// agent is properly typed as MyAgent
// connection and request available if called from a request handler
}
}使えるコンテキストは、メソッドの呼び出され方によって変わります。
| 呼び出し | agent |
connection |
request |
email |
|---|---|---|---|---|
onRequest() |
はい | いいえ | はい | いいえ |
onConnect() |
はい | はい | はい | いいえ |
onMessage() |
はい | はい | いいえ | いいえ |
onEmail() |
はい | いいえ | いいえ | はい |
| カスタムメソッド(RPC 経由) | はい | はい | いいえ | いいえ |
| スケジュールタスク | はい | いいえ | いいえ | いいえ |
| キューコールバック | はい | 場合による | 場合による | 場合による |
-
可能なときは
thisを使う: エージェントメソッド内では、getCurrentAgent()よりthis.name、this.stateなどを優先します。 -
外部関数では
getCurrentAgent()を使う:thisにアクセスできないユーティリティ関数やライブラリで、エージェントコンテキストが必要なときです。 -
undefined を確認する: エージェントコンテキストの外で呼ぶと、戻り値は
undefinedになることがあります。const { agent } = getCurrentAgent(); if (agent) { // Safe to use agent console.log(agent.name); }const { agent } = getCurrentAgent(); if (agent) { // Safe to use agent console.log(agent.name); } -
エージェントに型を付ける: 正しい型付けのため、エージェントクラスを型パラメーターとして渡します。
const { agent } = getCurrentAgent(); // agent is typed as MyAgent | undefinedconst { agent } = getCurrentAgent<MyAgent>(); // agent is typed as MyAgent | undefined