Skip to content

Personal AI, On Personal Devices

Python

feat: add native dynamic weather tool (#897)

Elliot Sluskyd6fd2a15036b
diff --git a/docs/getting-started/configuration.md b/docs/getting-started/configuration.md
index 2d580714..238a4db9 100644
--- a/docs/getting-started/configuration.md
+++ b/docs/getting-started/configuration.md
@@ -406,6 +406,36 @@ enabled = true
---
+### `[tools.weather]` — Native Weather Tool
+
+Controls defaults for the `get_weather` native tool. The requested location,
+unit system, and language remain overridable on every tool call.
+
+```toml
+[tools]
+enabled = "get_weather"
+
+[tools.weather]
+provider = "openweathermap"
+default_location = ""
+units = "metric"
+lang = "en"
+```
+
+| Field | Type | Default | Description |
+|-------|------|---------|-------------|
+| `provider` | string | `"openweathermap"` | Weather provider; currently only OpenWeatherMap is supported. |
+| `default_location` | string | `""` | Optional fallback when a tool call omits its location. |
+| `units` | string | `"metric"` | Default unit system: `metric` or `imperial`. |
+| `lang` | string | `"en"` | Default OpenWeatherMap response language. |
+
+Keep the API key out of `config.toml`. Set `OPENWEATHERMAP_API_KEY`, save it
+through the tool credentials API/UI, or connect the Weather connector. The
+native tool reuses the connector's stored credential when no tool credential or
+environment variable is present.
+
+---
+
### `[server]` — API Server
Controls the OpenAI-compatible API server started by `jarvis serve`.
diff --git a/docs/user-guide/data-boundary-scan.md b/docs/user-guide/data-boundary-scan.md
index 60a17fa6..3944e962 100644
--- a/docs/user-guide/data-boundary-scan.md
+++ b/docs/user-guide/data-boundary-scan.md
@@ -58,6 +58,7 @@ The current checks cover:
`telemetry.db`, `scheduler.db`, embeddings, skill index, `.vault_key`, and memory files
- connector credential files under `connectors/*.json`, without reading them
- API-key and other runtime credential environment variables (presence only)
+- native weather lookups, where a requested location is sent to OpenWeatherMap
- a scope note for frontend credential storage when cloud/API-key surfaces exist
Configured database paths (for example `traces.db_path` or `memory.db_path`)
diff --git a/docs/user-guide/tools.md b/docs/user-guide/tools.md
index f22bcd23..754f5447 100644
--- a/docs/user-guide/tools.md
+++ b/docs/user-guide/tools.md
@@ -188,6 +188,7 @@ All built-in tools are registered via `@ToolRegistry.register()` and are availab
| **Code** | `code_interpreter_docker` | Execute Python code in a disposable Docker container |
| **Code** | `repl` | Persistent Python REPL with state across calls |
| **Search** | `web_search` | Web search returning result summaries |
+| **Weather** | `get_weather` | Dynamic current conditions and forecast via OpenWeatherMap |
| **File I/O** | `file_read` | Read file contents with safety validations |
| **HTTP** | `http_request` | Make HTTP requests with SSRF protection |
| **Memory** | `retrieval` | Search the memory backend for relevant context |
@@ -383,6 +384,37 @@ Searches the web and returns a result summary. Useful for queries that need curr
|-----------|--------|----------|------------------------------------------|
| `query` | string | Yes | Search query string |
+### Weather
+
+**Registry key:** `get_weather` | **Category:** `weather`
+
+Returns structured current conditions for a dynamic location, with optional
+3-hour forecast intervals. Location text is sent to OpenWeatherMap, so avoid
+using a sensitive or exact address when a city or region is sufficient.
+
+Set `OPENWEATHERMAP_API_KEY` in the environment, save it through the tool
+credentials API/UI, or connect the existing Weather connector. The tool checks
+those secure credential sources at execution time and never includes the key in
+its result. Enable it like any native tool:
+
+```toml
+[tools]
+enabled = "get_weather"
+```
+
+**Parameters:**
+
+| Parameter | Type | Required | Description |
+|-----------|------|----------|-------------|
+| `location` | string | No | City, region, or `city,country-code`; falls back to the configured default |
+| `units` | string | No | `metric` or `imperial` |
+| `language` | string | No | OpenWeatherMap language code such as `en`, `de`, or `pt_br` |
+| `include_forecast` | boolean | No | Include 3-hour forecast intervals |
+| `forecast_hours` | integer | No | Forecast horizon from 3 to 120 hours (default: 24) |
+
+For example, an agent can call `get_weather` with `location="Vienna,AT"`,
+`language="de"`, and `include_forecast=true`.
+
### CodeInterpreter
**Registry key:** `code_interpreter` | **Category:** `code`
diff --git a/src/openjarvis/connectors/weather.py b/src/openjarvis/connectors/weather.py
index db36c998..83868773 100644
--- a/src/openjarvis/connectors/weather.py
+++ b/src/openjarvis/connectors/weather.py
@@ -7,6 +7,7 @@ All API calls are in module-level functions for easy mocking in tests.
from __future__ import annotations
import json
+import logging
from datetime import datetime
from pathlib import Path
from typing import Any, Dict, Iterator, Optional
@@ -14,17 +15,99 @@ from typing import Any, Dict, Iterator, Optional
import httpx
from openjarvis.connectors._stubs import BaseConnector, Document, SyncStatus
-from openjarvis.core.config import DEFAULT_CONFIG_DIR
+from openjarvis.core.paths import get_config_dir
from openjarvis.core.registry import ConnectorRegistry
-_DEFAULT_TOKEN_PATH = str(DEFAULT_CONFIG_DIR / "connectors" / "weather.json")
+_CURRENT_WEATHER_URL = "https://api.openweathermap.org/data/2.5/weather"
+_FORECAST_URL = "https://api.openweathermap.org/data/2.5/forecast"
+_STATUS_DETAILS = {
+ 400: "the request was invalid",
+ 401: "authentication failed",
+ 404: "the location was not found",
+ 429: "the provider rate limit was exceeded",
+}
+
+
+class _WeatherRequestLogFilter(logging.Filter):
+ """Keep OpenWeatherMap query credentials out of HTTPX request logs."""
+
+ def filter(self, record: logging.LogRecord) -> bool:
+ if isinstance(record.args, tuple):
+ record.args = tuple(
+ arg.copy_set_param("appid", "[REDACTED]")
+ if isinstance(arg, httpx.URL)
+ and arg.host == "api.openweathermap.org"
+ and "appid" in arg.params
+ else arg
+ for arg in record.args
+ )
+ return True
+
+
+# HTTPX logs successful requests at INFO, including the URL query. Sanitize
+# only this provider's credential parameter; preserve other request logging.
+# Connector discovery can reload this module, so install the filter only once.
+_httpx_logger = logging.getLogger("httpx")
+_filter_name = "openjarvis.weather.credentials"
+if not any(getattr(f, "name", None) == _filter_name for f in _httpx_logger.filters):
+ _httpx_logger.addFilter(_WeatherRequestLogFilter(_filter_name))
+
+
+class WeatherAPIError(RuntimeError):
+ """A credential-safe error returned by the OpenWeatherMap API."""
def _weather_api_get(url: str, params: Dict[str, str]) -> Dict[str, Any]:
- """Call an OpenWeatherMap API endpoint."""
- resp = httpx.get(url, params=params, timeout=30.0)
- resp.raise_for_status()
- return resp.json()
+ """Call an OpenWeatherMap API endpoint without leaking query credentials."""
+ try:
+ resp = httpx.get(url, params=params, timeout=30.0)
+ resp.raise_for_status()
+ payload = resp.json()
+ except httpx.HTTPStatusError as exc:
+ # The exception string contains the full request URL, including appid.
+ # Never surface provider-controlled text: it could echo a query value.
+ status = exc.response.status_code
+ detail = _STATUS_DETAILS.get(status, "the request failed")
+ raise WeatherAPIError(
+ f"OpenWeatherMap returned HTTP {status}: {detail}"
+ ) from None
+ except httpx.RequestError:
+ # RequestError also formats the request URL, so do not interpolate it.
+ raise WeatherAPIError("OpenWeatherMap could not be reached") from None
+ except (TypeError, ValueError):
+ raise WeatherAPIError(
+ "OpenWeatherMap returned an invalid JSON response"
+ ) from None
+
+ if not isinstance(payload, dict):
+ raise WeatherAPIError("OpenWeatherMap returned an invalid response")
+ return payload
+
+
+def fetch_weather(
+ *,
+ api_key: str,
+ location: str,
+ units: str,
+ language: str,
+ include_forecast: bool = False,
+ forecast_count: int = 8,
+) -> tuple[Dict[str, Any], Dict[str, Any] | None]:
+ """Fetch weather for a caller-provided location from fixed API endpoints."""
+ common_params = {
+ "q": location,
+ "appid": api_key,
+ "units": units,
+ "lang": language,
+ }
+ current = _weather_api_get(_CURRENT_WEATHER_URL, params=common_params)
+ forecast = None
+ if include_forecast:
+ forecast = _weather_api_get(
+ _FORECAST_URL,
+ params={**common_params, "cnt": str(forecast_count)},
+ )
+ return current, forecast
@ConnectorRegistry.register("weather")
@@ -35,8 +118,12 @@ class WeatherConnector(BaseConnector):
display_name = "Weather"
auth_type = "token"
- def __init__(self, *, token_path: str = _DEFAULT_TOKEN_PATH) -> None:
- self._token_path = Path(token_path)
+ def __init__(self, *, token_path: str | None = None) -> None:
+ self._token_path = (
+ Path(token_path)
+ if token_path is not None
+ else get_config_dir() / "connectors" / "weather.json"
+ )
self._status = SyncStatus()
def _load_config(self) -> Dict[str, str]:
@@ -44,6 +131,16 @@ class WeatherConnector(BaseConnector):
data = json.loads(self._token_path.read_text(encoding="utf-8"))
return data
+ def stored_api_key(self) -> str | None:
+ """Return the stored connector key, or ``None`` when unavailable."""
+ try:
+ value = self._load_config().get("api_key", "")
+ except (AttributeError, json.JSONDecodeError, OSError, TypeError):
+ return None
+ if not isinstance(value, str):
+ return None
+ return value.strip() or None
+
def configure(self, *, api_key: str, location: str) -> None:
"""Validate and persist the API key and required location."""
api_key = api_key.strip()
@@ -52,9 +149,11 @@ class WeatherConnector(BaseConnector):
raise ValueError("An OpenWeather API key is required")
if not location:
raise ValueError("A weather location is required")
- _weather_api_get(
- "https://api.openweathermap.org/data/2.5/weather",
- params={"q": location, "appid": api_key, "units": "imperial"},
+ fetch_weather(
+ api_key=api_key,
+ location=location,
+ units="imperial",
+ language="en",
)
from openjarvis.security.file_utils import secure_write_json
@@ -69,7 +168,7 @@ class WeatherConnector(BaseConnector):
try:
data = json.loads(self._token_path.read_text(encoding="utf-8"))
return bool(data.get("api_key"))
- except (json.JSONDecodeError, OSError):
+ except (AttributeError, json.JSONDecodeError, OSError, TypeError):
return False
def disconnect(self) -> None:
@@ -85,9 +184,13 @@ class WeatherConnector(BaseConnector):
location = config.get("location", "San Francisco,CA")
# Current weather
- current = _weather_api_get(
- "https://api.openweathermap.org/data/2.5/weather",
- params={"q": location, "appid": api_key, "units": "imperial"},
+ current, forecast = fetch_weather(
+ api_key=api_key,
+ location=location,
+ units="imperial",
+ language="en",
+ include_forecast=True,
+ forecast_count=4,
)
main = current.get("main", {})
weather_desc = ", ".join(
@@ -116,15 +219,7 @@ class WeatherConnector(BaseConnector):
)
# Forecast (next ~12 hours, 4 x 3-hour intervals)
- forecast = _weather_api_get(
- "https://api.openweathermap.org/data/2.5/forecast",
- params={
- "q": location,
- "appid": api_key,
- "units": "imperial",
- "cnt": "4",
- },
- )
+ assert forecast is not None
summaries = []
for entry in forecast.get("list", []):
dt_txt = entry.get("dt_txt", "")
@@ -148,3 +243,6 @@ class WeatherConnector(BaseConnector):
def sync_status(self) -> SyncStatus:
return self._status
+
+
+__all__ = ["WeatherAPIError", "WeatherConnector", "fetch_weather"]
diff --git a/src/openjarvis/core/config.py b/src/openjarvis/core/config.py
index 8c82022a..4e664dcf 100644
--- a/src/openjarvis/core/config.py
+++ b/src/openjarvis/core/config.py
@@ -1108,6 +1108,16 @@ class BrowserConfig:
viewport_height: int = 720
+@dataclass(slots=True)
+class WeatherToolConfig:
+ """Native weather tool settings (credentials stay outside config.toml)."""
+
+ provider: str = "openweathermap"
+ default_location: str = ""
+ units: str = "metric"
+ lang: str = "en"
+
+
@dataclass(slots=True)
class ToolsConfig:
"""Tools primitive settings — wraps storage and MCP configuration."""
@@ -1115,6 +1125,7 @@ class ToolsConfig:
storage: StorageConfig = field(default_factory=StorageConfig)
mcp: MCPConfig = field(default_factory=MCPConfig)
browser: BrowserConfig = field(default_factory=BrowserConfig)
+ weather: WeatherToolConfig = field(default_factory=WeatherToolConfig)
enabled: str = "" # comma-separated default tools
@@ -2259,6 +2270,13 @@ enabled = true
# viewport_width = 1280
# viewport_height = 720
+# Weather API credentials belong in credentials.toml or the environment, not here.
+# [tools.weather]
+# provider = "openweathermap"
+# default_location = ""
+# units = "metric" # metric or imperial
+# lang = "en" # OpenWeatherMap language code
+
[server]
# Loopback is safe for local use and works without API authentication.
host = "127.0.0.1"
@@ -2447,6 +2465,7 @@ __all__ = [
"VLLMEngineConfig",
"WebChatChannelConfig",
"WebhookChannelConfig",
+ "WeatherToolConfig",
"WhatsAppBaileysChannelConfig",
"WhatsAppChannelConfig",
"WorkflowConfig",
diff --git a/src/openjarvis/core/credentials.py b/src/openjarvis/core/credentials.py
index 7535a4be..4b3d28e5 100644
--- a/src/openjarvis/core/credentials.py
+++ b/src/openjarvis/core/credentials.py
@@ -34,6 +34,7 @@ def _default_path() -> Path:
TOOL_CREDENTIALS: dict[str, list[str]] = {
"web_search": ["TAVILY_API_KEY", "YOUDOTCOM_API_KEY"],
+ "get_weather": ["OPENWEATHERMAP_API_KEY"],
"image_generate": ["OPENAI_API_KEY"],
"slack": ["SLACK_BOT_TOKEN", "SLACK_APP_TOKEN"],
"telegram": ["TELEGRAM_BOT_TOKEN"],
diff --git a/src/openjarvis/security/capabilities.py b/src/openjarvis/security/capabilities.py
index 95fdaaaf..d5030d8a 100644
--- a/src/openjarvis/security/capabilities.py
+++ b/src/openjarvis/security/capabilities.py
@@ -171,6 +171,7 @@ class CapabilityPolicy:
DEFAULT_TOOL_CAPABILITIES: Dict[str, List[str]] = {
"file_read": [Capability.FILE_READ],
"web_search": [Capability.NETWORK_FETCH],
+ "get_weather": [Capability.NETWORK_FETCH],
"code_interpreter": [Capability.CODE_EXECUTE],
"memory_store": [Capability.MEMORY_WRITE],
"memory_retrieve": [Capability.MEMORY_READ],
diff --git a/src/openjarvis/security/data_boundary_audit.py b/src/openjarvis/security/data_boundary_audit.py
index a071d1ff..15c17c5d 100644
--- a/src/openjarvis/security/data_boundary_audit.py
+++ b/src/openjarvis/security/data_boundary_audit.py
@@ -63,6 +63,10 @@ API_KEY_ENV_VARS = {
"MINIMAX_API_KEY": ("MiniMax cloud inference", {"minimax"}),
"OPENAI_API_KEY": ("OpenAI cloud inference", {"openai", "gpt"}),
"OPENROUTER_API_KEY": ("OpenRouter cloud inference", {"openrouter"}),
+ "OPENWEATHERMAP_API_KEY": (
+ "OpenWeatherMap weather lookup",
+ {"get_weather", "openweathermap", "weather"},
+ ),
"TAVILY_API_KEY": ("Tavily web search", {"tavily", "web_search"}),
"YOUDOTCOM_API_KEY": ("You.com web search", {"youcom", "web_search"}),
}
@@ -211,6 +215,7 @@ BROWSER_TOOLS = {
"web_browser",
}
GENERIC_NETWORK_TOOLS = {"http_request"}
+WEATHER_TOOLS = {"get_weather"}
CHANNEL_OUTBOUND_TOOLS = {"channel_send"}
CLOUD_MEDIA_TOOLS = {"audio_transcribe", "image_generate", "text_to_speech"}
CLOUD_TTS_BACKENDS = {"cartesia", "openai", "openai_tts"}
@@ -221,12 +226,13 @@ EXTERNAL_TOOL_SURFACES = (
WEB_SEARCH_TOOLS
| BROWSER_TOOLS
| GENERIC_NETWORK_TOOLS
+ | WEATHER_TOOLS
| CHANNEL_OUTBOUND_TOOLS
| CLOUD_MEDIA_TOOLS
| KNOWLEDGE_ENGINE_TOOLS
)
# Narrower cloud inference / media API key surfaces (not browser-only egress).
-CLOUD_API_SURFACES = CLOUD_MEDIA_TOOLS | WEB_SEARCH_TOOLS
+CLOUD_API_SURFACES = CLOUD_MEDIA_TOOLS | WEB_SEARCH_TOOLS | WEATHER_TOOLS
OUTBOUND_TOOL_SURFACES = EXTERNAL_TOOL_SURFACES
LOCAL_ACCESS_TOOLS = {
"apply_patch",
@@ -986,6 +992,21 @@ def _audit_tool_surfaces(config: Any, builder: _FindingBuilder) -> None:
),
)
+ if tools & WEATHER_TOOLS:
+ builder.add(
+ finding_id="weather-tool-configured",
+ status="warn",
+ title="External weather lookup tool is configured",
+ potential_data_path=(
+ "user or agent location query -> OpenWeatherMap weather service"
+ ),
+ evidence=f"configured tool(s) = {_format_tools(tools & WEATHER_TOOLS)}",
+ recommendation=(
+ "Avoid sending sensitive or precise locations unless the external "
+ "weather lookup is intentional."
+ ),
+ )
+
if tools & CHANNEL_OUTBOUND_TOOLS:
builder.add(
finding_id="channel-outbound-tool-configured",
diff --git a/src/openjarvis/server/agent_manager_routes.py b/src/openjarvis/server/agent_manager_routes.py
index deb62e14..a66913ce 100644
--- a/src/openjarvis/server/agent_manager_routes.py
+++ b/src/openjarvis/server/agent_manager_routes.py
@@ -392,12 +392,16 @@ def build_tools_list() -> List[Dict[str, Any]]:
# the property descriptor and crashed on spec.description,
# silently dropping every real tool from the picker.
try:
- spec = tool_cls().spec
+ tool_instance = tool_cls()
+ spec = tool_instance.spec
except Exception as exc:
logger.debug("Could not instantiate tool %s: %s", name, exc)
spec = None
cred_keys = TOOL_CREDENTIALS.get(name, [])
has_fallback = bool(spec and spec.metadata.get("fallback"))
+ credentials_configured = (
+ spec.metadata.get("credentials_configured") if spec else None
+ )
items.append(
{
"name": name,
@@ -407,7 +411,12 @@ def build_tools_list() -> List[Dict[str, Any]]:
"requires_credentials": len(cred_keys) > 0 and not has_fallback,
"credential_keys": cred_keys,
"configured": (
- has_fallback or all(bool(os.environ.get(k)) for k in cred_keys)
+ has_fallback
+ or (
+ bool(credentials_configured)
+ if credentials_configured is not None
+ else all(bool(os.environ.get(k)) for k in cred_keys)
+ )
if cred_keys
else True
),
diff --git a/src/openjarvis/tools/__init__.py b/src/openjarvis/tools/__init__.py
index cc9f06bc..c45ad7be 100644
--- a/src/openjarvis/tools/__init__.py
+++ b/src/openjarvis/tools/__init__.py
@@ -37,6 +37,11 @@ try:
except ImportError:
pass
+try:
+ import openjarvis.tools.weather # noqa: F401
+except ImportError:
+ pass
+
try:
import openjarvis.tools.code_interpreter # noqa: F401
except ImportError:
diff --git a/src/openjarvis/tools/weather.py b/src/openjarvis/tools/weather.py
new file mode 100644
index 00000000..e8888d79
--- /dev/null
+++ b/src/openjarvis/tools/weather.py
@@ -0,0 +1,316 @@
+"""Native, parameterized weather tool backed by OpenWeatherMap."""
+
+from __future__ import annotations
+
+import json
+import math
+import re
+from datetime import datetime, timezone
+from typing import Any
+
+from openjarvis.connectors import weather as weather_connector
+from openjarvis.core.credentials import get_tool_credential
+from openjarvis.core.registry import ToolRegistry
+from openjarvis.core.types import ToolResult
+from openjarvis.tools._stubs import BaseTool, ToolSpec
+
+_TOOL_NAME = "get_weather"
+_API_KEY_ENV = "OPENWEATHERMAP_API_KEY"
+_VALID_UNITS = frozenset({"metric", "imperial"})
+_LANGUAGE_PATTERN = re.compile(r"^[a-z]{2}(?:_[a-z]{2})?$")
+_MAX_LOCATION_LENGTH = 200
+_MIN_FORECAST_HOURS = 3
+_MAX_FORECAST_HOURS = 120
+
+
+def _weather_description(payload: dict[str, Any]) -> str:
+ weather = payload.get("weather")
+ if not isinstance(weather, list):
+ return ""
+ descriptions = []
+ for entry in weather:
+ if isinstance(entry, dict):
+ description = str(entry.get("description", "")).strip()
+ if description:
+ descriptions.append(description)
+ return ", ".join(descriptions)
+
+
+def _utc_timestamp(value: Any, fallback: Any = "") -> str:
+ if isinstance(value, (int, float)) and not isinstance(value, bool):
+ try:
+ return datetime.fromtimestamp(value, tz=timezone.utc).isoformat()
+ except (OSError, OverflowError, ValueError):
+ pass
+ return str(fallback or "")
+
+
+def _structured_conditions(payload: dict[str, Any]) -> dict[str, Any]:
+ main = payload.get("main")
+ wind = payload.get("wind")
+ rain = payload.get("rain")
+ snow = payload.get("snow")
+ if not isinstance(main, dict):
+ main = {}
+ if not isinstance(wind, dict):
+ wind = {}
+ if not isinstance(rain, dict):
+ rain = {}
+ if not isinstance(snow, dict):
+ snow = {}
+ return {
+ "time": _utc_timestamp(payload.get("dt"), payload.get("dt_txt")),
+ "temperature": main.get("temp"),
+ "feels_like": main.get("feels_like"),
+ "temperature_min": main.get("temp_min"),
+ "temperature_max": main.get("temp_max"),
+ "description": _weather_description(payload),
+ "humidity_percent": main.get("humidity"),
+ "wind_speed": wind.get("speed"),
+ "wind_direction_degrees": wind.get("deg"),
+ "precipitation_probability_percent": (
+ round(float(payload["pop"]) * 100, 1)
+ if isinstance(payload.get("pop"), (int, float))
+ and not isinstance(payload.get("pop"), bool)
+ else None
+ ),
+ "rain_mm": rain.get("1h", rain.get("3h")),
+ "snow_mm": snow.get("1h", snow.get("3h")),
+ }
+
+
[email protected]("get_weather")
+class WeatherTool(BaseTool):
+ """Fetch current or forecast weather for a dynamic location."""
+
+ tool_id = _TOOL_NAME
+ is_local = False
+
+ def __init__(
+ self,
+ *,
+ api_key: str | None = None,
+ connector: weather_connector.WeatherConnector | None = None,
+ config: Any = None,
+ ) -> None:
+ self._api_key = (api_key or "").strip() or None
+ self._connector = connector or weather_connector.WeatherConnector()
+ self._config_error = False
+ if config is None:
+ try:
+ from openjarvis.core.config import load_config
+
+ config = load_config().tools.weather
+ except Exception:
+ self._config_error = True
+ config = None
+ self._provider = str(getattr(config, "provider", "openweathermap") or "")
+ self._default_location = str(
+ getattr(config, "default_location", "") or ""
+ ).strip()
+ self._default_units = str(getattr(config, "units", "metric") or "").lower()
+ self._default_language = str(getattr(config, "lang", "en") or "").lower()
+
+ def _resolve_api_key(self) -> str | None:
+ if self._api_key:
+ return self._api_key
+ try:
+ key = get_tool_credential(_TOOL_NAME, _API_KEY_ENV)
+ except (AttributeError, OSError, TypeError, ValueError):
+ key = None
+ if isinstance(key, str) and key.strip():
+ return key.strip()
+ return self._connector.stored_api_key()
+
+ def is_configured(self) -> bool:
+ """Return credential presence without exposing the credential value."""
+ return self._resolve_api_key() is not None
+
+ @property
+ def spec(self) -> ToolSpec:
+ return ToolSpec(
+ name=_TOOL_NAME,
+ description=(
+ "Get current weather and an optional forecast for a dynamic city, "
+ "region, or 'city,country-code' location. Pass the "
+ "location requested by the user; descriptions use the requested "
+ "language."
+ ),
+ parameters={
+ "type": "object",
+ "properties": {
+ "location": {
+ "type": "string",
+ "description": (
+ "Location to look up, such as 'Vienna,AT', "
+ "or 'Sankt Johann in Tirol'."
+ ),
+ },
+ "units": {
+ "type": "string",
+ "enum": sorted(_VALID_UNITS),
+ "description": (
+ "Unit system. Defaults to [tools.weather].units "
+ "(metric unless configured)."
+ ),
+ },
+ "language": {
+ "type": "string",
+ "description": (
+ "OpenWeatherMap language code such as 'en', 'de', "
+ "'fr', or 'pt_br'."
+ ),
+ },
+ "include_forecast": {
+ "type": "boolean",
+ "description": (
+ "Include 3-hour forecast intervals. Use for future, "
+ "rain, or tomorrow questions. Defaults to false."
+ ),
+ },
+ "forecast_hours": {
+ "type": "integer",
+ "minimum": _MIN_FORECAST_HOURS,
+ "maximum": _MAX_FORECAST_HOURS,
+ "description": (
+ "Forecast horizon in hours, from 3 to 120. Defaults to 24."
+ ),
+ },
+ },
+ "additionalProperties": False,
+ },
+ category="weather",
+ latency_estimate=1.0,
+ timeout_seconds=30.0,
+ required_capabilities=["network:fetch"],
+ metadata={
+ "provider": "openweathermap",
+ "requires_api_key": _API_KEY_ENV,
+ "credentials_configured": self.is_configured(),
+ },
+ )
+
+ def execute(self, **params: Any) -> ToolResult:
+ if self._config_error:
+ return self._failure("Weather configuration could not be loaded.")
+ if self._provider.lower() != "openweathermap":
+ return self._failure(
+ f"Unsupported weather provider '{self._provider}'. "
+ "Only 'openweathermap' is supported."
+ )
+
+ location_value = params.get("location", self._default_location)
+ if not isinstance(location_value, str):
+ return self._failure("Location must be a string.")
+ location = location_value.strip()
+ if not location:
+ return self._failure(
+ "A weather location is required. Pass location or configure "
+ "[tools.weather].default_location."
+ )
+ if len(location) > _MAX_LOCATION_LENGTH:
+ return self._failure(
+ f"Location must be at most {_MAX_LOCATION_LENGTH} characters."
+ )
+ if any(ord(char) < 32 or ord(char) == 127 for char in location):
+ return self._failure("Location must not contain control characters.")
+
+ units_value = params.get("units", self._default_units)
+ if not isinstance(units_value, str):
+ return self._failure("Units must be 'metric' or 'imperial'.")
+ units = units_value.strip().lower()
+ if units not in _VALID_UNITS:
+ return self._failure("Units must be 'metric' or 'imperial'.")
+
+ language_value = params.get("language", self._default_language)
+ if not isinstance(language_value, str):
+ return self._failure("Language must be an OpenWeatherMap language code.")
+ language = language_value.strip().lower()
+ if not _LANGUAGE_PATTERN.fullmatch(language):
+ return self._failure(
+ "Language must be a two-letter code with an optional region, "
+ "such as 'de' or 'pt_br'."
+ )
+
+ include_forecast = params.get("include_forecast", False)
+ if not isinstance(include_forecast, bool):
+ return self._failure("include_forecast must be true or false.")
+ forecast_hours = params.get("forecast_hours", 24)
+ if isinstance(forecast_hours, bool) or not isinstance(forecast_hours, int):
+ return self._failure("forecast_hours must be an integer from 3 to 120.")
+ if not _MIN_FORECAST_HOURS <= forecast_hours <= _MAX_FORECAST_HOURS:
+ return self._failure("forecast_hours must be between 3 and 120.")
+
+ api_key = self._resolve_api_key()
+ if not api_key:
+ return self._failure(
+ "No OpenWeatherMap API key configured. Connect the Weather "
+ f"connector or set {_API_KEY_ENV}."
+ )
+
+ forecast_count = math.ceil(forecast_hours / 3)
+ try:
+ current_payload, forecast_payload = weather_connector.fetch_weather(
+ api_key=api_key,
+ location=location,
+ units=units,
+ language=language,
+ include_forecast=include_forecast,
+ forecast_count=forecast_count,
+ )
+ except weather_connector.WeatherAPIError as exc:
+ return self._failure(f"Weather lookup failed: {exc}")
+ except Exception:
+ # Do not stringify unknown provider exceptions: request exceptions
+ # can contain the URL query and therefore the API key.
+ return self._failure("Weather lookup failed unexpectedly.")
+
+ sys_payload = current_payload.get("sys")
+ coord_payload = current_payload.get("coord")
+ if not isinstance(sys_payload, dict):
+ sys_payload = {}
+ if not isinstance(coord_payload, dict):
+ coord_payload = {}
+ result: dict[str, Any] = {
+ "provider": "openweathermap",
+ "location": {
+ "requested": location,
+ "name": current_payload.get("name"),
+ "country": sys_payload.get("country"),
+ "latitude": coord_payload.get("lat"),
+ "longitude": coord_payload.get("lon"),
+ },
+ "units": units,
+ "language": language,
+ "current": _structured_conditions(current_payload),
+ }
+ forecast_entries: list[dict[str, Any]] = []
+ if forecast_payload is not None:
+ raw_entries = forecast_payload.get("list")
+ if isinstance(raw_entries, list):
+ forecast_entries = [
+ _structured_conditions(entry)
+ for entry in raw_entries[:forecast_count]
+ if isinstance(entry, dict)
+ ]
+ result["forecast"] = forecast_entries
+
+ return ToolResult(
+ tool_name=_TOOL_NAME,
+ content=json.dumps(result, ensure_ascii=False, separators=(",", ":")),
+ success=True,
+ metadata={
+ "provider": "openweathermap",
+ "location": location,
+ "units": units,
+ "language": language,
+ "forecast_entries": len(forecast_entries),
+ },
+ )
+
+ @staticmethod
+ def _failure(message: str) -> ToolResult:
+ return ToolResult(tool_name=_TOOL_NAME, content=message, success=False)
+
+
+__all__ = ["WeatherTool"]
diff --git a/tests/core/test_config_weather.py b/tests/core/test_config_weather.py
new file mode 100644
index 00000000..67fd457a
--- /dev/null
+++ b/tests/core/test_config_weather.py
@@ -0,0 +1,33 @@
+"""Configuration coverage for the native weather tool."""
+
+from __future__ import annotations
+
+from openjarvis.core.config import load_config
+
+
+def test_weather_tool_config_loads_from_nested_toml(tmp_path):
+ config_path = tmp_path / "config.toml"
+ config_path.write_text(
+ """
+[tools]
+enabled = "get_weather"
+
+[tools.weather]
+provider = "openweathermap"
+default_location = "Vienna,AT"
+units = "imperial"
+lang = "de"
+""".strip(),
+ encoding="utf-8",
+ )
+ load_config.cache_clear()
+ try:
+ config = load_config(config_path)
+ finally:
+ load_config.cache_clear()
+
+ assert config.tools.enabled == "get_weather"
+ assert config.tools.weather.provider == "openweathermap"
+ assert config.tools.weather.default_location == "Vienna,AT"
+ assert config.tools.weather.units == "imperial"
+ assert config.tools.weather.lang == "de"
diff --git a/tests/security/test_data_boundary_audit.py b/tests/security/test_data_boundary_audit.py
index 767e8e07..823dff64 100644
--- a/tests/security/test_data_boundary_audit.py
+++ b/tests/security/test_data_boundary_audit.py
@@ -19,6 +19,7 @@ from openjarvis.security.data_boundary_audit import (
LOCAL_ACCESS_TOOLS,
OUTBOUND_TOOL_SURFACES,
RUNTIME_CREDENTIAL_ENV_KEYS,
+ WEATHER_TOOLS,
WEB_SEARCH_TOOLS,
build_data_boundary_report,
)
@@ -33,6 +34,7 @@ EXPECTED_BROWSER_TOOLS = {
}
EXPECTED_GENERIC_NETWORK_TOOLS = {"http_request"}
+EXPECTED_WEATHER_TOOLS = {"get_weather"}
EXPECTED_CHANNEL_OUTBOUND_TOOLS = {"channel_send"}
EXPECTED_CLOUD_MEDIA_TOOLS = {
"audio_transcribe",
@@ -88,6 +90,7 @@ CLASSIFIED_TOOLS = (
WEB_SEARCH_TOOLS
| BROWSER_TOOLS
| GENERIC_NETWORK_TOOLS
+ | WEATHER_TOOLS
| CHANNEL_OUTBOUND_TOOLS
| CLOUD_MEDIA_TOOLS
| KNOWLEDGE_ENGINE_TOOLS
@@ -722,11 +725,13 @@ def test_required_registered_tool_names_are_classified():
assert EXPECTED_BROWSER_TOOLS <= BROWSER_TOOLS
assert EXPECTED_LOCAL_ACCESS_TOOLS <= LOCAL_ACCESS_TOOLS
assert EXPECTED_GENERIC_NETWORK_TOOLS <= GENERIC_NETWORK_TOOLS
+ assert EXPECTED_WEATHER_TOOLS <= WEATHER_TOOLS
assert EXPECTED_CHANNEL_OUTBOUND_TOOLS <= CHANNEL_OUTBOUND_TOOLS
assert EXPECTED_CLOUD_MEDIA_TOOLS <= CLOUD_MEDIA_TOOLS
assert EXPECTED_KNOWLEDGE_ENGINE_TOOLS <= KNOWLEDGE_ENGINE_TOOLS
assert (
EXPECTED_GENERIC_NETWORK_TOOLS
+ | EXPECTED_WEATHER_TOOLS
| EXPECTED_CHANNEL_OUTBOUND_TOOLS
| EXPECTED_CLOUD_MEDIA_TOOLS
| EXPECTED_BROWSER_TOOLS
@@ -735,6 +740,40 @@ def test_required_registered_tool_names_are_classified():
assert EXPECTED_KNOWLEDGE_ENGINE_TOOLS <= EXTERNAL_TOOL_SURFACES
[email protected]("tool_name", sorted(EXPECTED_WEATHER_TOOLS))
+def test_weather_tool_produces_outbound_warn(tmp_path, tool_name):
+ config = _low_noise_config()
+ config.tools.enabled = tool_name
+
+ report = build_data_boundary_report(config, tmp_path)
+ payload = report.to_dict(show_paths=True)
+
+ findings = {finding.id: finding for finding in report.findings}
+ finding = findings["weather-tool-configured"]
+ assert finding.status == "warn"
+ assert tool_name in finding.evidence
+ assert "location query" in finding.potential_data_path
+ assert "OPENWEATHERMAP_API_KEY" not in str(payload)
+
+
+def test_openweathermap_api_key_presence_is_reported_without_value(
+ tmp_path, monkeypatch
+):
+ config = _low_noise_config()
+ config.tools.enabled = "get_weather"
+ secret = "weather-key-that-must-not-leak"
+ monkeypatch.setenv("OPENWEATHERMAP_API_KEY", secret)
+
+ report = build_data_boundary_report(config, tmp_path)
+ payload = report.to_dict(show_paths=True)
+ findings = {finding.id: finding for finding in report.findings}
+
+ finding = findings["env-credential-openweathermap_api_key"]
+ assert finding.status == "warn"
+ assert "OPENWEATHERMAP_API_KEY is set" in finding.evidence
+ assert secret not in str(payload)
+
+
def test_builtin_registry_tools_are_classified_or_explicitly_exempt():
unclassified = EXPECTED_BUILTIN_TOOLS - CLASSIFIED_TOOLS - EXPLICITLY_EXEMPT_TOOLS
assert not unclassified, (
diff --git a/tests/server/test_tools_endpoint.py b/tests/server/test_tools_endpoint.py
index 5cb81bf7..4af23591 100644
--- a/tests/server/test_tools_endpoint.py
+++ b/tests/server/test_tools_endpoint.py
@@ -61,6 +61,28 @@ def test_web_search_available_without_tavily_key(monkeypatch):
assert web_search["requires_credentials"] is False
+def test_weather_tool_picker_recognizes_connector_credential(tmp_path, monkeypatch):
+ """An existing Weather connector keeps the native tool configured."""
+ from openjarvis.server.agent_manager_routes import build_tools_list
+
+ root = tmp_path / "openjarvis-home"
+ connector_path = root / "connectors" / "weather.json"
+ connector_path.parent.mkdir(parents=True)
+ connector_path.write_text(
+ '{"api_key":"connector-key","location":"Boston,US"}',
+ encoding="utf-8",
+ )
+ monkeypatch.setenv("OPENJARVIS_HOME", str(root))
+ monkeypatch.delenv("OPENWEATHERMAP_API_KEY", raising=False)
+
+ tools = build_tools_list()
+ weather = next(t for t in tools if t["name"] == "get_weather")
+
+ assert weather["requires_credentials"] is True
+ assert weather["credential_keys"] == ["OPENWEATHERMAP_API_KEY"]
+ assert weather["configured"] is True
+
+
def test_tool_credentials_browser_lifecycle(tmp_path, monkeypatch):
"""The browser API can save, report, and remove a Tavily key.
@@ -99,3 +121,36 @@ def test_tool_credentials_browser_lifecycle(tmp_path, monkeypatch):
"TAVILY_API_KEY": False,
"YOUDOTCOM_API_KEY": False,
}
+
+
+def test_weather_tool_credentials_browser_lifecycle(tmp_path, monkeypatch):
+ """Weather credentials can be managed without entering config.toml."""
+ from fastapi import FastAPI
+ from fastapi.testclient import TestClient
+
+ from openjarvis.server.agent_manager_routes import create_agent_manager_router
+
+ monkeypatch.setenv("OPENJARVIS_HOME", str(tmp_path / "openjarvis-home"))
+ monkeypatch.delenv("OPENWEATHERMAP_API_KEY", raising=False)
+ app = FastAPI()
+ tools_router = create_agent_manager_router(MagicMock())[3]
+ app.include_router(tools_router)
+ client = TestClient(app)
+
+ saved = client.post(
+ "/v1/tools/get_weather/credentials",
+ json={"OPENWEATHERMAP_API_KEY": "weather-browser-test"},
+ )
+ assert saved.status_code == 200
+ assert saved.json() == {"saved": ["OPENWEATHERMAP_API_KEY"]}
+ assert client.get("/v1/tools/get_weather/credentials/status").json() == {
+ "OPENWEATHERMAP_API_KEY": True
+ }
+
+ deleted = client.delete(
+ "/v1/tools/get_weather/credentials/OPENWEATHERMAP_API_KEY",
+ )
+ assert deleted.status_code == 200
+ assert client.get("/v1/tools/get_weather/credentials/status").json() == {
+ "OPENWEATHERMAP_API_KEY": False
+ }
diff --git a/tests/tools/test_tool_registration.py b/tests/tools/test_tool_registration.py
index 4746e9c5..4e573e72 100644
--- a/tests/tools/test_tool_registration.py
+++ b/tests/tools/test_tool_registration.py
@@ -24,6 +24,8 @@ EXPECTED_TOOLS = {
"file_write",
# web_search.py
"web_search",
+ # weather.py
+ "get_weather",
# code_interpreter.py
"code_interpreter",
# code_interpreter_docker.py
diff --git a/tests/tools/test_weather.py b/tests/tools/test_weather.py
new file mode 100644
index 00000000..b0ab4aa0
--- /dev/null
+++ b/tests/tools/test_weather.py
@@ -0,0 +1,547 @@
+"""Tests for the native parameterized OpenWeatherMap tool."""
+
+from __future__ import annotations
+
+import importlib
+import json
+import logging
+from types import SimpleNamespace
+from unittest.mock import Mock, patch
+
+import httpx
+import pytest
+
+from openjarvis.connectors import weather as weather_connector
+from openjarvis.core.registry import ConnectorRegistry, ToolRegistry
+from openjarvis.core.types import ToolCall
+from openjarvis.security.capabilities import DEFAULT_TOOL_CAPABILITIES
+from openjarvis.tools._stubs import ToolExecutor
+from openjarvis.tools.weather import WeatherTool
+
+
+def _config(**overrides):
+ values = {
+ "provider": "openweathermap",
+ "default_location": "",
+ "units": "metric",
+ "lang": "en",
+ }
+ values.update(overrides)
+ return SimpleNamespace(**values)
+
+
+def _current_response():
+ return {
+ "dt": 1_800_000_000,
+ "name": "Wien",
+ "coord": {"lat": 48.2082, "lon": 16.3738},
+ "sys": {"country": "AT"},
+ "main": {
+ "temp": 19.5,
+ "feels_like": 19.0,
+ "temp_min": 18.0,
+ "temp_max": 21.0,
+ "humidity": 61,
+ },
+ "weather": [{"description": "leichter Regen"}],
+ "wind": {"speed": 3.4, "deg": 250},
+ "rain": {"1h": 0.4},
+ }
+
+
+def _forecast_response():
+ return {
+ "list": [
+ {
+ "dt_txt": "2027-01-15 12:00:00",
+ "main": {"temp": 20.0, "humidity": 59},
+ "weather": [{"description": "bewölkt"}],
+ "wind": {"speed": 3.0},
+ "pop": 0.375,
+ "rain": {"3h": 1.2},
+ }
+ ]
+ }
+
+
+def test_registered_and_declared_external():
+ import openjarvis.tools.weather as weather_module
+
+ weather_module = importlib.reload(weather_module)
+ assert ToolRegistry.contains("get_weather")
+ tool_cls = ToolRegistry.get("get_weather")
+ assert tool_cls is weather_module.WeatherTool
+ tool = tool_cls(api_key="test-key", config=_config())
+ assert tool.is_local is False
+ assert tool.spec.required_capabilities == ["network:fetch"]
+ assert DEFAULT_TOOL_CAPABILITIES["get_weather"] == ["network:fetch"]
+ assert tool.spec.parameters["properties"]["location"]["type"] == "string"
+ assert tool.spec.metadata["credentials_configured"] is True
+
+
[email protected]("agent_type", ["simple", "native_react", "orchestrator"])
+def test_managed_agent_resolver_instantiates_native_weather_tool(agent_type):
+ from openjarvis.agents.tool_resolver import resolve_agent_tools
+
+ ToolRegistry.register_value("get_weather", WeatherTool)
+ resolved = resolve_agent_tools(
+ {"agent_type": agent_type, "config": {"tools": ["get_weather"]}},
+ engine=None,
+ model="test-model",
+ )
+ try:
+ assert set(resolved.by_name) == {"get_weather"}
+ assert resolved.openai_specs[0]["function"]["name"] == "get_weather"
+ finally:
+ resolved.close()
+
+
+def test_tool_executor_applies_external_boundary_guard():
+ guard = Mock()
+ guard.check_outbound.side_effect = lambda call: call
+ tool = WeatherTool(api_key="test-key", config=_config())
+ executor = ToolExecutor([tool], boundary_guard=guard)
+ call = ToolCall(
+ id="weather-1",
+ name="get_weather",
+ arguments='{"location":"Vienna,AT"}',
+ )
+ with patch(
+ "openjarvis.tools.weather.weather_connector.fetch_weather",
+ return_value=(_current_response(), None),
+ ):
+ result = executor.execute(call)
+
+ assert result.success is True
+ guard.check_outbound.assert_called_once_with(call)
+
+
+def test_dynamic_location_units_language_and_structured_current():
+ tool = WeatherTool(api_key="secret-key", config=_config())
+ with patch(
+ "openjarvis.tools.weather.weather_connector.fetch_weather",
+ return_value=(_current_response(), None),
+ ) as fetch:
+ result = tool.execute(location=" Vienna,AT ", units="metric", language="de")
+
+ assert result.success is True
+ fetch.assert_called_once_with(
+ api_key="secret-key",
+ location="Vienna,AT",
+ units="metric",
+ language="de",
+ include_forecast=False,
+ forecast_count=8,
+ )
+ payload = json.loads(result.content)
+ assert payload["location"] == {
+ "requested": "Vienna,AT",
+ "name": "Wien",
+ "country": "AT",
+ "latitude": 48.2082,
+ "longitude": 16.3738,
+ }
+ assert payload["current"]["temperature"] == 19.5
+ assert payload["current"]["description"] == "leichter Regen"
+ assert payload["current"]["humidity_percent"] == 61
+ assert payload["current"]["wind_speed"] == 3.4
+ assert "secret-key" not in result.content
+ assert "secret-key" not in str(result.metadata)
+
+
+def test_forecast_is_bounded_and_structured():
+ tool = WeatherTool(api_key="test-key", config=_config())
+ with patch(
+ "openjarvis.tools.weather.weather_connector.fetch_weather",
+ return_value=(_current_response(), _forecast_response()),
+ ) as fetch:
+ result = tool.execute(
+ location="Innsbruck,AT",
+ include_forecast=True,
+ forecast_hours=25,
+ )
+
+ assert result.success is True
+ assert fetch.call_args.kwargs["forecast_count"] == 9
+ forecast = json.loads(result.content)["forecast"]
+ assert forecast[0]["time"] == "2027-01-15 12:00:00"
+ assert forecast[0]["precipitation_probability_percent"] == 37.5
+ assert forecast[0]["rain_mm"] == 1.2
+ assert result.metadata["forecast_entries"] == 1
+
+
[email protected](("hours", "expected"), [(3, 1), (25, 9), (120, 40)])
+def test_forecast_response_is_capped_when_provider_ignores_count(hours, expected):
+ tool = WeatherTool(api_key="test-key", config=_config())
+ forecast = {"list": _forecast_response()["list"] * 100}
+ with patch.object(
+ weather_connector, "fetch_weather", return_value=(_current_response(), forecast)
+ ):
+ result = tool.execute(
+ location="Vienna,AT", include_forecast=True, forecast_hours=hours
+ )
+
+ assert result.success is True
+ assert len(json.loads(result.content)["forecast"]) == expected
+ assert result.metadata["forecast_entries"] == expected
+
+
[email protected]("stored_key", [None, False, 123, [], {}, "", " "])
+def test_corrupt_connector_key_is_unconfigured_and_never_sent(
+ tmp_path, monkeypatch, stored_key
+):
+ path = tmp_path / "weather.json"
+ path.write_text(json.dumps({"api_key": stored_key}), encoding="utf-8")
+ connector = weather_connector.WeatherConnector(token_path=str(path))
+ monkeypatch.setattr("openjarvis.tools.weather.get_tool_credential", lambda *_: None)
+ tool = WeatherTool(connector=connector, config=_config())
+
+ assert tool.is_configured() is False
+ with patch.object(weather_connector, "fetch_weather") as fetch:
+ result = tool.execute(location="Vienna")
+
+ assert result.success is False
+ assert "No OpenWeatherMap API key" in result.content
+ fetch.assert_not_called()
+
+
+ "credential_toml",
+ [
+ "[get_weather]\nOPENWEATHERMAP_API_KEY = 123\n",
+ '[get_weather]\nOPENWEATHERMAP_API_KEY = ["invalid"]\n',
+ "[get_weather]\nOPENWEATHERMAP_API_KEY = true\n",
+ '[get_weather]\nOPENWEATHERMAP_API_KEY = {invalid = "key"}\n',
+ "get_weather = 123\n",
+ 'get_weather = ["invalid"]\n',
+ "get_weather = true\n",
+ ],
+)
[email protected]("connector_configured", [False, True])
+def test_malformed_tool_credentials_preserve_discovery_and_connector_fallback(
+ tmp_path, monkeypatch, credential_toml, connector_configured
+):
+ monkeypatch.setenv("OPENJARVIS_HOME", str(tmp_path))
+ monkeypatch.delenv("OPENWEATHERMAP_API_KEY", raising=False)
+ (tmp_path / "credentials.toml").write_text(credential_toml, encoding="utf-8")
+ if connector_configured:
+ connector_path = tmp_path / "connectors" / "weather.json"
+ connector_path.parent.mkdir()
+ connector_path.write_text('{"api_key":"connector-key"}', encoding="utf-8")
+ tool = WeatherTool(config=_config())
+
+ assert tool.is_configured() is connector_configured
+ assert tool.spec.metadata["credentials_configured"] is connector_configured
+ with patch.object(
+ weather_connector, "fetch_weather", return_value=(_current_response(), None)
+ ) as fetch:
+ result = tool.execute(location="Vienna,AT")
+
+ assert result.success is connector_configured
+ if connector_configured:
+ assert fetch.call_args.kwargs["api_key"] == "connector-key"
+ assert "connector-key" not in result.content
+ else:
+ assert "No OpenWeatherMap API key" in result.content
+ fetch.assert_not_called()
+ assert (tmp_path / "credentials.toml").read_text(
+ encoding="utf-8"
+ ) == credential_toml
+
+
+def test_tool_uses_fixed_endpoints_and_query_parameters():
+ tool = WeatherTool(api_key="secret-key", config=_config())
+ responses = [_current_response(), _forecast_response()]
+
+ def respond(url, *, params, timeout):
+ request = httpx.Request("GET", url, params=params)
+ return httpx.Response(200, request=request, json=responses.pop(0))
+
+ with patch.object(weather_connector.httpx, "get", side_effect=respond) as get:
+ result = tool.execute(
+ location="Vienna,AT&appid=other",
+ units="imperial",
+ language="de",
+ include_forecast=True,
+ forecast_hours=6,
+ )
+
+ assert result.success is True
+ assert [call.args[0] for call in get.call_args_list] == [
+ "https://api.openweathermap.org/data/2.5/weather",
+ "https://api.openweathermap.org/data/2.5/forecast",
+ ]
+ for call in get.call_args_list:
+ assert call.kwargs["params"]["q"] == "Vienna,AT&appid=other"
+ assert call.kwargs["params"]["appid"] == "secret-key"
+ assert call.kwargs["params"]["units"] == "imperial"
+ assert call.kwargs["params"]["lang"] == "de"
+ assert call.kwargs["timeout"] == 30.0
+ assert get.call_args_list[1].kwargs["params"]["cnt"] == "2"
+ assert "secret-key" not in result.content
+
+
+def test_config_defaults_are_used_when_arguments_are_omitted():
+ tool = WeatherTool(
+ api_key="test-key",
+ config=_config(
+ default_location="Sankt Johann in Tirol",
+ units="imperial",
+ lang="de",
+ ),
+ )
+ with patch(
+ "openjarvis.tools.weather.weather_connector.fetch_weather",
+ return_value=(_current_response(), None),
+ ) as fetch:
+ result = tool.execute()
+
+ assert result.success is True
+ assert fetch.call_args.kwargs["location"] == "Sankt Johann in Tirol"
+ assert fetch.call_args.kwargs["units"] == "imperial"
+ assert fetch.call_args.kwargs["language"] == "de"
+
+
+def test_secure_tool_credential_precedes_connector(monkeypatch):
+ connector = Mock()
+ connector.stored_api_key.return_value = "connector-key"
+ tool = WeatherTool(connector=connector, config=_config())
+ monkeypatch.setattr(
+ "openjarvis.tools.weather.get_tool_credential",
+ lambda *_args, **_kwargs: "credential-key",
+ )
+ with patch(
+ "openjarvis.tools.weather.weather_connector.fetch_weather",
+ return_value=(_current_response(), None),
+ ) as fetch:
+ result = tool.execute(location="Paris,FR")
+
+ assert result.success is True
+ assert fetch.call_args.kwargs["api_key"] == "credential-key"
+ connector.stored_api_key.assert_not_called()
+
+
+def test_existing_connector_credential_is_reused(monkeypatch):
+ connector = Mock()
+ connector.stored_api_key.return_value = "connector-key"
+ tool = WeatherTool(connector=connector, config=_config())
+ monkeypatch.setattr(
+ "openjarvis.tools.weather.get_tool_credential",
+ lambda *_args, **_kwargs: None,
+ )
+ with patch(
+ "openjarvis.tools.weather.weather_connector.fetch_weather",
+ return_value=(_current_response(), None),
+ ) as fetch:
+ result = tool.execute(location="Boston,US")
+
+ assert result.success is True
+ assert fetch.call_args.kwargs["api_key"] == "connector-key"
+
+
+def test_default_connector_path_honors_runtime_openjarvis_home(tmp_path, monkeypatch):
+ root = tmp_path / "relocated-home"
+ credential_path = root / "connectors" / "weather.json"
+ credential_path.parent.mkdir(parents=True)
+ credential_path.write_text(
+ '{"api_key":"relocated-connector-key","location":"Vienna"}',
+ encoding="utf-8",
+ )
+ monkeypatch.setenv("OPENJARVIS_HOME", str(root))
+ monkeypatch.setattr(
+ "openjarvis.tools.weather.get_tool_credential",
+ lambda *_args, **_kwargs: None,
+ )
+ tool = WeatherTool(connector=weather_connector.WeatherConnector(), config=_config())
+
+ assert tool.is_configured() is True
+ with patch(
+ "openjarvis.tools.weather.weather_connector.fetch_weather",
+ return_value=(_current_response(), None),
+ ) as fetch:
+ result = tool.execute(location="Vienna")
+
+ assert result.success is True
+ assert fetch.call_args.kwargs["api_key"] == "relocated-connector-key"
+
+
+def test_missing_credentials_fails_without_calling_provider(monkeypatch):
+ connector = Mock()
+ connector.stored_api_key.return_value = None
+ tool = WeatherTool(connector=connector, config=_config())
+ monkeypatch.setattr(
+ "openjarvis.tools.weather.get_tool_credential",
+ lambda *_args, **_kwargs: None,
+ )
+ with patch("openjarvis.tools.weather.weather_connector.fetch_weather") as fetch:
+ result = tool.execute(location="Vienna")
+
+ assert result.success is False
+ assert "OPENWEATHERMAP_API_KEY" in result.content
+ fetch.assert_not_called()
+
+
+ ("params", "expected"),
+ [
+ ({}, "location is required"),
+ ({"location": 123}, "must be a string"),
+ ({"location": "x" * 201}, "at most 200"),
+ ({"location": "Vienna\nappid=stolen"}, "control characters"),
+ ({"location": "Vienna", "units": "kelvin"}, "metric"),
+ ({"location": "Vienna", "language": "../../de"}, "two-letter"),
+ ({"location": "Vienna", "include_forecast": "yes"}, "true or false"),
+ ({"location": "Vienna", "forecast_hours": True}, "integer"),
+ ({"location": "Vienna", "forecast_hours": 121}, "between 3 and 120"),
+ ],
+)
+def test_invalid_arguments_fail_before_network(params, expected):
+ tool = WeatherTool(api_key="test-key", config=_config())
+ with patch("openjarvis.tools.weather.weather_connector.fetch_weather") as fetch:
+ result = tool.execute(**params)
+
+ assert result.success is False
+ assert expected in result.content
+ fetch.assert_not_called()
+
+
+def test_provider_error_never_exposes_api_key():
+ secret = "super-secret-weather-key"
+ tool = WeatherTool(api_key=secret, config=_config())
+ with patch(
+ "openjarvis.tools.weather.weather_connector.fetch_weather",
+ side_effect=httpx.RequestError(
+ f"request failed: https://example.test/?appid={secret}"
+ ),
+ ):
+ result = tool.execute(location="Vienna")
+
+ assert result.success is False
+ assert secret not in result.content
+ assert "unexpectedly" in result.content
+
+
+def test_http_status_error_is_credential_safe():
+ secret = "status-secret-key"
+ request = httpx.Request(
+ "GET", f"https://api.openweathermap.org/weather?appid={secret}"
+ )
+ response = httpx.Response(
+ 401,
+ request=request,
+ json={"cod": 401, "message": "Invalid API key"},
+ )
+ with patch("openjarvis.connectors.weather.httpx.get", return_value=response):
+ with pytest.raises(weather_connector.WeatherAPIError) as exc_info:
+ weather_connector._weather_api_get(
+ "https://api.openweathermap.org/weather",
+ {"appid": secret},
+ )
+
+ message = str(exc_info.value)
+ assert message == "OpenWeatherMap returned HTTP 401: authentication failed"
+ assert secret not in message
+
+
+def test_http_status_provider_message_cannot_echo_credential():
+ secret = "echoed-secret-key"
+ request = httpx.Request(
+ "GET", f"https://api.openweathermap.org/weather?appid={secret}"
+ )
+ response = httpx.Response(
+ 400,
+ request=request,
+ json={"message": f"bad appid {secret}"},
+ )
+ with patch("openjarvis.connectors.weather.httpx.get", return_value=response):
+ with pytest.raises(weather_connector.WeatherAPIError) as exc_info:
+ weather_connector._weather_api_get(
+ "https://api.openweathermap.org/weather",
+ {"appid": secret},
+ )
+
+ assert secret not in str(exc_info.value)
+ assert str(exc_info.value) == (
+ "OpenWeatherMap returned HTTP 400: the request was invalid"
+ )
+
+
+def test_request_error_is_credential_safe():
+ secret = "request-secret-key"
+ request = httpx.Request(
+ "GET", f"https://api.openweathermap.org/weather?appid={secret}"
+ )
+ with patch(
+ "openjarvis.connectors.weather.httpx.get",
+ side_effect=httpx.ConnectError("connection failed", request=request),
+ ):
+ with pytest.raises(weather_connector.WeatherAPIError) as exc_info:
+ weather_connector._weather_api_get(
+ "https://api.openweathermap.org/weather",
+ {"appid": secret},
+ )
+
+ assert str(exc_info.value) == "OpenWeatherMap could not be reached"
+ assert secret not in str(exc_info.value)
+
+
[email protected]("status", [200, 401])
+def test_httpx_request_logs_redact_key_without_changing_outbound_request(
+ caplog, monkeypatch, status
+):
+ secret = "a-weather-key/with+reserved?characters"
+ requests = []
+
+ def respond(request):
+ requests.append(request)
+ return httpx.Response(status, json=_current_response())
+
+ with httpx.Client(transport=httpx.MockTransport(respond)) as client:
+ monkeypatch.setattr(weather_connector.httpx, "get", client.get)
+ with caplog.at_level(logging.INFO, logger="httpx"):
+ result = WeatherTool(api_key=secret, config=_config()).execute(
+ location="Vienna,AT"
+ )
+
+ assert result.success is (status == 200)
+ assert requests[0].url.params["appid"] == secret
+ assert "HTTP Request:" in caplog.text
+ assert "REDACTED" in caplog.text
+ assert secret not in caplog.text
+ assert str(requests[0].url) not in caplog.text
+ assert secret not in result.content
+
+
+def test_httpx_logging_keeps_unrelated_request_urls(caplog):
+ url = "https://example.test/weather?appid=public-id"
+ with httpx.Client(
+ transport=httpx.MockTransport(lambda _: httpx.Response(200))
+ ) as c:
+ with caplog.at_level(logging.INFO, logger="httpx"):
+ c.get(url)
+
+ assert url in caplog.text
+
+
+def test_weather_tool_handles_provider_error_after_connector_registry_repopulation(
+ monkeypatch,
+):
+ """Connector reloads must not stale the tool's exception identity."""
+ from openjarvis.server.connectors_router import _ensure_connectors_registered
+
+ secret = "reload-secret-weather-key"
+ tool = WeatherTool(api_key=secret, config=_config())
+ ConnectorRegistry.clear()
+ _ensure_connectors_registered()
+
+ def fail_after_reload(**_kwargs):
+ raise weather_connector.WeatherAPIError("OpenWeatherMap could not be reached")
+
+ monkeypatch.setattr(weather_connector, "fetch_weather", fail_after_reload)
+ result = tool.execute(location="Vienna")
+
+ assert result.success is False
+ assert result.content == (
+ "Weather lookup failed: OpenWeatherMap could not be reached"
+ )
+ assert secret not in result.content