MCP 集成
Model Context Protocol (MCP) 是一种开放协议,用于标准化应用向 LLM 提供工具和上下文的方式。以下内容摘自 MCP 文档:
MCP 是一种开放协议,用于标准化应用向 LLM 提供上下文的方式。可以将 MCP 视为 AI 应用的 USB-C 端口。正如 USB-C 提供了一种将设备连接到各种外设和配件的标准化方式,MCP 也提供了一种将 AI 模型连接到不同数据源和工具的标准化方式。
此 SDK 支持三种类型的 MCP 服务器:
- 远程 MCP 服务器工具——由 OpenAI Responses API 作为工具使用的远程 MCP 服务器
- Streamable HTTP MCP 服务器——实现 Streamable HTTP 传输的本地或远程服务器
- Stdio MCP 服务器——通过标准输入/输出访问的服务器(最简单的选项)
注意:SDK 还提供了
MCPServerSSE,用于旧版服务器发送事件(Server-Sent Events)传输,但 MCP 项目已弃用 SSE。对于新的集成,请优先选择 Streamable HTTP 或 stdio。
请根据使用场景选择服务器类型:
| 需求 | 推荐选项 |
|---|---|
| 使用默认的 OpenAI Responses 模型调用可公开访问的远程服务器 | 1. 托管 MCP 工具 |
| 使用可公开访问的远程服务器,但在本地触发工具调用 | 2. Streamable HTTP |
| 使用在本地运行的 Streamable HTTP 服务器 | 2. Streamable HTTP |
| 使用非 OpenAI Responses 模型访问任意 Streamable HTTP 服务器 | 2. Streamable HTTP |
| 使用仅支持标准 I/O 协议的本地 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 服务器工具”托管工具将整个往返调用流程交由模型处理。OpenAI Responses API 会调用远程工具端点,并将结果以流式传输的方式返回给模型,而不是由您的代码调用 MCP 服务器。
以下是使用托管 MCP 工具的最简单示例。您可以将远程 MCP 服务器的标签和 URL 传递给 hostedMcpTool 实用函数,以便创建远程 MCP 服务器工具。
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 回调批准或拒绝该工具调用。如果需要人工审批,您可以采用与本地函数工具相同的人机协作(HITL)方式,使用 interruptions 处理。
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')[] | 仅适用于 Responses 的非空列表,用于控制托管 MCP 工具能否被直接调用、通过编程式工具调用来调用,或同时支持这两种方式。 |
deferLoading | boolean | 仅适用于 Responses 的托管 MCP 工具延迟加载。要求同一智能体中包含 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 回调会接收当前运行上下文和审批项,然后返回一个 Promise,其结果包含 approve 和可选的 reason。
基于连接器的托管服务器
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。
完整可运行的代码示例(托管工具/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 | 将仅供 SDK 使用的 JSON 元数据附加到生成的本地 MCP 工具输出项。回调可以读取 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。 |
构造函数还接受其他 MCP TypeScript SDK 选项,例如 authProvider、requestInit、fetch、reconnectionOptions 和 sessionId。详情请参阅 MCP TypeScript SDK 仓库及其文档。
toolInputGuardrails 和 toolOutputGuardrails 使用 SDK 的本地函数工具护栏处理流程。在流式传输和非流式传输运行中,它们都适用于从此服务器转换而来的每个工具。它们不适用于由 Responses API 远程执行的托管 MCP 工具。关于拒绝行为和审批顺序,请参阅工具护栏。
3. Stdio MCP 服务器
Section titled “3. Stdio MCP 服务器”对于仅提供标准 I/O 的服务器,请使用 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 | 将仅供 SDK 使用的 JSON 元数据附加到生成的本地 MCP 工具输出项。回调可以读取 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 服务器报告的工具名称。如果两个本地 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 实例或已启用的交接名称冲突。此设置影响所有本地 MCP 传输机制,包括 Streamable HTTP、SSE 和 stdio;托管 MCP 工具则保留其托管服务器标签和工具元数据。
您可以通过 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——上文提及的可运行代码示例。