OpenAI Agents SDK 新增 MCP 支持

[中文正文内容]

Table of contents

Model context protocol (MCP)

Model context protocol (又名 MCP) 是一种向 LLM 提供工具和上下文的方式。 从 MCP 文档中:

MCP 是一种开放协议,用于标准化应用程序如何向 LLM 提供上下文。 将 MCP 视为 AI 应用程序的 USB-C 端口。 正如 USB-C 提供了一种将设备连接到各种外围设备和配件的标准化方式一样,MCP 提供了一种将 AI 模型连接到不同数据源和工具的标准化方式。

Agents SDK 支持 MCP。 这使您可以使用各种 MCP 服务器来为您的 Agents 提供工具。

MCP 服务器

目前,MCP 规范根据它们使用的传输机制定义了两种服务器:

  1. stdio 服务器作为应用程序的子进程运行。 您可以将它们视为“本地”运行。
  2. HTTP over SSE 服务器远程运行。 您通过 URL 连接到它们。

您可以使用 MCPServerStdioMCPServerSse 类来连接到这些服务器。

例如,以下是如何使用官方 MCP 文件系统服务器

[](https://openai.github.io/openai-agents-python/mcp/<#__codelineno-0-1>)async with MCPServerStdio(
[](https://openai.github.io/openai-agents-python/mcp/<#__codelineno-0-2>)  params={
[](https://openai.github.io/openai-agents-python/mcp/<#__codelineno-0-3>)    "command": "npx",
[](https://openai.github.io/openai-agents-python/mcp/<#__codelineno-0-4>)    "args": ["-y", "@modelcontextprotocol/server-filesystem", samples_dir],
[](https://openai.github.io/openai-agents-python/mcp/<#__codelineno-0-5>)  }
[](https://openai.github.io/openai-agents-python/mcp/<#__codelineno-0-6>)) as server:
[](https://openai.github.io/openai-agents-python/mcp/<#__codelineno-0-7>)  tools = await server.list_tools()

使用 MCP 服务器

MCP 服务器可以添加到 Agents 中。 Agents SDK 每次运行 Agent 时都会调用 MCP 服务器上的 list_tools()。 这使得 LLM 知道 MCP 服务器的工具。 当 LLM 调用来自 MCP 服务器的工具时,SDK 会调用该服务器上的 call_tool()

[](https://openai.github.io/openai-agents-python/mcp/<#__codelineno-1-1>)agent=Agent(
[](https://openai.github.io/openai-agents-python/mcp/<#__codelineno-1-2>)  name="Assistant",
[](https://openai.github.io/openai-agents-python/mcp/<#__codelineno-1-3>)  instructions="Use the tools to achieve the task",
[](https://openai.github.io/openai-agents-python/mcp/<#__codelineno-1-4>)  mcp_servers=[mcp_server_1, mcp_server_2]
[](https://openai.github.io/openai-agents-python/mcp/<#__codelineno-1-5>))

缓存

每次 Agent 运行时,它都会在 MCP 服务器上调用 list_tools()。 这可能会导致延迟,尤其是在服务器是远程服务器的情况下。 要自动缓存工具列表,您可以将 cache_tools_list=True 传递给 MCPServerStdioMCPServerSse。 只有在您确定工具列表不会更改时才应这样做。

如果要使缓存失效,可以在服务器上调用 invalidate_tools_cache()

端到端示例

examples/mcp 查看完整的示例。

Tracing

Tracing 会自动捕获 MCP 操作,包括:

  1. 调用 MCP 服务器以列出工具
  2. 函数调用中与 MCP 相关的信息

MCP Tracing Screenshot