🤖 MCP工具调用代理
一个具有自主工具选择和执行能力的生产就绪AI代理,使用模型上下文协议(MCP)架构构建。
   ](https://docker.com/) 
🎬 现场演示
快速演示命令:
"Search for latest AI news"→ 使用DuckDuckGo进行网络搜索"Calculate 15% of 280"→ 安全数学计算"What's the weather in London?"→ 实时天气数据- 上传PDF→ 智能文档摘要
"List files in current directory"→ 系统信息访问
📋 目录
🎯 项目概述
这 MCP工具调用代理 是一个生产就绪的人工智能系统,可以根据用户查询自主选择和执行工具。它遵循模型上下文协议(MCP)原则构建,为人工智能驱动的自动化和智能任务执行提供了坚实的基础。
什么是MCP/工具调用?
模型上下文协议(MCP) 是一种架构模式,使AI模型能够:
- 自动选择 针对特定任务的适当工具
- 执行工具 通过适当的参数验证
- 链式多工具 用于复杂的多步推理
- 提供结构化的响应 具有执行透明度
主要特点
✨ 自主工具选择 -LLM驱动的决策制定\ 🔧 6内置工具 -搜索、计算器、PDF、天气、RAG、系统\ 🔄 多步推理 -处理需要多种工具的复杂查询\ 🛡️ 安全与验证 -全面的输入验证和错误处理\ 🎨 现代用户界面 -干净、响应迅速的web界面\ 🐳 Docker就绪 -使用Docker Compose轻松部署\ 📊 综合录井 -详细的执行跟踪\ 🔌 可扩展架构 -易于添加新工具
🏗️ 建筑
┌─────────────────────────────────────────────────────────────┐
│ USER INTERFACE │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ Query Input │ │ PDF Upload │ │ Results View│ │
│ └─────────────┘ └─────────────┘ └─────────────┘ │
└─────────────────────────────────────────────────────────────┘
│
HTTP/REST API
│
┌─────────────────────────────────────────────────────────────┐
│ FASTAPI BACKEND │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ /agent │ │ /upload-pdf │ │ /tools │ │
│ │ /health │ │ /uploads │ │ /docs │ │
│ └─────────────┘ └─────────────┘ └─────────────┘ │
└─────────────────────────────────────────────────────────────┘
│
┌─────────────────────────────────────────────────────────────┐
│ MCP AGENT CORE │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ AGENT ORCHESTRATOR │ │
│ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ │
│ │ │Query Analysis│ │Multi-step │ │Answer │ │ │
│ │ │ │ │Execution │ │Generation │ │ │
│ │ └─────────────┘ └─────────────┘ └─────────────┘ │ │
│ └─────────────────────────────────────────────────────┘ │
│ │ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ LLM INTERFACE │ │
│ │ ┌─────────────┐ ┌─────────────┐ │ │
│ │ │Tool Selection│ │Answer Gen │ │ │
│ │ │(GPT/Fallback)│ │(GPT/Fallback)│ │ │
│ │ └─────────────┘ └─────────────┘ │ │
│ └─────────────────────────────────────────────────────┘ │
│ │ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ TOOL MANAGER │ │
│ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ │
│ │ │Tool Registry│ │Validation │ │Execution │ │ │
│ │ └─────────────┘ └─────────────┘ └─────────────┘ │ │
│ └─────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
│
┌─────────────────────────────────────────────────────────────┐
│ TOOL LAYER │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │Search Tool │ │Calculator │ │PDF Summarizer│ │
│ │DuckDuckGo │ │Safe Math │ │PyPDF2 + LLM │ │
│ └─────────────┘ └─────────────┘ └─────────────┘ │
│ │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │Weather Tool │ │ RAG Tool │ │System Tool │ │
│ │Open-Meteo │ │FAISS+Sentence│ │psutil + OS │ │
│ └─────────────┘ └─────────────┘ └─────────────┘ │
└─────────────────────────────────────────────────────────────┘🛠️ 工具和功能
🔍 1.搜索工具
- 提供者:DuckDuckGo API
- 能力:具有前5个结果的网络搜索
- 输入:搜索查询字符串
- 输出:标题、URL和片段
JSON工具调用示例:
{
"tool": "search_tool",
"arguments": {
"query": "latest artificial intelligence news",
"num_results": 5
}
}🧮 2.计算器工具
- 提供者:基于AST的Python安全评估
- 能力:算术、高等数学函数
- 输入:数学表达式
- 输出:具有格式的计算结果
JSON工具调用示例:
{
"tool": "calculator_tool",
"arguments": {
"expression": "sqrt(16) + 25% of 80",
"precision": 2
}
}📄 3.PDF摘要生成器工具
- 提供者:PyPDF2+OpenAI GPT
- 能力:文本提取和智能摘要
- 输入:PDF文件路径、摘要首选项
- 输出:摘要、要点、元数据
JSON工具调用示例:
{
"tool": "pdf_summarizer_tool",
"arguments": {
"file_path": "/uploads/document.pdf",
"summary_length": "medium",
"focus_area": "key findings"
}
}🌤️ 4.天气工具
- 提供者:Open-Meteo API(免费)
- 能力:当前天气和3天预报
- 输入:位置名称
- 输出:温度、湿度、条件、预报
JSON工具调用示例:
{
"tool": "weather_tool",
"arguments": {
"location": "London, UK",
"include_forecast": true,
"units": "celsius"
}
}🧠 5.RAG工具(检索增强生成)
- 提供者:FAISS+句子转换+OpenAI
- 能力:文档搜索和问答
- 输入:关于索引文档的问题
- 输出:检索上下文+生成答案
JSON工具调用示例:
{
"tool": "rag_tool",
"arguments": {
"question": "What are the main benefits of AI?",
"top_k": 3,
"generate_answer": true
}
}💻 6.系统工具
- 提供者:psutil+操作系统模块
- 能力:系统信息、文件操作、磁盘使用情况
- 输入:操作类型和路径
- 输出:系统指标、文件列表、元数据
JSON工具调用示例:
{
"tool": "system_tool",
"arguments": {
"operation": "list_directory",
"path": "/home/user/documents",
"include_hidden": false
}
}🚀 快速开始
先决条件
- Python 3.11+
- Docker(可选)
- OpenAI API密钥(可选-可用的回退模式)
1分钟设置
# Clone the repository
git clone https://github.com/yourusername/mcp-tool-calling-agent.git
cd mcp-tool-calling-agent
# Copy environment file
cp .env.example .env
# Edit .env with your OpenAI API key (optional)
# Run with Docker (recommended)
docker-compose up --build
# Or run locally
pip install -r backend/requirements.txt
cd backend
python main.py🎉 访问代理:: http://localhost:8000
📦 安装
选项1:Docker(推荐)
# Clone repository
git clone https://github.com/yourusername/mcp-tool-calling-agent.git
cd mcp-tool-calling-agent
# Start with Docker Compose
docker-compose up --build方案2:地方发展
# Clone repository
git clone https://github.com/yourusername/mcp-tool-calling-agent.git
cd mcp-tool-calling-agent
# Create virtual environment
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
# Install dependencies
pip install -r backend/requirements.txt
# Copy configuration
cp .env.example .env⚙️ 配置
环境变量
编辑 .env 使用您的配置文件:
# OpenAI Configuration (Optional)
OPENAI_API_KEY=your_openai_api_key_here
# Server Settings
HOST=0.0.0.0
PORT=8000
LOG_LEVEL=info
# Tool Configuration
SEARCH_TOOL_ENABLED=true
CALCULATOR_TOOL_ENABLED=true
PDF_SUMMARIZER_TOOL_ENABLED=true
WEATHER_TOOL_ENABLED=true
RAG_TOOL_ENABLED=true
SYSTEM_TOOL_ENABLED=true
# Agent Settings
MAX_RETRIES=3
RETRY_DELAY=1.0
AGENT_TIMEOUT=300没有OpenAI API密钥
代理人包括 智能回退逻辑 在没有OpenAI的情况下工作:
- 工具选择使用基于关键字的启发式方法
- 答案生成使用提取式摘要
- 所有核心功能仍然可用
🏃♂️ 运行代理
发展模式
cd backend
python main.py生产模式
# With Docker
docker-compose up -d
# Or with uvicorn
uvicorn main:app --host 0.0.0.0 --port 8000 --workers 4健康检查
curl http://localhost:8000/health📝 查询示例
单个工具示例
🔍 网络搜索:
"Search for the latest developments in artificial intelligence"🧮 计算:
"Calculate the compound interest on $1000 at 5% for 3 years"🌤️ 天气:
"What's the weather forecast for Tokyo this week?"📄 PDF分析:
"Summarize the main points from the uploaded research paper"💻 系统信息:
"Show me the files in my current directory"多步推理示例
复杂查询1:
"Search for recent AI news and then calculate what 15% of the current Bitcoin price would be"预期代理行为:
- 🔍 执行search_tool(“最近的AI新闻”)
- 🧮 执行计算器工具(“比特币价格\*0.15”)
- 🧠 生成两个结果的组合答案
复杂查询2:
"Summarize this PDF and then tell me the weather in the author's city"预期代理行为:
- 📄 执行pdf_summarizer_tool(上传文件)
- 🌤️ 执行weather_tool(提取城市)
- 🧠 将PDF摘要与天气信息相结合
错误处理示例
无效输入:
"Calculate the square root of negative one hundred"答复: 用建议的替代方案进行优雅的错误解释
网络问题:
"Search for something" (when API is down)答复: 重试尝试的回退行为
📚 API文档
核心终点
发布 /agent
使用MCP代理处理查询。
请求正文:
{
"query": "Your question here",
"context": {
"uploaded_file": "path/to/file.pdf"
}
}答复:
{
"query": "Your question here",
"final_answer": "Generated response...",
"tools_used": ["search_tool", "calculator_tool"],
"steps": [
"Retrieved available tools",
"Selected 2 tool(s): search_tool, calculator_tool",
"Executing search_tool with arguments: {...}",
"✓ search_tool completed successfully",
"✓ Query processing completed successfully"
],
"raw_outputs": [
{
"success": true,
"tool_name": "search_tool",
"results": [...],
"timestamp": "2024-12-02T10:30:00Z"
}
],
"execution_time_seconds": 2.45,
"success": true,
"timestamp": "2024-12-02T10:30:00Z"
}发布 /upload-pdf
上传PDF文件进行处理。
请求: 包含PDF文件的多部分表单数据
答复:
{
"success": true,
"filename": "20241202_103000_document.pdf",
"file_path": "/app/uploads/20241202_103000_document.pdf",
"size_bytes": 1048576,
"upload_time": "2024-12-02T10:30:00Z"
}获取 /tools
获取有关可用工具的信息。
答复:
{
"success": true,
"tools": [
{
"name": "search_tool",
"description": "Search the web using DuckDuckGo",
"input_schema": {...},
"output_schema": {...}
}
],
"statistics": {
"total_tools": 6,
"tool_names": ["search_tool", "calculator_tool", ...]
}
}获取 /health
健康检查端点。
答复:
{
"status": "healthy",
"timestamp": "2024-12-02T10:30:00Z",
"agent_info": {
"agent_status": "healthy",
"llm_available": true,
"tools_available": 6,
"tool_list": ["search_tool", "calculator_tool", ...]
}
}交互式API文档
- Swagger用户界面: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
🔧 发展
项目结构
mcp-tool-calling-agent/
├── backend/ # FastAPI backend
│ ├── main.py # FastAPI application
│ ├── agent.py # Core agent logic
│ ├── llm.py # LLM interface
│ ├── tool_manager.py # Tool management
│ ├── tools/ # Individual tools
│ │ ├── search_tool.py
│ │ ├── calculator_tool.py
│ │ ├── pdf_summarizer.py
│ │ ├── weather_tool.py
│ │ ├── rag_tool.py
│ │ └── system_tool.py
│ ├── tests/ # Test files
│ ├── utils/ # Utility functions
│ └── requirements.txt # Dependencies
├── frontend/ # Web UI
│ ├── index.html # Main page
│ ├── styles.css # Styling
│ └── app.js # JavaScript logic
├── diagrams/ # Architecture diagrams
├── uploads/ # Uploaded files storage
├── Dockerfile # Docker configuration
├── docker-compose.yml # Docker Compose setup
├── .env.example # Environment template
└── README.md # This file添加新工具
- 创建工具模块 (
backend/tools/my_tool.py):
class MyTool:
def __init__(self):
self.name = "my_tool"
self.description = "Description of what this tool does"
def get_schema(self):
return {
"name": self.name,
"description": self.description,
"input_schema": {...},
"output_schema": {...}
}
def execute(self, arguments):
# Tool implementation
return {
"success": True,
"result": "Tool output"
}
my_tool = MyTool()- 注册工具 (
backend/tool_manager.py):
from tools.my_tool import my_tool
def _register_tools(self):
available_tools = [
# ... existing tools
my_tool,
]- 更新LLM接口 (
backend/llm.py):
为新工具添加关键字检测和回退逻辑。
代码风格
# Format code
black backend/
# Lint code
flake8 backend/
# Type checking
mypy backend/🧪 测试
运行测试
# Install test dependencies
pip install pytest pytest-asyncio
# Run all tests
pytest backend/tests/
# Run with coverage
pytest --cov=backend backend/tests/测试结构
backend/tests/
├── test_agent.py # Agent core tests
├── test_tools.py # Individual tool tests
├── test_api.py # API endpoint tests
├── conftest.py # Test configuration
└── fixtures/ # Test data示例测试
import pytest
from agent import mcp_agent
@pytest.mark.asyncio
async def test_simple_query():
response = await mcp_agent.process_query("Calculate 2 + 2")
assert response["success"] is True
assert "calculator_tool" in response["tools_used"]
assert "4" in response["final_answer"]📊 监控
健康监测
# Check agent health
curl http://localhost:8000/health
# Monitor tool availability
curl http://localhost:8000/tools日志记录
日志的结构包括:
- 请求/响应详细信息
- 工具执行轨迹
- 带有堆栈跟踪的错误信息
- 性能指标
日志位置: logs/mcp_agent.log
日志格式:
2024-12-02 10:30:00 | INFO | Processing query: Calculate 2+2
2024-12-02 10:30:01 | INFO | Selected 1 tools: calculator_tool
2024-12-02 10:30:01 | INFO | Tool calculator_tool execution completed successfully
2024-12-02 10:30:02 | INFO | Query processed successfully in 1.23s性能指标
- 查询处理时间
- 工具执行持续时间
- 成功/失败率
- 资源使用情况(CPU、内存)
🚀 部署
Docker部署
# Production deployment
docker-compose --profile production up -d
# With custom environment
docker-compose --env-file .env.prod up -d云部署
AWS ECS
# Build and push to ECR
aws ecr get-login-password --region us-west-2 | docker login --username AWS --password-stdin .dkr.ecr.us-west-2.amazonaws.com
docker build -t mcp-agent .
docker tag mcp-agent:latest .dkr.ecr.us-west-2.amazonaws.com/mcp-agent:latest
docker push .dkr.ecr.us-west-2.amazonaws.com/mcp-agent:latest谷歌云运行
# Deploy to Cloud Run
gcloud run deploy mcp-agent \
--image gcr.io/$PROJECT_ID/mcp-agent \
--platform managed \
--region us-central1 \
--allow-unauthenticated环境特定配置
发展 (.env.dev):
DEBUG=true
LOG_LEVEL=debug
RELOAD=true生产 (.env.prod):
DEBUG=false
LOG_LEVEL=info
RELOAD=false
WORKERS=4🗺️ 路线图
第一阶段:核心增强✅
- \[x\] 多步工具推理
- \[x\] 全面的错误处理
- \[x\] Docker部署
- \[x\] 交互式web UI
第二阶段:高级功能🚧
- \[\]工具输出缓存
- \[\]自定义工具插件API
- \[\]流媒体响应
- \[\]身份验证和授权
- \[\]速率限制
第三阶段:企业特性📋
- \[\]多代理编排
- \[\]工作流自动化
- \[\]集成市场
- \[\]高级分析仪表板
- \[\]企业SSO
第四阶段:人工智能增强🔮
- \[\]从使用模式中学习工具
- \[\]自动创建工具
- \[\]高级推理能力
- \[\]多模态工具支持
🤝 贡献
我们欢迎捐款!以下是如何开始:
开发设置
# Fork and clone the repository
git clone https://github.com/yourusername/mcp-tool-calling-agent.git
cd mcp-tool-calling-agent
# Create a feature branch
git checkout -b feature/amazing-feature
# Make your changes and test
pytest backend/tests/
# Submit a pull request贡献指南
- 代码质量:遵循PEP 8,添加类型提示,编写测试
- 文档:更新README和文档字符串
- 测试:确保所有测试通过并添加新的测试
- 提交消息:使用常规提交格式
问题和功能请求
- 🐛 错误报告:使用错误报告模板
- ✨ 功能请求:使用功能请求模板
- 🤔 问题:使用GitHub讨论
______________________________________________________________________
📄 许可证
此项目根据MIT许可证获得许可-请参阅 许可证 文件以获取详细信息。
🙏 致谢
- 开放人工智能 -对于GPT模型和API
- 快速API -对于优秀的web框架
- 句子转换器 -用于嵌入模型
- FAISS -用于矢量搜索功能
- 开放天气 -免费天气API
______________________________________________________________________
📞 支持
- 文档:此自述文件和
/docs端点 - 社区:GitHub讨论
- 问题:GitHub问题
- 电子邮件: \[your-email@domain.com\]
______________________________________________________________________
⭐ 如果这个项目对你有帮助,请在GitHub上给它一颗星! ⭐
