天气MCP服务器

一个基于Model Context Protocol (MCP)的天气信息服务器,通过OpenMeteo API提供实时天气数据和7天预报,支持自然语言查询并与Claude Desktop集成。

  • by 9meo
  • Shell
  • 本地部署
  • 1 星标
  • 更新于
在 GitHub 查看 9meo/mcp-server-tutorial

使用说明

气象MCP服务器

一种模型上下文协议(MCP)服务器,使用OpenMeteo API提供天气信息。该服务器与Claude Desktop集成,允许自然语言天气查询。

🌦️ 特性

  • 当前天气:获取具有坐标的任何位置的实时天气数据
  • 天气预报:7天天气预报,包括温度和降水数据
  • 城市搜索:主要城市(曼谷、东京、纽约等)的快速天气查询
  • MCP集成:与Claude Desktop和其他MCP客户端无缝集成
  • 错误处理:针对SSL、网络和API问题的强大错误处理
  • 多个传输:支持stdio、HTTP和SSE传输
  • 交叉平台的:适用于Windows、macOS、Linux和WSL

🚀 快速开始

选项1:自动设置

macOS:

curl -sSL https://raw.githubusercontent.com/9meo/mcp-server-tutorial/main/setup_mac.sh | bash

Linux/WSL:

curl -sSL https://raw.githubusercontent.com/9meo/mcp-server-tutorial/main/setup.sh | bash

窗户:

curl -sSL https://raw.githubusercontent.com/9meo/mcp-server-tutorial/main/setup.bat -o setup.bat && setup.bat

WSL(Linux的Windows子系统):

# Open WSL terminal and run:
curl -sSL https://raw.githubusercontent.com/9meo/mcp-server-tutorial/main/setup.sh | bash

选项2:手动设置

先决条件

  • Python 3.8或更高版本
  • 用于访问API的Internet连接
  • WSL用户:建议使用WSL 2

分步安装

  1. 安装UV包管理器

    Linux/MOSC/WSL:

    curl -LsSf https://astral.sh/uv/install.sh | sh
    source ~/.bashrc  # or restart terminal
    

    窗户:

    powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
    
  2. 创建项目目录

    mkdir weather-mcp && cd weather-mcp
    uv init --name weather-mcp
    
  3. 再进行

    uv add mcp httpx
    
  4. 下载服务器代码

    复制 weather_server.py 从该存储库中创建文件,或使用提供的代码手动创建。

  5. 试验装置

    # Test dependencies
    uv run python -c "import mcp, httpx; print('✅ Dependencies installed successfully')"
    
    # Test the server
    uv run python weather_server.py
    

WSL用户

WSL(Windows Linux子系统)完全受支持,建议Windows用户使用:

# 1. Open WSL terminal (Ubuntu/Debian recommended)
wsl

# 2. Update packages
sudo apt update && sudo apt install -y curl git

# 3. Follow Linux installation steps above
curl -LsSf https://astral.sh/uv/install.sh | sh

⚙️ 配置

Claude桌面设置

  1. 查找配置文件:

    • macOS: ~/Library/Application Support/Claude/claude_desktop_config.json
    • 视窗: %APPDATA%/Claude/claude_desktop_config.json
  2. 根据您的设置选择配置:

    标准安装(Linux/macOS/Windows):

    {
      "mcpServers": {
        "weather": {
          "command": "uv",
          "args": ["run", "--directory", "/absolute/path/to/weather-mcp", "python", "weather_server.py"],
          "env": {
            "SSL_VERIFY": "false"
          }
        }
      }
    }
    

    WSL配置(推荐给WSL用户):

    {
      "mcpServers": {
        "weather": {
          "command": "wsl",
          "args": ["-e", "bash", "-c", "cd /home/[USERNAME]/weather-mcp && uv run python weather_server.py"],
          "env": {
            "SSL_VERIFY": "false"
          }
        }
      }
    }
    

    WSL替代方案(使用Windows UNC路径):

    {
      "mcpServers": {
        "weather": {
          "command": "uv", 
          "args": ["run", "--directory", "\\\\wsl$\\Ubuntu\\home\\[USERNAME]\\weather-mcp", "python", "weather_server.py"],
          "env": {
            "SSL_VERIFY": "false"
          }
        }
      }
    }
    
  3. 重要提示:

    • 替换 /absolute/path/to/weather-mcp 使用您的实际项目路径
    • 替换 [USERNAME] 使用您的实际用户名
    • 使用正斜杠 / 对于Unix路径,反斜杠 \\ 对于Windows路径
    • 更改后重新启动Claude Desktop

