Skip to content

Model context protocol (MCP)

Model context protocol(MCP)標準化了應用程式如何向大型語言模型 (LLM) 暴露工具 (Tools) 與上下文。根據官方文件說明:

MCP 是一個開放協議,標準化應用程式如何向 LLM 提供上下文。你可以把 MCP 想像成 AI 應用程式的 USB-C 連接埠。就像 USB-C 提供了一個標準化的方式,讓你的裝置可以連接各種週邊與配件一樣,MCP 也提供了一個標準化的方式,讓 AI 模型能夠連接到不同的資料來源與工具 (Tools)。

Agents Python SDK 支援多種 MCP 傳輸方式。這讓你能夠重複利用現有的 MCP 伺服器,或自行建置 MCP 伺服器,將檔案系統、HTTP 或連接器支援的工具 (Tools) 暴露給代理 (Agent)。

選擇 MCP 整合方式

在將 MCP 伺服器串接到代理 (Agent) 前,請先決定工具 (Tools) 呼叫應該在哪裡執行,以及你可以存取哪些傳輸方式。下表總結了 Python SDK 支援的選項。

你的需求 推薦選項
讓 OpenAI 的 Responses API 代表模型呼叫可公開存取的 MCP 伺服器 Hosted MCP server tools,透過 [HostedMCPTool][agents.tool.HostedMCPTool]
連接你本地或遠端執行的 Streamable HTTP 伺服器 Streamable HTTP MCP servers,透過 [MCPServerStreamableHttp][agents.mcp.server.MCPServerStreamableHttp]
與實作 HTTP 並支援 Server-Sent Events 的伺服器通訊 HTTP with SSE MCP servers,透過 [MCPServerSse][agents.mcp.server.MCPServerSse]
啟動本地程序並透過 stdin/stdout 溝通 stdio MCP servers,透過 [MCPServerStdio][agents.mcp.server.MCPServerStdio]

以下章節將逐一說明每個選項、如何設定,以及何時應優先選用哪一種傳輸方式。

1. Hosted MCP server tools

Hosted 工具 (Hosted tools) 會將整個工具 (Tools) 的來回流程推送到 OpenAI 的基礎設施中。你的程式碼不需要自行列舉與呼叫工具 (Tools),[HostedMCPTool][agents.tool.HostedMCPTool] 會將伺服器標籤(以及可選的連接器中繼資料)轉發給 Responses API。模型會列舉遠端伺服器的工具 (Tools) 並直接呼叫,而不需要額外回呼你的 Python 程序。Hosted 工具 (Hosted tools) 目前適用於支援 Responses API 的 Hosted MCP 整合的 OpenAI 模型。

基本的 hosted MCP tool

只要在代理 (Agent) 的 tools 清單中加入一個 [HostedMCPTool][agents.tool.HostedMCPTool],即可建立 hosted 工具 (hosted tool)。tool_config 字典結構與你傳送到 REST API 的 JSON 相同:

import asyncio

from agents import Agent, HostedMCPTool, Runner

async def main() -> 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 = await Runner.run(agent, "Which language is this repository written in?")
    print(result.final_output)

asyncio.run(main())

託管伺服器會自動公開其工具 (Tools);你不需要將其加入mcp_servers

串流託管 MCP 結果

託管工具 (Tools) 支援與函式工具 (function tools) 完全相同的串流結果方式。傳遞stream=TrueRunner.run_streamed,即可在模型仍在運作時,消費增量的 MCP 輸出:

result = Runner.run_streamed(agent, "Summarise this repository's top languages")
async for event in result.stream_events():
    if event.type == "run_item_stream_event":
        print(f"Received: {event.item}")
print(result.final_output)

可選的審核流程

如果一個伺服器可以執行敏感操作,你可以在每次工具 (Tools) 執行前要求人工或程式化審核。請在tool_config中設定require_approval,可以使用單一政策("always""never")或是以工具名稱對應政策的 dict。若要在 Python 內部做決策,請提供on_approval_request callback。

from agents import MCPToolApprovalFunctionResult, MCPToolApprovalRequest

SAFE_TOOLS = {"read_project_metadata"}

def approve_tool(request: MCPToolApprovalRequest) -> MCPToolApprovalFunctionResult:
    if request.data.name in SAFE_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,
        )
    ],
)

此回呼(callback)可以是同步或非同步的,並且會在模型需要審批資料以持續運作時被觸發。

由 Connector 支援的託管伺服器

託管 MCP 也支援 OpenAI connectors。你可以不用指定server_url,而是提供connector_id以及存取權杖(access token)。
Responses API 會處理驗證,且託管伺服器會公開 connector 的工具 (Tools)。

import os

HostedMCPTool(
    tool_config={
        "type": "mcp",
        "server_label": "google_calendar",
        "connector_id": "connector_googlecalendar",
        "authorization": os.environ["GOOGLE_CALENDAR_AUTHORIZATION"],
        "require_approval": "never",
    }
)

完整可運作的託管工具範例——包括串流、審核與連接器——可在 examples/hosted_mcp 找到。

2. Streamable HTTP MCP 伺服器

當你希望自行管理網路連線時,請使用 [MCPServerStreamableHttp][agents.mcp.server.MCPServerStreamableHttp]。Streamable HTTP 伺服器非常適合在你能控制傳輸層,或希望將伺服器部署於自有基礎設施、同時保持低延遲的情境下使用。

import asyncio
import os

from agents import Agent, Runner
from agents.mcp import MCPServerStreamableHttp
from agents.model_settings import ModelSettings

async def main() -> None:
    token = os.environ["MCP_SERVER_TOKEN"]
    async with MCPServerStreamableHttp(
        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,
    ) as server:
        agent = Agent(
            name="Assistant",
            instructions="Use the MCP tools to answer the questions.",
            mcp_servers=[server],
            model_settings=ModelSettings(tool_choice="required"),
        )

        result = await Runner.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_attemptsretry_backoff_seconds_baselist_tools()call_tool() 增加自動重試機制。
  • tool_filter 讓你僅公開部分工具(請參閱 Tool filtering)。

3. HTTP with SSE MCP 伺服器

如果 MCP 伺服器實作了 HTTP with SSE 傳輸方式,請實例化 [MCPServerSse][agents.mcp.server.MCPServerSse]。除了傳輸方式不同之外,API 與 Streamable HTTP 伺服器完全相同。

from agents import Agent, Runner
from agents.model_settings import ModelSettings
from mcp import MCPServerSse

workspace_id = "demo-workspace"

async with MCPServerSse(
    name="SSE Python Server",
    params={
        "url": "http://localhost:8000/sse",
        "headers": {"X-Workspace": workspace_id},
    },
    cache_tools_list=True,
) as server:
    agent = Agent(
        name="Assistant",
        mcp_servers=[server],
        model_settings=ModelSettings(tool_choice="required"),
    )
    result = await Runner.run(agent, "What's the weather in Tokyo?")
    print(result.final_output)

4. stdio MCP 伺服器

對於以本地子行程(subprocess)方式執行的 MCP 伺服器,請使用 [MCPServerStdio][agents.mcp.server.MCPServerStdio]。SDK 會啟動該行程,保持管道(pipes)開啟,並在 context manager 結束時自動關閉。這個選項適合用於快速概念驗證(proof of concept),或當伺服器僅提供命令列介面(Command Line Interface)進入點時使用。

from pathlib import Path
from agents import Agent, Runner
from agents.mcp import MCPServerStdio

current_dir = Path(__file__).parent
samples_dir = current_dir / "sample_files"

async with MCPServerStdio(
    name="Filesystem Server via npx",
    params={
        "command": "npx",
        "args": ["-y", "@modelcontextprotocol/server-filesystem", str(samples_dir)],
    },
) as server:
    agent = Agent(
        name="Assistant",
        instructions="Use the files in the sample directory to answer questions.",
        mcp_servers=[server],
    )
    result = await Runner.run(agent, "List the files available to you.")
    print(result.final_output)

工具 (Tools) 過濾

每個 MCP 伺服器都支援工具過濾功能,讓你只暴露 Agent 所需的功能。過濾可以在建構時進行,也可以在每次執行時動態調整。

靜態工具過濾

使用 [create_static_tool_filter][agents.mcp.create_static_tool_filter] 來設定簡單的允許/封鎖清單:

from pathlib import Path

from agents.mcp import MCPServerStdio, create_static_tool_filter

samples_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_namesblocked_tool_names 時,SDK 會先套用 allow-list,然後從剩餘集合中移除任何被封鎖的工具 (Tools)。

動態工具 (Tools) 過濾

若需要更複雜的邏輯,可以傳入一個可呼叫物件(callable),該物件會接收一個 [ToolFilterContext][agents.mcp.ToolFilterContext]。這個可呼叫物件可以是同步或非同步的,當工具 (Tool) 應該被暴露時,需回傳 True

from pathlib import Path

from agents.mcp import MCPServerStdio, ToolFilterContext

samples_dir = Path("/path/to/files")

async def context_aware_filter(context: ToolFilterContext, tool) -> bool:
    if context.agent.name == "Code Reviewer" and tool.name.startswith("danger_"):
        return False
    return True

async with MCPServerStdio(
    params={
        "command": "npx",
        "args": ["-y", "@modelcontextprotocol/server-filesystem", str(samples_dir)],
    },
    tool_filter=context_aware_filter,
) as server:
    ...

篩選器內容(filter context)會公開當前的 run_context、請求工具(Tools)的 agent,以及 server_name

提示詞 (Prompts)

MCP 伺服器(MCP Servers)也可以提供動態產生代理(Agent)指令的提示詞(prompts)。支援提示詞的伺服器會公開兩個方法:

  • list_prompts() 用於列舉所有可用的提示詞範本(prompt templates)。
  • get_prompt(name, arguments) 用於擷取具體的提示詞,可選擇性地帶入參數。
from agents import Agent

prompt_result = await server.get_prompt(
    "generate_code_review_instructions",
    {"focus": "security vulnerabilities", "language": "python"},
)
instructions = prompt_result.messages[0].content.text

agent = Agent(
    name="Code Reviewer",
    instructions=instructions,
    mcp_servers=[server],
)

快取

每次 Agent 執行時,會在每個 MCP 伺服器上呼叫 list_tools()。遠端伺服器可能會帶來明顯的延遲,因此所有 MCP 伺服器類別都提供 cache_tools_list 選項。只有在你確信工具 (Tools) 定義不會經常變動時,才建議將其設為 True。若之後需要強制取得最新清單,可在伺服器實例上呼叫 invalidate_tools_cache()

追蹤 (Tracing)

Tracing 會自動捕捉 MCP 活動,包括:

  1. 呼叫 MCP 伺服器以列出工具 (Tools)。
  2. 工具 (Tools) 呼叫時的 MCP 相關資訊。

MCP Tracing Screenshot

延伸閱讀