# 多日天氣預報功能說明
## 📋 功能概述
Weather MCP 現已支援多日天氣預報功能,可以查詢:
- 📅 指定日期的天氣(例如:明天、後天)
- 📊 未來多天的天氣預報(1-16 天)
- 🤖 自然語言時間理解(Agent 自動計算日期)
## 🚀 快速開始
### 方法 1:直接使用 Client API
```python
from weather_mcp import WeatherMCPClient
from datetime import datetime, timedelta
client = WeatherMCPClient()
# 查詢明天東京的天氣
tomorrow = (datetime.now() + timedelta(days=1)).strftime("%Y-%m-%d")
result = client.get_city_weather(
city="Tokyo",
forecast_days=2,
target_date=tomorrow
)
# 查詢未來 7 天巴黎的天氣
result = client.get_city_weather(
city="Paris",
forecast_days=7
)
```
### 方法 2:使用 Agent(自然語言)
```python
from weather_mcp import WeatherAgent
agent = WeatherAgent()
# Agent 會自動理解時間並計算日期
response = agent.ask_weather("明天東京天氣如何?")
print(response)
response = agent.ask_weather("未來 3 天台北的天氣")
print(response)
response = agent.ask_weather("後天倫敦會下雨嗎?")
print(response)
```
## 🔧 API 參數說明
### `get_weather()` 方法
```python
def get_weather(
lat: float,
lon: float,
hours: int = 12,
forecast_days: int = 1, # 新增:預報天數
target_date: str = "", # 新增:指定日期
timeout: Optional[float] = None
) -> Dict[str, Any]:
```
**參數說明**:
- `lat`: 緯度
- `lon`: 經度
- `hours`: 查詢小時數(1-24),若指定 `target_date` 則忽略此參數
- `forecast_days`: 預報天數(1-16 天,預設 1)
- `target_date`: 指定日期,格式:`YYYY-MM-DD`(可選)
- `timeout`: 請求超時時間
### `get_city_weather()` 方法
```python
def get_city_weather(
city: str,
hours: int = 12,
forecast_days: int = 1, # 新增:預報天數
target_date: str = "", # 新增:指定日期
timeout: Optional[float] = None
) -> Dict[str, Any]:
```
**參數說明**:同 `get_weather()`,但會先自動進行地理編碼。
## 📊 使用範例
### 範例 1:查詢明天的天氣
```python
from datetime import datetime, timedelta
from weather_mcp import WeatherMCPClient
client = WeatherMCPClient()
# 計算明天日期
tomorrow = (datetime.now() + timedelta(days=1)).strftime("%Y-%m-%d")
# 查詢明天東京全天 24 小時的天氣
result = client.get_city_weather(
city="Tokyo",
forecast_days=2, # 需要 2 天數據(今天 + 明天)
target_date=tomorrow # 指定明天日期
)
# 取得天氣數據
weather = result.get("weather", {})
hourly = weather.get("hourly", {})
print(f"明天日期:{tomorrow}")
print(f"時間:{hourly.get('time', [])}")
print(f"溫度:{hourly.get('temperature_2m', [])} °C")
```
### 範例 2:查詢未來 7 天天氣
```python
from weather_mcp import WeatherMCPClient
client = WeatherMCPClient()
# 查詢未來 7 天倫敦的天氣
result = client.get_city_weather(
city="London",
forecast_days=7, # 7 天預報
hours=24 # 每天取 24 小時(取前 24 小時)
)
# 處理數據
weather = result.get("weather", {})
hourly = weather.get("hourly", {})
# 顯示前 24 小時(第一天)的天氣
times = hourly.get("time", [])[:24]
temps = hourly.get("temperature_2m", [])[:24]
for time, temp in zip(times, temps):
print(f"{time}: {temp}°C")
```
### 範例 3:使用 Agent 自然語言查詢
```python
from weather_mcp import WeatherAgent
agent = WeatherAgent()
# Agent 會自動:
# 1. 理解「明天」並計算日期
# 2. 轉換城市名稱(東京 -> Tokyo)
# 3. 調用正確的工具參數
questions = [
"明天東京天氣如何?",
"後天台北會下雨嗎?",
"未來 3 天倫敦的天氣",
"這週巴黎的天氣預報"
]
for question in questions:
print(f"\n問題:{question}")
answer = agent.ask_weather(question)
print(f"回答:{answer}")
```
## 🤖 Agent 時間理解能力
Agent 會自動理解以下時間表達:
| 使用者輸入 | Agent 行為 |
|----------|----------|
| 「今天東京天氣」 | `forecast_days=1`, `target_date=今天日期` |
| 「明天東京天氣」 | `forecast_days=2`, `target_date=明天日期` |
| 「後天東京天氣」 | `forecast_days=3`, `target_date=後天日期` |
| 「未來 3 天天氣」 | `forecast_days=3`(不指定 target_date) |
| 「這週天氣」 | `forecast_days=7` |
Agent 會在 prompt 中接收當前時間,並自動計算對應日期。
## 📡 API 行為說明
### Open-Meteo API
- **預設預報**:7 天
- **最大預報**:16 天
- **參數**:`forecast_days=N`
- **時間起點**:總是從當前時間開始
### 數據過濾邏輯
1. **指定 `target_date`**:
- 從 API 返回的數據中篩選指定日期的所有小時
- 忽略 `hours` 參數
- 返回該日期的完整 24 小時數據
2. **未指定 `target_date`**:
- 使用 `hours` 參數(1-24)
- 從當前時間開始取前 N 小時
- 保持向後兼容
### 錯誤處理
如果指定的日期超出預報範圍,會返回錯誤訊息:
```json
{
"error": "No data found for date '2025-10-20'",
"available_dates": ["2025-10-02", "2025-10-03"]
}
```
## 🔍 日誌記錄
所有函數呼叫都會記錄在 `mcp_server.log`:
```
🌤️ get_weather(lat=35.6895, lon=139.6917, hours=24, forecast_days=2, target_date='2025-10-03')
```
可以追蹤每次查詢的參數。
## 📝 測試
新增了測試案例驗證多日預報功能:
```bash
# 執行測試
pytest tests/test_client.py -v
# 測試項目包括:
# - test_weather_parameters: 驗證新參數
# - test_city_weather_parameters: 驗證城市天氣新參數
```
## 🔄 向後兼容
所有新參數都有預設值,確保向後兼容:
- `forecast_days=1`:預設查詢 1 天
- `target_date=""`:預設不指定日期
舊代碼無需修改即可繼續運作:
```python
# 舊代碼仍然有效
client = WeatherMCPClient()
result = client.get_city_weather("Tokyo", hours=12)
```
## 🎯 實際應用場景
### 場景 1:行程規劃
```python
# 查詢未來一週的天氣,規劃旅行
result = client.get_city_weather("Paris", forecast_days=7)
```
### 場景 2:活動安排
```python
# 確認明天是否適合戶外活動
from datetime import datetime, timedelta
tomorrow = (datetime.now() + timedelta(days=1)).strftime("%Y-%m-%d")
result = client.get_city_weather("Tokyo", forecast_days=2, target_date=tomorrow)
# 檢查降雨機率
hourly = result["weather"]["hourly"]
rain_prob = hourly.get("precipitation_probability", [])
avg_rain = sum(rain_prob) / len(rain_prob) if rain_prob else 0
print(f"明天平均降雨機率:{avg_rain:.1f}%")
```
### 場景 3:多城市比較
```python
# 比較未來 3 天不同城市的天氣
cities = ["Tokyo", "London", "New York"]
for city in cities:
result = client.get_city_weather(city, forecast_days=3)
print(f"{city}: {result}")
```
## 📚 相關文件
- [README.md](../README.md) - 專案主要文件
- [LOGGING.md](LOGGING.md) - 日誌系統說明
- [SERVER_STARTUP.md](SERVER_STARTUP.md) - 伺服器啟動機制
- [client.py](../src/weather_mcp/client.py) - Client 實作
- [server.py](../src/weather_mcp/server.py) - Server 實作
- [agent.py](../src/weather_mcp/agent.py) - Agent 實作
## ❓ 常見問題
### Q1: 為什麼查詢明天需要 `forecast_days=2`?
A: 因為 API 從今天開始計算,要包含明天的數據需要至少 2 天。
### Q2: `target_date` 和 `hours` 的關係?
A: 當指定 `target_date` 時,會忽略 `hours` 參數,返回該日期的完整 24 小時數據。
### Q3: 最多可以查詢多少天?
A: Open-Meteo API 支援最多 16 天的預報(`forecast_days=16`)。
### Q4: Agent 是否支援英文查詢?
A: 是的,Agent 支援中英文混合查詢,會自動理解時間並調用正確的工具。
---
**更新日期**: 2025-10-02
**狀態**: ✅ 多日預報功能已實作並測試