内容
# Weather MCP Server
一个轻量级的 FastMCP 服务,通过简单的 RPC 风格的“工具”暴露国家气象局的警报和预报。
## 安装
首先,如果你还没有安装 [uv](https://github.com/astral-sh/uv)(一个快速的 Python 包管理器),请先安装它:
```bash
curl -LsSf https://astral.sh/uv/install.sh | sh
```
# 创建虚拟环境并激活它
```bash
uv venv
source .venv/bin/activate
```
# 安装依赖
```bash
uv add "mcp[cli]" httpx
```
然后从 PyPI 安装:
```bash
pip install weather-mcp-server
```
或者从源代码安装以进行开发:
```bash
git clone https://github.com/YourOrg/weather-mcp-server.git
cd weather-mcp-server
pip install -e ".[dev]"
```
## 使用
### 作为 Python 库
```python
from weather.nws_client import NWSClient
import asyncio
async def main():
client = NWSClient()
alerts = await client.get_alerts("CA")
for alert in alerts:
print(alert["headline"], alert["event"], alert["severity"])
asyncio.run(main())
```
### 作为 FastMCP 服务器
```bash
weather-mcp-server --transport stdio
```
或者
```bash
uv run main.py
```
要运行 MCP Inspector:
```bash
npx @modelcontextprotocol/inspector
```
复制会话令牌和代理服务器地址(见下面示例)。
```bash
Proxy server listening on 127.0.0.1:6277
Session token: dc7a47f8b6b1a3eede7c507a8d1c9a7f7e6b3ff46c138f8480bbfbae3c45a9e4
```
在浏览器中打开 MCP Inspector: http://127.0.0.1:6274,并在配置中,将值粘贴到以下字段中:
```
Command: uv
Argument: run main.py
Inspector Proxy Address: http://127.0.0.1:6274
Proxy Session Token: dc7a47f8b6b1a3eede7c507a8d1c9a7f7e6b3ff46c138f8480bbfbae3c45a9e4
```
## API 参考
### get_alerts
获取给定两字母美国州代码的格式化天气警报。
**参数:**
- `state` (str): 两个字母的大写州缩写(例如 "CA")。
**返回:**
- `str`: 用 `---` 分隔的格式化警报,或错误信息。
### get_forecast
获取某个地点的格式化天气预报。
**参数:**
- `latitude` (float): 纬度,范围在 -90 到 90 之间。
- `longitude` (float): 经度,范围在 -180 到 180 之间。
**返回:**
- `str`: 最多 5 个时段的预报或错误信息。
### /health
健康检查端点。
**HTTP GET** `/health`
**返回 JSON:**
- `{"status": "ok"}`
## 测试与覆盖率
- 测试使用 `pytest`、`pytest-asyncio` 和 `pytest-cov`。
- 网络调用在单元测试中被猴子补丁处理以实现隔离。
- 使用以下命令运行所有测试:
```sh
pytest
```
- 使用以下命令生成 HTML 覆盖率报告:
```sh
pytest --cov=src --cov-report=html
open htmlcov/index.html
```
## Fixtures & Mocking
- 测试夹具和猴子补丁用于模拟 NWS API 响应,并将测试与网络依赖隔离。
- 请参见 `tests/conftest.py` 以获取可重用的夹具。
## 参考文献
* [https://medium.com/data-engineering-with-dremio/building-a-basic-mcp-server-with-python-4c34c41031ed](https://medium.com/data-engineering-with-dremio/building-a-basic-mcp-server-with-python-4c34c41031ed)
* [https://modelcontextprotocol.io/quickstart/server](https://modelcontextprotocol.io/quickstart/server)