Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions atomic-forge/tools/weather/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ Looks up current conditions and a daily/hourly forecast for any location using t

### Input Schema
- `location` (str): city name, `'City, Region'`, or `'lat,lon'`.
- `country_code` (str, optional): two-letter ISO 3166-1 country code for city lookup, such as `GB` or `US`. Case-insensitive; omitted by default. Coordinates bypass geocoding, so the filter does not apply to `lat,lon`.
- `units` (str): `metric` (Celsius / km/h / mm) or `imperial` (Fahrenheit / mph / inches). Default `metric`.
- `forecast_days` (int): 1–16, default 3.
- `include_hourly` (bool): include hourly forecast data, default `False`.
Expand Down Expand Up @@ -46,6 +47,14 @@ else:
print(day.date, day.temperature_min, "→", day.temperature_max, day.weather_description)
```

For an ambiguous city name, use an explicit country filter:

```python
out = tool.run(WeatherToolInputSchema(location="London", country_code="GB"))
```

The filter uses Open-Meteo's [`countryCode` parameter](https://open-meteo.com/en/docs/geocoding-api). If no city matches in that country, the tool returns a lookup error without fetching a forecast for another country.

## Notes
- Weather codes are translated to human-readable descriptions via the WMO interpretation table (Open-Meteo).
- The tool fails gracefully and returns `error` set on the output rather than raising.
Expand Down
106 changes: 106 additions & 0 deletions atomic-forge/tools/weather/tests/test_country_filter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
import json
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlsplit

import pytest
from pydantic import ValidationError

from tool.weather import WeatherTool, WeatherToolConfig, WeatherToolInputSchema


@pytest.fixture
def service():
requests = []
locations = {
"GB": {"name": "London", "country": "United Kingdom", "latitude": 51.5085, "longitude": -0.1257},
"US": {"name": "London", "country": "United States", "latitude": 39.8865, "longitude": -83.4483},
}

class Handler(BaseHTTPRequestHandler):
def do_GET(self):
url = urlsplit(self.path)
params = parse_qs(url.query)
requests.append((url.path, params))
if url.path == "/geocode":
location = locations.get(params.get("countryCode", ["US"])[0])
body = {"results": [location] if location else []}
else:
body = {"current": {"time": "2026-01-01T00:00", "temperature_2m": 12.5}}
encoded = json.dumps(body).encode()
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(encoded)))
self.end_headers()
self.wfile.write(encoded)

def log_message(self, *args):
pass

server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
thread = threading.Thread(target=server.serve_forever, kwargs={"poll_interval": 0.01}, daemon=True)
thread.start()
origin = f"http://127.0.0.1:{server.server_port}"
tool = WeatherTool(WeatherToolConfig(geocoding_url=origin + "/geocode", forecast_url=origin + "/forecast"))
try:
yield tool, requests, locations
finally:
tool._session.close()
server.shutdown()
thread.join()
server.server_close()


@pytest.mark.parametrize("country_code", ["gb", "GB", "US"])
def test_ambiguous_city_uses_requested_country_coordinates_for_forecast(service, country_code):
tool, requests, locations = service
result = tool.run(WeatherToolInputSchema(location="London", country_code=country_code, language="fr"))
expected = locations[country_code.upper()]

assert result.error is None
assert result.country == expected["country"]
assert (result.latitude, result.longitude) == (expected["latitude"], expected["longitude"])
assert result.current.temperature == 12.5
assert requests[0] == (
"/geocode",
{"name": ["London"], "count": ["1"], "language": ["fr"], "format": ["json"], "countryCode": [country_code.upper()]},
)
assert requests[1][0] == "/forecast"
assert requests[1][1]["latitude"] == [str(expected["latitude"])]
assert requests[1][1]["longitude"] == [str(expected["longitude"])]
assert "countryCode" not in requests[1][1]


def test_omitting_country_keeps_unfiltered_geocoding(service):
tool, requests, _ = service
result = tool.run(WeatherToolInputSchema(location="London"))

assert result.error is None
assert result.country == "United States"
assert "countryCode" not in requests[0][1]


def test_country_without_a_matching_city_does_not_fetch_another_countrys_forecast(service):
tool, requests, _ = service
result = tool.run(WeatherToolInputSchema(location="London", country_code="JP"))

assert result.error == "Location 'London' not found."
assert result.current is None
assert [path for path, _ in requests] == ["/geocode"]


def test_explicit_coordinates_bypass_country_geocoding(service):
tool, requests, _ = service
result = tool.run(WeatherToolInputSchema(location="48.8566,2.3522", country_code="GB"))

assert result.error is None
assert (result.latitude, result.longitude) == (48.8566, 2.3522)
assert result.country is None
assert [path for path, _ in requests] == ["/forecast"]
assert "countryCode" not in requests[0][1]


@pytest.mark.parametrize("country_code", ["", "G", "GBR", "G1", " GB", "GB ", "éé", "US,GB"])
def test_malformed_country_filters_are_rejected_before_lookup(country_code):
with pytest.raises(ValidationError, match="country_code"):
WeatherToolInputSchema(location="London", country_code=country_code)
13 changes: 11 additions & 2 deletions atomic-forge/tools/weather/tool/weather.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,13 @@ class WeatherToolInputSchema(BaseIOSchema):
" IL'`), or a `lat,lon` pair (e.g. `'48.8566,2.3522'`)."
),
)
country_code: Optional[str] = Field(
default=None,
min_length=2,
max_length=2,
pattern=r"^[A-Za-z]{2}$",
description="Optional ISO 3166-1 alpha-2 country filter for city lookup (e.g. GB). Ignored for lat,lon input.",
)
units: Literal["metric", "imperial"] = Field(
default="metric",
description="'metric' uses Celsius and km/h; 'imperial' uses Fahrenheit and mph.",
Expand Down Expand Up @@ -188,8 +195,10 @@ def parse_latlon(cls, value: str) -> Optional[Tuple[float, float]]:
return None
return lat, lon

def _geocode(self, query: str, language: str) -> dict:
def _geocode(self, query: str, language: str, country_code: Optional[str] = None) -> dict:
params = {"name": query, "count": "1", "language": language, "format": "json"}
if country_code is not None:
params["countryCode"] = country_code.upper()
response = self._session.get(self.geocoding_url, params=params, timeout=self.timeout)
response.raise_for_status()
data = response.json()
Expand Down Expand Up @@ -326,7 +335,7 @@ def run(self, params: WeatherToolInputSchema) -> WeatherToolOutputSchema:
location_name = f"{latitude:.4f}, {longitude:.4f}"
country = None
else:
geocoded = self._geocode(params.location, params.language)
geocoded = self._geocode(params.location, params.language, params.country_code)
latitude = geocoded["latitude"]
longitude = geocoded["longitude"]
location_name = geocoded.get("name", params.location)
Expand Down
Loading