如何使用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 的不斷普及,它有望簡化情境感知人工智慧應用的開發,最終帶來更智慧、反應更靈敏的人工智慧助手。

評論留言