获取项目路径

Linux/MOSC/WSL:

cd weather-mcp && pwd

窗户:

cd weather-mcp && echo %cd%

环境变量

  • SSL_VERIFY:设置为 "false" 禁用SSL验证(在使用代理服务器的公司环境中很有用)

🛠️ 可用工具

get_current_weather(latitude, longitude)

获取指定坐标的当前天气状况。

参数:

  • latitude (浮动):位置的纬度
  • longitude (浮动):位置的经度

例子:

await get_current_weather(13.7563, 100.5018)  # Bangkok

get_forecast(latitude, longitude)

获取指定坐标的7天天气预报。

参数:

  • latitude (浮动):位置的纬度
  • longitude (浮动):位置的经度

get_weather_by_city(city_name)

按城市名称获取当前天气(支持主要城市)。

参数:

  • city_name (str):城市名称

支持城市:

  • 曼谷、东京、纽约、伦敦、巴黎、新加坡、悉尼、洛杉矶

📚 资源

weather://popular-cities

返回受支持的热门城市及其坐标列表 get_weather_by_city 工具。

🔧 发展

项目结构

weather-mcp/
├── weather_server.py          # Main MCP server implementation
├── test_server.py             # Comprehensive test suite
├── pyproject.toml             # Project configuration and dependencies
├── Makefile                   # Development commands
├── Dockerfile                 # Container deployment
├── setup.sh                   # Linux/macOS setup script
├── setup.bat                  # Windows setup script
├── README.md                  # This documentation
├── QUICK_START.md             # Quick setup guide
├── .github/workflows/test.yml # CI/CD pipeline
├── .vscode/                   # VS Code configuration
│   ├── settings.json          # Editor settings
│   └── launch.json            # Debug configuration
├── .gitignore                 # Git ignore rules
└── .venv/                     # Virtual environment (created by UV)

开发命令

使用Make(Linux/MOSC/WSL):

# Install dependencies
make install

# Run tests
make test

# Start server
make run

# Format code
make format

# Run linting
make lint

# Run all checks
make check

# Start MCP Inspector
make inspector

# Quick development setup
make dev-install

直接使用UV:

# Install dependencies
uv sync

# Add development dependencies
uv add --dev pytest pytest-asyncio black isort mypy

# Run tests
uv run python test_server.py

# Start server
uv run python weather_server.py

# Format code
uv run black weather_server.py test_server.py
uv run isort weather_server.py test_server.py

# Type checking
uv run mypy weather_server.py test_server.py

运行测试

综合测试套件:

# Run all tests
uv run python test_server.py

# Expected output:
# 🧪 Weather MCP Server Test Suite
# ✅ Import tests passed
# ✅ API connectivity working
# ✅ Current weather function working
# ✅ Weather forecast function working
# ✅ City weather function working
# ✅ Error handling working
# 🎉 All tests passed!

单项测试:

# Test dependencies only
uv run python -c "import mcp; import httpx; print('✅ Dependencies OK')"

# Test API connectivity only
uv run python -c "
import asyncio, httpx
async def test():
    async with httpx.AsyncClient() as client:
        response = await client.get('https://api.open-meteo.com/v1/forecast?latitude=13.7563&longitude=100.5018&current=temperature_2m')
        print('✅ API connectivity OK' if response.status_code == 200 else '❌ API error')
asyncio.run(test())
"

Docker开发

构建和运行:

# Build image
docker build -t weather-mcp .

# Run container
docker run -it --rm weather-mcp

# Development with volume mount
docker run -it --rm -v $(pwd):/app weather-mcp bash

VS代码设置

该项目包括VS代码配置,以获得最佳开发体验:

  1. 安装推荐的扩展 (Python、WSL(如适用))
  2. 在VS代码中打开项目:
    code weather-mcp
    
  3. 选择Python解释器: 选择UV虚拟环境
  4. 使用调试: F5以断点开始

代码质量

格式:

  • 黑色:代码格式
  • isort:导入排序

Linting:

  • mypy:静态类型检查
  • VS代码:实时错误检测

测试:

  • pytest:单元测试框架
  • 自定义测试套件:集成测试

