feat(weather): KMA current weather inside Korea with the app's stored key

The 기능 screen's 기상청 날씨 card stores the KMA API hub key encrypted
(kmaApiKey, masked in logs). On start the app passes it to the worker in
JARVIS_KMA_API_KEY; the worker takes it out of its environment before any
child process starts. Inside Korea getWeather reads 초단기실황 and the
coming hour's sky from 초단기예보, and falls back to open-meteo, then
met.no, on any KMA failure. The key is in KMA's URLs, so failures are
logged by their kind only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
javis-bot
2026-11-18 10:05:31 +09:00
parent e99831e540
commit 282f114e60
10 changed files with 383 additions and 22 deletions

View File

@@ -1,4 +1,8 @@
"""Weather tool implementation using Open-Meteo API (free, no API key required)."""
"""Weather tool: KMA inside Korea when the app gives a key, else Open-Meteo (no key), then met.no."""
import math
import os
from datetime import datetime, timedelta, timezone
import requests
from typing import Dict, Any, Optional
@@ -246,6 +250,94 @@ def _met_no_current(lat: float, lon: float) -> Dict[str, Any]:
return {}
# KMA (기상청 API허브): current weather inside Korea when the app gives a key (admin.spec.md).
KMA_KEY_ENV = "JARVIS_KMA_API_KEY"
_KMA_URL = "https://apihub.kma.go.kr/api/typ02/openApi/VilageFcstInfoService_2.0/"
_KMA_TIMEOUT_SEC = 5
_KST = timezone(timedelta(hours=9))
# KMA's own words: PTY (precipitation type, 0 = none) wins over SKY (sky state).
_KMA_PTY_KO = {1: "비", 2: "비나 눈", 3: "눈", 5: "빗방울", 6: "빗방울과 눈날림", 7: "눈날림"}
_KMA_PTY_WMO = {1: 63, 2: 69, 3: 73, 5: 51, 6: 68, 7: 71}
_KMA_SKY_KO = {1: "맑음", 3: "구름 많음", 4: "흐림"}
_KMA_SKY_WMO = {1: 0, 3: 2, 4: 3}
_kma_key = ""
def take_kma_key() -> None:
"""Keep the app's KMA key here and take it out of the environment, so no child process
(MCP servers, MeloTTS) inherits it. Without a call the environment is read on each request."""
global _kma_key
_kma_key = os.environ.pop(KMA_KEY_ENV, "").strip()
def _kma_key_now() -> str:
return _kma_key or os.environ.get(KMA_KEY_ENV, "").strip()
def _kma_grid(lat: float, lon: float) -> tuple:
"""KMA's 5 km forecast grid point (nx, ny) for a place (the Lambert conformal conic of KMA's guide)."""
re_, grid = 6371.00877 / 5.0, math.radians(1)
slat1, slat2, olon, olat = 30 * grid, 60 * grid, 126 * grid, 38 * grid
sn = math.log(math.cos(slat1) / math.cos(slat2)) / math.log(
math.tan(math.pi / 4 + slat2 / 2) / math.tan(math.pi / 4 + slat1 / 2))
sf = math.tan(math.pi / 4 + slat1 / 2) ** sn * math.cos(slat1) / sn
ro = re_ * sf / math.tan(math.pi / 4 + olat / 2) ** sn
ra = re_ * sf / math.tan(math.pi / 4 + lat * grid / 2) ** sn
theta = lon * grid - olon
theta = (theta + math.pi) % (2 * math.pi) - math.pi
theta *= sn
return int(ra * math.sin(theta) + 43 + 0.5), int(ro - ra * math.cos(theta) + 136 + 0.5)
def _kma_items(service: str, key: str, base: datetime, nx: int, ny: int) -> list:
"""One KMA call's items; raises on any failure. The key is in the URL: never log the error text."""
resp = requests.get(_KMA_URL + service, timeout=_KMA_TIMEOUT_SEC, params={
"pageNo": 1, "numOfRows": 100, "dataType": "JSON", "base_date": base.strftime("%Y%m%d"),
"base_time": base.strftime("%H%M"), "nx": nx, "ny": ny, "authKey": key})
resp.raise_for_status()
body = (resp.json() or {}).get("response") or {}
code = (body.get("header") or {}).get("resultCode")
if code != "00":
raise ValueError(f"KMA result code {code}")
return ((body.get("body") or {}).get("items") or {}).get("item") or []
def _kma_current(lat: float, lon: float, key: str, now: Optional[datetime] = None) -> Dict[str, Any]:
"""Current weather from KMA in open-meteo's 'current' keys plus 'condition_ko'; {} on failure.
초단기실황 (each hour's observation, out at about :40) gives the temperature, humidity, wind and
precipitation; it has no sky state, so 초단기예보 (out at about :45) gives the coming hour's SKY.
"""
now = (now or datetime.now(_KST)).astimezone(_KST)
nx, ny = _kma_grid(lat, lon)
try:
obs_base = (now - timedelta(minutes=40)).replace(minute=0, second=0, microsecond=0)
obs = {i.get("category"): i.get("obsrValue") for i in _kma_items("getUltraSrtNcst", key, obs_base, nx, ny)}
fc_base = (now - timedelta(minutes=45)).replace(minute=30, second=0, microsecond=0)
sky = sorted((i.get("fcstDate", "") + i.get("fcstTime", ""), i.get("fcstValue"))
for i in _kma_items("getUltraSrtFcst", key, fc_base, nx, ny) if i.get("category") == "SKY")
temp, pty, sky_v = float(obs["T1H"]), int(float(obs.get("PTY") or 0)), int(sky[0][1]) if sky else None
if pty in _KMA_PTY_KO:
ko, wmo = _KMA_PTY_KO[pty], _KMA_PTY_WMO[pty]
elif sky_v in _KMA_SKY_KO:
ko, wmo = _KMA_SKY_KO[sky_v], _KMA_SKY_WMO[sky_v]
else:
raise ValueError("KMA gave no sky state")
wind = obs.get("WSD")
return {
"temperature_2m": temp,
"apparent_temperature": None,
"relative_humidity_2m": float(obs["REH"]) if obs.get("REH") is not None else None,
"weather_code": wmo,
"condition_ko": ko,
"wind_speed_10m": round(float(wind) * 3.6, 1) if wind is not None else None,
}
except Exception as e:
why = str(e) if isinstance(e, (ValueError, KeyError)) else type(e).__name__
debug_log(f"KMA failed ({why}); using open-meteo", "tools")
return {}
class WeatherTool(Tool):
"""Tool for getting current weather using Open-Meteo API."""
@@ -318,7 +410,8 @@ class WeatherTool(Tool):
display_name = ", ".join(display_parts) if display_parts else "your location"
return {"lat": lat, "lon": lon, "display_name": display_name}
return {"lat": lat, "lon": lon, "display_name": display_name,
"country_code": location_info.get("country_code")}
except Exception as e:
debug_log(f" ⚠️ location detection error: {e}", "tools")
return None
@@ -339,6 +432,7 @@ class WeatherTool(Tool):
lat: Optional[float] = None
lon: Optional[float] = None
location_display: str = ""
country_code: Optional[str] = None
# Track whether we inferred the place name from the user's text
# rather than receiving it from the caller — used only for the
@@ -359,6 +453,7 @@ class WeatherTool(Tool):
lat = user_loc["lat"]
lon = user_loc["lon"]
location_display = user_loc["display_name"]
country_code = user_loc.get("country_code")
debug_log(
f" 📍 using detected location: {location_display} ({lat}, {lon})",
"tools",
@@ -456,6 +551,7 @@ class WeatherTool(Tool):
place_name = place.get("name", location_str)
country = place.get("country", "")
admin1 = place.get("admin1", "") # State/region
country_code = place.get("country_code")
# Build display name
location_display = place_name
@@ -480,15 +576,22 @@ class WeatherTool(Tool):
"timezone": "auto"
}
try:
weather_response = requests.get(weather_url, params=weather_params,
timeout=_OPEN_METEO_TIMEOUT_SEC)
weather_response.raise_for_status()
current = (weather_response.json() or {}).get("current", {})
except Exception as e:
# Live 2026-11-18: the forecast server stopped answering while geocoding worked.
debug_log(f"open-meteo forecast failed ({type(e).__name__}); trying met.no", "tools")
current = _met_no_current(lat, lon)
current: Dict[str, Any] = {}
kma_key = _kma_key_now()
if kma_key and country_code == "KR":
current = _kma_current(lat, lon, kma_key)
if current:
debug_log(" 🌤️ current weather from KMA", "tools")
if not current:
try:
weather_response = requests.get(weather_url, params=weather_params,
timeout=_OPEN_METEO_TIMEOUT_SEC)
weather_response.raise_for_status()
current = (weather_response.json() or {}).get("current", {})
except Exception as e:
# Live 2026-11-18: the forecast server stopped answering while geocoding worked.
debug_log(f"open-meteo forecast failed ({type(e).__name__}); trying met.no", "tools")
current = _met_no_current(lat, lon)
if not current:
return ToolExecutionResult(
success=False,
@@ -514,7 +617,7 @@ class WeatherTool(Tool):
# tool result is normally re-synthesised by the LLM, but a small
# model rambles and leaks °F / CJK fragments, so we hand it a clean
# Korean sentence it can echo verbatim (one-sentence system rule).
_ko = WMO_CODES_KO.get(weather_code, weather_desc)
_ko = current.get("condition_ko") or WMO_CODES_KO.get(weather_code, weather_desc)
_short_loc = location_display.split(",")[0].strip() or location_display
_ko_parts = [f"지금 {_short_loc} 날씨는 {_ko}"]
if temp_c is not None: