跳到主要内容
模型上下文协议 (MCP) 是一个开放协议,它标准化了应用程序如何向 LLM 提供工具和上下文。LangChain 代理可以使用 langchain-mcp-adapters 库使用 MCP 服务器上定义的工具。

安装

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

传输类型

MCP 支持不同的传输机制用于客户端-服务器通信
  • stdio – 客户端将服务器作为子进程启动,并通过标准输入/输出进行通信。最适合本地工具和简单设置。
  • 可流式 HTTP – 服务器作为独立进程运行,处理 HTTP 请求。支持远程连接和多个客户端。
  • 服务器发送事件 (SSE) – 可流式 HTTP 的变体,针对实时流通信进行了优化。

使用 MCP 工具

@langchain/mcp-adapters 使代理能够使用在一个或多个 MCP 服务器上定义的工具。
访问多个 MCP 服务器
import { MultiServerMCPClient } from "@langchain/mcp-adapters";  
import { ChatAnthropic } from "@langchain/anthropic";
import { createAgent } from "langchain";

const client = new MultiServerMCPClient({  
    math: {
        transport: "stdio",  // Local subprocess communication
        command: "node",
        // Replace with absolute path to your math_server.js file
        args: ["/path/to/math_server.js"],
    },
    weather: {
        transport: "sse",  // Server-Sent Events for streaming
        // Ensure you start your weather server on port 8000
        url: "https://:8000/mcp",
    },
});

const tools = await client.getTools();  
const agent = createAgent({
    model: "claude-sonnet-4-5-20250929",
    tools,  
});

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?" }],
});
MultiServerMCPClient 默认是无状态的。每次工具调用都会创建一个新的 MCP ClientSession,执行工具,然后进行清理。

自定义 MCP 服务器

要创建自己的 MCP 服务器,可以使用 @modelcontextprotocol/sdk 库。该库提供了一种简单的方法来定义工具并将其作为服务器运行。
npm install @modelcontextprotocol/sdk
使用以下参考实现来测试您的代理与 MCP 工具服务器。
数学服务器(stdio 传输)
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
    CallToolRequestSchema,
    ListToolsRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";

const server = new Server(
    {
        name: "math-server",
        version: "0.1.0",
    },
    {
        capabilities: {
        tools: {},
        },
    }
);

server.setRequestHandler(ListToolsRequestSchema, async () => {
    return {
        tools: [
        {
            name: "add",
            description: "Add two numbers",
            inputSchema: {
            type: "object",
            properties: {
                a: {
                type: "number",
                description: "First number",
                },
                b: {
                type: "number",
                description: "Second number",
                },
            },
            required: ["a", "b"],
            },
        },
        {
            name: "multiply",
            description: "Multiply two numbers",
            inputSchema: {
            type: "object",
            properties: {
                a: {
                type: "number",
                description: "First number",
                },
                b: {
                type: "number",
                description: "Second number",
                },
            },
            required: ["a", "b"],
            },
        },
        ],
    };
});

server.setRequestHandler(CallToolRequestSchema, async (request) => {
    switch (request.params.name) {
        case "add": {
        const { a, b } = request.params.arguments as { a: number; b: number };
        return {
            content: [
            {
                type: "text",
                text: String(a + b),
            },
            ],
        };
        }
        case "multiply": {
        const { a, b } = request.params.arguments as { a: number; b: number };
        return {
            content: [
            {
                type: "text",
                text: String(a * b),
            },
            ],
        };
        }
        default:
        throw new Error(`Unknown tool: ${request.params.name}`);
    }
});

async function main() {
    const transport = new StdioServerTransport();
    await server.connect(transport);
    console.error("Math MCP server running on stdio");
}

main();
天气服务器(SSE 传输)
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
import {
    CallToolRequestSchema,
    ListToolsRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";
import express from "express";

const app = express();
app.use(express.json());

const server = new Server(
    {
        name: "weather-server",
        version: "0.1.0",
    },
    {
        capabilities: {
        tools: {},
        },
    }
);

server.setRequestHandler(ListToolsRequestSchema, async () => {
    return {
        tools: [
        {
            name: "get_weather",
            description: "Get weather for location",
            inputSchema: {
            type: "object",
            properties: {
                location: {
                type: "string",
                description: "Location to get weather for",
                },
            },
            required: ["location"],
            },
        },
        ],
    };
});

server.setRequestHandler(CallToolRequestSchema, async (request) => {
    switch (request.params.name) {
        case "get_weather": {
        const { location } = request.params.arguments as { location: string };
        return {
            content: [
            {
                type: "text",
                text: `It's always sunny in ${location}`,
            },
            ],
        };
        }
        default:
        throw new Error(`Unknown tool: ${request.params.name}`);
    }
});

app.post("/mcp", async (req, res) => {
    const transport = new SSEServerTransport("/mcp", res);
    await server.connect(transport);
});

const PORT = process.env.PORT || 8000;
app.listen(PORT, () => {
    console.log(`Weather MCP server running on port ${PORT}`);
});

有状态的工具使用

对于在工具调用之间维护上下文的有状态服务器,请使用 client.session() 创建持久的 ClientSession
使用 MCP ClientSession 进行有状态的工具使用
import { loadMCPTools } from "@langchain/mcp-adapters/tools.js";

const client = new MultiServerMCPClient({...});
const session = await client.session("math");
const tools = await loadMCPTools(session);

附加资源


以编程方式连接这些文档到 Claude、VSCode 等,通过 MCP 获取实时答案。
© . This site is unofficial and not affiliated with LangChain, Inc.