🐛 故障排除

常见问题

1.SSL证书错误

症状: certificate verify failed 或SSL连接错误 解决:

# Option 1: Disable SSL verification (development only)
export SSL_VERIFY=false

# Option 2: Use corporate CA bundle
export SSL_CERT_FILE=/path/to/corporate-ca-bundle.crt

# Option 3: Update certificates
# Ubuntu/Debian
sudo apt update && sudo apt install ca-certificates

# macOS
brew install ca-certificates

2.找不到模块错误

症状: ModuleNotFoundError: No module named 'mcp' 或类似 解决:

# Ensure virtual environment is activated and dependencies installed
uv sync

# Check installation
uv show mcp
uv show httpx

# Reinstall if needed
uv add --force mcp httpx

3.克劳德桌面看不到工具

症状: 克劳德没有回应天气查询或找不到工具 解决:

  • ✅ 验证中的绝对路径 claude_desktop_config.json
  • ✅ 检查JSON语法是否有效(使用在线JSON验证器)
  • ✅ 配置更改后重新启动Claude Desktop
  • ✅ 独立测试服务器: uv run python weather_server.py

4.WSL具体问题

症状: WSL中找不到命令或路径问题 解决:

# Check WSL version
wsl --version

# Update WSL
wsl --update

# Check if UV is in PATH
which uv
echo $PATH

# Reinstall UV if needed
curl -LsSf https://astral.sh/uv/install.sh | sh
source ~/.bashrc

5.API请求失败

症状: “无法获取天气数据”消息 解决:

# Test API connectivity directly
curl "https://api.open-meteo.com/v1/forecast?latitude=13.75&longitude=100.5&current=temperature_2m"

# Check firewall/proxy settings
ping api.open-meteo.com

# Test with timeout
curl --max-time 10 "https://api.open-meteo.com/v1/forecast?latitude=0&longitude=0&current=temperature_2m"

6.权限问题(Linux/MOSC/WSL)

症状: 权限被拒绝错误 解决:

# Make script executable
chmod +x weather_server.py

# Check directory permissions
ls -la weather_server.py

# Fix ownership if needed
sudo chown $USER:$USER weather_server.py

调试模式和日志记录

启用调试日志记录:

# Add to weather_server.py
import logging
logging.basicConfig(level=logging.DEBUG)

检查日志:

  • 克劳德桌面日志:
    • macOS: ~/Library/Logs/Claude/
    • 窗户: %APPDATA%/Claude/logs/
  • 服务器输出: 检查运行服务器的终端

独立测试服务器:

# Run server and test tools manually
uv run python test_server.py

# Use MCP Inspector for GUI testing
npx @modelcontextprotocol/inspector uv run python weather_server.py

获取帮助

  1. 查看此自述文件 常见解决方案
  2. 查看克劳德桌面日志 针对特定错误
  3. 独立测试服务器 隔离问题
  4. 验证API连接 使用curl命令
  5. 检查GitHub问题 对于类似的问题

如果你仍然有问题:

  • 🐛 打开一个问题 包含详细的错误信息
  • 📋 包括您的操作系统、Python版本和错误日志
  • 🔍 如果您正在使用WSL或公司网络,请注明

🤝 使用示例

一旦配置了Claude Desktop,您就可以使用自然语言进行交互:

基本天气查询

  • “曼谷的天气怎么样?”
  • “给我看看东京现在的温度”
  • “坐标40.7128-74.0060处的天气怎么样?” (纽约)

预测查询

  • “你能得到伦敦的7天天气预报吗?”
  • “本周新加坡的天气会怎么样?”
  • “给我看看未来几天巴黎的天气预报”

支持城市(通过 get_weather_by_city 工具)

  • 曼谷、东京、纽约、伦敦、巴黎、新加坡、悉尼、洛杉矶

高级查询

  • “比较曼谷和东京的天气”
  • “现在纽约的湿度是多少?”
  • “这个星期伦敦会下雨吗?”

交互示例

User: "What's the weather like in Bangkok right now?"

Claude: I'll check the current weather in Bangkok for you.

[Claude calls get_current_weather(13.7563, 100.5018)]

Based on the current weather data for Bangkok:

🌡️ **Temperature**: 32°C
💧 **Humidity**: 65%
🌦️ **Conditions**: Partly cloudy
💧 **Precipitation**: 0mm

