コンテンツにスキップ

MCP 連携

Model Context Protocol (MCP) は、アプリケーションが LLM にツールやコンテキストを提供する方法を標準化するオープンプロトコルです。MCP のドキュメントから引用します。

MCP は、アプリケーションが LLM にコンテキストを提供する方法を標準化するオープンプロトコルです。MCP を AI アプリケーション向けの USB-C ポートと考えてください。USB-C が各種デバイスを周辺機器やアクセサリーに接続する標準化された方法を提供するのと同様に、MCP は AI モデルをさまざまなデータソースやツールに接続する標準化された方法を提供します。

この SDK がサポートする MCP サーバーは 3 種類あります。

  1. リモート MCP サーバーツールOpenAI Responses API によってツールとして使用されるリモート MCP サーバー
  2. Streamable HTTP MCP サーバーStreamable HTTP トランスポート を実装したローカルまたはリモートサーバー
  3. Stdio MCP サーバー – 標準入出力経由でアクセスするサーバー(最もシンプルなオプション)

ユースケースに応じてサーバータイプを選択してください。

必要な内容推奨オプション
OpenAI Responses のデフォルトモデルで、公開アクセス可能なリモートサーバーを呼び出す1. リモート MCP サーバーツール
公開アクセス可能なリモートサーバーを利用しつつ、ツール呼び出しをローカルで実行したい2. Streamable HTTP
ローカルで実行している Streamable HTTP サーバーを使用する2. Streamable HTTP
OpenAI Responses 以外のモデルで、任意の Streamable HTTP サーバーを使用する2. Streamable HTTP
標準入出力プロトコルのみをサポートするローカル MCP サーバーと連携する3. Stdio

リモートツールでは、往復処理全体をモデル内部で完結させます。あなたのコードが MCP サーバーを呼び出す代わりに、OpenAI Responses API がリモートツールのエンドポイントを呼び出し、その結果をストリーミングでモデルへ返します。

以下はリモート MCP サーバーツールを使用する最小限の例です。リモート MCP サーバーの labelurlhostedMcpTool ユーティリティ関数に渡します。

hostedAgent.ts
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: 'gitmcp',
serverUrl: 'https://gitmcp.io/openai/codex',
}),
],
});

その後、run 関数(または独自の Runner インスタンスの run メソッド)でエージェントを実行できます。

Run with hosted MCP tools
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 を渡してください。

Run with hosted MCP tools (streaming)
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?',
{ stream: true },
);
for await (const event of result) {
if (
event.type === 'raw_model_stream_event' &&
event.data.type === 'model' &&
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);

機微な操作の場合、個別のツール呼び出しに対して人による承認を必須にできます。requireApproval: 'always' もしくは、ツール名を 'never' / 'always' でマッピングした詳細オブジェクトを渡してください。

ツール呼び出しが安全かどうかをプログラムで判断できる場合は、onApproval コールバック を使用して承認または拒否を行えます。人による承認が必要な場合は、ローカル関数ツールと同様に interruptions を使った 人間の介入(HITL)のアプローチ を利用できます。

Human in the loop with hosted MCP tools
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: 'gitmcp',
serverUrl: 'https://gitmcp.io/openai/codex',
// 'always' | 'never' | { never, always }
requireApproval: {
never: {
toolNames: ['search_codex_code', 'fetch_codex_documentation'],
},
always: {
toolNames: ['fetch_generic_url_content'],
},
},
}),
],
});
let result = await run(agent, 'Which language is this repo written in?');
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.rawItem.name;
const params = item.rawItem.providerData?.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);

完全な動作例(リモートツール / Streamable HTTP / Stdio における Streaming、HITL、onApproval など)は GitHub リポジトリの examples/mcp にあります。

エージェントがローカルまたはリモートの Streamable HTTP MCP サーバーと直接通信する場合、MCPServerStreamableHttp をサーバーの urlname、および任意の設定とともにインスタンス化します。

Run with Streamable HTTP MCP servers
import { Agent, run, MCPServerStreamableHttp } from '@openai/agents';
async function main() {
const mcpServer = new MCPServerStreamableHttp({
url: 'https://gitmcp.io/openai/codex',
name: 'GitMCP Documentation Server',
});
const agent = new Agent({
name: 'GitMCP Assistant',
instructions: 'Use the tools to respond to user requests.',
mcpServers: [mcpServer],
});
try {
await mcpServer.connect();
const result = await run(agent, 'Which language is this repo written in?');
console.log(result.finalOutput);
} finally {
await mcpServer.close();
}
}
main().catch(console.error);

コンストラクタでは、authProviderrequestInitreconnectionOptionssessionId などの MCP TypeScript-SDK 追加オプションも指定できます。詳細は MCP TypeScript SDK のリポジトリ とドキュメントを参照してください。

標準入出力のみを公開するサーバーの場合、fullCommand を指定して MCPServerStdio をインスタンス化します。

Run with Stdio MCP servers
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 npx',
fullCommand: `npx -y @modelcontextprotocol/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);

Streamable HTTPStdio サーバーでは、Agent が実行されるたびに list_tools() を呼び出して利用可能なツールを取得します。この往復処理は、とくにリモートサーバーでは遅延を招く可能性があるため、MCPServerStdio または MCPServerStreamableHttpcacheToolsList: true を渡して結果をメモリにキャッシュできます。

ツール一覧が変わらないと確信できる場合のみ有効にしてください。後でキャッシュを無効化するには、サーバーインスタンスの invalidateToolsCache() を呼び出します。