天气服务MCP服务器

一个基于Model Context Protocol (MCP)的生产级天气服务服务器,提供实时天气和预报功能,支持Docker容器化和Traefik集成。

  • by Yuval-Moag
  • JavaScript
  • 本地部署
  • 更新于
在 GitHub 查看 Yuval-Moag/mcp-weather-server

使用说明

MCP气象服务器-概念验证

模型上下文协议(MCP)服务器的生产就绪实现,使用 可流式HTTP传输这既是一个工作示例,也是构建额外MCP服务的模板。

🎯 这表明了什么

  • ✅ 可流式HTTP传输 -MCP官方传输协议
  • ✅ 外部API集成 -以真实天气API集成为例
  • ✅ Docker容器化 -生产就绪容器设置
  • ✅ 健康检查 -监控和API连接验证
  • ✅ Traefik集成 -自动SSL和子域路由
  • ✅ 模块化设计 -快速MCP部署的模板结构

📋 特性

MCP能力

  • 工具:两个与天气相关的工具,演示工具注册和执行
  • 可流式传输的HTTP:兼容Open WebUI和未来的LLM平台
  • 服务发现: /mcp/v1/capabilities 工具发现端点

已实施的工具

  1. get_weather:获取任何位置的当前天气
  2. 获取预测:获取三天天气预报

端点

GET  /health                    - Health check and API connectivity
GET  /mcp/v1/capabilities       - MCP service capabilities and tools
POST /mcp/v1/execute            - Execute MCP tool requests

🚀 快速开始

先决条件

  • Node.js 20+
  • Docker&Docker编写
  • WeatherAPI.com API密钥(免费层:https://www.weatherapi.com/signup.aspx)

本地开发

  1. 克隆并安装
cd mcp-poc
npm install
  1. 配置环境
cp .env.example .env
# Edit .env and add your WEATHER_API_KEY
  1. 运行开发服务器
npm run dev
  1. 测试服务器
# Health check
curl http://localhost:3001/health

# Get capabilities
curl http://localhost:3001/mcp/v1/capabilities

# Execute a tool
curl -X POST http://localhost:3001/mcp/v1/execute \
  -H "Content-Type: application/json" \
  -d '{
    "method": "tools/call",
    "params": {
      "name": "get_weather",
      "arguments": {
        "location": "London"
      }
    }
  }'

🐳 Docker部署

构建和运行单个容器

# Build image
docker build -t mcp-weather-server .

# Run container
docker run -p 3001:3001 \
  -e WEATHER_API_KEY=your_key_here \
  -e SERVICE_NAME=weather-mcp \
  mcp-weather-server

全栈Traefik

# Start complete infrastructure
docker-compose up -d

# View logs
docker-compose logs -f mcp-weather

# Check health
curl http://localhost/health

# Stop services
docker-compose down

使用SSL进行生产部署

对于使用自定义域的生产:

  1. 更新docker-compose.yml:
# Replace weather.yourdomain.com with your actual domain
- "traefik.http.routers.weather.rule=Host(`weather.yourdomain.com`)"
  1. 配置DNS:
A Record: weather.yourdomain.com → Your Server IP
  1. 部署:
docker-compose up -d

Traefik会自动设置Let’s Encrypt SSL证书。访问地址:

  • https://weather.yourdomain.com/health
  • https://weather.yourdomain.com/mcp/v1/capabilities

📁 项目结构

mcp-poc/
├── src/
│   └── server.ts              # Main MCP server implementation
├── package.json               # Dependencies and scripts
├── tsconfig.json              # TypeScript configuration
├── Dockerfile                 # Production container image
├── docker-compose.yml         # Multi-service orchestration
├── .env.example               # Environment variables template
└── README.md                  # This file

🔧 配置

环境变量

变量 描述 必填
PORT HTTP服务器端口 否(默认值:3001)
SERVICE_NAME MCP服务标识符 否(默认:天气MCP)
WEATHER_API_KEY WeatherAPI.com API密钥 是
USE_STDIO 启用stdio传输 否(默认值:false)

API密钥设置

获取免费的WeatherAPI密钥:

  1. 注册地址:https://www.weatherapi.com/signup.aspx
  2. 复制API密钥
  3. 增添 .env 文件: WEATHER_API_KEY=your_key_here

🧪 测试MCP协议

使用curl

# List available tools
curl -X POST http://localhost:3001/mcp/v1/execute \
  -H "Content-Type: application/json" \
  -d '{"method": "tools/list"}'

