跳到内容

MCP 集成

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

MCP

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

npm install @langchain/mcp-adapters

使用 MCP 工具

@langchain/mcp-adapters 包使代理能够使用一个或多个 MCP 服务器上定义的工具。

import { MultiServerMCPClient } from "@langchain/mcp-adapters";
import { initChatModel } from "langchain/chat_models/universal";
import { createReactAgent } from "@langchain/langgraph/prebuilt";

const client = new MultiServerMCPClient({
  mcpServers: {
    "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",
    }
  }
})

const llm = await initChatModel("anthropic:claude-3-7-sonnet-latest");
const agent = createReactAgent({
  llm,
  tools: await client.getTools()
});

const mathResponse = await agent.invoke(
  { messages: [ { role: "user", content: "what's (3 + 5) x 12?" } ] }
);
const weatherResponse = await agent.invoke(
  { messages: [ { role: "user", content: "what is the weather in nyc?" } ] }
);
await client.close();

自定义 MCP 服务器

要创建您自己的 MCP 服务器,您可以使用 Python 中的 mcp 库(或 TypeScript 中的 @modelcontextprotocol/sdk)。这些库提供了一种简单的方式来定义工具并将它们作为服务器运行。

安装 MCP 库

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

数学服务器示例(标准输入/输出传输)
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")

更多资源