Skip to content

MCP 集成

模型上下文协议(MCP) 是一个开放协议,它标准化了应用程序如何为语言模型提供工具和上下文。LangGraph 代理可以通过 langchain-mcp-adapters 库使用 MCP 服务器上定义的工具。

MCP

安装 langchain-mcp-adapters 库以在 LangGraph 中使用 MCP 工具:

pip install langchain-mcp-adapters

使用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",
            # 用您的math_server.py文件的绝对路径替换
            "args": ["/path/to/math_server.py"],
            "transport": "stdio",
        },
        "weather": {
            # 确保您的天气服务器在端口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": "什么数字是(3 + 5) x 12?"}]}
    )
    weather_response = await agent.ainvoke(
        {"messages": [{"role": "user", "content": "纽约市的天气如何?"}]}
    )

自定义MCP服务器

要创建自己的MCP服务器,可以使用mcp库。该库提供了一种简单的方式来定义工具并将其作为服务器运行。

安装MCP库:

pip install mcp

使用以下参考实现来测试您的代理与MCP工具服务器的交互。

示例数学服务器(stdio传输)
from mcp.server.fastmcp import FastMCP

mcp = FastMCP("Math")

@mcp.tool()
def add(a: int, b: int) -> int:
    """加两个数"""
    return a + b

@mcp.tool()
def multiply(a: int, b: int) -> int:
    """乘以两个数"""
    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:
    """获取位置的天气。"""
    return "纽约总是阳光明媚"

if __name__ == "__main__":
    mcp.run(transport="sse")

额外资源

Comments