MCP 集成¶
模型上下文协议 (MCP) 是一种开放协议,用于规范应用程序如何向语言模型提供工具和上下文。LangGraph 智能体可以通过 langchain-mcp-adapters
库使用在 MCP 服务器上定义的工具。
安装 langchain-mcp-adapters
库以在 LangGraph 中使用 MCP 工具
使用 MCP 工具¶
langchain-mcp-adapters
包使智能体能够使用在一个或多个 MCP 服务器上定义的工具。
使用在 MCP 服务器上定义的工具的智能体
from langchain_mcp_adapters.client import MultiServerMCPClient
from langgraph.prebuilt import create_react_agent
async with MultiServerMCPClient(
{
"math": {
"command": "python",
# Replace with absolute path to your math_server.py file
"args": ["/path/to/math_server.py"],
"transport": "stdio",
},
"weather": {
# Ensure your start your weather server on port 8000
"url": "http://localhost:8000/sse",
"transport": "sse",
}
}
) as client:
agent = create_react_agent(
"anthropic:claude-3-7-sonnet-latest",
client.get_tools()
)
math_response = await agent.ainvoke(
{"messages": [{"role": "user", "content": "what's (3 + 5) x 12?"}]}
)
weather_response = await agent.ainvoke(
{"messages": [{"role": "user", "content": "what is the weather in nyc?"}]}
)
自定义 MCP 服务器¶
要创建自己的 MCP 服务器,可以使用 mcp
库。该库提供了一种简单的方式来定义工具并将其作为服务器运行。
安装 MCP 库
使用以下参考实现来测试您的智能体与 MCP 工具服务器的交互。示例数学服务器 (stdio 传输)
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("Math")
@mcp.tool()
def add(a: int, b: int) -> int:
"""Add two numbers"""
return a + b
@mcp.tool()
def multiply(a: int, b: int) -> int:
"""Multiply two numbers"""
return a * b
if __name__ == "__main__":
mcp.run(transport="stdio")
示例天气服务器 (SSE 传输)
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("Weather")
@mcp.tool()
async def get_weather(location: str) -> str:
"""Get weather for location."""
return "It's always sunny in New York"
if __name__ == "__main__":
mcp.run(transport="sse")