如何使用OpenAI集成的MCP协议构建AI代理?

如何使用OpenAI集成的MCP协议构建AI代理?

为了提高人工智能的互操作性,OpenAI 宣布支持 Anthropic 的模型上下文协议(MCP),这是一项开源标准,旨在简化人工智能助手与各种数据系统之间的集成。这一合作标志着在为人工智能应用创建统一框架以有效访问和利用外部数据源方面迈出了关键一步。

了解模型上下文协议(MCP)

由 Anthropic 开发的 MCP 是一种开放标准,可促进人工智能模型与外部数据存储库、业务工具和开发环境之间的无缝连接。通过提供标准化协议,MCP 消除了定制集成的需要,允许人工智能系统动态访问必要的上下文。这种方法可实现实时数据检索和交互,从而提高人工智能生成的响应的相关性和准确性。

MCP的主要特点

  • 通用兼容性:MCP 可作为“AI 应用的 USB-C 端口”,提供将人工智能模型连接到各种数据源的标准化方法。
  • 双向通信:该协议支持人工智能应用(MCP 客户端)和数据源(MCP 服务器)之间的安全双向互动,促进了动态数据交换。
  • 开源生态系统:MCP 是开源的,鼓励社区合作和开发广泛的集成和工具。

什么是MCP图示

Source: Microsoft

什么是MCP?

这里有一个更简单易懂的 MCP:

如果您正在使用人工智能模型进行构建,您可能会遇到这种情况:

  • 你从一个模型一个 LLM 开始,一切都很顺利。
  • 然后你的团队问:“我们能不能加上 GPT-4o-mini、Mistral,也许还有 Claude?

现在事情变得一团糟。

  • 每个模型都有不同的应用程序接口
  • 为了发送提示,您需要重新编写代码
  • 响应看起来完全不同
  • 切换模型会破坏一切

这令人沮丧,而且耗费太多时间。

这就是 MCP(模型上下文协议)的用武之地:

无MCP

  • 每个提供商都有自己的设置(例如,OpenAI、Mistral、Anthropic)
  • 提示和响应不一致
  • 切换模型意味着要反复修改代码

有MCP

  • 所有模型只有一种简单的格式
  • 提示自动转换
  • 回复看起来一样
  • 立即交换模型–无需更改代码
  • 将来可轻松添加新的 LLM

MCP 为您节省时间,简化代码,让多 LLM 工作变得更轻松。

OpenAI集成了MCP

OpenAI 采用 MCP 的决定强调了其对增强人工智能产品功能和互操作性的承诺。首席执行官 Sam Altman 强调了对MCP的热情,并表示OpenAI的所有产品都将集成对MCP的支持。Agents SDK 中已经提供了集成,ChatGPT 桌面应用程序和 Responses API 也即将提供支持。

对OpenAI产品的影响

  • 增强数据访问:通过利用 MCP,OpenAI 的人工智能模型可以访问更广泛的数据源,从而做出更明智、与上下文更相关的响应。
  • 简化集成:开发人员可以利用 MCP 将 OpenAI 的人工智能系统与各种工具和数据集连接起来,而无需定制连接器,从而简化了开发流程。
  • 社区协作:OpenAI 对 MCP 等开放标准的支持促进了协作环境,鼓励了人工智能社区内的创新和共同进步。

行业采用和未来展望

自诞生以来,MCP 已获得多家机构的支持。Block、Apollo、Replit、Codeium 和 Sourcegraph 等公司都已将 MCP 集成到自己的平台中,并认识到它在标准化人工智能数据交互方面的潜力。

OpenAI 和微软等行业领导者采用 MCP 标志着人工智能集成标准化的大趋势。随着越来越多的企业采用 MCP,生态系统有望得到发展,为开发人员提供一个强大的框架,用于构建可与各种数据源无缝交互的人工智能应用程序。

使用MCP获取Git仓库信息

下面介绍如何使用 MCP:

首先,搜索 OpenAI Agent SDK 并打开模型上下文协议(MCP)

MCP 是一个开放协议,它规范了应用程序向 LLM 提供上下文的方式。把 MCP 想象成人工智能应用的 USB-C 端口。就像 USB-C 提供了将设备连接到各种外设和配件的标准化方式一样,MCP 也提供了将人工智能模型连接到不同数据源和工具的标准化方式。

让我们从实现开始:

我正在获取有关 Langmanus 仓库的信息,为此,请在系统中克隆该仓库,并将路径保存在手边。

Langmanus 仓库

克隆仓库:openai-agents-python

克隆仓库:openai-agents-python 

然后,输入您的 OpenAI API 密钥:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
export OPENAI_API_KEY: SK-XXXXXX
export OPENAI_API_KEY: SK-XXXXXX
export OPENAI_API_KEY: SK-XXXXXX

之后,进入 openai-agents-python 目录

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
cd openai-agents-python/
cd openai-agents-python/
cd openai-agents-python/

然后运行此命令:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
uv run python examples/mcp/git_example/main.py
uv run python examples/mcp/git_example/main.py
uv run python examples/mcp/git_example/main.py

