【免费下载】 LangChain MCP Adapters 使用教程
2026-01-30 04:14:48作者:毕习沙Eudora
1. 项目介绍
LangChain MCP Adapters 是一个开源库,它提供了一个轻量级的包装器,使得 Anthropic Model Context Protocol (MCP) 工具能够与 LangChain 和 LangGraph 兼容。这个库的主要功能是将 MCP 工具转换为 LangChain 工具,以便与 LangGraph 代理一起使用,并且提供了一个客户端实现,允许连接到多个 MCP 服务器并从中加载工具。
2. 项目快速启动
首先,确保你已经安装了以下依赖项:
pip install langchain-mcp-adapters langgraph langchain-openai
接下来,设置你的 OpenAI API 密钥:
export OPENAI_API_KEY=<你的_api_key>
创建 MCP 服务器
下面是一个简单的 MCP 服务器示例,它可以进行加法和乘法运算:
# math_server.py
from mcp.server.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")
创建 MCP 客户端
接下来,创建一个客户端来连接服务器,并使用 LangGraph 代理:
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
from langchain_mcp_adapters.tools import load_mcp_tools
from langgraph.prebuilt import create_react_agent
from langchain_openai import ChatOpenAI
model = ChatOpenAI(model="gpt-4o")
server_params = StdioServerParameters(
command="python",
args=["/path/to/math_server.py"],
transport="stdio"
)
async with stdio_client(server_params) as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
tools = await load_mcp_tools(session)
agent = create_react_agent(model, tools)
agent_response = await agent.ainvoke({"messages": "what's (3 + 5) x 12?"})
print(agent_response)
确保将 /path/to/math_server.py 替换为你的 math_server.py 文件的绝对路径。
3. 应用案例和最佳实践
连接多个 MCP 服务器
LangChain MCP Adapters 允许你连接到多个 MCP 服务器并从中加载工具。以下是如何做到这一点的示例:
from langchain_mcp_adapters.client import MultiServerMCPClient
async with MultiServerMCPClient({
"math": {
"command": "python",
"args": ["/path/to/math_server.py"],
"transport": "stdio"
},
"weather": {
"url": "http://localhost:8000/sse",
"transport": "sse"
}
}) as client:
agent = create_react_agent(model, client.get_tools())
math_response = await agent.ainvoke({"messages": "what's (3 + 5) x 12?"})
weather_response = await agent.ainvoke({"messages": "what is the weather in nyc?"})
print(math_response)
print(weather_response)
确保你的天气服务器正在端口 8000 上运行。
与 LangGraph API 服务器一起使用
如果你想在 LangGraph API 服务器中使用 LangGraph 代理和 MCP 工具,可以按照以下设置:
# graph.py
from contextlib import asynccontextmanager
from langchain_mcp_adapters.client import MultiServerMCPClient
from langgraph.prebuilt import create_react_agent
from langchain_anthropic import ChatAnthropic
model = ChatAnthropic(model="claude-3-5-sonnet-latest")
@asynccontextmanager
async def make_graph():
async with MultiServerMCPClient({
"math": {
"command": "python",
"args": ["/path/to/math_server.py"],
"transport": "stdio"
},
"weather": {
"url": "http://localhost:8000/sse",
"transport": "sse"
}
}) as client:
agent = create_react_agent(model, client.get_tools())
yield agent
# 在 langgraph.json 中指定 make_graph 作为 graph entrypoint
4. 典型生态项目
目前 LangChain MCP Adapters 项目的生态系统中,没有列出具体的典型项目。不过,这个库可以与任何支持 MCP 协议的服务器一起使用,并且可以集成到使用 LangChain 和 LangGraph 的项目中,为各种自然语言处理和自动化任务提供支持。
登录后查看全文
热门项目推荐
相关项目推荐
atomcodeClaude Code 的开源替代方案。连接任意大模型,编辑代码,运行命令,自动验证 — 全自动执行。用 Rust 构建,极致性能。 | An open-source alternative to Claude Code. Connect any LLM, edit code, run commands, and verify changes — autonomously. Built in Rust for speed. Get StartedRust0213
cann-learning-hubCANN 学习中心仓,支持在线互动运行、边学边练,提供教程、示例与优化方案,一站式助力昇腾开发者快速上手。Jupyter Notebook0137
JoyAI-EchoJoyAI-Echo,这是一个独立的、仅用于推理的版本,旨在实现分钟级多镜头音视频生成。它采用了经过蒸馏的DMD生成器、配对的跨模态记忆以及故事级别的一致性。其性能的核心在于,一个跨模态视听记忆库能够在长达五分钟的视频中保持角色外观和语音音色的一致性。同时,一个训练后处理流程将基于记忆的强化学习与分布匹配蒸馏相结合,实现了7.5倍的速度提升,显著增强了视觉质量和对齐效果。00
GLM-5.2智谱开源 GLM-5.2,这是针对长文本任务的最新旗舰模型。相较于前代产品 GLM-5.1,它在长文本任务处理能力上实现了显著飞跃,并且首次在稳定的 100 万 token 上下文中提供这一能力。Jinja00
SwanLab⚡️SwanLab - an open-source, modern-design AI training tracking and visualization tool. Supports Cloud / Self-hosted use. Integrated with PyTorch / Transformers / LLaMA Factory / veRL/ Swift / Ultralytics / MMEngine / Keras etc.Python00
tiny-universe《大模型白盒子构建指南》:一个全手搓的Tiny-UniverseJupyter Notebook03
项目优选
收起
deepin linux kernel
C
32
16
openEuler内核是openEuler操作系统的核心,既是系统性能与稳定性的基石,也是连接处理器、设备与服务的桥梁。
C
468
461
暂无描述
Dockerfile
776
5.08 K
Ascend Extension for PyTorch
Python
756
962
本项目是CANN提供的transformer类大模型算子库,实现网络在NPU上加速计算。
C++
873
2.02 K
本项目是CANN提供的神经网络类计算算子库,实现网络在NPU上加速计算。
C++
697
1.4 K
昇腾LLM分布式训练框架
Python
183
230
本项目是CANN提供的数学类基础计算算子库,实现网络在NPU上加速计算。
C++
1.1 K
1.14 K
本仓库是 Flutter SDK 与 Flutter Engine 的 OpenHarmony 适配版本,由 CPF-Flutter 团队维护。开发者可使用熟悉的 Flutter 技术栈开发 OpenHarmony 应用,3.35.7 及以后的适配版本可基于本仓库源码构建支持 OpenHarmony 的 Flutter Engine。
Dart
1.04 K
271
Oohos_react_native
React Native鸿蒙化仓库
C++
361
430