Model Context Protocol (MCP) 是一个开源协议,它标准化了应用程序如何向 LLMs 提供工具和上下文。LangChain agent 可以使用定义在 MCP 服务器上的工具,通过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.
langchain-mcp-adapters 库实现。
快速开始
安装langchain-mcp-adapters 库:
pip install langchain-mcp-adapters
langchain-mcp-adapters 使 agent 能够使用一个或多个 MCP 服务器上定义的工具。
MultiServerMCPClient 默认是无状态的。每次工具调用都会创建一个全新的 MCP ClientSession,执行工具,然后进行清理。详情请参阅 状态会话 部分。访问多个 MCP 服务器
import asyncio
from langchain_mcp_adapters.client import MultiServerMCPClient
from langchain.agents import create_agent
async def main():
client = MultiServerMCPClient(
{
"math": {
"transport": "stdio", # 本地子进程通信
"command": "python",
# math_server.py 文件的绝对路径
"args": ["/path/to/math_server.py"],
},
"weather": {
"transport": "http", # HTTP 远程服务器
# 确保在端口 8000 启动 weather 服务器
"url": "http://localhost:8000/mcp",
}
}
)
tools = await client.get_tools()
agent = create_agent(
"claude-sonnet-4-6",
tools
)
math_response = await agent.ainvoke(
{"messages": [{"role": "user", "content": "what's (3 + 5) x 12?"}]}
)
weather_response = await agent.ainvoke(
{"messages": [{"role": "user", "content": "what is the weather in nyc?"}]}
)
print(math_response)
print(weather_response)
if __name__ == "__main__":
asyncio.run(main())
自定义服务器
要创建一个自定义 MCP 服务器,请使用 FastMCP 库:pip install fastmcp
from 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")
数学服务器 (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>

