使用说明
LangChain MCP服务器演示
本项目演示了如何使用LangChain创建和使用模型上下文协议(MCP)服务器。MCP是一种协议,允许AI模型通过标准化的接口与外部工具和数据源进行交互。
什么是MCP?
模型上下文协议(MCP)是一种协议,它使AI模型能够:
- 连接到外部工具和数据源
- 在远程服务器上执行功能
- 访问实时信息
- 与数据库、API和其他服务交互
项目结构
langchain-mcp-server/
├── client.py # Main client that connects to MCP servers
├── mathserver.py # Math MCP server (stdio transport)
├── weather.py # Weather MCP server (HTTP transport)
├── requirements.txt # Python dependencies
└── README.md # This file
组件
1.数学服务器(mathserver.py)
一个提供数学运算的简单MCP服务器:
- 运输:stdio(标准输入/输出)
- 工具:
add(a: int, b: int) -> int:将两个数字相加multiply(a: int, b: int) -> int:将两个数字相乘
2.气象服务器(weather.py)
提供天气信息的基本MCP服务器:
- 运输:可流式传输http(基于http)
- 工具:
get_weather(city: str) -> str:返回给定城市的天气
3.客户(client.py)
连接到多个MCP服务器并将其与AI代理一起使用的LangChain客户端:
- 连接到数学和天气服务器
- 使用Groq的Qwen模型进行推理
- 创建可以使用MCP工具的ReAct代理
设置和安装
-
安装依赖项:
pip install -r requirements.txt -
设置环境变量: 创建一个
.env使用Groq API密钥提交:GROQ_API_KEY=your_groq_api_key_here -
启动天气服务器 (在单独的终端中):
python weather.py这将启动天气服务器
http://localhost:8000/mcp
用法
运行演示
-
启动天气服务器 (如果尚未运行):
python weather.py -
运行主客户端:
python client.py
客户将:
- 连接到数学服务器(通过stdio)和天气服务器(通过HTTP)
- 让AI代理解决一个数学问题:
(19 + 17) * 45 - 让AI代理获取东京的天气信息
- 显示响应
期望输出
Math Response: The result of (19 + 17) * 45 is 1620
Weather Response: The weather in Tokyo is sunny
运作原理
MCP服务器创建
每个MCP服务器都是使用 FastMCP 框架:
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("ServerName")
@mcp.tool()
def my_function(param: str) -> str:
"""Function description"""
return "result"
if __name__ == "__main__":
mcp.run(transport="stdio") # or "streamable-http"
客户端配置
客户端使用以下方式连接到多个服务器 MultiServerMCPClient:
client = MultiServerMCPClient({
"math": {
"command": "python",
"args": ["mathserver.py"],
"transport": "stdio",
},
"weather": {
"url": "http://localhost:8000/mcp",
"transport": "streamable-http",
}
})
运输类型
- 标准输入输出:使用标准输入/输出进行本地通信
- 可流式传输http:使用HTTP进行网络通信
关键概念演示
- 多服务器架构:同时连接到多个MCP服务器
- 不同的传输协议:stdio用于本地服务器,HTTP用于远程服务器
- 工具集成:MCP工具可供LangChain代理商使用
- AI代理推理:代理可以根据用户的请求选择使用哪些工具
扩展项目
添加新的MCP服务器
- 创建新的服务器文件(例如。,
databaseserver.py) - 使用定义工具
@mcp.tool()装饰器 - 将服务器配置添加到
client.py - 重新启动客户端
添加新工具
要向现有服务器添加新工具,只需使用以下命令添加新功能 @mcp.tool() 装饰师:
@mcp.tool()
def divide(a: float, b: float) -> float:
"""Divide two numbers"""
return a / b
依赖项
langchain-groq:Groq LLM集成langchain-mcp-adapters:LangChain的MCP客户端适配器mcp:模型上下文协议框架langgraph:用于创建ReAct代理
这个项目是对MCP服务器的简单介绍,并演示了它们如何与LangChain集成,用于AI驱动的应用程序。