openai-agents-python MCP 服务器 API 完全指南:MCPServer 抽象基类与 Stdio / SSE / Streamable HTTP 三种传输实现
openai-agents-python MCP 服务器 API 完全指南:MCPServer 抽象基类与 Stdio / SSE / Streamable HTTP 三种传输实现
导读
本文基于 openai-agents-python 仓库的 MCP 服务器 API 参考文档(docs/ref/mcp/server.md,由 docs/scripts/generate_ref_files.py 生成的 mkdocstrings 存根,实际内容渲染自 src/agents/mcp/server.py),系统讲解 agents.mcp.server 模块的全部公开接口:从 MCPServer 抽象基类的统一契约,到 MCPServerStdio、MCPServerSse、MCPServerStreamableHttp 三种本地传输实现,以及审批策略、工具过滤、缓存、重试、分页、凭证安全等横切能力。读完本文,你将能够为 Agent 接入任意 MCP 服务器,并按照生产级要求配置超时、重试、审批与工具可见范围。
说明:本文聚焦"本地 MCP 服务器"(代码自行建立连接、列出并调用工具),不涉及由 OpenAI Responses API 代为连接的
HostedMCPTool,后者的连接由云端基础设施管理,可参见 docs/mcp.md 中的托管章节。
一、模块概览与导入方式
agents.mcp 包对外公开了全部服务器类与配套类型,统一从 agents.mcp 导入即可(见 src/agents/mcp/init.py):
from agents.mcp import (
MCPServer, # 抽象基类
MCPServerStdio, # stdio 传输
MCPServerSse, # HTTP + SSE 传输
MCPServerStreamableHttp, # Streamable HTTP 传输
MCPServerStdioParams, # stdio 参数 TypedDict
MCPServerSseParams, # SSE 参数 TypedDict
MCPServerStreamableHttpParams, # Streamable HTTP 参数 TypedDict
MCPUtil,
ToolFilter,
ToolFilterContext,
create_static_tool_filter,
MCPToolMetaContext,
MCPToolMetaResolver,
)
模块通过 __getattr__ 实现惰性导入,只有真正访问某个名字时才加载对应子模块,因此仅 import agents.mcp 不会带来额外的导入开销。
从源码结构看,server.py 的类型层次如下:
MCPServer(抽象基类)
└── _MCPServerWithClientSession(基于 mcp.ClientSession 的公共实现)
├── MCPServerStdio
├── MCPServerSse
└── MCPServerStreamableHttp
_MCPServerWithClientSession 是内部基类(以下划线开头,不对外导出),承载了三种传输共享的会话管理、重试、缓存、过滤、分页与错误脱敏逻辑;三个公开子类只负责各自的 create_streams() 实现。
二、MCPServer:所有 MCP 服务器的统一契约
MCPServer 是抽象基类(src/agents/mcp/server.py 第 543 行起),它定义了每个 MCP 服务器实现必须满足的生命周期与能力接口。所有子类都共享同一套构造参数,理解这些参数是掌握整个模块的前提。
2.1 抽象方法:生命周期与核心能力
| 方法 | 签名 | 职责 |
|---|---|---|
connect() |
async def connect(self) |
连接服务器,例如拉起子进程或建立网络连接;连接后保持到 cleanup() 被调用 |
cleanup() |
async def cleanup(self) |
清理服务器,例如关闭子进程或网络连接 |
name |
@property,返回 str |
服务器可读名称,用于日志与工具命名 |
list_tools() |
async def list_tools(run_context, agent) -> list[MCPTool] |
列出服务器可用工具 |
call_tool() |
async def call_tool(tool_name, arguments, meta) -> CallToolResult |
调用服务器上的工具 |
list_prompts() |
async def list_prompts() -> ListPromptsResult |
列出服务器可用的提示模板 |
get_prompt() |
async def get_prompt(name, arguments) -> GetPromptResult |
获取具体提示内容 |
资源相关方法(list_resources、list_resource_templates、read_resource)在基类中默认抛出 NotImplementedError——服务器若不支持资源能力,可直接不覆写;若支持,则需按 cursor 分页语义实现(见下文"分页"一节)。
2.2 构造参数:跨传输的公共配置
所有服务器类构造时都接受以下参数,含义完全一致:
use_structured_content: bool = False:调用 MCP 工具时是否优先使用tool_result.structured_content。默认False是为了向后兼容——多数 MCP 服务器仍会把结构化内容一并放进tool_result.content,默认开启会造成内容重复。只有当你确定服务器不会在content中重复结构化内容时才设为True。require_approval:工具审批策略(详见第三节),支持字符串、布尔、字典、分组对象与可调用对象。failure_error_function:将 MCP 工具失败转换为模型可见错误信息的函数。显式传None时,工具错误将直接抛出而非转换;不传(保持默认哨兵值)时使用 Agent 级配置或 SDK 默认错误格式器。tool_meta_resolver:在call_tool()之前为 MCP 请求生成_meta元数据的可调用对象(例如注入租户 ID、跟踪上下文)。custom_data_extractor:为发出的 MCP 工具输出条目生成仅 SDK 使用的自定义数据。tool_input_guardrails/tool_output_guardrails:作用于该服务器上所有工具的输入/输出护栏列表,在工具调用前后执行(详见 docs/ref/guardrail.md)。
2.3 三个实用的派生能力
cached_tools属性:返回最近一次抓取的工具列表快照;若尚未抓取或缓存被禁用则返回None。实现通过_snapshot_tools()深拷贝,防止调用方篡改缓存中的 schema。invalidate_tools_cache()方法(在_MCPServerWithClientSession上):将缓存标记为脏,下次list_tools()会强制重新抓取。__aenter__/__aexit__:三个公开类都实现了异步上下文管理器协议,async with server:等价于先connect()再在退出时cleanup(),这是官方示例的推荐用法。
三、require_approval:本地 MCP 工具的审批策略
require_approval 是本地 MCP 服务器(MCPServerStdio、MCPServerSse、MCPServerStreamableHttp)共有的安全能力,用于在工具执行前引入人工或程序化审批。_normalize_needs_approval()(src/agents/mcp/server.py 第 719 行起)把多种输入形式统一归一化为"布尔值 / 工具名到布尔值的映射 / 可调用策略"三类策略。
3.1 支持的输入形式
| 输入形式 | 含义 |
|---|---|
"always" / "never" |
全部工具都需审批 / 都不需审批 |
True / False |
等价于 "always" / "never" |
{"delete_file": "always", "read_file": "never"} |
按工具名逐个指定策略 |
{"always": {"tool_names": ["delete_file"]}, "never": {"tool_names": ["read_file"]}} |
分组对象形式,镜像 TypeScript SDK 的 requireApproval |
| 同步/异步可调用对象 | 接收 (run_context, agent, tool),返回该次调用是否需要审批 |
源码对分组对象形式有严格的校验:always / never 之外的键会直接抛出 UserError;同一个工具名不能同时出现在 always 和 never 中;tool_names 必须是字符串列表。
3.2 可调用策略的解析与兜底
当传入可调用对象时,SDK 会在每次需要决策时调用它,并兼容同步与异步返回值(通过 inspect.isawaitable(result) 判断)。一个值得注意的兜底行为:当使用可调用策略但调用方没有提供 agent 时(例如遗留代码直接用 MCPUtil.to_function_tool()),_get_needs_approval_for_tool() 会返回 True,即默认放行需审批的失败关闭(fail-closed)语义,避免绕过审批。
from agents.mcp import MCPServerStreamableHttp
def approve(run_context, agent, tool) -> bool:
return tool.name.startswith("danger_")
async with MCPServerStreamableHttp(
name="Filesystem MCP",
params={"url": "http://localhost:8000/mcp"},
require_approval=approve, # 可同步也可异步
) as server:
...
审批在运行时的完整暂停/恢复流程参见 docs/human_in_the_loop.md 与 examples/mcp/get_all_mcp_tools_example/main.py。
四、三种本地传输实现详解
4.1 MCPServerStdio:本地子进程传输
MCPServerStdio(第 1888 行起)通过标准输入输出与本地子进程通信(对应 MCP stdio 规范)。它接收一个 MCPServerStdioParams 字典,该 TypedDict 镜像 mcp.client.stdio.StdioServerParameters,无需额外导入即可传参:
| 参数 | 类型 | 说明 |
|---|---|---|
command |
str(必填) |
启动服务器的可执行文件,如 python 或 node |
args |
list[str] |
传给命令的参数,如 ['foo.py'] 或 ['server.js', '--port', '8080'] |
env |
dict[str, str] |
为服务器设置的环境变量 |
cwd |
str | Path |
生成进程时的工作目录 |
encoding |
str |
收发消息的文本编码,默认 utf-8 |
encoding_error_handler |
"strict" | "ignore" | "replace" |
编码错误处理器,默认 strict |
构造时 SDK 会把这些参数包装成 StdioServerParameters,未提供的字段取默认值(args 为空列表、encoding="utf-8"、encoding_error_handler="strict")。未指定 name 时自动生成 f"stdio: {command}" 形式的名称。create_streams() 直接返回 stdio_client(self.params)。
from pathlib import Path
from agents import Agent, Runner
from agents.mcp import MCPServerStdio
current_dir = Path(__file__).parent
async with MCPServerStdio(
name="Filesystem Server via npx",
params={
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", str(current_dir)],
"env": {"MY_VAR": "value"}, # 可选
"encoding_error_handler": "strict", # 可选,默认值
},
cache_tools_list=True,
) as server:
agent = Agent(
name="Assistant",
mcp_servers=[server],
)
result = await Runner.run(agent, "List the files available to you.")
print(result.final_output)
完整可运行示例见 examples/mcp/filesystem_example/main.py 与 examples/mcp/tool_filter_example/main.py。
4.2 MCPServerSse:HTTP + SSE 传输
MCPServerSse(第 2030 行起)对接实现 HTTP with SSE 传输的服务器。注意 docs/mcp.md 明确提示:MCP 项目已弃用 SSE 传输,新集成应优先 Streamable HTTP 或 stdio,SSE 仅用于遗留服务器。
MCPServerSseParams 字段:
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
url |
str(必填) |
— | 服务器 URL |
headers |
dict[str, str] |
None |
发送给服务器的请求头 |
timeout |
float |
5 |
HTTP 请求超时(秒) |
sse_read_timeout |
float |
300(5 分钟) |
SSE 连接读取超时(秒) |
auth |
Any |
— | 认证处理器:MCP v1 用 httpx.Auth,MCP v2 用 httpx2.Auth |
httpx_client_factory |
HttpClientFactory |
— | 自定义 HTTP 客户端工厂:MCP v1 返回 httpx.AsyncClient,MCP v2 返回 httpx2.AsyncClient |
from agents import Agent, Runner
from agents.mcp import MCPServerSse
from agents.model_settings import ModelSettings
async with MCPServerSse(
name="SSE Python Server",
params={
"url": "http://localhost:8000/sse",
"headers": {"X-Workspace": "demo-workspace"},
},
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.3 MCPServerStreamableHttp:Streamable HTTP 传输(推荐)
MCPServerStreamableHttp(第 2200 行起)实现 Streamable HTTP 传输,适用于自己掌控网络连接、希望把服务器跑在自己基础设施内并保持低延迟的场景,是当前文档与示例中最推荐的本地远程传输。
MCPServerStreamableHttpParams 在 SSE 参数基础上增加了两个字段:
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
terminate_on_close |
bool |
True |
关闭时是否向服务器发送 terminate 终止会话 |
ignore_initialized_notification_failure |
bool |
False |
是否忽略发送 notifications/initialized 失败。设为 True 时失败仅记录日志,后续请求可继续;该选项仅支持 MCP Python SDK v1,MCP v2 会在连接前直接拒绝(因为其公开传输 API 不暴露这类失败) |
其余字段(url、headers、timeout、sse_read_timeout、httpx_client_factory、auth)与 SSE 一致,其中 timeout 与 sse_read_timeout 的类型扩展为 timedelta | float。
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}"}, # 推荐用 Authorization 头而非 URL 传凭证
"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())
完整可运行版本见 examples/mcp/streamablehttp_example/main.py(含服务器端 examples/mcp/streamablehttp_example/server.py),远程服务器示例见 examples/mcp/streamable_http_remote_example/main.py,自定义 HTTP 客户端示例见 examples/mcp/streamablehttp_custom_client_example/main.py。
会话 ID 与隔离会话重试
Streamable HTTP 实现还有两个值得一提的独特能力:
session_id属性:返回服务器分配的 MCP 会话 ID。对现代协议版本返回None;对遗留服务器,该 ID 稳定于当前连接,可在重连时通过Mcp-Session-Id请求头恢复服务器端会话:
async with MCPServerStreamableHttp(params={"url": url}) as server:
session_id = server.session_id
# 新进程 / 新 worker 中:
async with MCPServerStreamableHttp(
params={"url": url, "headers": {"Mcp-Session-Id": session_id}}
) as server:
... # 恢复同一服务器端会话
- 共享会话失效时自动切换到隔离会话重试:当共享会话上的工具调用遇到会话关闭、连接错误、超时或 5xx 状态码时,
_should_retry_in_isolated_session()判定其适合重试,SDK 会新开一个隔离会话重放该调用(_call_tool_with_isolated_retry),并把此次重试计入max_retry_attempts预算(一次隔离重试按两次消耗计算)。
五、横切能力:缓存、重试、超时与工具过滤
5.1 cache_tools_list:工具列表缓存
每次 Agent 运行都会对每个 MCP 服务器调用 list_tools(),远程服务器会带来明显延迟。cache_tools_list=True 时,工具列表只在首次抓取,之后直接命中缓存,可大幅减少往返。仅在确信工具定义不会频繁变化时开启;需要强制刷新时调用 invalidate_tools_cache()。
缓存实现位于 _MCPServerWithClientSession.list_tools():命中缓存时直接返回 _snapshot_tools() 深拷贝;未命中时通过 _run_with_retries 分页抓取,成功后写入 self._tools_list 并清除脏标记。
5.2 重试与退避
三个公开类均支持:
max_retry_attempts: int = 0:list_tools()/call_tool()失败后的重试次数,默认不重试;设为-1表示无限重试。retry_backoff_seconds_base: float = 1.0:指数退避的基准延迟(秒)。retry_backoff_seconds_max: float | None = None:退避上限(秒),None表示不设上限。构造时校验必须是"非负有限秒数",布尔值或非法类型会抛TypeError/ValueError。
退避算法为 base * 2**n(见 _retry_backoff_seconds()),设置了上限时取 min(backoff, max);计算溢出时按正无穷处理再截断到上限。
5.3 client_session_timeout_seconds:会话读取超时
client_session_timeout_seconds(三个类默认 5)控制 MCP ClientSession 读取超时。校验规则(_client_session_read_timeout()):
- 正有限值(能被
datetime.timedelta表示且至少 1 微秒)→ 启用对应超时; None与0→ 禁用超时;- 负数、非有限值、过小(小于 timedelta 分辨率)或溢出 → 构造时抛
TypeError/ValueError。
该值在构造时校验一次,连接时还会再校验一次(防止调用方在构造后、连接前篡改公共属性)。
5.4 tool_filter:工具过滤
tool_filter 支持静态与动态两种形式(实现见 _apply_tool_filter(),第 1002 行起):
静态过滤——使用 create_static_tool_filter(allowed_tool_names=[...], blocked_tool_names=[...]) 构造 allow/block 列表。SDK 先应用 allow 列表,再从中剔除 block 列表命中的工具:
from agents.mcp import MCPServerStdio, create_static_tool_filter
filesystem_server = MCPServerStdio(
params={"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/files"]},
tool_filter=create_static_tool_filter(
allowed_tool_names=["read_file", "write_file"],
blocked_tool_names=["delete_file"],
),
)
动态过滤——传入同步/异步可调用对象,接收 ToolFilterContext(暴露 run_context、agent、server_name),返回 True 表示保留该工具。注意动态过滤需要 run_context 与 agent,二者缺失时抛 UserError:
async def context_aware_filter(context: ToolFilterContext, tool) -> bool:
if context.agent.name == "Code Reviewer" and tool.name.startswith("danger_"):
return False
return True
动态过滤实现上使用 _snapshot_tools() 的深拷贝副本供过滤器检查,防止过滤器篡改缓存;过滤器抛异常时该工具被安全地排除(fail-safe)。
5.5 分页:工具与提示自动分页,资源显式分页
list_tools()/list_prompts()会自动跟随nextCursor(MCP v1)或next_cursor(MCP v2)抓取全部页面,list_prompts()最终返回合并结果且nextCursor=None。- 若某一页失败或服务器重复返回相同游标,SDK 会抛错而不是暴露或缓存部分结果(防止无限循环与数据不完整)。
- 资源 API(
list_resources、list_resource_templates)保持显式分页:把上一页返回的nextCursor作为cursor参数传入取下一页。
六、MCP Python SDK v1 / v2 双版本适配
agents.mcp.server 的源码对 mcp 包大版本做了大量分支适配(仓库依赖范围为 mcp>=1.19.0,<3)。理解这些差异有助于排查 HTTP 传输问题:
| 定制点 | MCP Python SDK v1 | MCP Python SDK v2 |
|---|---|---|
params["auth"] 类型 |
httpx.Auth |
httpx2.Auth(否则构造时报 UserError) |
params["httpx_client_factory"] 返回值 |
httpx.AsyncClient |
httpx2.AsyncClient(否则报 UserError) |
ignore_initialized_notification_failure=True |
支持 | 不支持,连接前拒绝 |
- v2 下
_validate_v2_http_auth()会强制auth必须是httpx2.Auth实例;_validated_v2_http_client_factory()会校验工厂返回httpx2.AsyncClient。 - v2 的 Streamable HTTP 客户端通过响应钩子捕获
initialize响应中的mcp-session-id头(_configure_v2_session_id_hook),从而支持会话恢复。 - v2 下会话管理走
mcp.Client(mode="auto"),先发送server/discover探测,老服务器不支持时回退到遗留initialize握手——安装 v2 不会强制所有连接使用最新协议版本。 - 一个实现细节:v1 的
ClientSession读取超时传timedelta,v2 传秒数(见_client_session_read_timeout的return timeout_seconds if MCP_V2 else timeout)。
建议:普通应用让依赖解析器选择兼容版本即可;如需锁定大版本,可在 openai-agents 旁加显式约束(mcp>=1.19.0,<2 或 mcp>=2,<3)。HTTP 定制始终优先使用 Authorization 请求头,它在两个大版本下都无需改动。
七、凭证安全与错误脱敏:源码中的防御设计
server.py 内含一整套针对 HTTP 传输错误的凭证安全处理,值得在接入远程服务器时了解:
- 日志脱敏:
get_mcp_server_log_name()生成不含 URL 凭证的诊断名称(_error_name);日志默认关闭工具数据(_debug.DONT_LOG_TOOL_DATA)时更是只记固定消息。 - 传输错误映射:连接/请求失败时,
_user_error_for_http_error()把 HTTPX 异常映射为不含 URL 的UserError,消息形如Failed to connect to MCP server '...': HTTP error 404 (Not Found)。 - 异常组净化:
_credential_safe_exception_group()/_credential_safe_exception_leaf()把携带凭证 URL 的异常组替换为固定数据图,保留取消/控制语义但去除敏感信息。 - 清理路径:
cleanup()中若 HTTP 错误发生在正常退出(非连接失败)阶段,只记日志不抛出,避免掩盖原始异常;RuntimeError("...cancel scope...")这类已知的 MCP 库清理问题会被识别并抑制(源码注释明确说明)。
docs/mcp.md 的安全警告同样适用于本地服务器:只连接可信服务器,使用最小权限凭证,把访问令牌放在授权头而非 URL 中,对敏感操作启用审批。
八、多服务器编排与 Prompts 能力
8.1 MCPServerManager 快速参考
当有多个 MCP 服务器时,可用 MCPServerManager 统一连接并只暴露成功连接的子集(详见 docs/ref/mcp/manager.md,示例见 examples/mcp/manager_example/app.py):
active_servers只包含成功连接的服务器(drop_failed_servers=True默认);- 失败记录在
failed_servers与errors; strict=True时首个连接失败即抛出;reconnect(failed_only=True)只重试失败的服务器,failed_only=False重启全部;connect_all()/reconnect()/cleanup_all()串行化执行,生命周期操作互斥;connect_timeout_seconds、cleanup_timeout_seconds默认 10 秒,接受正有限秒数或None(禁用),零值会被拒绝(会产生立即截止的期限)。
8.2 Prompts:动态生成指令
MCP 服务器可提供提示模板动态生成 Agent 指令。list_prompts() 枚举模板,get_prompt(name, arguments) 带参获取具体提示:
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],
)
服务端实现示例见 examples/mcp/prompt_server/server.py 与 examples/mcp/prompt_server/main.py。
九、与 Agent 的接线:Agent.mcp_config 补充说明
除了服务器级参数,docs/mcp.md 还展示了 Agent.mcp_config 这一 Agent 级配置入口,用于统一调整本 Agent 上所有本地 MCP 工具的准备方式:
from agents import Agent
agent = Agent(
name="Assistant",
mcp_servers=[server],
mcp_config={
"convert_schemas_to_strict": True, # 尽力把 MCP 工具 schema 转为严格 JSON schema,失败则用原 schema
"failure_error_function": None, # 设为 None 时工具失败以异常抛出而非转成模型可见错误文本
"include_server_in_tool_names": True, # 本地 MCP 工具名加服务器前缀,避免多服务器同名工具冲突
},
)
要点:failure_error_function 未设置时使用 SDK 默认错误格式器;服务器级 failure_error_function 优先于 Agent 级配置(_get_failure_error_function() 中 _UNSET 哨兵语义即实现此优先级);include_server_in_tool_names 生成的名称 ASCII 安全、不超 FunctionTool 名称长度上限,且 SDK 仍会以原始工具名调用原服务器。
十、快速自查清单
接入任意 MCP 服务器时,对照以下决策点即可完成配置:
- 选传输:本地子进程选
MCPServerStdio;遗留 SSE 服务器选MCPServerSse(新项目避免);自管网络连接选MCPServerStreamableHttp。 - 配参数:根据上文的
*Params表填充url/command/headers/超时等字段;凭证放Authorization头。 - 定安全:用
require_approval给敏感工具加审批;用tool_filter收窄工具可见面。 - 调性能:工具列表稳定时开
cache_tools_list=True;按需配置max_retry_attempts与retry_backoff_seconds_base/max。 - 管理生命周期:用
async with server:确保connect/cleanup成对执行;多服务器用MCPServerManager。 - 验证能力:服务器支持提示时用
list_prompts/get_prompt;资源 API 按游标显式分页;每次变更工具定义后调用invalidate_tools_cache()。
上述全部 API 的权威签名与完整 docstring 均可在 src/agents/mcp/server.py 中查阅,可运行示例集中在 examples/mcp 目录,单元与集成测试(如 tests/mcp/test_connect_disconnect.py、tests/mcp/test_mcp_server_manager.py)则验证了连接、清理、审批与分页等行为。