MCP 連携
Model Context Protocol (MCP) は、アプリケーションが LLM にツールとコンテキストを提供する方法を標準化するオープンプロトコルです。MCP のドキュメントでは、次のように説明されています。
MCP は、アプリケーションが LLM にコンテキストを提供する方法を標準化するオープンプロトコルです。MCP は、AI アプリケーション向けの USB-C ポートのようなものだと考えてください。USB-C がデバイスをさまざまな周辺機器やアクセサリーへ接続するための標準化された方法を提供するのと同様に、MCP は AI モデルをさまざまなデータソースやツールへ接続するための標準化された方法を提供します。
この SDK は、次の 3 種類の MCP サーバーをサポートしています。
- リモート MCP サーバーツール – OpenAI Responses API がツールとして使用するリモート MCP サーバー
- Streamable HTTP MCP サーバー – Streamable HTTP トランスポートを実装するローカルまたはリモートのサーバー
- Stdio MCP サーバー – 標準入出力経由でアクセスするサーバー(最も簡単な選択肢)
注:SDK には従来の Server-Sent Events トランスポート向けに
MCPServerSSEも含まれていますが、SSE は MCP プロジェクトで非推奨になっています。新しい連携では、Streamable HTTP または stdio を使用してください。
ユースケースに応じて、サーバーの種類を選択してください。
| 必要なこと | 推奨オプション |
|---|---|
| デフォルトの OpenAI Responses モデルで、公開アクセス可能なリモートサーバーを呼び出す | 1. リモート MCP サーバーツール |
| 公開アクセス可能なリモートサーバーを使用しつつ、ツール呼び出しをローカルで開始する | 2. Streamable HTTP |
| ローカルで稼働する Streamable HTTP サーバーを使用する | 2. Streamable HTTP |
| OpenAI Responses 以外のモデルで任意の Streamable HTTP サーバーを使用する | 2. Streamable HTTP |
| 標準入出力プロトコルのみをサポートするローカル MCP サーバーを使用する | 3. Stdio |
MCP SDK v2 と v1 サーバーの互換性
Section titled “MCP SDK v2 と v1 サーバーの互換性”Agents SDK は内部で MCP TypeScript SDK v2 クライアントを使用します。このために、MCP サーバーを v2 サーバーパッケージへ移行する必要はありません。stdio および Streamable HTTP 接続では、Agents SDK がプロトコルを自動的にネゴシエートし、互換性のあるプロトコルバージョンをサポートしている場合は、MCP TypeScript SDK v1 で実装された既存のサーバーとの互換性も維持します。
アプリケーションで Agents SDK の MCPServerStdio、MCPServerStreamableHttp、または MCPServerSSE クラスのみを使用している場合、この互換性のために MCP v1 と v2 のパッケージをインストールしたり、橋渡ししたりする必要はありません。v2 MCP SDK API を採用する場合は、アプリケーションが所有する MCP SDK オブジェクトを別途移行してください。MCP TypeScript SDK の v1 から v2 への移行ガイドを参照してください。
1. リモート MCP サーバーツール
Section titled “1. リモート MCP サーバーツール”組み込みツール(Hosted)は、処理の往復全体をモデル内で行います。コードから MCP サーバーを呼び出す代わりに、OpenAI Responses API がリモートツールのエンドポイントを呼び出し、実行結果をモデルへストリーミングします。
次に、リモート MCP サーバーツールを使用する最も簡単な例を示します。リモート MCP サーバーのラベルと URL を hostedMcpTool ユーティリティ関数へ渡すことで、リモート MCP サーバーツールを簡単に作成できます。
import { Agent, hostedMcpTool } from '@openai/agents';
export const agent = new Agent({ name: 'MCP Assistant', instructions: 'You must always use the MCP tools to answer questions.', tools: [ hostedMcpTool({ serverLabel: 'deepwiki', serverUrl: 'https://mcp.deepwiki.com/mcp', }), ],});続いて、run 関数(または独自にカスタマイズした Runner インスタンスの run メソッド)を使用してエージェントを実行できます。
import { run } from '@openai/agents';import { agent } from './hostedAgent';
async function main() { const result = await run( agent, 'Which language is the repo I pointed in the MCP tool settings written in?', ); console.log(result.finalOutput);}
main().catch(console.error);MCP の実行結果を段階的にストリーミングするには、Agent の実行時に stream: true を渡します。
import { isOpenAIResponsesRawModelStreamEvent, run } from '@openai/agents';import { agent } from './hostedAgent';
async function main() { const result = await run( agent, 'Which language is the repo I pointed in the MCP tool settings written in?', { stream: true }, );
for await (const event of result) { if ( isOpenAIResponsesRawModelStreamEvent(event) && event.data.event.type !== 'response.mcp_call_arguments.delta' && event.data.event.type !== 'response.output_text.delta' ) { console.log(`Got event of type ${JSON.stringify(event.data)}`); } } console.log(`Done streaming; final result: ${result.finalOutput}`);}
main().catch(console.error);オプションの承認フロー
Section titled “オプションの承認フロー”機密性の高い操作では、個々のツール呼び出しに人間の承認を必須にできます。requireApproval: 'always' を渡すか、ツール名を 'never' または 'always' にマッピングする詳細なオブジェクトを渡します。
ツール呼び出しが安全かどうかをプログラムで判断できる場合は、onApproval コールバックを使用して、ツール呼び出しを承認または拒否できます。人間の承認が必要な場合は、ローカル関数ツールと同様に、interruptions を使用する人間の介入(HITL)のアプローチを利用できます。
import { Agent, run, hostedMcpTool, RunToolApprovalItem } from '@openai/agents';
async function main(): Promise<void> { const agent = new Agent({ name: 'MCP Assistant', instructions: 'You must always use the MCP tools to answer questions.', tools: [ hostedMcpTool({ serverLabel: 'deepwiki', serverUrl: 'https://mcp.deepwiki.com/mcp', // 'always' | 'never' | { never, always } requireApproval: { never: { toolNames: ['read_wiki_structure', 'read_wiki_contents'], }, always: { toolNames: ['ask_question'], }, }, }), ], });
let result = await run( agent, 'For the repository openai/codex, tell me the primary programming language.', ); while (result.interruptions && result.interruptions.length) { for (const interruption of result.interruptions) { // Human in the loop here const approval = await confirm(interruption); if (approval) { result.state.approve(interruption); } else { result.state.reject(interruption); } } result = await run(agent, result.state); } console.log(result.finalOutput);}
import { stdin, stdout } from 'node:process';import * as readline from 'node:readline/promises';
async function confirm(item: RunToolApprovalItem): Promise<boolean> { const rl = readline.createInterface({ input: stdin, output: stdout }); const name = item.name; const params = item.arguments; const answer = await rl.question( `Approve running tool (mcp: ${name}, params: ${params})? (y/n) `, ); rl.close(); return answer.toLowerCase().trim() === 'y';}
main().catch(console.error);リモート MCP サーバーツールのオプションリファレンス
Section titled “リモート MCP サーバーツールのオプションリファレンス”hostedMcpTool(...) は、MCP サーバー URL とコネクター基盤のサーバーの両方をサポートします。
| オプション | 型 | 説明 |
|---|---|---|
serverLabel | string | イベントとトレース内でリモート MCP サーバーを識別する必須のラベル |
serverUrl | string | リモート MCP サーバーの URL(通常のリモート MCP サーバーで使用) |
connectorId | string | OpenAI コネクター ID(コネクター基盤のリモートサーバーでは serverUrl の代わりに使用) |
authorization | string | リモート MCP バックエンドへ送信するオプションの認証トークン |
headers | Record<string, string> | オプションの追加リクエストヘッダー |
allowedTools | string[] | object | モデルに公開するツール名の許可リスト。string[] または { toolNames?: string[] } を指定 |
allowedCallers | ('direct' | 'programmatic')[] | リモート MCP サーバーツールを直接、Programmatic Tool Calling 経由、またはその両方から呼び出せるかを制御する、Responses API 専用の空でないリスト |
deferLoading | boolean | リモート MCP サーバーツール向けの Responses API 専用遅延読み込み。同じエージェント内に toolSearchTool() が必要 |
requireApproval | 'never' | 'always' | object | リモート MCP サーバーツール呼び出しの承認ポリシー。ツールごとに上書きする場合はオブジェクト形式を使用。デフォルトは 'never' |
onApproval | 承認コールバック | requireApproval で承認処理が必要な場合に、プログラムによる承認または拒否を行うオプションのコールバック |
リモート MCP サーバーのツール定義を最初から公開せず、ツール検索を介してモデルが必要に応じて読み込むようにするには、deferLoading: true を設定します。この機能は OpenAI Responses API でのみ動作し、同じリクエスト内に toolSearchTool() が必要です。また、GPT-5.4 以降のサポート対象モデルリリースで使用する必要があります。遅延読み込みの完全な設定については、ツールを参照してください。
リモート MCP サーバーツールをモデルが生成した JavaScript からのみ呼び出す場合は、allowedCallers: ['programmatic'] を設定します。どちらの経路も許可するには、'direct' と 'programmatic' の両方を含めます。同じエージェントに programmaticToolCallingTool() を追加してください。プログラムが MCP ツールを呼び出す場合でも、既存の requireApproval および onApproval ポリシーが適用されます。完全な設定については、Programmatic Tool Callingを参照してください。
requireApproval のオブジェクト形式では、オプションの always および never エントリを指定できます。各エントリでは、toolNames または読み取り専用アノテーションを使用してツールを選択できます。オプションの onApproval コールバックは、現在の実行コンテキストと承認項目を受け取り、approve とオプションの reason を含む Promise を返します。
コネクター基盤のリモートサーバー
Section titled “コネクター基盤のリモートサーバー”リモート MCP は OpenAI コネクターもサポートしています。serverUrl を指定する代わりに、コネクターの connectorId と authorization トークンを渡します。その後、Responses API が認証を処理し、コネクターのツールをリモート MCP インターフェース経由で公開します。
import { Agent, hostedMcpTool } from '@openai/agents';
const authorization = process.env.GOOGLE_CALENDAR_AUTHORIZATION!;
export const connectorAgent = new Agent({ name: 'Calendar Assistant', instructions: "You are a helpful assistant that can answer questions about the user's calendar.", tools: [ hostedMcpTool({ serverLabel: 'google_calendar', connectorId: 'connector_googlecalendar', authorization, requireApproval: 'never', }), ],});この例では、GOOGLE_CALENDAR_AUTHORIZATION 環境変数に Google OAuth Playground から取得した OAuth トークンが格納されています。このトークンにより、コネクター基盤のサーバーが Calendar API を呼び出せるようになります。ストリーミングも示す実行可能なサンプルについては、examples/connectorsを参照してください。
完全に動作するサンプル(組み込みツール(Hosted)/Streamable HTTP/stdio + ストリーミング、HITL、onApproval)は、GitHub リポジトリの examples/mcpにあります。
エージェントレベルの MCP 設定
Section titled “エージェントレベルの MCP 設定”トランスポートの選択に加えて、Agent.mcpConfig を設定することで、ローカル MCP ツールの準備方法を調整できます。
import { Agent, MCPServerStreamableHttp } from '@openai/agents';
const server = new MCPServerStreamableHttp({ url: 'https://your-own-domain-here/mcp', name: 'Docs server',});
const agent = new Agent({ name: 'Assistant', mcpServers: [server], mcpConfig: { // Try to convert MCP tool schemas to strict JSON schema. convertSchemasToStrict: true, // Set to null to raise MCP tool failures instead of returning model-visible error text. errorFunction: null, // Prefix local MCP tool names with their server name. includeServerInToolNames: true, },});注:
convertSchemasToStrictはベストエフォートで動作します。スキーマを変換できない場合は、元のスキーマが使用されます。errorFunctionは、MCP ツール呼び出しの失敗をモデルへどのように提示するかを制御します。errorFunctionが設定されていない場合、SDK はデフォルトのツールエラーフォーマッターを使用します。- サーバーレベルの
errorFunction値は、そのサーバーに対するAgent.mcpConfig.errorFunctionを上書きします。 includeServerInToolNamesは、明示的に有効化する設定です。有効にすると、各ローカル MCP ツールがサーバー名を接頭辞とする決定的な名前でモデルに公開されます。これにより、複数の MCP サーバーが同じ名前のツールを公開する場合の競合を回避できます。- SDK は、URL 由来のサーバー名とトランスポートエラーをログ、トレース、エラーメッセージで公開する前に、URL の認証情報、クエリパラメーター、フラグメントを削除します。安定したサーバーラベルが必要な場合は、明示的で一意かつ機密情報を含まない
nameを設定してください。 - 異なる URL 由来のサーバー名が、認証情報、クエリパラメーター、フラグメントの削除後に同一となり、同じツール名を公開する場合、モデルへのリクエスト前に設定が失敗します。それらのサーバーには、明示的で一意かつ機密情報を含まない
name値を設定してください。
2. Streamable HTTP MCP サーバー
Section titled “2. Streamable HTTP MCP サーバー”エージェントがローカルまたはリモートの Streamable HTTP MCP サーバーと直接通信する場合は、サーバーの url、name、および任意の設定を指定して MCPServerStreamableHttp をインスタンス化します。
import { Agent, run, MCPServerStreamableHttp } from '@openai/agents';
async function main() { const mcpServer = new MCPServerStreamableHttp({ url: 'https://mcp.deepwiki.com/mcp', name: 'DeepWiki MCP Server', }); const agent = new Agent({ name: 'DeepWiki Assistant', instructions: 'Use the tools to respond to user requests.', mcpServers: [mcpServer], });
try { await mcpServer.connect(); const result = await run( agent, 'For the repository openai/codex, tell me the primary programming language.', ); console.log(result.finalOutput); } finally { await mcpServer.close(); }}
main().catch(console.error);コンストラクターのオプション:
| オプション | 型 | 説明 |
|---|---|---|
url | string | Streamable HTTP サーバーの URL |
name | string | サーバーのオプションのラベル |
cacheToolsList | boolean | レイテンシーを削減するためにツールリストをキャッシュ |
clientSessionTimeoutSeconds | number | MCP クライアントセッションのタイムアウト |
toolFilter | MCPToolFilterCallable | MCPToolFilterStatic | 利用可能なツールをフィルタリング |
toolMetaResolver | MCPToolMetaResolver | 呼び出しごとに MCP の _meta リクエストフィールドを挿入 |
toolInputGuardrails | ToolInputGuardrailDefinition[] | このサーバーから変換された各ツールを呼び出す前に実行するガードレール |
toolOutputGuardrails | ToolOutputGuardrailDefinition[] | このサーバーから変換された各ツールを呼び出した後に実行するガードレール |
useStructuredContent | boolean | 利用可能で、かつ実行結果がエラーでない場合、JSON にシリアル化した MCP の structuredContent をモデルに提示する出力として使用。デフォルトは false |
customDataExtractor | MCPToolCustomDataExtractor | 出力されたローカル MCP ツールの出力項目に、SDK 専用の JSON メタデータを付加。コールバックは、MCP の実行結果に含まれる _meta、structuredContent、isError、およびモデルに提示するツール出力を読み取り可能 |
errorFunction | MCPToolErrorFunction | null | MCP 呼び出しの失敗をモデルに提示するテキストへ変換 |
timeout | number | リクエストごとのタイムアウト(ミリ秒) |
logger | Logger | カスタムロガー |
authProvider | OAuthClientProvider | MCP TypeScript SDK の OAuth プロバイダー |
requestInit | RequestInit | リクエスト用の Fetch 初期化オプション |
fetch | FetchLike | カスタム Fetch 実装 |
reconnectionOptions | StreamableHTTPReconnectionOptions | 再接続の調整オプション |
sessionId | string | MCP 接続用の明示的なセッション ID |
コンストラクターは、authProvider、requestInit、fetch、reconnectionOptions、sessionId など、MCP TypeScript SDK の追加オプションも受け付けます。詳細については、MCP TypeScript SDK リポジトリとそのドキュメントを参照してください。
toolInputGuardrails と toolOutputGuardrails は、SDK のローカル関数ツール用ガードレールパイプラインを使用します。これらは、ストリーミング実行と非ストリーミング実行の両方で、このサーバーから変換されたすべてのツールに適用されます。Responses API がリモートで実行するリモート MCP サーバーツールには適用されません。拒否時の動作と承認順序については、ツールガードレールを参照してください。
3. Stdio MCP サーバー
Section titled “3. Stdio MCP サーバー”標準入出力のみを公開するサーバーでは、fullCommand を指定して MCPServerStdio をインスタンス化します。
import { Agent, run, MCPServerStdio } from '@openai/agents';import * as path from 'node:path';
async function main() { const samplesDir = path.join(__dirname, 'sample_files'); const mcpServer = new MCPServerStdio({ name: 'Filesystem MCP Server, via local package', fullCommand: `pnpm exec mcp-server-filesystem ${samplesDir}`, }); await mcpServer.connect(); try { const agent = new Agent({ name: 'FS MCP Assistant', instructions: 'Use the tools to read the filesystem and answer questions based on those files. If you are unable to find any files, you can say so instead of assuming they exist.', mcpServers: [mcpServer], }); const result = await run(agent, 'Read the files and list them.'); console.log(result.finalOutput); } finally { await mcpServer.close(); }}
main().catch(console.error);コンストラクターのオプション:
| オプション | 型 | 説明 |
|---|---|---|
command / args | string / string[] | stdio サーバー用のコマンドと引数 |
fullCommand | string | command と args の代わりに使用する完全なコマンド文字列 |
env | Record<string, string> | サーバープロセスの環境変数 |
cwd | string | サーバープロセスの作業ディレクトリ |
cacheToolsList | boolean | レイテンシーを削減するためにツールリストをキャッシュ |
clientSessionTimeoutSeconds | number | MCP クライアントセッションのタイムアウト |
name | string | サーバーのオプションのラベル |
encoding | string | stdio ストリームのエンコーディング |
encodingErrorHandler | 'strict' | 'ignore' | 'replace' | エンコーディングエラーの処理方法 |
toolFilter | MCPToolFilterCallable | MCPToolFilterStatic | 利用可能なツールをフィルタリング |
toolMetaResolver | MCPToolMetaResolver | 呼び出しごとに MCP の _meta リクエストフィールドを挿入 |
toolInputGuardrails | ToolInputGuardrailDefinition[] | このサーバーから変換された各ツールを呼び出す前に実行するガードレール |
toolOutputGuardrails | ToolOutputGuardrailDefinition[] | このサーバーから変換された各ツールを呼び出した後に実行するガードレール |
useStructuredContent | boolean | 利用可能で、かつ実行結果がエラーでない場合、JSON にシリアル化した MCP の structuredContent をモデルに提示する出力として使用。デフォルトは false |
customDataExtractor | MCPToolCustomDataExtractor | 出力されたローカル MCP ツールの出力項目に、SDK 専用の JSON メタデータを付加。コールバックは、MCP の実行結果に含まれる _meta、structuredContent、isError、およびモデルに提示するツール出力を読み取り可能 |
errorFunction | MCPToolErrorFunction | null | MCP 呼び出しの失敗をモデルに提示するテキストへ変換 |
timeout | number | リクエストごとのタイムアウト(ミリ秒) |
logger | Logger | カスタムロガー |
MCP サーバーのライフサイクル管理
Section titled “MCP サーバーのライフサイクル管理”複数の MCP サーバーを使用する場合、connectMcpServers を使用してまとめて接続し、失敗を追跡して、一括で閉じることができます。このヘルパーは、active、failed、errors コレクションを持つ MCPServers インスタンスを返すため、正常なサーバーのみをエージェントに渡せます。
import { Agent, MCPServerStreamableHttp, connectMcpServers, run,} from '@openai/agents';
async function main() { const servers = [ new MCPServerStreamableHttp({ url: 'https://mcp.deepwiki.com/mcp', name: 'DeepWiki MCP Server', }), new MCPServerStreamableHttp({ url: 'http://localhost:8001/mcp', name: 'Local MCP Server', }), ];
const mcpServers = await connectMcpServers(servers, { connectInParallel: true, });
try { console.log(`Active servers: ${mcpServers.active.length}`); console.log(`Failed servers: ${mcpServers.failed.length}`); for (const [server, error] of mcpServers.errors) { console.warn(`${server.name} failed to connect: ${error.message}`); }
const agent = new Agent({ name: 'MCP lifecycle agent', instructions: 'Use MCP tools to answer user questions.', mcpServers: mcpServers.active, });
const result = await run( agent, 'Which language is the openai/codex repository written in?', ); console.log(result.finalOutput); } finally { await mcpServers.close(); }}
main().catch(console.error);ユースケース:
- 複数サーバーの同時利用 :すべてへ並列に接続し、エージェントでは
mcpServers.activeを使用します。 - 部分的な失敗の処理 :
failedとerrorsを確認し、続行するか再試行するかを決定します。 - 失敗したサーバーの再試行 :
mcpServers.reconnect()を呼び出します(デフォルトでは失敗したサーバーのみを再試行します)。
厳密な「オール・オア・ナッシング」接続や異なるタイムアウトが必要な場合は、connectMcpServers(servers, options) を使用し、環境に合わせてオプションを調整します。
connectMcpServers のオプション:
| オプション | 型 | デフォルト | 説明 |
|---|---|---|---|
connectTimeoutMs | number | null | 10000 | 各サーバーの connect() のタイムアウト。無効にするには null を使用 |
closeTimeoutMs | number | null | 10000 | 各サーバーの close() のタイムアウト。無効にするには null を使用 |
dropFailed | boolean | true | 失敗したサーバーを active から除外 |
strict | boolean | false | いずれかのサーバーへの接続が失敗した場合に例外をスロー |
suppressAbortError | boolean | true | 失敗したサーバーを追跡しながら、中断に類似するエラーを無視 |
connectInParallel | boolean | false | すべてのサーバーへ順番にではなく同時に接続 |
mcpServers.reconnect(options) は、次のオプションをサポートします。
| オプション | 型 | デフォルト | 説明 |
|---|---|---|---|
failedOnly | boolean | true | 失敗したサーバーのみを再試行(true)するか、すべてのサーバーへ再接続(false) |
再接続の前に、MCPServers は選択されたサーバーを閉じます。正常に閉じられたサーバーのみに再接続します。クリーンアップの失敗は、引き続き failed と errors から確認できます。
非同期破棄(オプション)
Section titled “非同期破棄(オプション)”ランタイムが Symbol.asyncDispose をサポートしている場合、MCPServers は await using パターンもサポートします。TypeScript では、tsconfig.json で esnext.disposable を有効にします。
{ "compilerOptions": { "lib": ["ES2018", "DOM", "esnext.disposable"] }}その後、次のように記述できます。
import { MCPServerStreamableHttp, connectMcpServers } from '@openai/agents';
async function main() { const servers = [ new MCPServerStreamableHttp({ url: 'https://your-own-domain-here/mcp', name: 'Docs server', }), ];
await using mcpServers = await connectMcpServers(servers);}
main().catch(console.error);その他の留意事項
Section titled “その他の留意事項”Streamable HTTP および Stdio サーバーでは、Agent を実行するたびに、利用可能なツールを検出するため list_tools() が呼び出される場合があります。この往復処理は、特にリモートサーバーでレイテンシーを増加させる可能性があります。MCPServerStdio または MCPServerStreamableHttp に cacheToolsList: true を渡すことで、実行結果をメモリにキャッシュできます。
ツールリストが変更されないことを確信できる場合にのみ、この機能を有効にしてください。後でキャッシュを無効化するには、サーバーインスタンスで invalidateToolsCache() を呼び出します。getAllMcpTools(...) による共有 MCP ツールキャッシュを使用している場合は、invalidateServerToolsCache(serverName) を使用してサーバー名ごとに無効化することもできます。
高度なユースケースでは、getAllMcpTools({ generateMCPToolCacheKey }) を使用して、キャッシュの分割方法をカスタマイズできます。たとえば、サーバー、エージェント、実行コンテキストの組み合わせごとに分割できます。
サーバー名を接頭辞とするツール名
Section titled “サーバー名を接頭辞とするツール名”デフォルトでは、ローカル MCP ツールは MCP サーバーから通知されたツール名を維持します。2 つのローカル MCP サーバーが同じツール名を公開している場合、モデルが安全に選択できないため、SDK はツール名の重複エラーを発生させます。
決定的なサーバー名を接頭辞とする名前を明示的に有効化するには、エージェントで mcpConfig.includeServerInToolNames: true を設定します。
import { Agent, MCPServerStreamableHttp } from '@openai/agents';
const docsServer = new MCPServerStreamableHttp({ url: 'https://your-own-domain-here/docs/mcp', name: 'docs',});const calendarServer = new MCPServerStreamableHttp({ url: 'https://your-own-domain-here/calendar/mcp', name: 'calendar',});
const agent = new Agent({ name: 'Assistant', mcpServers: [docsServer, calendarServer], mcpConfig: { includeServerInToolNames: true, },});この設定では、docs サーバーの search ツールは mcp_docs__search としてモデルに公開され、calendar サーバーの search ツールは mcp_calendar__search として公開されます。SDK は引き続き、元のサーバーで元の MCP ツール名を呼び出します。
生成される名前は ASCII セーフで、FunctionTool インスタンスの名前の長さ制限内に収まり、同じエージェント上のローカル FunctionTool インスタンスや有効なハンドオフの名前と競合しません。この設定は、Streamable HTTP、SSE、stdio を含むすべてのローカル MCP トランスポートに影響します。リモート MCP サーバーツールでは、リモートサーバーのラベルとツールメタデータが維持されます。
ツールのフィルタリング
Section titled “ツールのフィルタリング”createMCPToolStaticFilter による静的フィルターまたはカスタム関数を渡すことで、各サーバーから公開するツールを制限できます。次に、両方のアプローチを組み合わせた例を示します。
import { MCPServerStdio, MCPServerStreamableHttp, createMCPToolStaticFilter, MCPToolFilterContext,} from '@openai/agents';
interface ToolFilterContext { allowAll: boolean;}
const server = new MCPServerStdio({ fullCommand: 'my-server', toolFilter: createMCPToolStaticFilter({ allowed: ['safe_tool'], blocked: ['danger_tool'], }),});
const dynamicServer = new MCPServerStreamableHttp({ url: 'http://localhost:3000', toolFilter: async ({ runContext }: MCPToolFilterContext, tool) => (runContext.context as ToolFilterContext).allowAll || tool.name !== 'admin',});- Model Context Protocol – 公式仕様
- examples/mcp – 上記で参照した実行可能なデモ