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も含まれていますが、MCP プロジェクトでは SSE は非推奨となっています。新たに連携する場合は、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 サーバーツールの作成に便利なユーティリティ関数 hostedMcpTool に、リモート MCP サーバーのラベルと URL を渡せます。
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 ツールを直接呼び出すか、プログラムによるツール呼び出し経由で呼び出すか、両方を許可するかを制御する空でないリスト。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 のポリシーが適用されます。設定全体については、プログラムによるツール呼び出しを参照してください。
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 | MCP の structuredContent が利用可能で、結果がエラーでない場合、JSON にシリアライズした内容をモデルに提示する出力として使用します。デフォルトは 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 | MCP の structuredContent が利用可能で、結果がエラーでない場合、JSON にシリアライズした内容をモデルに提示する出力として使用します。デフォルトは 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 – 上記で参照した実行可能なコード例