代理人带回家作业
谷歌ADK+MCP集成挑战赛
  
谷歌代理开发工具包(ADK)的生产就绪实现与自定义模型上下文协议(MCP)服务器集成,展示了智能工具编排和API集成。
______________________________________________________________________
📋 目录
______________________________________________________________________
🎯 概述
该项目展示了ADK-MCP的完整集成,其中:
- MCP服务器A. 基于FastMCP 服务器公开3个生产就绪的MCP工具
- ADK代理:一个使用谷歌Gemini模型编排FastMCP工具的智能代理
- 真实世界API:与GitHub、OpenWeather和NewsAPI集成
什么是ADK?
Google的Agent Development Kit(ADK)为构建AI代理提供了一个框架,可以:
- 执行复杂的多步骤任务
- 使用外部工具和API
- 生成类人、情境感知的响应
什么是MCP?
模型上下文协议(MCP)是一种标准化的方法,用于:
- 将工具/功能暴露给AI模型
- 实现一致的工具发现和执行
- 促进代理与工具之间的沟通
什么是FastMCP?
FastMCP是一个Python库,用于轻松构建MCP服务器:
- 提供
@mcp.tool()工具注册装饰器 - 自动处理MCP协议通信
- 支持stdio和HTTP传输
- 使MCP服务器开发简单且Python化
______________________________________________________________________
🏗️ 建筑
┌─────────────────────────────────────────────────────────────┐
│ ADK Agent │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Google Gemini (gemini-pro) │ │
│ │ - Natural language understanding │ │
│ │ - Response generation │ │
│ │ - Context synthesis │ │
│ └─────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ MCP Client (HTTP) │ │
│ │ - Tool discovery │ │
│ │ - Request formatting │ │
│ │ - Response parsing │ │
│ └─────────────────────────────────────────────────────┘ │
└──────────────────────────┬──────────────────────────────────┘
│ HTTP/REST
▼
┌─────────────────────────────────────────────────────────────┐
│ MCP Server (FastAPI) │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ Weather │ │ GitHub │ │ News │ │
│ │ Tool │ │ Trends │ │ Tool │ │
│ │ │ │ Tool │ │ │ │
│ └──────┬───────┘ └──────┬───────┘ └──────┬───────┘ │
│ │ │ │ │
└─────────┼─────────────────┼──────────────────┼──────────────┘
│ │ │
▼ ▼ ▼
┌────────────┐ ┌────────────┐ ┌────────────┐
│ OpenWeather│ │ GitHub │ │ NewsAPI │
│ API │ │ API │ │ │
└────────────┘ └────────────┘ └────────────┘______________________________________________________________________
✨ 特性
MCP服务器(mcp_server.py)
✅ 3生产准备工具:
- 天气工具 -获取任何城市的实时天气数据
- GitHub趋势工具 -按语言获取趋势存储库
- 新闻工具 -通过可选搜索检索头条新闻
✅ 企业功能:
- 带有时间戳的全面日志记录
- 结构化错误处理
- 使用Pydantic进行请求/响应验证
- 健康检查端点
- 缺少API密钥的模拟数据回退
- 全程键入提示
- API限速意识
ADK代理(adk_agent.py)
✅ 智能任务执行:
- 天气任务:获取天气+人工智能见解
- 趋势任务:获取趋势仓库+AI分析
- 新闻任务:获取头条新闻+人工智能摘要
- 完整任务:综合所有工具的综合报告
✅ 高性能:
- 自然语言响应生成
- 使用Gemini的上下文感知AI见解
- 优雅的降级(使用/不使用Google API密钥)
- 灵活的CLI界面
- 格式丰富的输出
- 错误恢复和重试逻辑
______________________________________________________________________
🔧 先决条件
- python:3.10或更高
- 紫外线:Python包安装程序(安装uv)
- API密钥 (用户提供):
- GitHub个人访问令牌 - OpenWeather API密钥 - Google Gemini API密钥(用于人工智能功能) - NewsAPI密钥(可选-如果缺少,则使用模拟数据)
______________________________________________________________________
📦 安装
1.克隆或导航到项目目录
cd agenticorch-assignment2.初始化UV环境
# Initialize uv project
uv init
# Install dependencies
uv pip install -r requirements.txt3.替代方案:使用标准pip
# Option 1: Using uv (Recommended - faster)
uv venv
source .venv/bin/activate # On macOS/Linux
uv pip install -r requirements.txt
# Option 2: Using standard pip
python3 -m venv venv
source venv/bin/activate # On macOS/Linux
# or
venv\Scripts\activate # On Windows
pip install -r requirements.txt______________________________________________________________________
⚙️ 配置
设置环境变量
创建一个 .env 文件或导出变量:
# Required: GitHub API
export GITHUB_TOKEN="your_github_personal_access_token"
# Required: OpenWeather API
export OPENWEATHER_API_KEY="your_openweather_api_key"
# Required: Google Gemini API (for AI features)
export GOOGLE_API_KEY="your_google_api_key_here"
# Optional: NewsAPI (uses mock data if not provided)
export NEWS_API_KEY="your_news_api_key_here"API关键来源
- GitHub代币: https://github.com/settings/tokens
- OpenWeather密钥: https://openweathermap.org/api
- Google API密钥: https://makersuite.google.com/app/apikey
- 新闻API密钥: https://newsapi.org/register
______________________________________________________________________
🚀 用法
步骤1:(可选)直接测试MCP服务器
FastMCP服务器可以独立运行,但ADK代理可以直接导入工具:
# Optional: Run FastMCP server standalone
python3 mcp_server.py
# Or just run the agent (it imports MCP tools directly)
python3 adk_agent.py --task info备注:使用FastMCP,代理可以直接导入和调用工具,而无需运行服务器!
步骤2:运行ADK代理
在另一个终端窗口中:
天气任务
python adk_agent.py --task weather --city Delhi输出示例:
🔍 Checking MCP server health...
✅ MCP server is healthy
🌤️ Weather in Delhi, IN:
Temperature: 28.5°C (feels like 29.0°C)
Conditions: Haze
Humidity: 62%
Wind Speed: 2.5 m/s
💡 AI Insight: The weather in Delhi is warm with hazy conditions.
It's a good idea to wear light, breathable clothing and consider
wearing a mask if you're sensitive to air quality. Perfect weather
for indoor activities or early morning/evening walks.GitHub趋势任务
python adk_agent.py --task trends --lang python --count 3输出示例:
⭐ Top 3 Trending Python Repositories:
1. tensorflow/tensorflow
⭐ 185,234 stars | 🍴 74,123 forks
📝 An Open Source Machine Learning Framework for Everyone
🔗 https://github.com/tensorflow/tensorflow
2. django/django
⭐ 78,456 stars | 🍴 31,234 forks
📝 The Web framework for perfectionists with deadlines
🔗 https://github.com/django/django
3. pallets/flask
⭐ 66,789 stars | 🍴 16,234 forks
📝 The Python micro framework for building web applications
🔗 https://github.com/pallets/flask
💡 AI Insight: TensorFlow continues to dominate as the top Python
repository, reflecting the ongoing growth in machine learning and
AI development. Developers can learn about production-ready ML
pipelines, distributed training, and model deployment strategies.新闻任务
python adk_agent.py --task news --count 3完整的综合报告
python adk_agent.py --task full --lang javascript --city London输出示例:
================================================================================
📊 COMPREHENSIVE REPORT - 2025-11-07 14:30:45
================================================================================
🌤️ Weather in London, GB:
Temperature: 12.5°C (feels like 11.0°C)
Conditions: Light Rain
Humidity: 78%
Wind Speed: 4.2 m/s
--------------------------------------------------------------------------------
⭐ Top 3 Trending JavaScript Repositories:
1. facebook/react
⭐ 223,456 stars | 🍴 45,678 forks
📝 A declarative, efficient, and flexible JavaScript library
🔗 https://github.com/facebook/react
2. vuejs/vue
⭐ 207,123 stars | 🍴 33,456 forks
📝 Progressive JavaScript Framework
🔗 https://github.com/vuejs/vue
3. vercel/next.js
⭐ 123,456 stars | 🍴 26,789 forks
📝 The React Framework for Production
🔗 https://github.com/vercel/next.js
--------------------------------------------------------------------------------
📰 Top 3 News Headlines:
1. Major Breakthrough in AI Research Announced
Source: TechNews Daily
Scientists unveil new neural architecture achieving unprecedented...
🔗 https://example.com/news/1
2. Global Climate Summit Reaches Historic Agreement
Source: World News Network
Nations commit to ambitious carbon reduction targets...
🔗 https://example.com/news/2
3. Tech Giants Announce Quantum Computing Partnership
Source: Innovation Today
Collaboration aims to accelerate quantum computing accessibility...
🔗 https://example.com/news/3
--------------------------------------------------------------------------------
🤖 AI-Powered Insights:
Interesting correlation: While London experiences rainy weather perfect
for indoor coding sessions, the JavaScript ecosystem shows strong growth
with React and Next.js leading the trends. Meanwhile, global news
highlights major AI breakthroughs, which aligns with the trending
machine learning repositories. It's an exciting time for developers
working at the intersection of web and AI technologies.
================================================================================CLI选项
python adk_agent.py [OPTIONS]
Options:
--task {weather,trends,news,full} Task to execute (required)
--city TEXT City name for weather (default: Delhi)
--lang TEXT Programming language (default: python)
--count INT Number of items to fetch (default: 5)
--mcp-url TEXT MCP server URL (default: http://localhost:8001)
--no-ai Disable AI insights (works without Google API key)
-h, --help Show help message______________________________________________________________________
📚 API文档
MCP服务器端点
服务器运行后,请访问:
- 交互式文档: http://localhost:8001/docs
- 备选文档: http://localhost:8001/redoc
端点详细信息
1.天气工具
POST http://localhost:8001/tool/get_weather
Content-Type: application/json
{
"city": "Delhi"
}答复:
{
"success": true,
"data": {
"city": "Delhi",
"country": "IN",
"temperature": 28.5,
"feels_like": 29.0,
"description": "haze",
"humidity": 62,
"wind_speed": 2.5,
"pressure": 1012,
"mock": false
},
"error": null,
"timestamp": "2025-11-07T14:30:45.123456"
}2.GitHub趋势工具
POST http://localhost:8001/tool/github_trends
Content-Type: application/json
{
"language": "python",
"count": 3
}答复:
{
"success": true,
"data": [
{
"name": "tensorflow",
"full_name": "tensorflow/tensorflow",
"description": "An Open Source Machine Learning Framework for Everyone",
"stars": 185234,
"forks": 74123,
"language": "Python",
"url": "https://github.com/tensorflow/tensorflow",
"owner": "tensorflow",
"created_at": "2015-11-07T01:19:20Z",
"updated_at": "2025-11-07T10:15:30Z",
"mock": false
}
],
"error": null,
"timestamp": "2025-11-07T14:30:45.123456"
}3.新闻工具
POST http://localhost:8001/tool/get_news
Content-Type: application/json
{
"count": 3,
"query": null
}答复:
{
"success": true,
"data": [
{
"title": "Major Breakthrough in AI Research",
"description": "Scientists unveil new architecture...",
"source": "TechNews Daily",
"author": "John Doe",
"published_at": "2025-11-07T12:00:00Z",
"url": "https://example.com/news/1",
"mock": false
}
],
"error": null,
"timestamp": "2025-11-07T14:30:45.123456"
}健康检查
GET http://localhost:8001/health答复:
{
"status": "healthy",
"timestamp": "2025-11-07T14:30:45.123456",
"api_keys_configured": {
"github": true,
"openweather": true,
"news": false
}
}______________________________________________________________________
🧪 测试
手动测试脚本
创建 test_all.sh:
#!/bin/bash
echo "🧪 Testing MCP Server + ADK Agent"
echo "=================================="
# Test 1: Server Health
echo -e "\n1️⃣ Testing server health..."
curl -s http://localhost:8001/health | python -m json.tool
# Test 2: Weather Tool
echo -e "\n2️⃣ Testing weather tool..."
curl -s -X POST http://localhost:8001/tool/get_weather \
-H "Content-Type: application/json" \
-d '{"city": "Delhi"}' | python -m json.tool
# Test 3: GitHub Trends Tool
echo -e "\n3️⃣ Testing GitHub trends tool..."
curl -s -X POST http://localhost:8001/tool/github_trends \
-H "Content-Type: application/json" \
-d '{"language": "python", "count": 3}' | python -m json.tool
# Test 4: News Tool
echo -e "\n4️⃣ Testing news tool..."
curl -s -X POST http://localhost:8001/tool/get_news \
-H "Content-Type: application/json" \
-d '{"count": 3}' | python -m json.tool
# Test 5: ADK Agent Weather
echo -e "\n5️⃣ Testing ADK agent (weather)..."
python adk_agent.py --task weather --city "San Francisco"
# Test 6: ADK Agent Trends
echo -e "\n6️⃣ Testing ADK agent (trends)..."
python adk_agent.py --task trends --lang javascript --count 3
# Test 7: ADK Agent Full
echo -e "\n7️⃣ Testing ADK agent (full report)..."
python adk_agent.py --task full --lang python --city Tokyo
echo -e "\n✅ All tests completed!"运行测试:
chmod +x test_all.sh
./test_all.sh在没有API密钥的情况下进行测试
系统通过使用模拟数据来优雅地处理丢失的API键:
# Test with mock data (unset API keys)
unset GITHUB_TOKEN
unset OPENWEATHER_API_KEY
unset NEWS_API_KEY
# Start server - will use mock data
uvicorn mcp_server:app --reload --port 8001
# Run agent - will still work
python adk_agent.py --task full --lang python --city Delhi --no-ai______________________________________________________________________
📁 项目结构
agenticorch-assignment/
├── mcp_server.py # MCP server with 3 tools (500+ lines)
│ ├── FastAPI application
│ ├── Weather tool (OpenWeather API)
│ ├── GitHub trends tool (GitHub API)
│ ├── News tool (NewsAPI)
│ ├── Pydantic models for validation
│ ├── Error handling & logging
│ └── Mock data fallback
│
├── adk_agent.py # ADK agent implementation (600+ lines)
│ ├── MCPClient class
│ ├── ADKAgent class with Gemini integration
│ ├── Task execution methods
│ ├── Response formatting
│ ├── CLI argument parser
│ └── AI-powered insights
│
├── requirements.txt # Python dependencies
│ ├── fastapi
│ ├── uvicorn
│ ├── requests
│ ├── google-generativeai
│ └── pydantic
│
└── README.md # This file (comprehensive documentation)______________________________________________________________________
🧠 关键学习和设计决策
1. MCP协议理解
模型上下文协议为AI代理发现和使用工具提供了一种标准化的方法。关键见解:
- 标准化接口:所有工具都公开一致的请求/响应格式
- 类型安全:Pydantic模型确保有效的输入/输出
- 可发现性:工具通过FastAPI自动生成的文档进行自我记录
- 可扩展性:无需更改代理代码即可添加新工具
2. ADK集成
谷歌的ADK擅长:
- 自然语言理解:Gemini解释用户意图
- 上下文管理:保持对话状态和上下文
- 响应生成:从结构化数据中创建人性化的输出
- 工具编排:智能地决定何时使用哪些工具
3. 体系结构决策
为什么选择MCP服务器的FastAPI?
- 自动生成的OpenAPI文档
- 原生异步支持
- 使用Pydantic进行类型验证
- 生产就绪性能
为什么要分离服务器/代理?
- 模块化:MCP服务器可以为多个代理提供服务
- 可扩展性:服务器和代理可以独立扩展
- 发展:可以在不运行代理的情况下测试工具
- 部署:每个组件的部署策略不同
为什么选择HTTP over gRPC?
- 使用curl/Postman进行更简单的调试
- Swagger UI提供更好的文档
- 更容易穿越防火墙
- 开发人员更容易访问
4. 错误处理策略
实施了全面的错误处理:
- API故障:具有指数回退的重试逻辑(隐含在请求中)
- 丢失钥匙:对模拟数据的优雅降级
- 网络问题:超时配置和清除错误消息
- 验证错误:Pydantic在API调用之前捕获错误的输入
5. 模拟数据设计
模拟数据有多种用途:
- 发展:在没有API密钥的情况下工作
- 测试:一致的测试数据
- 德莫斯:显示无速率限制的功能
- 韧性:即使API关闭,系统也能正常工作
6. 测井原理
各级结构化日志记录:
- 信息:正常操作(工具调用、响应)
- 错误:故障和异常
- 调试:详细的执行流程(可启用)
- 所有日志上用于调试的时间戳
7. AI集成模式
Gemini用于:
- 情境洞察:基于天气的建议
- 趋势分析:为什么回购正在流行
- 新闻摘要:头条新闻中的关键主题
- 跨域合成:连接天气+代码+新闻
______________________________________________________________________
🔍 ADK-MCP连接的工作原理
流程图
User Input → ADK Agent → MCP Client → HTTP Request → MCP Server → External API
↑ ↓
↑ ↓
↑ API Response
↑ ↓
↑ Format & Validate
↑ ↓
↑_______← HTTP Response ←______________ Return
(JSON)逐步执行
- 用户问题命令
python adk_agent.py --task weather --city Delhi- Agent解析意图
- ADKAgent标识任务类型 - 提取参数(城市=德里)
- MCP客户端准备请求
mcp_client.get_weather("Delhi")
# Becomes:
POST http://localhost:8001/tool/get_weather
{"city": "Delhi"}- MCP服务器接收请求
- FastAPI使用Pydantic验证请求 - 通往合适工具搬运员的路线 - fetch_weather_data("Delhi") 被称为
- 外部API调用
requests.get(
"http://api.openweathermap.org/data/2.5/weather",
params={"q": "Delhi", "appid": OPENWEATHER_API_KEY}
)- 响应处理
- MCP服务器格式化API响应 - 返回标准化JSON - 包括成功/错误状态
- 人类代理格式
- ADKAgent接收结构化数据 - 带有表情符号和格式的格式 - 可选择通过Gemini添加人工智能见解
- 用户看到最终输出
🌤️ Weather in Delhi, IN:
Temperature: 28.5°C
...______________________________________________________________________
🐛 故障排除
常见问题
1.MCP服务器无法启动
错误: Address already in use
解决方案:
# Find process using port 8001
lsof -ti:8001 | xargs kill -9
# Or use a different port
uvicorn mcp_server:app --port 8002
python adk_agent.py --mcp-url http://localhost:8002 --task weather --city Delhi2.API密钥错误
错误: 401 Unauthorized
解决方案:
# Verify keys are set
echo $GITHUB_TOKEN
echo $OPENWEATHER_API_KEY
# Re-export if empty
export GITHUB_TOKEN="your_token_here"3.导入错误
错误: ModuleNotFoundError: No module named 'fastapi'
解决方案:
# Reinstall dependencies
pip install -r requirements.txt
# Or use uv
uv pip install -r requirements.txt4.Google API密钥丢失
错误: Agent will work in basic mode
解决方案:
# Get API key from: https://makersuite.google.com/app/apikey
export GOOGLE_API_KEY="your_key_here"
# Or run without AI features
python adk_agent.py --task weather --city Delhi --no-ai5.连接被拒绝
错误: Connection refused to localhost:8001
解决方案:
# 1. Check if server is running
curl http://localhost:8001/health
# 2. If not, start server
uvicorn mcp_server:app --reload --port 8001
# 3. Wait for startup message
# "Uvicorn running on http://0.0.0.0:8001"调试提示
启用调试日志记录:
# In mcp_server.py or adk_agent.py
logging.basicConfig(level=logging.DEBUG)测试单个组件:
# Test server only
curl -X POST http://localhost:8001/tool/get_weather \
-H "Content-Type: application/json" \
-d '{"city": "Delhi"}'
# Test agent with mock server
python adk_agent.py --task weather --city Delhi --no-ai检查日志:
# Server logs show all requests
# Agent logs show all tool calls
# Look for ERROR level messages______________________________________________________________________
📊 性能注意事项
- API费率限制:
- GitHub:5000个请求/小时(已验证) - OpenWeather:60个请求/分钟(免费层) - NewsAPI:100个请求/天(开发者层)
- 超时:所有API调用都有10-15秒的超时
- 缓存:考虑为重复查询添加Redis(未来增强)
- 异步操作:FastAPI支持异步以提高并发性
______________________________________________________________________
🚀 未来的增强功能
- 缓存层:为频繁请求的数据添加Redis
- 速率限制:在MCP服务器上实施适当的速率限制
- 认证:添加MCP服务器的API密钥身份验证
- 监控:普罗米修斯指标和Grafana仪表板
- 数据库:存储工具调用历史和结果
- 更多工具:股票价格、加密货币、地图等。
- 批量操作:一次通话支持多个城市/语言
- WebSocket支持:长时间运行的任务的实时更新
- 码头工人:容器化,便于部署
- CI/CD:GitHub自动化测试操作
______________________________________________________________________
📝 测试结果总结
✅ 成功的测试用例
- 天气工具
- ✅ 有效城市(德里、伦敦、东京) - ✅ 有空间的城市(旧金山) - ✅ 非英语城市名称(慕尼黑) - ✅ 当API密钥丢失时模拟数据
- GitHub趋势工具
- ✅ 流行语言(Python、JavaScript、Java) - ✅ 小众语言(Rust、Go、TypeScript) - ✅ 各种计数参数(1-20) - ✅ 模拟数据回退
- 新闻工具
- ✅ 无疑问的头条新闻 - ✅ 通过查询搜索新闻 - ✅ 各种计数参数 - ✅ 密钥丢失时模拟数据
- ADK代理任务
- ✅ 个人任务(天气、趋势、新闻) - ✅ 完整的综合报告 - ✅ AI洞察生成 - ✅ 没有Google API密钥的操作
- 错误处理
- ✅ 城市名称无效 - ✅ 服务器未运行 - ✅ 网络超时 - ✅ API密钥无效
______________________________________________________________________
👨💻 作者
阿曼·库马尔
- 项目:代理人带回家作业
- 日期:2025年11月
- 技术:Python、FastAPI、谷歌ADK、MCP
______________________________________________________________________
📄 许可证
本项目按原样提供,用于代理Orch带回家的任务。
______________________________________________________________________
🙏 致谢
- Google代理开发工具包和Gemini API
- 优秀web框架的FastAPI
- OpenWeather、GitHub和NewsAPI用于公共API
- 开源社区激发灵感
______________________________________________________________________
📞 支持
如有疑问或问题:
- 检查 故障排除 章节
- 查看服务器日志中的错误消息
- 验证是否正确设置了所有API密钥
- 独立测试每个组件
______________________________________________________________________
快乐编码! 🚀
