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

安装

安装 langchain-mcp-adapters 库以在 LangGraph 中使用 MCP 工具:
pip install langchain-mcp-adapters

传输类型

MCP 支持不同的客户端-服务器通信传输机制:
  • stdio – 客户端将服务器作为子进程启动并通过标准输入/输出进行通信。最适合本地工具和简单设置。
  • 可流式 HTTP – 服务器作为处理 HTTP 请求的独立进程运行。支持远程连接和多个客户端。
  • 服务器发送事件(SSE) – 针对实时流式通信优化的可流式 HTTP 变体。

使用 MCP 工具

langchain-mcp-adapters 使智能体能够使用在一个或多个 MCP 服务器上定义的工具。
Accessing multiple MCP servers
from langchain_mcp_adapters.client import MultiServerMCPClient  
from langchain.agents import create_agent


client = MultiServerMCPClient(  
    {
        "math": {
            "transport": "stdio",  # Local subprocess communication
            "command": "python",
            # Absolute path to your math_server.py file
            "args": ["/path/to/math_server.py"],
        },
        "weather": {
            "transport": "streamable_http",  # HTTP-based remote server
            # Ensure you start your weather server on port 8000
            "url": "http://localhost:8000/mcp",
        }
    }
)

tools = await client.get_tools()  
agent = create_agent(
    "claude-sonnet-4-5-20250929",
    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?"}]}
)
MultiServerMCPClient is stateless by default. Each tool invocation creates a fresh MCP ClientSession, executes the tool, and then cleans up.

自定义 MCP 服务器

要创建您自己的 MCP 服务器,您可以使用 mcp 库。该库提供了一种简单的方法来定义工具并将它们作为服务器运行。
pip install mcp
Use the following reference implementations to test your agent with MCP tool servers.
Math server (stdio transport)
from mcp.server.fastmcp import FastMCP

mcp = FastMCP("Math")

@mcp.tool()
def add(a: int, b: int) -> int:
    """Add two numbers"""
    return a + b

@mcp.tool()
def multiply(a: int, b: int) -> int:
    """Multiply two numbers"""
    return a * b

if __name__ == "__main__":
    mcp.run(transport="stdio")
Weather server (streamable HTTP transport)
from mcp.server.fastmcp import FastMCP

mcp = FastMCP("Weather")

@mcp.tool()
async def get_weather(location: str) -> str:
    """Get weather for location."""
    return "It's always sunny in New York"

if __name__ == "__main__":
    mcp.run(transport="streamable-http")

有状态工具使用

对于在工具调用之间维护上下文的有状态服务器,使用 client.session() 创建持久的 ClientSession
Using MCP ClientSession for stateful tool usage
from langchain_mcp_adapters.tools import load_mcp_tools

client = MultiServerMCPClient({...})
async with client.session("math") as session:
    tools = await load_mcp_tools(session)

其他资源


Connect these docs programmatically to Claude, VSCode, and more via MCP for real-time answers.