使用说明
🚀 ZORA MCP服务
模型上下文协议服务 -独立的API服务,为ZORA AI聊天机器人提供天气、时间和所有者信息端点。
📋 概述
MCP Service是一个基于FastAPI的微服务,通过RESTful API为ZORA AI聊天机器人提供专用工具。使用 开放天气 (完全免费)天气数据,不需要API密钥。
特性
- ✅ 100%免费 -使用Open-Meteo(不需要API密钥)
- ✅ RESTful API -易于集成
- ✅ 实时天气 -30+越南城市
- ✅ 世界时间 -15+个国家/时区
- ✅ 自动文档 -包含Swagger用户界面
- ✅ 快速可靠 -平均响应时间<200ms
🌐 API终点
基础URL
http://localhost:8001
1.️⃣ 天气API
获取越南城市的当前天气。
端点:
GET /api/weather?city={city_name}
参数:
| 名称 | 类型 | 必填 | 描述 |
|---|---|---|---|
| city | string | Yes | 城市名称(例如,河内、胡志明、岘港) |
请求示例:
curl "http://localhost:8001/api/weather?city=Hanoi"
示例响应:
{
"success": true,
"city": "Hanoi",
"temperature": 28.5,
"description": "Trời quang đãng",
"humidity": 65,
"wind_speed": 12.5,
"weather_code": 0,
"emoji": "☀️"
}
支持城市(30+):
Hà Nội, TP HCM (Sài Gòn), Đà Nẵng, Huế, Nha Trang,
Cần Thơ, Hải Phòng, Vũng Tàu, Biên Hòa, Đà Lạt,
Quy Nhơn, Hạ Long, Vinh, Buôn Ma Thuột, Phan Thiết, ...
天气代码:
| 代码 | 描述 | 表情符号 |
|---|---|---|
| <0>天空晴朗>☀️ | ||
| 1-2部分是云。🌤️ | ||
| 3微米。☁️ | ||
| 45-48有雾🌫️ | ||
| 51-67雨🌧️ | ||
| 71-77下雪了❄️ | ||
| 80-82集雨🌧️ | ||
| 95-99风暴⛈️ |
2.️⃣ 时间API
获取任何国家的当前时间。
端点:
GET /api/time?country={country_name}
参数:
| 名称 | 类型 | 必填 | 描述 |
|---|---|---|---|
| country | string | Yes | 国家名称(例如越南、美国、日本) |
请求示例:
curl "http://localhost:8001/api/time?country=Vietnam"
示例响应:
{
"success": true,
"country": "Vietnam",
"timezone": "Asia/Ho_Chi_Minh",
"current_time": "14:30:45",
"date": "15/11/2025",
"timestamp": "2025-11-15T14:30:45+07:00"
}
支持的国家(15+):
Việt Nam, Mỹ (USA), Nhật Bản (Japan), Anh (UK),
Pháp (France), Đức (Germany), Singapore, Thái Lan (Thailand),
Hàn Quốc (South Korea), Úc (Australia), Canada,
Ấn Độ (India), Indonesia, Malaysia, Philippines
3.️⃣ 所有者信息API
获取有关ZORA AI创建者的信息。
端点:
GET /api/owner
参数: 无
请求示例:
curl "http://localhost:8001/api/owner"
示例响应:
{
"success": true,
"name": "Nguyễn Trung Thành (Jimmy Nguyen)",
"phone": "0432047700",
"email": "ng.trungthanh04@gmail.com",
"role": "AI Developer & Software Engineer",
"bio": "Tôi là Nguyễn Trung Thành, người sáng tạo ra ZORA AI...",
"skills": [
"Python",
"FastAPI",
"LangChain",
"Machine Learning",
"Natural Language Processing",
"RAG Systems",
"PostgreSQL",
"Docker",
"MCP Protocol"
]
}
4.️⃣ 工具元数据API
获取包含用于检测的关键字的可用工具列表。
端点:
GET /api/tools
参数: 无
请求示例:
curl "http://localhost:8001/api/tools"
示例响应:
{
"tools": [
{
"name": "get_weather",
"endpoint": "/api/weather",
"method": "GET",
"description": "Lấy thông tin thời tiết hiện tại của một thành phố ở Việt Nam",
"parameters": {
"city": {
"type": "string",
"required": true,
"description": "Tên thành phố (vd: Hanoi, Ho Chi Minh, Da Nang)"
}
},
"keywords": [
"thời tiết", "nhiệt độ", "nóng", "lạnh", "mưa", "nắng",
"weather", "temperature", "hot", "cold", "rain", "sunny"
],
"example": "GET /api/weather?city=Hanoi"
},
// ... more tools
],
"cities": ["Hanoi", "Ho Chi Minh City", "Da Nang", ...],
"countries": ["vietnam", "usa", "japan", ...]
}
5.️⃣ 健康检查
检查服务状态。
端点:
GET /health
示例响应:
{
"status": "healthy",
"timestamp": "2025-11-15T14:30:45.123456"
}
🚀 快速开始
安装
- 克隆或创建项目:
mkdir mcp-service
cd mcp-service
- 安装依赖项:
pip install fastapi uvicorn httpx pytz
-
创建
main.py带有MCP服务代码 -
运行服务:
python main.py
或者直接使用uvicorn:
uvicorn main:app --host 0.0.0.0 --port 8001 --reload
- 访问Swagger用户界面:
http://localhost:8001/docs
Docker部署
Dockerfile:
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY main.py .
EXPOSE 8001
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8001"]
构建并运行:
docker build -t zora-mcp-service .
docker run -p 8001:8001 zora-mcp-service
📊 演出
基准(来自越南):
Weather API:
├── Average latency: 180ms
├── Success rate: 99.9%
├── Rate limit: 10,000+ calls/day
└── Uptime: 99.9%+
Time API:
├── Average latency: <5ms
├── Success rate: 100%
├── Rate limit: Unlimited
└── Uptime: 100%
Owner Info API:
├── Average latency: <5ms
├── Success rate: 100%
├── Rate limit: Unlimited
└── Uptime: 100%
🔧 配置
环境变量
创建 .env 文件(可选):
# Service configuration
SERVICE_HOST=0.0.0.0
SERVICE_PORT=8001
# CORS settings (if needed)
ALLOWED_ORIGINS=http://localhost:3000,http://localhost:8000
自定义配置
编辑 main.py 自定义:
添加新城市:
VIETNAM_CITIES = {
"your_city": ("Your City Name", latitude, longitude),
# Example:
"phu quoc": ("Phu Quoc", 10.2291, 103.9673),
}
添加新国家:
COUNTRY_TIMEZONES = {
"your_country": "Continent/City",
# Example:
"brazil": "America/Sao_Paulo",
}
🧪 测试
手动测试
测试天气:
curl "http://localhost:8001/api/weather?city=Hanoi"
测试时间:
curl "http://localhost:8001/api/time?country=Vietnam"
测试所有者信息:
curl "http://localhost:8001/api/owner"
自动化测试
创建 test_mcp_service.py:
import httpx
import pytest
BASE_URL = "http://localhost:8001"
@pytest.mark.asyncio
async def test_weather_api():
async with httpx.AsyncClient() as client:
response = await client.get(f"{BASE_URL}/api/weather?city=Hanoi")
assert response.status_code == 200
data = response.json()
assert data["success"] == True
assert "temperature" in data
@pytest.mark.asyncio
async def test_time_api():
async with httpx.AsyncClient() as client:
response = await client.get(f"{BASE_URL}/api/time?country=Vietnam")
assert response.status_code == 200
data = response.json()
assert data["success"] == True
assert "current_time" in data
@pytest.mark.asyncio
async def test_owner_api():
async with httpx.AsyncClient() as client:
response = await client.get(f"{BASE_URL}/api/owner")
assert response.status_code == 200
data = response.json()
assert data["success"] == True
assert "name" in data
运行测试:
pytest test_mcp_service.py -v
🔐 安全
最佳实践
- 速率限制 (必要时添加):
from slowapi import Limiter
from slowapi.util import get_remote_address
limiter = Limiter(key_func=get_remote_address)
app.state.limiter = limiter
@app.get("/api/weather")
@limiter.limit("100/minute")
async def get_weather(request: Request, city: str):
# ...
- API密钥验证 (可选):
from fastapi import Header, HTTPException
async def verify_api_key(x_api_key: str = Header(...)):
if x_api_key != "your-secret-key":
raise HTTPException(status_code=401, detail="Invalid API key")
- CORS配置:
app.add_middleware(
CORSMiddleware,
allow_origins=["https://your-frontend.com"], # Specific domains only
allow_credentials=True,
allow_methods=["GET"],
allow_headers=["*"],
)
📈 监控
健康检查集成
正常运行时间监控:
*/5 * * * * curl -f http://localhost:8001/health || alert
普罗米修斯指标 (必要时添加):
from prometheus_fastapi_instrumentator import Instrumentator
Instrumentator().instrument(app).expose(app)
日志记录
import logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
@app.get("/api/weather")
async def get_weather(city: str):
logger.info(f"Weather request for city: {city}")
# ...
🐛 故障排除
常见问题
1.服务无法启动:
# Check if port 8001 is in use
lsof -i :8001
# Kill process if needed
kill -9 <PID>
2.天气API返回500:
- 检查互联网连接
- 验证Open-Meteo API状态:https://open-meteo.com
- 检查日志以了解详细错误
3.时间API返回错误的时区:
- 验证国家名称拼写
- 检查
COUNTRY_TIMEZONES映射 - 使用支持列表中的确切国家名称
4.CORS错误:
- 更新
allow_origins在CORS中间件中 - 检查浏览器控制台以了解详细错误
📚 API集成示例
python
import httpx
async def get_weather(city: str):
async with httpx.AsyncClient() as client:
response = await client.get(
"http://localhost:8001/api/weather",
params={"city": city}
)
return response.json()
# Usage
weather = await get_weather("Hanoi")
print(f"Temperature: {weather['temperature']}°C")
JavaScript/TypeScript
async function getWeather(city) {
const response = await fetch(
`http://localhost:8001/api/weather?city=${city}`
);
return await response.json();
}
// Usage
const weather = await getWeather('Hanoi');
console.log(`Temperature: ${weather.temperature}°C`);
卷曲
# Weather
curl "http://localhost:8001/api/weather?city=Hanoi"
# Time
curl "http://localhost:8001/api/time?country=Vietnam"
# Owner Info
curl "http://localhost:8001/api/owner"
🎯 用例
1.聊天机器人集成
# In your chatbot service
if "weather" in user_question:
city = extract_city(user_question)
weather = await mcp_client.get_weather(city)
return format_weather_response(weather)
2.多智能体系统
# Detect intent and call appropriate API
intents = agent_detector.detect(user_question)
for intent in intents:
if intent.type == "weather":
response = await mcp_client.get_weather(intent.params["city"])
3.语音助手
# Convert speech to text, call MCP, convert response to speech
text = speech_to_text(audio)
if "thời tiết" in text:
weather = await mcp_client.get_weather(extract_city(text))
audio_response = text_to_speech(format_weather(weather))
🤝 贡献
想添加更多功能吗?
思想:
- 货币汇率
- 新闻提要
- 股票价格
- 翻译服务
- 维基百科搜索
- 计算器/数学求解器
如何做出贡献:
- 分叉存储库
- 创建特征分支
- 添加您的端点
- 彻底测试
- 提交拉取请求
📞 支持
造物主: 饰Jimmy Nguyen
- 📧 电子邮件:ng.trungthanh04@gmail.com
- 📱 电话:0432047700
服务问题:
- 检查
/health端点 - 查看日志
- 验证Open Meteo状态
📜 许可证
MIT许可证-可在您的项目中免费使用!
🎉 更新日志
v1.0.0(2025-11-15)
- ✨ 初始版本
- ✅ 天气API(Open-Meteo)
- ✅ 时间API
- ✅ 所有者信息API
- ✅ 自动文档(Swagger)
- ✅ 健康检查端点
- ✅ 30+越南城市
- ✅ 15+个国家
由以下材料制成❤️ 通过Nguyễn张
由Open Meteo提供技术支持🌤️ (免费和开源)
