Skip to content

非公式本サイトは非公式の日本語ドキュメントであり、Cloudflare 公式サイトではありません。最新情報はdevelopers.cloudflare.comをご確認ください。

getCurrentAgent()

最終更新 Markdown で表示Agent セットアップ

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

設定は不要です。フレームワークは自動で次を行います。

  1. エージェントクラスのカスタムメソッドをスキャンします。
  2. 初期化時に、それらをエージェントコンテキストでラップします。
  3. メソッドから呼ぶすべての外部関数で、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;
	}
}

組み込みメソッドとカスタムメソッド

  • 組み込みメソッドonRequestonEmailonStateChanged): すでにコンテキストがあります。
  • カスタムメソッド(自分で定義したメソッド): 初期化時に自動でラップされます。
  • 外部関数: 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()

よくあるユースケース

AI SDK のツールと使う

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

この方法で復元したコンテキストでは、connectionrequestemail は未設定です。ライブなクライアント I/O には結び付きません。

McpAgent 上のサーバー起点 MCP リクエスト(elicitInputcreateMessagelistRoots)では、この迂回は不要です。MCP トランスポートが所有エージェントを保持するためです。

API リファレンス

getCurrentAgent()

利用可能な任意のコンテキストから、現在のエージェントを取得します。

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 経由) はい はい いいえ いいえ
スケジュールタスク はい いいえ いいえ いいえ
キューコールバック はい 場合による 場合による 場合による

ベストプラクティス

  1. 可能なときは this を使う: エージェントメソッド内では、getCurrentAgent() より this.namethis.state などを優先します。

  2. 外部関数では getCurrentAgent() を使う: this にアクセスできないユーティリティ関数やライブラリで、エージェントコンテキストが必要なときです。

  3. 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);
    }
  4. エージェントに型を付ける: 正しい型付けのため、エージェントクラスを型パラメーターとして渡します。

    const { agent } = getCurrentAgent();
    // agent is typed as MyAgent | undefined
    const { agent } = getCurrentAgent<MyAgent>();
    // agent is typed as MyAgent | undefined

次のステップ

Agents API

Agents SDK の API リファレンスです。

状態管理

エージェント状態を管理し、同期します。

役に立ちましたか?