最后,输入仓库路径:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
Please enter the path to the git repository: /home/pankaj/langmanus
Please enter the path to the git repository: /home/pankaj/langmanus
Please enter the path to the git repository: /home/pankaj/langmanus

输入仓库路径

输出

The most frequent contributor is **Henry Li**, with multiple commits in the history provided.--------------------------------------------Running: Summarize the last change in the repository.The last change in the repository was made by MSc. João Gabriel Lima on March 23, 2025. The commit hash is `646c3e06c4bd58e252967c8b1065c7a0b0f0309b`.### Commit Message- **Type:** feat- **Summary:** ChatLiteLLMV2 missing function (#103)#### Details:- Added parameter filtering and supported parameters methods in ChatLiteLLMV2.- This change was repeated several times in the commit message details, highlighting its importance.

下面是 Main.py

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import asyncio
import shutil
from agents import Agent, Runner, trace
from agents.mcp import MCPServer, MCPServerStdio
async def run(mcp_server: MCPServer, directory_path: str):
agent = Agent(
name="Assistant",
instructions=f"Answer questions about the git repository at {directory_path}, use that for repo_path",
mcp_servers=[mcp_server],
)
message = "Who's the most frequent contributor?"
print("\n" + "-" * 40)
print(f"Running: {message}")
result = await Runner.run(starting_agent=agent, input=message)
print(result.final_output)
message = "Summarize the last change in the repository."
print("\n" + "-" * 40)
print(f"Running: {message}")
result = await Runner.run(starting_agent=agent, input=message)
print(result.final_output)
async def main():
# Ask the user for the directory path
directory_path = input("Please enter the path to the git repository: ")
async with MCPServerStdio(
cache_tools_list=True, # Cache the tools list, for demonstration
params={"command": "uvx", "args": ["mcp-server-git"]},
) as server:
with trace(workflow_name="MCP Git Example"):
await run(server, directory_path)
if __name__ == "__main__":
if not shutil.which("uvx"):
raise RuntimeError("uvx is not installed. Please install it with `pip install uvx`.")
asyncio.run(main())
import asyncio import shutil from agents import Agent, Runner, trace from agents.mcp import MCPServer, MCPServerStdio async def run(mcp_server: MCPServer, directory_path: str): agent = Agent( name="Assistant", instructions=f"Answer questions about the git repository at {directory_path}, use that for repo_path", mcp_servers=[mcp_server], ) message = "Who's the most frequent contributor?" print("\n" + "-" * 40) print(f"Running: {message}") result = await Runner.run(starting_agent=agent, input=message) print(result.final_output) message = "Summarize the last change in the repository." print("\n" + "-" * 40) print(f"Running: {message}") result = await Runner.run(starting_agent=agent, input=message) print(result.final_output) async def main(): # Ask the user for the directory path directory_path = input("Please enter the path to the git repository: ") async with MCPServerStdio( cache_tools_list=True, # Cache the tools list, for demonstration params={"command": "uvx", "args": ["mcp-server-git"]}, ) as server: with trace(workflow_name="MCP Git Example"): await run(server, directory_path) if __name__ == "__main__": if not shutil.which("uvx"): raise RuntimeError("uvx is not installed. Please install it with `pip install uvx`.") asyncio.run(main())
import asyncio
import shutil
from agents import Agent, Runner, trace
from agents.mcp import MCPServer, MCPServerStdio
async def run(mcp_server: MCPServer, directory_path: str):
agent = Agent(
name="Assistant",
instructions=f"Answer questions about the git repository at {directory_path}, use that for repo_path",
mcp_servers=[mcp_server],
)
message = "Who's the most frequent contributor?"
print("\n" + "-" * 40)
print(f"Running: {message}")
result = await Runner.run(starting_agent=agent, input=message)
print(result.final_output)
message = "Summarize the last change in the repository."
print("\n" + "-" * 40)
print(f"Running: {message}")
result = await Runner.run(starting_agent=agent, input=message)
print(result.final_output)
async def main():
# Ask the user for the directory path
directory_path = input("Please enter the path to the git repository: ")
async with MCPServerStdio(
cache_tools_list=True,  # Cache the tools list, for demonstration
params={"command": "uvx", "args": ["mcp-server-git"]},
) as server:
with trace(workflow_name="MCP Git Example"):
await run(server, directory_path)
if __name__ == "__main__":
if not shutil.which("uvx"):
raise RuntimeError("uvx is not installed. Please install it with `pip install uvx`.")
asyncio.run(main())

小结

OpenAI 采用 Anthropic 的“模型上下文协议”标志着在寻求标准化、高效和安全的人工智能数据集成方面取得了重大进展。通过采用 MCP,OpenAI 不仅增强了自身人工智能系统的能力,还为人工智能行业更广泛的协作创新运动做出了贡献。随着 MCP 的不断普及,它有望简化情境感知人工智能应用的开发,最终带来更智能、反应更灵敏的人工智能助手。

评论留言