🤖 MCP多工具人工智能代理
基于 模型上下文协议(MCP) 通过自然语言理解协调多种工具。由Groq的Llama 3.3 70B提供支持,并具有生产就绪的web界面。
______________________________________________________________________
📋 目录
______________________________________________________________________
🎯 概述
MCP多工具人工智能代理是一个企业级的对话式人工智能系统,展示了先进的人工智能编排模式。它使用LLM驱动的决策将用户请求智能地路由到适当的工具(天气API、网络搜索),通过实时流媒体界面返回自然语言响应。
关键能力
- 智能刀具路径:LLM分析请求并自主选择合适的工具
- 实时流媒体:服务器发送事件(SSE)在处理过程中提供实时状态更新
- 可扩展架构:模块化MCP设计允许无缝集成新工具
- 生产就绪:使用Flask、LangGraph构建,并为企业部署提供适当的错误处理
______________________________________________________________________
✨ 特性
核心功能
- 🧠 自然语言理解:由Groq的Llama 3.3 70B提供支持,用于意图识别和工具选择
- 🌤️ 天气情报:任何全球位置的实时天气数据检索
- 🔍 网页搜索:用于当前信息收集的集成Serper API
- 💬 对话式人工智能:在不需要工具的情况下处理随意对话
- 📊 实时更新:实时状态流显示代理的决策过程
技术特性
- 🔄 有状态的工作流:LangGraph通过适当的状态管理来管理多步代理逻辑
- 🔌 HTTP/REST通信:使用Flask的可靠客户端-服务器架构
- 🎨 现代用户界面:具有渐变设计和实时指示器的响应式聊天界面
- 🛡️ 错误处理:全面的异常管理和重试逻辑
- 📈 可扩展设计:支持横向扩展的微服务架构
______________________________________________________________________
🏗️ 建筑
系统设计
┌─────────────────────────────────────────────────────────────┐
│ User Interface │
│ (Flask + SSE + Real-time UI) │
└────────────────────────┬────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ LangGraph Orchestrator │
│ ┌──────────────┐ ┌──────────────┐ │
│ │ Route │───────▶│ Respond │ │
│ │ (Groq LLM) │ │ (Groq LLM) │ │
│ └──────────────┘ └──────────────┘ │
└────────────────────────┬────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ MCP Tool Server │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ Weather │ │ Web Search │ │ Future │ │
│ │ Tool │ │ Tool │ │ Tools │ │
│ └─────────────┘ └─────────────┘ └─────────────┘ │
└─────────────────────────────────────────────────────────────┘请求流
- 用户输入 → 前端捕获消息并创建会话
- 意向分析 → Groq LLM分析查询并选择工具
- 工具执行 → MCP服务器执行所选工具
- 响应生成 → Groq LLM格式自然生成
- 流媒体响应 → SSE为UI提供实时更新
______________________________________________________________________
🛠️ 技术栈
后端
- Python 3.8+:核心运行时环境
- 烧瓶:前端和API的Web框架
- LangGraph:用于代理工作流编排的状态机
- FastMCP:模型上下文协议实现
- Groq SDK:LLM API集成(Llama 3.3 70B)
- 请求::用于外部API的HTTP客户端
前端
- HTML5/CSS3:现代响应式UI
- 原生 JavaScript:无框架开销,纯性能
- 服务器发送事件(SSE):实时双向通信
- CSS网格/Flexbox:响应式布局系统
外部API
- 格罗克API:自由层LLM推理(Llama 3.3 70B)
- Serper API公司:网络搜索(每月2500次免费搜索)
- wttr.in:天气数据(免费,无需API密钥)
______________________________________________________________________
📦 安装
先决条件
- Python 3.8或更高版本
- pip包管理器
- 活动互联网连接
- Groq和Serper提供的免费API密钥
步骤1:克隆存储库
git clone https://github.com/yourusername/mcp-agent.git
cd mcp-agent第二步:创建虚拟环境
# Windows
python -m venv .venv
.venv\Scripts\activate
# Linux/Mac
python3 -m venv .venv
source .venv/bin/activate步骤3:安装依赖项
pip install -r requirements.txtrequirements.txt:
fastmcp
pydantic
requests
python-dotenv
langgraph
groq
flask步骤4:获取API密钥
Groq API(免费)
- 访问:https://console.groq.com
- 注册并导航到“API密钥”
- 单击“创建API密钥”
- 复制密钥
Serper API(免费层)
- 访问:https://serper.dev
- 注册(每月2500次免费搜索)
- 从仪表板复制API密钥
步骤5:配置环境
创建 .env 项目根目录中的文件:
# Groq API Configuration
GROQ_API_KEY=your_groq_api_key_here
# Serper API Configuration
SERPER_API_KEY=your_serper_api_key_here______________________________________________________________________
⚙️ 配置
环境变量
| 变量 | 必填 | 描述 | 默认值 |
|---|---|---|---|
GROQ_API_KEY | 是 | Groq API身份验证密钥 | - |
SERPER_API_KEY | 是 | Serper网络搜索API密钥 | - |
MCP_SERVER_PORT | 无 | MCP服务器端口 | 5000 |
FRONTEND_PORT | 否 | 前端应用程序端口 | 8000 |
服务器配置
MCP服务器(MCP_Server_http.py):
app.run(host="0.0.0.0", port=5000, debug=False)前端服务器(app.py):
app.run(host="0.0.0.0", port=8000, debug=True, threaded=True)______________________________________________________________________
🚀 用法
启动系统
终端1:MCP工具服务器
python mcp_server_http.py预期产量:
🔥 MCP HTTP Server starting on http://localhost:5000
* Running on http://127.0.0.1:5000终端2:前端应用程序
python app.py预期产量:
🚀 MCP AGENT FRONTEND STARTING
📡 Frontend URL: http://localhost:8000
✅ MCP Server is running
🌐 Open http://localhost:8000 in your browser访问界面
打开浏览器: http://localhost:8000
查询示例
天气信息:
What's the weather in Tokyo?
How's the weather in Lagos, Nigeria?
Is it raining in London right now?网络搜索:
Search for latest AI developments
Find recent news about SpaceX launches
What are the top tech trends in 2025?一般对话:
Hello, how are you?
Tell me a joke
What can you help me with?健康检查端点
# Check frontend health
curl http://localhost:8000/health
# Check MCP server health
curl http://localhost:5000/health
# List available tools
curl http://localhost:5000/tools______________________________________________________________________
📁 项目结构
mcp-agent/
│
├── .env # Environment variables (not in git)
├── .gitignore # Git ignore rules
├── requirements.txt # Python dependencies
├── README.md # This file
│
├── mcp_server_http.py # MCP tool server (HTTP-based)
│ ├── get_weather() # Weather tool implementation
│ └── web_search() # Web search tool implementation
│
├── app.py # Main frontend application
│ ├── Agent workflow # LangGraph orchestration
│ ├── Flask routes # API endpoints
│ └── SSE streaming # Real-time updates
│
├── templates/
│ └── index.html # Chat interface UI
│
└── tests/
├── test_tools.py # Tool unit tests
└── test_agent.py # Agent workflow tests______________________________________________________________________
📚 API 文档
前端API
POST/聊天
向代理发送消息。
请求:
{
"message": "What's the weather in Paris?",
"session_id": "session_12345"
}答复:
{
"status": "processing",
"session_id": "session_12345"
}GET/stream/{session_id}
服务器发送事件流以进行实时更新。
事件类型:
status:处理状态更新routing:工具选择推理final:完整答复
GET/健康
系统健康检查。
答复:
{
"status": "healthy",
"frontend": "online",
"mcp_server": "online",
"groq_api": "configured"
}MCP服务器API
POST/工具/呼叫
执行一个工具。
请求:
{
"name": "get_weather",
"arguments": {
"city": "Tokyo"
}
}答复:
{
"success": true,
"data": {
"location": "Tokyo, Japan",
"temperature": "15°C / 59°F",
"condition": "Clear",
"humidity": "65%"
}
}______________________________________________________________________
🔧 发展
添加新工具
- 在MCP服务器(MCP_server_http.py)中定义工具:
def calculate(expression: str):
"""Calculator tool"""
try:
result = eval(expression) # Use safely in production!
return {"success": True, "data": {"result": result}}
except Exception as e:
return {"success": False, "error": str(e)}
@app.route('/tools/call', methods=['POST'])
def call_tool():
# ... existing code ...
elif tool_name == "calculate":
expr = arguments.get("expression")
return jsonify(calculate(expr))- 在app.py中更新路由提示:
routing_prompt = f"""
Available tools:
1. get_weather - Get weather for a city
2. web_search - Search the web
3. calculate - Perform math calculations # NEW
User request: {state["msg"]}
"""运行测试
# Install test dependencies
pip install pytest pytest-cov
# Run all tests
pytest
# Run with coverage
pytest --cov=. --cov-report=html代码质量
# Format code
black app.py mcp_server_http.py
# Lint code
flake8 app.py mcp_server_http.py
# Type checking
mypy app.py______________________________________________________________________
🌐 部署
Docker部署
Dockerfile:
FROM python:3.9-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 5000 8000
CMD ["python", "app.py"]docker-compose.yml:
version: '3.8'
services:
mcp-server:
build: .
command: python mcp_server_http.py
ports:
- "5000:5000"
env_file:
- .env
frontend:
build: .
command: python app.py
ports:
- "8000:8000"
depends_on:
- mcp-server
env_file:
- .env生产注意事项
- 使用 独角兽 而不是Flask开发服务器
- 启用 超文本传输安全协议 使用SSL证书
- 实施 速率限制 (瓶限制器)
- 添加 认证 (OAuth2,智威汤逊)
- 使用 瑞迪斯 用于会话管理
- 部署在后面 Nginx 反向代理
- 监视器 普罗米修斯 + 格拉法纳
______________________________________________________________________
🐛 故障排除
常见问题
问题:“找不到GROQ_API_KEY”
# Solution: Check .env file exists and has correct format
cat .env
# Should show: GROQ_API_KEY=gsk_...问题:“MCP服务器没有响应”
# Solution: Ensure server is running
curl http://localhost:5000/health
# If not running, check for port conflicts
netstat -an | grep 5000 # Windows: netstat -an | findstr 5000问题:“找不到模块”
# Solution: Reinstall dependencies
pip install -r requirements.txt --force-reinstall问题:“SSE连接超时”
# Solution: Check firewall settings and ensure both servers are running
# Increase timeout in app.py if needed调试模式
启用详细日志记录:
# In app.py
import logging
logging.basicConfig(level=logging.DEBUG)
# In mcp_server_http.py
app.run(debug=True)______________________________________________________________________
🤝 贡献
欢迎投稿!请按照以下步骤操作:
- 分叉存储库
- 创建要素分支(
git checkout -b feature/AmazingFeature) - 提交您的更改(
git commit -m 'Add AmazingFeature') - 推送到分支(
git push origin feature/AmazingFeature) - 打开拉取请求
编码标准
- 遵循PEP 8风格指南
- 将文档字符串添加到所有函数中
- 为新功能编写单元测试
- 更新README.md以获取重大更改
______________________________________________________________________
📄 许可证
此项目根据MIT许可证获得许可-请参阅 许可证 文件以获取详细信息。
______________________________________________________________________
🙏 致谢
- Anthropic -模型上下文协议规范
- Groq -免费访问Llama 3.3 70B API
- 瑟珀 -网络搜索API
- wttr.in -气象数据服务
- LangChain -LangGraph工作流框架
______________________________________________________________________
📞 联系
你的名字 - @你的推特 - your.email@example.com
项目链接: https://github.com/yourusername/mcp-agent
______________________________________________________________________
🗺️ 路线图
- \[\]添加对话历史/记忆
- \[\]实现用户身份验证
- \[\]添加更多工具(计算器、翻译器等)
- \[\]创建移动应用程序(React Native)
- \[\]添加语音输入/输出
- \[\]多语言支持
- \[\]Webhook集成(Slack、Discord)
- \[\]分析仪表板
- \[\]A/B测试框架
- \[\]企业自助托管指南
______________________________________________________________________
建于❤️ 使用MCP、Groq和现代Python
