Personal AI, On Personal Devices
Python
feat(tools): add fx_macro_data tool for macro releases, calendars and FX rates
Robert Tidball40c542c3c1c8
diff --git a/docs/getting-started/configuration.md b/docs/getting-started/configuration.mdindex 45aaebf1..265cb000 100644--- a/docs/getting-started/configuration.md+++ b/docs/getting-started/configuration.md@@ -1132,6 +1132,7 @@ OpenJarvis respects the following environment variables:| `YOUDOTCOM_API_KEY` | API key for the You.com web search engine. Optional — raises the keyless free-tier limits and enables You.com Contents extraction for URL queries. || `SERPLY_API_KEY` | API key for the Serply web search engine, which proxies Google. Optional. When set and no other search key is, `auto` engine selection prefers Serply over the keyless tier. Keys: [serply.io](https://serply.io). || `SERPLY_PROXY_LOCATION` | Two-letter country code asking Serply for that country's Google result set, for example `DE`. Optional. Unset means the API answers from its own default region. See [serply.io/docs](https://serply.io/docs). |+| `FXMACRODATA_API_KEY` | API key for the `fx_macro_data` tool. Optional: recent USD releases, the USD release calendar and every currency's indicator catalogue work without it. The key unlocks other currencies, full history and FX rates. Keys: [fxmacrodata.com](https://fxmacrodata.com/subscribe). || `OPENJARVIS_WEB_SEARCH_ENGINE` | Web search engine for the `web_search` tool: `auto` (default), `youcom`, `tavily`, `serply`, or `duckduckgo`. |In the desktop app, you can save `ATLASCLOUD_API_KEY` in **Cloud Models** ordiff --git a/docs/user-guide/tools.md b/docs/user-guide/tools.mdindex 754f5447..391511ee 100644--- a/docs/user-guide/tools.md+++ b/docs/user-guide/tools.md@@ -189,6 +189,7 @@ All built-in tools are registered via `@ToolRegistry.register()` and are availab| **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 |+| **Finance** | `fx_macro_data` | Official macro releases, release calendars and FX rates via FXMacroData || **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 |@@ -415,6 +416,43 @@ enabled = "get_weather"For example, an agent can call `get_weather` with `location="Vienna,AT"`,`language="de"`, and `include_forecast=true`.+### FX and Macro Data++**Registry key:** `fx_macro_data` | **Category:** `finance`++Looks up official central-bank and statistics-office data through the+[FXMacroData](https://fxmacrodata.com/documentation) REST API: an indicator's+release history (CPI, policy rate, payrolls, GDP), the upcoming release+calendar, the indicators published for a currency, and daily FX rates. Only the+currency codes, indicator names and dates in the call leave the machine.++It works without a key for USD releases from the last 90 days (published with a+15-minute delay), the USD release calendar and every currency's indicator+catalogue. Keyless results carry those limits in a `notices` list. Set+`FXMACRODATA_API_KEY`, or save it through the tool credentials API/UI, for other+currencies, full history, real-time releases and FX rates. The key is sent as an+`X-API-Key` header, redirects are refused, and the key never appears in results+or errors.++```toml+[tools]+enabled = "fx_macro_data"+```++**Parameters:**++| Parameter | Type | Required | Description |+|-----------|------|----------|-------------|+| `action` | string | Yes | `indicator_history`, `release_calendar`, `indicator_catalogue`, or `fx_rates` |+| `currency` | string | For all but `fx_rates` | Three-letter code such as `USD` |+| `indicator` | string | For `indicator_history` | Slug such as `inflation` or `policy_rate`; optional filter for `release_calendar` |+| `base`, `quote` | string | For `fx_rates` | Currency pair such as `EUR` and `USD` |+| `start_date`, `end_date` | string | No | `YYYY-MM-DD` bounds for history and FX rates |+| `limit` | integer | No | Rows to return, 1 to 100 (default: 20) |++For calendar rows, `reference_period` is the period the figure describes, and+`release_time_utc` is when it is published.+### CodeInterpreter**Registry key:** `code_interpreter` | **Category:** `code`diff --git a/src/openjarvis/core/credentials.py b/src/openjarvis/core/credentials.pyindex c81aa1a9..5e20492c 100644--- a/src/openjarvis/core/credentials.py+++ b/src/openjarvis/core/credentials.py@@ -35,6 +35,7 @@ def _default_path() -> Path:TOOL_CREDENTIALS: dict[str, list[str]] = {"web_search": ["TAVILY_API_KEY", "YOUDOTCOM_API_KEY", "SERPLY_API_KEY"],"get_weather": ["OPENWEATHERMAP_API_KEY"],+ "fx_macro_data": ["FXMACRODATA_API_KEY"],"image_generate": ["OPENAI_API_KEY"],"slack": ["SLACK_BOT_TOKEN", "SLACK_APP_TOKEN"],"telegram": ["TELEGRAM_BOT_TOKEN"],@@ -75,6 +76,9 @@ TOOL_CREDENTIALS: dict[str, list[str]] = {# result quality.OPTIONAL_TOOL_CREDENTIALS: dict[str, frozenset[str]] = {"web_search": frozenset({"TAVILY_API_KEY", "YOUDOTCOM_API_KEY", "SERPLY_API_KEY"}),+ # Recent USD releases, the USD calendar and every catalogue are keyless;+ # the key unlocks other currencies, full history and FX rates.+ "fx_macro_data": frozenset({"FXMACRODATA_API_KEY"}),}diff --git a/src/openjarvis/security/capabilities.py b/src/openjarvis/security/capabilities.pyindex 5e655cf2..dc8f529c 100644--- a/src/openjarvis/security/capabilities.py+++ b/src/openjarvis/security/capabilities.py@@ -241,6 +241,7 @@ DEFAULT_TOOL_CAPABILITIES: Dict[str, List[str]] = {"file_read": [Capability.FILE_READ],"file_write": [Capability.FILE_WRITE],"get_pending_actions": [Capability.MEMORY_READ],+ "fx_macro_data": [Capability.NETWORK_FETCH],"get_weather": [Capability.NETWORK_FETCH],"git_commit": [Capability.FILE_WRITE],"git_diff": [Capability.FILE_READ],diff --git a/src/openjarvis/security/data_boundary_audit.py b/src/openjarvis/security/data_boundary_audit.pyindex 82177274..eb865045 100644--- a/src/openjarvis/security/data_boundary_audit.py+++ b/src/openjarvis/security/data_boundary_audit.py@@ -58,6 +58,10 @@ API_KEY_ENV_VARS = {{"cartesia", "text_to_speech"},),"DEEPSEEK_API_KEY": ("DeepSeek cloud inference", {"deepseek"}),+ "FXMACRODATA_API_KEY": (+ "FXMacroData macro and FX data lookup",+ {"fx_macro_data", "fxmacrodata"},+ ),"GEMINI_API_KEY": ("Google/Gemini cloud inference", {"google", "gemini"}),"GOOGLE_API_KEY": ("Google/Gemini cloud inference", {"google", "gemini"}),"MINIMAX_API_KEY": ("MiniMax cloud inference", {"minimax"}),@@ -217,6 +221,7 @@ BROWSER_TOOLS = {}GENERIC_NETWORK_TOOLS = {"http_request"}WEATHER_TOOLS = {"get_weather"}+MARKET_DATA_TOOLS = {"fx_macro_data"}CHANNEL_OUTBOUND_TOOLS = {"channel_send"}CLOUD_MEDIA_TOOLS = {"audio_transcribe", "image_generate", "text_to_speech"}CLOUD_TTS_BACKENDS = {"cartesia", "openai", "openai_tts"}@@ -228,12 +233,15 @@ EXTERNAL_TOOL_SURFACES = (| BROWSER_TOOLS| GENERIC_NETWORK_TOOLS| WEATHER_TOOLS+ | MARKET_DATA_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 | WEATHER_TOOLS+CLOUD_API_SURFACES = (+ CLOUD_MEDIA_TOOLS | WEB_SEARCH_TOOLS | WEATHER_TOOLS | MARKET_DATA_TOOLS+)OUTBOUND_TOOL_SURFACES = EXTERNAL_TOOL_SURFACESLOCAL_ACCESS_TOOLS = {"apply_patch",@@ -1008,6 +1016,23 @@ def _audit_tool_surfaces(config: Any, builder: _FindingBuilder) -> None:),)+ if tools & MARKET_DATA_TOOLS:+ builder.add(+ finding_id="market-data-tool-configured",+ status="warn",+ title="External market data lookup tool is configured",+ potential_data_path=(+ "currency, indicator and date arguments -> FXMacroData API"+ ),+ evidence=(+ f"configured tool(s) = {_format_tools(tools & MARKET_DATA_TOOLS)}"+ ),+ recommendation=(+ "Only currency codes, indicator names and dates leave the machine; "+ "keep the tool disabled if no external lookup is wanted."+ ),+ )+if tools & CHANNEL_OUTBOUND_TOOLS:builder.add(finding_id="channel-outbound-tool-configured",diff --git a/src/openjarvis/tools/__init__.py b/src/openjarvis/tools/__init__.pyindex c45ad7be..ddbc60d8 100644--- a/src/openjarvis/tools/__init__.py+++ b/src/openjarvis/tools/__init__.py@@ -42,6 +42,11 @@ try:except ImportError:pass+try:+ import openjarvis.tools.fx_macro # noqa: F401+except ImportError:+ pass+try:import openjarvis.tools.code_interpreter # noqa: F401except ImportError:diff --git a/src/openjarvis/tools/fx_macro.py b/src/openjarvis/tools/fx_macro.pynew file mode 100644index 00000000..d896e6ae--- /dev/null+++ b/src/openjarvis/tools/fx_macro.py@@ -0,0 +1,376 @@+"""Native FX and macroeconomic data tool backed by the FXMacroData REST API.++The tool answers four kinds of question: the release history of one indicator+(CPI, policy rate, payrolls, GDP...), the upcoming release calendar, the list of+indicators published for a currency, and daily FX rates. USD releases from the+last 90 days, the USD calendar and every currency's catalogue answer without a+key; other currencies, full history and FX rates need ``FXMACRODATA_API_KEY``.+"""++from __future__ import annotations++import json+import re+from datetime import date+from typing import Any++import httpx++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 = "fx_macro_data"+_API_KEY_ENV = "FXMACRODATA_API_KEY"+_BASE_URL = "https://api.fxmacrodata.com/v1"+_ACTIONS = ("indicator_history", "release_calendar", "indicator_catalogue", "fx_rates")+_CURRENCY_PATTERN = re.compile(r"^[A-Za-z]{3}$")+_SLUG_PATTERN = re.compile(r"^[a-z0-9_]{1,64}$")+_DATE_PATTERN = re.compile(r"^\d{4}-\d{2}-\d{2}$")+_MAX_LIMIT = 100+_DEFAULT_LIMIT = 20+_STATUS_DETAILS = {+ 400: "the request was invalid",+ 401: "an API key is required for this request, or the key was rejected",+ 403: "the API key does not cover this request",+ 404: "the currency or indicator was not found",+ 422: "the request parameters were rejected",+ 429: "the rate limit was exceeded",+}+++class FXMacroDataError(RuntimeError):+ """A credential-safe error from the FXMacroData API."""+++def _api_get(path: str, params: dict[str, str], api_key: str | None) -> Any:+ """GET one fixed API path. Redirects are refused so the key never moves."""+ headers = {"Accept": "application/json"}+ if api_key:+ headers["X-API-Key"] = api_key+ try:+ resp = httpx.get(+ f"{_BASE_URL}{path}",+ params=params,+ headers=headers,+ timeout=30.0,+ follow_redirects=False,+ )+ except httpx.HTTPError:+ # Transport errors can format the request; never interpolate them.+ raise FXMacroDataError("FXMacroData could not be reached") from None+ if resp.is_redirect:+ raise FXMacroDataError("FXMacroData answered with an unexpected redirect")+ if resp.status_code != 200:+ detail = _STATUS_DETAILS.get(resp.status_code, "the request failed")+ raise FXMacroDataError(+ f"FXMacroData returned HTTP {resp.status_code}: {detail}"+ )+ try:+ payload = resp.json()+ except ValueError:+ raise FXMacroDataError("FXMacroData returned a non-JSON response") from None+ if not isinstance(payload, dict):+ raise FXMacroDataError("FXMacroData returned an unexpected response shape")+ if "detail" in payload and "data" not in payload:+ raise FXMacroDataError("FXMacroData returned an error response")+ return payload+++def _currency(value: Any, field: str) -> str:+ if not isinstance(value, str) or not _CURRENCY_PATTERN.fullmatch(value.strip()):+ raise ValueError(f"{field} must be a three-letter currency code such as USD.")+ return value.strip().lower()+++def _slug(value: Any, field: str) -> str:+ text = value.strip().lower() if isinstance(value, str) else ""+ if not _SLUG_PATTERN.fullmatch(text):+ raise ValueError(+ f"{field} must be an indicator slug such as 'inflation' or "+ "'policy_rate'; use action='indicator_catalogue' to list them."+ )+ return text+++def _date(value: Any, field: str) -> date | None:+ if value is None:+ return None+ text = value.strip() if isinstance(value, str) else ""+ if not _DATE_PATTERN.fullmatch(text):+ raise ValueError(f"{field} must be a date in YYYY-MM-DD form.")+ try:+ return date.fromisoformat(text)+ except ValueError:+ raise ValueError(f"{field} is not a real calendar date.") from None+++def _date_params(params: dict[str, Any]) -> dict[str, str]:+ start = _date(params.get("start_date"), "start_date")+ end = _date(params.get("end_date"), "end_date")+ if start and end and start > end:+ raise ValueError("start_date must be on or before end_date.")+ out = {}+ if start:+ out["start_date"] = start.isoformat()+ if end:+ out["end_date"] = end.isoformat()+ return out+++def _limit(value: Any) -> int:+ if value is None:+ return _DEFAULT_LIMIT+ if isinstance(value, bool) or not isinstance(value, int):+ raise ValueError(f"limit must be an integer from 1 to {_MAX_LIMIT}.")+ if not 1 <= value <= _MAX_LIMIT:+ raise ValueError(f"limit must be between 1 and {_MAX_LIMIT}.")+ return value+++def _rows(payload: dict[str, Any]) -> list[Any]:+ rows = payload.get("data")+ if not isinstance(rows, list):+ raise FXMacroDataError("FXMacroData returned no data list")+ return rows+++def _pagination(payload: dict[str, Any]) -> dict[str, Any] | None:+ """Return pagination, rejecting a present but malformed object."""+ if "pagination" not in payload:+ return None+ page = payload["pagination"]+ if not isinstance(page, dict) or not isinstance(page.get("has_more"), bool):+ raise FXMacroDataError("FXMacroData returned malformed pagination")+ return {"has_more": page["has_more"], "total_count": page.get("total_count")}+++def _notices(payload: dict[str, Any]) -> list[str]:+ """Surface the keyless 90-day window and 15-minute delay when they apply."""+ notices = []+ for field in ("freemium_window", "freemium_delay"):+ block = payload.get(field)+ if isinstance(block, dict) and block.get("applied") is True:+ message = block.get("message")+ if isinstance(message, str) and message.strip():+ notices.append(message.strip())+ return notices+++def _indicator_history(params: dict[str, Any], api_key: str | None) -> dict:+ currency = _currency(params.get("currency"), "currency")+ indicator = _slug(params.get("indicator"), "indicator")+ query = {**_date_params(params), "limit": str(_limit(params.get("limit")))}+ payload = _api_get(f"/announcements/{currency}/{indicator}", query, api_key)+ rows = [row for row in _rows(payload) if isinstance(row, dict)]+ return {+ "currency": currency.upper(),+ "indicator": indicator,+ "name": payload.get("name"),+ "source": payload.get("source"),+ "releases": [+ {+ "period": row.get("date"),+ "value": row.get("val"),+ "previous_value": row.get("previous_value"),+ "announced_at_utc": row.get("announcement_datetime"),+ "announced_at_local": row.get("announcement_datetime_local"),+ "source_url": row.get("source_url"),+ }+ for row in rows+ ],+ "pagination": _pagination(payload),+ "notices": _notices(payload),+ }+++def _release_calendar(params: dict[str, Any], api_key: str | None) -> dict:+ currency = _currency(params.get("currency"), "currency")+ query = {}+ if params.get("indicator") is not None:+ query["indicator"] = _slug(params.get("indicator"), "indicator")+ limit = _limit(params.get("limit"))+ payload = _api_get(f"/calendar/{currency}", query, api_key)+ rows = [row for row in _rows(payload) if isinstance(row, dict)]+ return {+ "currency": currency.upper(),+ "events": [+ {+ "release": row.get("release"),+ "name": row.get("name"),+ "release_time_utc": row.get("announcement_datetime_utc"),+ "reference_period": row.get("date"),+ "importance": row.get("event_importance"),+ }+ for row in rows[:limit]+ ],+ "notices": _notices(payload),+ }+++def _indicator_catalogue(params: dict[str, Any], api_key: str | None) -> dict:+ currency = _currency(params.get("currency"), "currency")+ payload = _api_get(f"/data_catalogue/{currency}", {}, api_key)+ indicators = []+ for slug, meta in payload.items():+ if not isinstance(meta, dict):+ continue+ coverage = meta.get("coverage")+ coverage = coverage if isinstance(coverage, dict) else {}+ indicators.append(+ {+ "indicator": slug,+ "name": meta.get("name"),+ "unit": meta.get("unit"),+ "latest_available_date": coverage.get("latest_available_date"),+ "requires_api_key": coverage.get("requires_api_key"),+ }+ )+ if not indicators:+ raise FXMacroDataError("FXMacroData returned an empty catalogue")+ return {"currency": currency.upper(), "indicators": indicators}+++def _fx_rates(params: dict[str, Any], api_key: str | None) -> dict:+ base = _currency(params.get("base"), "base")+ quote = _currency(params.get("quote"), "quote")+ query = {**_date_params(params), "limit": str(_limit(params.get("limit")))}+ payload = _api_get(f"/forex/{base}/{quote}", query, api_key)+ rows = [row for row in _rows(payload) if isinstance(row, dict)]+ return {+ "pair": f"{base.upper()}/{quote.upper()}",+ "rates": [{"date": row.get("date"), "rate": row.get("val")} for row in rows],+ "pagination": _pagination(payload),+ }+++_HANDLERS = {+ "indicator_history": _indicator_history,+ "release_calendar": _release_calendar,+ "indicator_catalogue": _indicator_catalogue,+ "fx_rates": _fx_rates,+}++[email protected](_TOOL_NAME)+class FXMacroDataTool(BaseTool):+ """Look up official macroeconomic releases, release calendars and FX rates."""++ tool_id = _TOOL_NAME+ is_local = False++ def __init__(self, *, api_key: str | None = None) -> None:+ self._api_key = (api_key or "").strip() or None++ 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):+ return None+ if isinstance(key, str) and key.strip():+ return key.strip()+ return None++ @property+ def spec(self) -> ToolSpec:+ return ToolSpec(+ name=_TOOL_NAME,+ description=(+ "Official central-bank and statistics-office data for 22 "+ "currencies: an indicator's release history (CPI, policy rate, "+ "payrolls, GDP...), the upcoming release calendar, the list of "+ "indicators for a currency, and daily FX rates. USD releases "+ "from the last 90 days, the USD calendar and every catalogue "+ "work without an API key; other currencies, full history and "+ "FX rates need FXMACRODATA_API_KEY."+ ),+ parameters={+ "type": "object",+ "properties": {+ "action": {+ "type": "string",+ "enum": list(_ACTIONS),+ "description": "Which lookup to run.",+ },+ "currency": {+ "type": "string",+ "description": "Three-letter currency code, such as USD.",+ },+ "indicator": {+ "type": "string",+ "description": (+ "Indicator slug such as 'inflation' or 'policy_rate'. "+ "Required for indicator_history; optional filter for "+ "release_calendar."+ ),+ },+ "base": {+ "type": "string",+ "description": "Base currency for fx_rates, such as EUR.",+ },+ "quote": {+ "type": "string",+ "description": "Quote currency for fx_rates, such as USD.",+ },+ "start_date": {+ "type": "string",+ "description": "Optional start date, YYYY-MM-DD.",+ },+ "end_date": {+ "type": "string",+ "description": "Optional end date, YYYY-MM-DD.",+ },+ "limit": {+ "type": "integer",+ "minimum": 1,+ "maximum": _MAX_LIMIT,+ "description": "Maximum rows to return (default 20).",+ },+ },+ "required": ["action"],+ "additionalProperties": False,+ },+ category="finance",+ latency_estimate=1.0,+ timeout_seconds=30.0,+ required_capabilities=["network:fetch"],+ metadata={+ "provider": "fxmacrodata",+ "optional_api_key": _API_KEY_ENV,+ "credentials_configured": self._resolve_api_key() is not None,+ },+ )++ def execute(self, **params: Any) -> ToolResult:+ handler = _HANDLERS.get(params.get("action"))+ if handler is None:+ return self._failure(f"action must be one of: {', '.join(_ACTIONS)}.")+ api_key = self._resolve_api_key()+ try:+ result = handler(params, api_key)+ except ValueError as exc:+ return self._failure(str(exc))+ except FXMacroDataError as exc:+ return self._failure(f"FXMacroData lookup failed: {exc}")+ except Exception:+ return self._failure("FXMacroData lookup failed unexpectedly.")+ content = json.dumps(result, ensure_ascii=False, separators=(",", ":"))+ if api_key:+ # Never hand the key back, even if the API echoed it in a field.+ content = content.replace(api_key, "[REDACTED]")+ return ToolResult(+ tool_name=_TOOL_NAME,+ content=content,+ success=True,+ metadata={"provider": "fxmacrodata", "action": params["action"]},+ )++ @staticmethod+ def _failure(message: str) -> ToolResult:+ return ToolResult(tool_name=_TOOL_NAME, content=message, success=False)+++__all__ = ["FXMacroDataTool"]diff --git a/tests/security/test_data_boundary_audit.py b/tests/security/test_data_boundary_audit.pyindex 2214b4da..a7b9bf4a 100644--- a/tests/security/test_data_boundary_audit.py+++ b/tests/security/test_data_boundary_audit.py@@ -17,6 +17,7 @@ from openjarvis.security.data_boundary_audit import (GENERIC_NETWORK_TOOLS,KNOWLEDGE_ENGINE_TOOLS,LOCAL_ACCESS_TOOLS,+ MARKET_DATA_TOOLS,OUTBOUND_TOOL_SURFACES,RUNTIME_CREDENTIAL_ENV_KEYS,WEATHER_TOOLS,@@ -35,6 +36,7 @@ EXPECTED_BROWSER_TOOLS = {EXPECTED_GENERIC_NETWORK_TOOLS = {"http_request"}EXPECTED_WEATHER_TOOLS = {"get_weather"}+EXPECTED_MARKET_DATA_TOOLS = {"fx_macro_data"}EXPECTED_CHANNEL_OUTBOUND_TOOLS = {"channel_send"}EXPECTED_CLOUD_MEDIA_TOOLS = {"audio_transcribe",@@ -91,6 +93,7 @@ CLASSIFIED_TOOLS = (| BROWSER_TOOLS| GENERIC_NETWORK_TOOLS| WEATHER_TOOLS+ | MARKET_DATA_TOOLS| CHANNEL_OUTBOUND_TOOLS| CLOUD_MEDIA_TOOLS| KNOWLEDGE_ENGINE_TOOLS@@ -756,6 +759,38 @@ def test_weather_tool_produces_outbound_warn(tmp_path, tool_name):assert "OPENWEATHERMAP_API_KEY" not in str(payload)+def test_market_data_tool_produces_outbound_warn(tmp_path):+ assert EXPECTED_MARKET_DATA_TOOLS <= MARKET_DATA_TOOLS <= OUTBOUND_TOOL_SURFACES+ config = _low_noise_config()+ config.tools.enabled = "fx_macro_data"++ report = build_data_boundary_report(config, tmp_path)+ findings = {finding.id: finding for finding in report.findings}++ finding = findings["market-data-tool-configured"]+ assert finding.status == "warn"+ assert "fx_macro_data" in finding.evidence+ assert "FXMacroData" in finding.potential_data_path+++def test_fxmacrodata_api_key_presence_is_reported_without_value(+ tmp_path, monkeypatch+):+ config = _low_noise_config()+ config.tools.enabled = "fx_macro_data"+ secret = "fxmacrodata-key-that-must-not-leak"+ monkeypatch.setenv("FXMACRODATA_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-fxmacrodata_api_key"]+ assert finding.status == "warn"+ assert "FXMACRODATA_API_KEY is set" in finding.evidence+ assert secret not in str(payload)++def test_openweathermap_api_key_presence_is_reported_without_value(tmp_path, monkeypatch):diff --git a/tests/tools/test_fx_macro.py b/tests/tools/test_fx_macro.pynew file mode 100644index 00000000..837bb7c3--- /dev/null+++ b/tests/tools/test_fx_macro.py@@ -0,0 +1,245 @@+"""Tests for the native FXMacroData macro and FX data tool."""++from __future__ import annotations++import importlib+import json+from unittest.mock import patch++import httpx+import pytest++from openjarvis.core.credentials import get_required_credentials, is_credential_optional+from openjarvis.core.registry import ToolRegistry+from openjarvis.security.capabilities import DEFAULT_TOOL_CAPABILITIES+from openjarvis.tools.fx_macro import FXMacroDataTool++_KEY = "fxmd-secret-key-123456"+_GET = "openjarvis.tools.fx_macro.httpx.get"+++def _response(status=200, body=None, *, text=None, headers=None):+ request = httpx.Request("GET", "https://api.fxmacrodata.com/v1/x")+ if text is not None:+ return httpx.Response(status, text=text, headers=headers, request=request)+ return httpx.Response(status, json=body, headers=headers, request=request)+++def _history_payload(**extra):+ payload = {+ "name": "Inflation (CPI)",+ "source": "BLS",+ "pagination": {"has_more": False, "total_count": 1},+ "freemium_window": {+ "applied": True,+ "message": "Anonymous access returns the most recent 90 days.",+ },+ "freemium_delay": {+ "applied": True,+ "message": "Free access is delayed by 15 minutes.",+ },+ "data": [+ {+ "date": "2026-08-31",+ "val": 3.4,+ "previous_value": 3.4,+ "announcement_datetime": 1789129800,+ "announcement_datetime_local": "2026-09-11T08:30:00-04:00",+ "source_url": "https://www.bls.gov/",+ }+ ],+ }+ payload.update(extra)+ return payload++[email protected](autouse=True)+def _no_ambient_key(monkeypatch):+ monkeypatch.delenv("FXMACRODATA_API_KEY", raising=False)+ monkeypatch.setattr(+ "openjarvis.tools.fx_macro.get_tool_credential", lambda *a, **k: None+ )+++def _run(tool=None, **params):+ tool = tool or FXMacroDataTool()+ return tool.execute(**params)+++def test_registered_with_network_capability_and_optional_key():+ import openjarvis.tools.fx_macro as module++ module = importlib.reload(module)+ assert ToolRegistry.get("fx_macro_data") is module.FXMacroDataTool+ tool = module.FXMacroDataTool()+ assert tool.is_local is False+ assert tool.spec.required_capabilities == ["network:fetch"]+ assert DEFAULT_TOOL_CAPABILITIES["fx_macro_data"] == ["network:fetch"]+ assert tool.spec.metadata["credentials_configured"] is False+ assert is_credential_optional("fx_macro_data", "FXMACRODATA_API_KEY")+ assert get_required_credentials("fx_macro_data") == []+++def test_keyless_history_sends_no_key_refuses_redirects_and_keeps_notices():+ with patch(_GET, return_value=_response(body=_history_payload())) as get:+ result = _run(action="indicator_history", currency=" usd ",+ indicator="Inflation", start_date="2026-07-01",+ end_date="2026-09-30", limit=5)+ assert result.success, result.content+ args, kwargs = get.call_args+ assert args[0] == "https://api.fxmacrodata.com/v1/announcements/usd/inflation"+ assert "X-API-Key" not in kwargs["headers"]+ assert kwargs["follow_redirects"] is False+ assert kwargs["params"] == {+ "start_date": "2026-07-01", "end_date": "2026-09-30", "limit": "5"+ }+ data = json.loads(result.content)+ assert data["releases"][0]["value"] == 3.4+ assert data["releases"][0]["period"] == "2026-08-31"+ assert data["pagination"] == {"has_more": False, "total_count": 1}+ assert len(data["notices"]) == 2+++def test_key_from_credentials_is_sent_as_header_and_never_returned(monkeypatch):+ monkeypatch.setattr(+ "openjarvis.tools.fx_macro.get_tool_credential", lambda *a, **k: f" {_KEY} "+ )+ body = _history_payload()+ body["data"][0]["source_url"] = f"https://example.test/?k={_KEY}"+ with patch(_GET, return_value=_response(body=body)) as get:+ result = _run(action="indicator_history", currency="EUR",+ indicator="policy_rate")+ assert get.call_args.kwargs["headers"]["X-API-Key"] == _KEY+ assert result.success+ assert _KEY not in result.content+ assert "[REDACTED]" in result.content+ assert FXMacroDataTool().spec.metadata["credentials_configured"] is True++[email protected]("status", [301, 302, 307, 308])+def test_redirect_is_an_error(status):+ response = _response(status, text="", headers={"location": "http://evil.test/"})+ with patch(_GET, return_value=response):+ result = _run(FXMacroDataTool(api_key=_KEY), action="release_calendar",+ currency="USD")+ assert not result.success+ assert "redirect" in result.content+ assert _KEY not in result.content++[email protected]("status", [401, 403, 404, 422, 429, 500])+def test_http_errors_are_clean_and_do_not_echo_the_body(status):+ response = _response(status, body={"detail": f"bad key {_KEY}"})+ with patch(_GET, return_value=response):+ result = _run(FXMacroDataTool(api_key=_KEY), action="fx_rates",+ base="EUR", quote="USD")+ assert not result.success+ assert f"HTTP {status}" in result.content+ assert _KEY not in result.content+++def test_transport_error_text_is_never_interpolated():+ error = httpx.ConnectError(f"failed for X-API-Key={_KEY}")+ with patch(_GET, side_effect=error):+ result = _run(FXMacroDataTool(api_key=_KEY), action="indicator_catalogue",+ currency="USD")+ assert not result.success+ assert result.content == "FXMacroData lookup failed: FXMacroData could not be reached"+++def test_unexpected_exception_is_generic():+ with patch(_GET, side_effect=RuntimeError(_KEY)):+ result = _run(action="indicator_catalogue", currency="USD")+ assert result.content == "FXMacroData lookup failed unexpectedly."+++ "response",+ [+ _response(text="<html>oops</html>"),+ _response(body=[1, 2]),+ _response(body={"detail": "This endpoint requires an API key"}),+ _response(body={"data": {"not": "a list"}}),+ _response(body=_history_payload(pagination=[])),+ _response(body=_history_payload(pagination={"has_more": "no"})),+ ],+)+def test_bad_200_bodies_are_errors(response):+ with patch(_GET, return_value=response):+ result = _run(action="indicator_history", currency="USD",+ indicator="inflation")+ assert not result.success+ assert result.content.startswith("FXMacroData lookup failed:")+++ ("params", "message"),+ [+ ({"action": "nope"}, "action must be one of"),+ ({"action": "indicator_history", "currency": "US", "indicator": "cpi"},+ "three-letter"),+ ({"action": "indicator_history", "currency": "USD", "indicator": "c p i"},+ "indicator slug"),+ ({"action": "indicator_history", "currency": "USD"}, "indicator slug"),+ ({"action": "indicator_history", "currency": "USD", "indicator": "cpi",+ "start_date": "2026/01/01"}, "YYYY-MM-DD"),+ ({"action": "indicator_history", "currency": "USD", "indicator": "cpi",+ "start_date": "2026-02-30"}, "real calendar date"),+ ({"action": "indicator_history", "currency": "USD", "indicator": "cpi",+ "start_date": "2026-05-01", "end_date": "2026-04-01"}, "on or before"),+ ({"action": "indicator_history", "currency": "USD", "indicator": "cpi",+ "limit": 101}, "between 1 and 100"),+ ({"action": "indicator_history", "currency": "USD", "indicator": "cpi",+ "limit": True}, "integer"),+ ({"action": "fx_rates", "base": "EUR"}, "quote must be"),+ ],+)+def test_invalid_input_never_calls_the_api(params, message):+ with patch(_GET) as get:+ result = _run(**params)+ assert not result.success+ assert message in result.content+ get.assert_not_called()+++def test_calendar_filters_and_truncates_to_limit():+ rows = [+ {"release": f"r{i}", "name": "Payrolls",+ "announcement_datetime_utc": "2026-10-09T12:30:00+00:00",+ "date": "2026-09-30", "event_importance": "high"}+ for i in range(5)+ ]+ with patch(_GET, return_value=_response(body={"data": rows})) as get:+ result = _run(action="release_calendar", currency="USD",+ indicator="non_farm_payrolls", limit=2)+ assert get.call_args.kwargs["params"] == {"indicator": "non_farm_payrolls"}+ events = json.loads(result.content)["events"]+ assert [e["release"] for e in events] == ["r0", "r1"]+ assert events[0]["reference_period"] == "2026-09-30"+++def test_catalogue_is_summarised_and_empty_is_an_error():+ body = {"inflation": {"name": "Inflation (CPI)", "unit": "%",+ "coverage": {"latest_available_date": "2026-08-31",+ "requires_api_key": False}}}+ with patch(_GET, return_value=_response(body=body)):+ result = _run(action="indicator_catalogue", currency="usd")+ assert json.loads(result.content)["indicators"] == [{+ "indicator": "inflation", "name": "Inflation (CPI)", "unit": "%",+ "latest_available_date": "2026-08-31", "requires_api_key": False,+ }]+ with patch(_GET, return_value=_response(body={})):+ assert not _run(action="indicator_catalogue", currency="usd").success+++def test_fx_rates_map_rows():+ body = {"data": [{"date": "2026-10-06", "val": 1.0931}],+ "pagination": {"has_more": True, "total_count": 300}}+ with patch(_GET, return_value=_response(body=body)) as get:+ result = _run(FXMacroDataTool(api_key=_KEY), action="fx_rates",+ base="eur", quote="usd", limit=1)+ assert get.call_args.args[0].endswith("/forex/eur/usd")+ data = json.loads(result.content)+ assert data["pair"] == "EUR/USD"+ assert data["rates"] == [{"date": "2026-10-06", "rate": 1.0931}]+ assert data["pagination"]["has_more"] is Truediff --git a/tests/tools/test_tool_registration.py b/tests/tools/test_tool_registration.pyindex 4e573e72..ce1cf7ee 100644--- a/tests/tools/test_tool_registration.py+++ b/tests/tools/test_tool_registration.py@@ -26,6 +26,8 @@ EXPECTED_TOOLS = {"web_search",# weather.py"get_weather",+ # fx_macro.py+ "fx_macro_data",# code_interpreter.py"code_interpreter",# code_interpreter_docker.py