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 |
| 標準 I/O プロトコルのみをサポートするローカル 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 ツール(Hosted)を使用する最も簡単な例を示します。リモート 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 専用の空でないリストです。 |
deferLoading | boolean | リモート MCP サーバーツールを遅延読み込みする Responses 専用オプションです。同じエージェントに 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 リクエストフィールドを挿入します。 |
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 リポジトリとそのドキュメントを参照してください。
3. Stdio MCP サーバー
Section titled “3. Stdio MCP サーバー”標準 I/O のみを公開するサーバーでは、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 リクエストフィールドを挿入します。 |
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 | 失敗したサーバーを追跡しながら、abort 系のエラーを無視します。 |
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 – 上記で参照した実行可能なデモ