# Call get_weather tool
curl -X POST http://localhost:3001/mcp/v1/execute \
  -H "Content-Type: application/json" \
  -d '{
    "method": "tools/call",
    "params": {
      "name": "get_weather",
      "arguments": {"location": "New York"}
    }
  }'

# Call get_forecast tool
curl -X POST http://localhost:3001/mcp/v1/execute \
  -H "Content-Type: application/json" \
  -d '{
    "method": "tools/call",
    "params": {
      "name": "get_forecast",
      "arguments": {"location": "Tokyo", "days": 3}
    }
  }'

预期响应格式

{
  "content": [
    {
      "type": "text",
      "text": "{\"location\":\"London\",\"temperature_c\":15.2,...}"
    }
  ]
}

🔌 集成示例

使用开放式WebUI

  1. 在Open WebUI中配置MCP服务器:
{
  "name": "Weather MCP",
  "url": "https://weather.yourdomain.com",
  "transport": "streamable-http"
}
  1. Open WebUI将通过以下方式自动发现可用工具 /mcp/v1/capabilities

使用自定义MCP客户端

import { Client } from '@modelcontextprotocol/sdk/client/index.js';

const client = new Client({
  name: 'my-app',
  version: '1.0.0'
});

await client.connect({
  url: 'https://weather.yourdomain.com/mcp/v1/execute',
  transport: 'streamable-http'
});

const result = await client.callTool({
  name: 'get_weather',
  arguments: { location: 'Paris' }
});

📊 监控

健康检查响应

{
  "status": "healthy",
  "service": "weather-mcp",
  "api_connectivity": "ok",
  "uptime": 86400,
  "version": "1.0.0",
  "timestamp": "2024-11-19T10:30:00.000Z"
}

Docker健康检查

内置的Docker健康检查每30秒运行一次:

# Check container health
docker ps
# Look for "healthy" status

# View health check logs
docker inspect mcp-weather | grep -A 10 Health

🎓 如何扩展此模板

添加新工具

  1. 定义工具 在 ListToolsRequestSchema 处理程序:
{
  name: "search_news",
  description: "Search news articles",
  inputSchema: {
    type: "object",
    properties: {
      query: { type: "string" }
    }
  }
}
  1. 实施该工具 在 CallToolRequestSchema 处理程序:
case "search_news": {
  const news = await fetchNews(args.query);
  return {
    content: [{ type: "text", text: JSON.stringify(news) }]
  };
}
  1. 增加API集成功能:
async function fetchNews(query: string) {
  const response = await axios.get(NEWS_API_URL, {
    params: { q: query, apiKey: NEWS_API_KEY }
  });
  return response.data;
}

创建新的MCP服务

  1. 复制此模板:
cp -r mcp-poc mcp-semrush
cd mcp-semrush
  1. 更新配置:
# Update package.json name
# Update SERVICE_NAME in .env
# Replace API integration in src/server.ts
  1. 添加到docker-compose.yml:
mcp-semrush:
  build: ./mcp-semrush
  environment:
    - SEMRUSH_API_KEY=${SEMRUSH_API_KEY}
  labels:
    - "traefik.http.routers.semrush.rule=Host(`semrush.yourdomain.com`)"
  1. 部署:
docker-compose up -d mcp-semrush

🔒 安全最佳实践

  • ✅ 非root Docker用户
  • ✅ 最小容器图像(基于Alpine)
  • ✅ secrets的环境变量(从不commit.env)
  • ✅ 通过Traefik强制执行HTTPS
  • ✅ API超时和错误处理
  • ✅ 可靠性健康检查

生产秘密管理

对于生产,使用Docker secrets或外部秘密管理器:

services:
  mcp-weather:
    secrets:
      - weather_api_key
    environment:
      - WEATHER_API_KEY=/run/secrets/weather_api_key

secrets:
  weather_api_key:
    external: true

🚀 性能注意事项

  • 超时:所有API调用都有5秒超时
  • 错误处理:包含详细信息的优雅错误响应
  • 健康检查:在流量之前验证API连接
  • 容器资源:可以在docker-compose.yml中设置CPU/内存限制
deploy:
  resources:
    limits:
      cpus: '0.5'
      memory: 512M

📚 参考文献

🤝 贡献

这是一个概念验证模板。欢迎改进:

  • 其他运输实施
  • 更全面的例子
  • 更好的错误处理模式
  • 性能优化

📝 许可证

MIT许可证-您可以自由地将其用作您自己的MCP服务的模板。


作者:尤瓦尔·米兹拉奇
目的:概念验证MCP服务器,演示可流式HTTP传输和模块化微服务架构
日期2024年11月