Skip to main content

Documentation Index

Fetch the complete documentation index at: https://langchain-zh.cn/llms.txt

Use this file to discover all available pages before exploring further.

Model Context Protocol (MCP) 是一个开源协议,它标准化了应用程序如何向 LLMs 提供工具和上下文。LangChain agent 可以使用定义在 MCP 服务器上的工具,通过 @langchain/mcp-adapters 库实现。

快速开始

安装 @langchain/mcp-adapters 库:
npm install @langchain/mcp-adapters
@langchain/mcp-adapters 使 agent 能够使用一个或多个 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",  // 本地子进程通信
        command: "node",
        // 替换为 math_server.js 文件的绝对路径
        args: ["/path/to/math_server.js"],
    },
    weather: {
        transport: "http",  // HTTP 远程服务器
        // 确保在端口 8000 启动 weather 服务器
        url: "http://localhost:8000/mcp",
    },
});

const tools = await client.getTools();
const agent = createAgent({
    model: "claude-sonnet-4-6",
    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 工具服务器测试你的 agent,请使用以下示例: :::js
数学服务器 (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: "相加两个数字",
            inputSchema: {
                type: "object",
                properties: {
                    a: {
                        type: "number",
                        description: "第一个数字",
                    },
                    b: {
                        type: "number",
                        description: "第二个数字",
                    },
                },
                required: ["a", "b"],
            },
        },
        {
            name: "multiply",
            description: "相乘两个数字",
            inputSchema: {
                type: "object",
                properties: {
                    a: {
                        type: "number",
                        description: "第一个数字",
                    },
                    b: {
                        type: "number",
                        description: "第二个数字",
                    },
                },
                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: "获取地点天气",
            inputSchema: {
            type: "object",
            properties: {
                location: {
                type: "string",
                description: "要获取天气的地点",
                },
            },
            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

---

<div className="source-links">
<Callout icon="edit">
    [Edit this page on GitHub](https://github.com/langchain-ai/docs/edit/main/src/i18n\zh-CN\oss\langchain\mcp.mdx) or [file an issue](https://github.com/langchain-ai/docs/issues/new/choose).
</Callout>
<Callout icon="terminal-2">
    [Connect these docs](/use-these-docs) to Claude, VSCode, and more via MCP for real-time answers.
</Callout>
</div>