The weather in Bangkok is warm and humid with partly cloudy skies.

📚 技术细节

API集成

  • 数据源: OpenMeteo API -免费天气API,无需API密钥
  • 更新频率:实时数据,每小时更新一次
  • 覆盖:任何坐标的全球天气数据
  • 速率限制:合理使用政策,无需身份验证

MCP协议特性

  • 运输:stdio(适用于Claude Desktop),还支持HTTP和SSE
  • 工具:3个与天气相关的工具暴露给克劳德
  • 资源:热门城市列表供参考
  • 错误处理:优美的回退和信息丰富的错误消息

性能和可靠性

  • 超时:30秒请求超时
  • 重试逻辑:内置网络问题错误处理
  • SSL支持:可配置的SSL验证
  • 异步:非阻塞异步/等待实现

🌟 平台特定注意事项

windows用户

  • 推荐:使用WSL以获得更好的性能和兼容性
  • 替代:本机Windows安装正常,但在公司环境中可能存在SSL问题
  • 路径格式:使用反睫毛 \ 或双反睫毛 \\ 在配置文件中

macOS用户

  • 家酿:可以通过以下方式安装UV brew install uv
  • 路径格式:使用正斜杠 / 在配置文件中
  • 权限:可能需要在“系统首选项”中允许终端访问

Linux用户

  • 包装经理:UV在大多数软件包存储库中可用
  • 依赖项:可能需要安装 curl, git,以及 build-essential
  • 权限:确保具有适当的文件权限 chmod +x

WSL用户(推荐用于Windows)

  • 演出:比原生Windows更适合Python开发
  • 兼容性:完全兼容Linux
  • 整合:与WSL扩展轻松集成VS代码
  • 配置:在Claude配置中使用WSL命令或UNC路径

🚀 快速命令参考

设置

# One-line setup (Linux/macOS/WSL)
curl -sSL https://raw.githubusercontent.com/your-repo/weather-mcp/main/setup.sh | bash

# Manual setup
mkdir weather-mcp && cd weather-mcp
uv init && uv add mcp httpx
# Copy weather_server.py and configure Claude Desktop

测试

# Test everything
make test  # or: uv run python test_server.py

# Test specific components
uv run python -c "import mcp, httpx; print('✅ OK')"
make inspector  # GUI testing tool

跑步

# Start server
make run  # or: uv run python weather_server.py

# Debug mode
DEBUG=true uv run python weather_server.py

发展

# Format code
make format  # or: uv run black . && uv run isort .

# Type checking
make lint  # or: uv run mypy weather_server.py

# All checks
make check

📝 许可证

此项目根据MIT许可证获得许可-有关详细信息,请参阅许可证文件。

🔗 相关链接

🤝 贡献

我们欢迎捐款!以下是如何开始:

  1. 分叉存储库 在GitHub上
  2. 创建要素分支: git checkout -b feature/amazing-feature
  3. 进行更改 并在适用的情况下添加测试
  4. 运行测试套件: make check 或 uv run python test_server.py
  5. 提交您的更改: git commit -m 'Add amazing feature'
  6. 推到您的分支: git push origin feature/amazing-feature
  7. 打开拉取请求 描述清晰

开发指南

  • 遵循现有代码样式(使用 make format)
  • 添加新功能的测试
  • 根据需要更新文档
  • 确保所有测试通过(make test)

📞 支持与社区

获取帮助

  1. 📖 查看此自述文件 用于全面的文档记录
  2. 🐛 搜索现有问题 在GitHub上
  3. 💬 打开新问题 详细信息包括:
    • 操作系统和版本
    • Python版本(python --version)
    • UV版本(uv --version)
    • 完整的错误消息和日志
    • 重现问题的步骤

社区

  • 💬 GitHub讨论 -提出问题并分享想法
  • 🐛 GitHub问题 -报告错误和请求功能
  • 📖 MCP社区 -加入更广泛的MCP生态系统讨论

报告问题

在报告问题时,请包括:

  • 环境:操作系统、Python版本、WSL(如适用)
  • 安装方法:自动脚本与手动
  • 错误日志:完整的错误消息
  • 重现步骤:错误发生前你做了什么
  • 预期行为:应该发生什么

由以下材料制成❤️ 对于MCP社区

星⭐ 如果你觉得这个仓库有用的话!