要点
- 适配了Anthropic Model Context Protocol (MCP) 所有的工具
- 既可以进行本地通信stdio,也可以及远程通信SSE
- 与LangChain LangGraph生态无缝适配
LangChain MCP 实战
pip install langchain-mcp-adapters
1、 首先创建MCP服务
- 这里创建了一个数学计算服务
math_server.py
,mcp服务的名称叫Math
,采用的通信方式为stdio
# math_server.py
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__":
# transport表示mcp通信的类型:stdio(标准输入输出) 适用于本地通信;SSE(Server-Sent Events) 适用于远程通信
mcp.run(transport="stdio")
2、创建client连接MCP服务
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", # 用python命令执行本地通信
args=["/path/to/math_server.py"], # 本地地址必须是绝对路径
)
asyncwith stdio_client(server_params) as (read, write):
asyncwith ClientSession(read, write) as session:
# 初始化链接client session
await session.initialize()
# 加载mcp服务中的工具,注册为langchian中的工具
tools = await load_mcp_tools(session)
# langchian创建agent,调用mcp中的工具进行运算
agent = create_react_agent(model, tools)
agent_response = await agent.ainvoke({"messages": "what's (3 + 5) x 12?"})
3、 创建多个MCP服务
- 创建一个查询天气的服务
math_server.py
# math_server.py
...
# weather_server.py
from typing import List
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("Weather")
@mcp.tool()
asyncdef get_weather(location: str) -> str:
"""Get weather for location."""
return"It's always sunny in New York"
if __name__ == "__main__":
mcp.run(transport="sse") # HTTP with SSE(Server-Sent Events) 适用于远程通信
启动远程服务
python weather_server.py
4、 连接多个MCP服务
from langchain_mcp_adapters.client import MultiServerMCPClient
from langgraph.prebuilt import create_react_agent
from langchain_openai import ChatOpenAI
model = ChatOpenAI(model="gpt-4o")
asyncwith MultiServerMCPClient(
{
"math": { # 启动math服务
"command": "python",
"args": ["/path/to/math_server.py"],
"transport": "stdio",
},
"weather": { # 启动weather服务
# make sure you start your weather server on port 8000
"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?"})
文章来源:微信公众号-CourseAI,原始发表时间:2025年03月30日。