AI代理工具

一个基于MCP协议和LangChain的AI代理工具,能够执行数学运算和获取天气信息。

  • by hvsssen
  • Python
  • 本地部署
  • 更新于
在 GitHub 查看 hvsssen/Mcpserver-McpLanggraphClient

使用说明

MCP代理项目

该项目演示了如何使用模型上下文协议(MCP)服务器与LangChain和LangGraph创建一个可以执行数学运算和获取天气信息的AI代理。

特性

  • 🧮 数学运算:使用MCP工具对数字进行加法和乘法运算
  • 🌤️ 天气信息:获取任何位置的天气数据
  • 🤖 反应代理:使用LangGraph的ReAct模式进行推理和行动
  • 🔗 多个传输:支持stdio和HTTP(streamable_HTTP)传输

建筑

该项目包括:

  • 数学服务器 (mathserver.py):带加法/乘法工具的MCP服务器(stdio传输)
  • 天气服务器 (weather.py):带天气工具的MCP服务器(HTTP传输)
  • 客户端 (client.py):连接到两个服务器并使用其工具的代理

先决条件

  • Python 3.11+
  • Groq API密钥

安装

  1. 克隆存储库:
git clone <your-repo-url>
cd mcpproj
  1. 创建虚拟环境:
python -m venv .venv
.venv\Scripts\activate  # On Windows
  1. 安装依赖项:
pip install -r requirements.txt

或使用紫外线:

uv add -r requirements.txt
  1. 创建一个 .env 使用Groq API密钥提交:
GROQ_API_KEY=your_api_key_here

用法

使用HTTP传输运行(天气服务器)

  1. 启动天气服务器 (在一个终端中):
python weather.py

这将启动服务器 http://127.0.0.1:8000

  1. 运行客户端 (在另一个终端中):
python client.py

运作原理

  1. 数学服务器(stdio):客户端在需要时自动启动
  2. 天气服务器(HTTP):必须在端口8000上单独运行
  3. 客户端:
    • 连接到两台服务器
    • 加载可用工具
    • 使用Groq的法学硕士创建ReAct代理
    • 使用工具处理用户查询

示例输出

Loaded environment variables.
Connecting to servers...
Set GROQ_API_KEY environment variable.
Getting tools from servers...
Retrieved 3 tools:
  - add
  - multiply
  - get_weather
Created ReAct agent with Groq model and MCP tools.

=== Math Question ===
Answer: The result of 12 * 8 plus 5 is 101.

=== Weather Question ===
Answer: The weather in Paris is Sunny.

项目结构

mcpproj/
├── client.py           # Main agent client
├── mathserver.py       # Math MCP server (stdio)
├── weather.py          # Weather MCP server (HTTP)
├── requirements.txt    # Python dependencies
├── .env               # Environment variables (not in git)
├── .gitignore         # Git ignore file
└── README.md          # This file

使用的技术

  • LangChain:构建LLM应用程序的框架
  • LangGraph:用于创建ReAct代理
  • MCP(模型上下文协议):用于工具集成
  • FastMCP:MCP服务器实现
  • Groq:快速LLM推理
  • langchain mcp适配器:将MCP工具连接到LangChain

运输

stdio运输

  • 使用人:Math Server
  • 由客户端自动启动
  • 通过stdin/stdout进行通信

streamable_http传输

  • 使用人:天气服务器
  • 必须单独启动
  • 基于HTTP的服务器发送事件(SSE)
  • 默认端口:8000

故障排除

气象服务器未连接:

  • 确保天气服务器在端口8000上运行
  • 检查端口8000是否已在使用中: netstat -ano | findstr :8000
  • 如果需要,使用端口8000终止任何进程

模型错误:

  • 确保您的Groq API密钥有效
  • 检查型号是否 llama-3.1-8b-instant 可用的

导入错误:

  • 确保安装了所有依赖项: pip install -r requirements.txt

代理试图使用不存在的工具:

  • 系统提示限制了工具的使用,但有些型号可能仍然会产生幻觉
  • 尝试使用其他模型或使提示更明确

许可证

麻省理工学院