模型上下文协议 (MCP)是一个开放协议,用于标准化应用如何向 LLM 提供工具和上下文。LangChain 智能体可以通过 @langchain/mcp-adapters 库使用 MCP 服务器上定义的工具。

快速开始

安装 @langchain/mcp-adapters 库:
npm install @langchain/mcp-adapters
@langchain/mcp-adapters 使智能体能够使用在一台或多台 MCP 服务器上定义的工具。
MultiServerMCPClient 默认无状态。每个工具调用都会创建一个新的 MCP ClientSession ,执行该工具,然后进行清理。请参阅有状态会话部分了解更多详细信息。
访问多个 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: "streamable_http",  // HTTP-based remote server
        // Ensure you start your weather server on port 8000
        url: "http://localhost: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?" }],
});

自定义服务器

要创建您自己的 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}`);
});

传输

MCP 支持客户端-服务器通信的不同传输机制。

HTTP 协议

http 传输(也称为 streamable-http )使用 HTTP 请求进行客户端-服务器通信。请参阅MCP HTTP 传输规范了解更多详情。
const client = new MultiServerMCPClient({
    weather: {
        transport: "sse",
        url: "http://localhost:8000/mcp",
    },
});

传递请求头

认证

标准输入输出

客户端将服务器作为子进程启动并通过标准输入/输出进行通信。最适合本地工具和简单的设置。
与 HTTP 传输不同, stdio 连接本质上是有状态的—子进程在客户端连接的生命周期内持续存在。然而,当使用 MultiServerMCPClient 时,如果没有明确的会话管理,每个工具调用仍然会创建一个新会话。参见有状态会话以管理持久连接。
const client = new MultiServerMCPClient({
    math: {
        transport: "stdio",
        command: "node",
        args: ["/path/to/math_server.js"],
    },
});

核心功能

工具

工具允许 MCP 服务器公开 LLM 可以调用的可执行函数来执行操作,例如查询数据库、调用 API 或与外部系统交互。LangChain 将 MCP 工具转换为 LangChain 工具,使它们可以直接在任何 LangChain 智能体或工作流程中使用。

加载工具

使用 client.get_tools() 从 MCP 服务器检索工具并将其传递给您的智能体:
import { MultiServerMCPClient } from "@langchain/mcp-adapters";
import { createAgent } from "langchain";

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

其他资源


连接这些文档通过 MCP 发送给 Claude、VSCode 等以获得实时答案。