首页
/ 【免费下载】 LangChain MCP Adapters 使用教程

【免费下载】 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 的项目中,为各种自然语言处理和自动化任务提供支持。

登录后查看全文
热门项目推荐
相关项目推荐