Model context protocol (MCP)
Model context protocol (MCP) は、アプリケーションが ツール とコンテキストを言語モデルに公開する方法を標準化します。公式ドキュメントより:
MCP is an open protocol that standardizes how applications provide context to LLMs. Think of MCP like a USB-C port for AIapplications. Just as USB-C provides a standardized way to connect your devices to various peripherals and accessories, MCPprovides a standardized way to connect AI models to different data sources and tools.
Agents Python SDK は、複数の MCP トランスポートを理解します。これにより、既存の MCP サーバーを再利用したり、独自に構築して、ファイルシステム、HTTP、またはコネクタをバックエンドとするツールを エージェント に公開したりできます。
Choosing an MCP integration
MCP サーバーを エージェント に接続する前に、ツール呼び出しをどこで実行するか、どのトランスポートに到達できるかを決めます。以下のマトリクスは、Python SDK がサポートするオプションをまとめたものです。
| 必要なこと | 推奨オプション |
|---|---|
| OpenAI の Responses API がモデルの代わりに公開到達可能な MCP サーバーを呼び出す | Hosted MCP server tools(ホスト型 MCP サーバー ツール) viaHostedMCPTool |
| ローカルまたはリモートで稼働する Streamable HTTP サーバーに接続する | Streamable HTTP MCP サーバー viaMCPServerStreamableHttp |
| Server-Sent Events を用いた HTTP を実装するサーバーと通信する | HTTP with SSE MCP サーバー viaMCPServerSse |
| ローカルプロセスを起動して stdin/stdout 経由で通信する | stdio MCP サーバー viaMCPServerStdio |
以下のセクションでは各オプションについて、設定方法と、どのトランスポートをいつ選ぶべきかを説明します。
1. Hosted MCP server tools
Hosted ツールは、ツールの往復処理全体を OpenAI のインフラに移します。あなたのコードが ツール を列挙・呼び出す代わりに、HostedMCPTool はサーバーラベル(およびオプションのコネクタメタデータ)を Responses API に転送します。モデルはリモートサーバーの ツール を列挙し、あなたの Python プロセスへの追加のコールバックなしでそれらを呼び出します。Hosted ツールは現在、Responses API のホスト型 MCP 連携をサポートする OpenAI モデルで動作します。
Basic hosted MCP tool
エージェント のtools リストにHostedMCPTool を追加して hosted ツールを作成します。tool_config 辞書は、REST API に送信する JSON を反映します:
importasynciofromagentsimportAgent,HostedMCPTool,Runnerasyncdefmain()->None:agent=Agent(name="Assistant",tools=[HostedMCPTool(tool_config={"type":"mcp","server_label":"gitmcp","server_url":"https://gitmcp.io/openai/codex","require_approval":"never",})],)result=awaitRunner.run(agent,"Which language is this repository written in?")print(result.final_output)asyncio.run(main())ホストされたサーバーは ツール を自動的に公開します。mcp_servers に追加する必要はありません。
Streaming hosted MCP results
Hosted ツールは、関数ツールとまったく同じ方法で ストリーミング に対応します。Runner.run_streamed にstream=True を渡すと、モデルがまだ処理中でも増分の MCP 出力を消費できます:
result=Runner.run_streamed(agent,"Summarise this repository's top languages")asyncforeventinresult.stream_events():ifevent.type=="run_item_stream_event":print(f"Received:{event.item}")print(result.final_output)Optional approval flows
サーバーが機密性の高い操作を実行できる場合、各 ツール 実行の前に人間またはプログラムによる承認を要求できます。tool_config のrequire_approval を、単一ポリシー("always"、"never")または ツール 名からポリシーへのマップを持つ辞書で構成します。判断を Python 内で行うには、on_approval_request コールバックを指定します。
fromagentsimportMCPToolApprovalFunctionResult,MCPToolApprovalRequestSAFE_TOOLS={"read_project_metadata"}defapprove_tool(request:MCPToolApprovalRequest)->MCPToolApprovalFunctionResult:ifrequest.data.nameinSAFE_TOOLS:return{"approve":True}return{"approve":False,"reason":"Escalate to a human reviewer"}agent=Agent(name="Assistant",tools=[HostedMCPTool(tool_config={"type":"mcp","server_label":"gitmcp","server_url":"https://gitmcp.io/openai/codex","require_approval":"always",},on_approval_request=approve_tool,)],)コールバックは同期または非同期のいずれでもよく、モデルが実行を継続するために承認データを必要とするたびに呼び出されます。
Connector-backed hosted servers
Hosted MCP は OpenAI コネクタにも対応します。server_url を指定する代わりに、connector_id とアクセストークンを指定します。Responses API が認証を処理し、ホストされたサーバーがコネクタの ツール を公開します。
importosHostedMCPTool(tool_config={"type":"mcp","server_label":"google_calendar","connector_id":"connector_googlecalendar","authorization":os.environ["GOOGLE_CALENDAR_AUTHORIZATION"],"require_approval":"never",})ストリーミング、承認、コネクタを含む完全な hosted ツールのサンプルはexamples/hosted_mcp にあります。
2. Streamable HTTP MCP servers
ネットワーク接続を自分で管理したい場合は、MCPServerStreamableHttp を使用します。Streamable HTTP サーバーは、トランスポートを自分で制御したい場合や、サーバーを自社インフラ内で稼働させつつレイテンシを低く保ちたい場合に最適です。
importasyncioimportosfromagentsimportAgent,Runnerfromagents.mcpimportMCPServerStreamableHttpfromagents.model_settingsimportModelSettingsasyncdefmain()->None:token=os.environ["MCP_SERVER_TOKEN"]asyncwithMCPServerStreamableHttp(name="Streamable HTTP Python Server",params={"url":"http://localhost:8000/mcp","headers":{"Authorization":f"Bearer{token}"},"timeout":10,},cache_tools_list=True,max_retry_attempts=3,)asserver:agent=Agent(name="Assistant",instructions="Use the MCP tools to answer the questions.",mcp_servers=[server],model_settings=ModelSettings(tool_choice="required"),)result=awaitRunner.run(agent,"Add 7 and 22.")print(result.final_output)asyncio.run(main())コンストラクタは追加オプションを受け付けます:
client_session_timeout_secondsは HTTP の読み取りタイムアウトを制御します。use_structured_contentは、テキスト出力よりもtool_result.structured_contentを優先するかどうかを切り替えます。max_retry_attemptsとretry_backoff_seconds_baseは、list_tools()とcall_tool()に自動リトライを追加します。tool_filterは、公開する ツール のサブセットのみを露出することを可能にします(Tool filtering を参照)。
3. HTTP with SSE MCP servers
MCP サーバーが HTTP with SSE トランスポートを実装している場合は、MCPServerSse をインスタンス化します。トランスポート以外は、API は Streamable HTTP サーバーと同一です。
fromagentsimportAgent,Runnerfromagents.model_settingsimportModelSettingsfromagents.mcpimportMCPServerSseworkspace_id="demo-workspace"asyncwithMCPServerSse(name="SSE Python Server",params={"url":"http://localhost:8000/sse","headers":{"X-Workspace":workspace_id},},cache_tools_list=True,)asserver:agent=Agent(name="Assistant",mcp_servers=[server],model_settings=ModelSettings(tool_choice="required"),)result=awaitRunner.run(agent,"What's the weather in Tokyo?")print(result.final_output)4. stdio MCP servers
ローカルのサブプロセスとして動作する MCP サーバーには、MCPServerStdio を使用します。SDK はプロセスを起動し、パイプを開いたままにし、コンテキストマネージャ終了時に自動でクローズします。このオプションは、迅速な PoC や、サーバーがコマンドラインのエントリポイントのみを公開する場合に有用です。
frompathlibimportPathfromagentsimportAgent,Runnerfromagents.mcpimportMCPServerStdiocurrent_dir=Path(__file__).parentsamples_dir=current_dir/"sample_files"asyncwithMCPServerStdio(name="Filesystem Server via npx",params={"command":"npx","args":["-y","@modelcontextprotocol/server-filesystem",str(samples_dir)],},)asserver:agent=Agent(name="Assistant",instructions="Use the files in the sample directory to answer questions.",mcp_servers=[server],)result=awaitRunner.run(agent,"List the files available to you.")print(result.final_output)Tool filtering
各 MCP サーバーは ツール フィルターをサポートしており、エージェント に必要な関数のみを公開できます。フィルタリングは、構築時または実行ごとに動的に行えます。
Static tool filtering
create_static_tool_filter を使用して、簡単な許可・拒否リストを構成します:
frompathlibimportPathfromagents.mcpimportMCPServerStdio,create_static_tool_filtersamples_dir=Path("/path/to/files")filesystem_server=MCPServerStdio(params={"command":"npx","args":["-y","@modelcontextprotocol/server-filesystem",str(samples_dir)],},tool_filter=create_static_tool_filter(allowed_tool_names=["read_file","write_file"]),)allowed_tool_names とblocked_tool_names の両方が指定された場合、SDK はまず許可リストを適用し、その後で残りのセットから拒否リストに該当する ツール を削除します。
Dynamic tool filtering
より精緻なロジックには、ToolFilterContext を受け取る呼び出し可能オブジェクトを渡します。呼び出し可能オブジェクトは同期または非同期のいずれでもよく、 ツール を公開すべき場合にTrue を返します。
frompathlibimportPathfromagents.mcpimportMCPServerStdio,ToolFilterContextsamples_dir=Path("/path/to/files")asyncdefcontext_aware_filter(context:ToolFilterContext,tool)->bool:ifcontext.agent.name=="Code Reviewer"andtool.name.startswith("danger_"):returnFalsereturnTrueasyncwithMCPServerStdio(params={"command":"npx","args":["-y","@modelcontextprotocol/server-filesystem",str(samples_dir)],},tool_filter=context_aware_filter,)asserver:...フィルターコンテキストは、アクティブなrun_context、 ツール を要求しているagent、およびserver_name を公開します。
Prompts
MCP サーバーは、エージェントの instructions を動的に生成するプロンプトも提供できます。プロンプトをサポートするサーバーは、次の 2 つのメソッドを公開します:
list_prompts()は、利用可能なプロンプト テンプレートを列挙します。get_prompt(name, arguments)は、必要に応じて パラメーター を指定して、具体的なプロンプトを取得します。
fromagentsimportAgentprompt_result=awaitserver.get_prompt("generate_code_review_instructions",{"focus":"security vulnerabilities","language":"python"},)instructions=prompt_result.messages[0].content.textagent=Agent(name="Code Reviewer",instructions=instructions,mcp_servers=[server],)Caching
すべての エージェント 実行は、各 MCP サーバーに対してlist_tools() を呼び出します。リモートサーバーは目に見えるレイテンシを導入する可能性があるため、すべての MCP サーバークラスはcache_tools_list オプションを公開します。ツール定義が頻繁に変わらないと確信できる場合にのみ、これをTrue に設定してください。後で新しい一覧を強制するには、サーバーインスタンスでinvalidate_tools_cache() を呼び出します。
Tracing
Tracing は MCP のアクティビティを自動的に記録します。含まれるもの:
- ツール を列挙するための MCP サーバーへの呼び出し。
- ツール 呼び出しに関する MCP 関連情報。

Further reading
- Model Context Protocol – 仕様と設計ガイド。
- examples/mcp – 実行可能な stdio、SSE、Streamable HTTP のサンプル。
- examples/hosted_mcp – 承認やコネクタを含む、完全な hosted MCP のデモ。