Skip to content

Building AI agents, atomically

Add FXMacroData tool to the Atomic Forge

Robert Tidball79f02c32a369
diff --git a/AGENTS.md b/AGENTS.md
index ac320a4..82972be 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -100,6 +100,7 @@ Each example is self-contained and demonstrates specific patterns and capabiliti
- `calculator/` - Mathematical computation tool
- `datetime_tool/` - Timezone-aware now / parse / convert / shift / diff
- `fia_signals/` - Crypto market intelligence (regime, signals, yields, gas, trending, wallet risk)
+- `fxmacrodata/` - Macroeconomic releases, release calendars, FX rates, and COT positioning via the FXMacroData API
- `hackernews_search/` - Hacker News search via the free Algolia API
- `pdf_reader/` - PDF text + metadata extraction (local file or URL, page-range support)
- `searxng_search/` - Privacy-focused search integration
diff --git a/README.md b/README.md
index 270f558..81bc8e4 100644
--- a/README.md
+++ b/README.md
@@ -349,6 +349,7 @@ Atomic Forge is a collection of tools that can be used with Atomic Agents to ext
- Calculator
- DateTime
- Fía Signals
+- FXMacroData
- Hacker News Search
- PDF Reader
- SearXNG Search
diff --git a/atomic-forge/README.md b/atomic-forge/README.md
index d34c5a0..ea4084a 100644
--- a/atomic-forge/README.md
+++ b/atomic-forge/README.md
@@ -18,6 +18,7 @@ The Atomic Forge project includes the following tools:
- [Calculator](/atomic-forge/tools/calculator/README.md)
- [DateTime](/atomic-forge/tools/datetime_tool/README.md) — timezone-aware now/parse/convert/shift/diff.
- [Fía Signals](/atomic-forge/tools/fia_signals/README.md)
+- [FXMacroData](/atomic-forge/tools/fxmacrodata/README.md)
- [Hacker News Search](/atomic-forge/tools/hackernews_search/README.md) — search HN stories, comments, Show HN, Ask HN via the free Algolia API.
- [PDF Reader](/atomic-forge/tools/pdf_reader/README.md) — extract text and metadata from a local or remote PDF, with page-range filtering.
- [SearXNG Search](/atomic-forge/tools/searxng_search/README.md)
diff --git a/atomic-forge/tools/fxmacrodata/.coveragerc b/atomic-forge/tools/fxmacrodata/.coveragerc
new file mode 100644
index 0000000..c45136e
--- /dev/null
+++ b/atomic-forge/tools/fxmacrodata/.coveragerc
@@ -0,0 +1,8 @@
+[run]
+source = tool
+omit = */tests/*
+
+[report]
+exclude_lines =
+ if __name__ == "__main__":
+show_missing = True
diff --git a/atomic-forge/tools/fxmacrodata/README.md b/atomic-forge/tools/fxmacrodata/README.md
new file mode 100644
index 0000000..c4c3598
--- /dev/null
+++ b/atomic-forge/tools/fxmacrodata/README.md
@@ -0,0 +1,74 @@
+# FXMacroData Tool
+
+## Overview
+Queries the [FXMacroData](https://fxmacrodata.com/?utm_source=github&utm_medium=referral&utm_campaign=atomic-agents&utm_content=readme) API for official-source macroeconomic data: release history with the official announcement timestamp of each print (CPI, GDP, unemployment, payrolls, policy rates, bond yields and more), the latest value of every indicator for a currency, upcoming release dates, the indicator catalogue, FX spot history, CFTC Commitments of Traders positioning, and commodity prices.
+
+USD releases, the USD release calendar and the indicator catalogue work without an API key. Other currencies, FX rates, COT and commodities need a key from [fxmacrodata.com/subscribe](https://fxmacrodata.com/subscribe?utm_source=github&utm_medium=referral&utm_campaign=atomic-agents&utm_content=readme).
+
+## Prerequisites and Dependencies
+- Python 3.12 or later
+- `atomic-agents`
+- `pydantic`
+- `requests`
+- Optional: an FXMacroData API key
+
+## Installation
+1. Use the Atomic Assembler CLI: run `atomic` and pick `fxmacrodata`.
+2. Or copy the `tool/` folder directly into your project.
+
+## Configuration
+- `api_key` (str): FXMacroData API key, sent in the `X-API-Key` header. Falls back to the `FXMACRODATA_API_KEY` environment variable. Leave empty for keyless USD access.
+- `base_url` (str): API base URL (default `https://api.fxmacrodata.com/v1`).
+- `timeout` (float): HTTP timeout in seconds (default 30).
+
+## Input & Output Structure
+
+### Input Schema
+- `endpoint` (str): one of
+ - `announcements`: release history for one indicator (`currency` and `indicator` required)
+ - `latest`: the most recent value of every indicator for a currency
+ - `calendar`: upcoming release dates for a currency, optionally filtered by `indicator`
+ - `catalogue`: indicator slugs, units and coverage available for a currency
+ - `forex`: FX spot history (`currency` is the base, `quote` required)
+ - `cot`: CFTC positioning for a currency
+ - `commodities`: price history for a commodity (`indicator`, e.g. `gold`)
+- `currency` (str, optional): three-letter code such as `usd`, `eur`, `jpy`.
+- `indicator` (str, optional): indicator slug such as `inflation`, `policy_rate`, `gdp`.
+- `quote` (str, optional): quote currency for `forex`.
+- `start_date`, `end_date` (str, optional): `YYYY-MM-DD`.
+- `limit` (int, optional): rows per page, 1-100. History endpoints return 20 rows by default.
+- `offset` (int, optional): row offset for paging.
+
+### Output Schema
+- `endpoint` (str): the endpoint that was called.
+- `url` (str): the request URL (the key is never included).
+- `data`: the rows returned by the API, with the API's own field names. Announcement rows carry `date` (reference period), `val`, and `announcement_datetime` (Unix seconds of the official release). For `catalogue` this is a mapping of indicator slug to metadata.
+- `pagination` (dict, optional): `has_more`, `next_offset` and `total_count` for paged endpoints.
+- `metadata` (dict): the remaining top-level response fields, such as source, provenance and data quality.
+- `error` (str, optional): set instead of raising when the input is incomplete or the request fails, so an agent can read the reason (for example a missing API key for a non-USD currency) and adjust.
+
+## Usage
+
+```python
+from tool.fxmacrodata import FXMacroDataTool, FXMacroDataToolInputSchema
+
+tool = FXMacroDataTool() # reads FXMACRODATA_API_KEY if set
+
+cpi = tool.run(FXMacroDataToolInputSchema(endpoint="announcements", currency="usd", indicator="inflation", limit=3))
+for row in cpi.data:
+ print(row["date"], row["val"], row["announcement_datetime"])
+
+upcoming = tool.run(FXMacroDataToolInputSchema(endpoint="calendar", currency="usd"))
+for row in upcoming.data[:5]:
+ print(row["announcement_datetime_utc"], row["name"])
+```
+
+To page through a long history, repeat the call with `offset=output.pagination["next_offset"]` until `has_more` is false.
+
+The full list of endpoints and response fields is in the [API reference](https://fxmacrodata.com/documentation/reference?utm_source=github&utm_medium=referral&utm_campaign=atomic-agents&utm_content=readme).
+
+## Contributing
+PRs welcome. See the main repo `CONTRIBUTING.md`.
+
+## License
+Same as the main Atomic Agents project.
diff --git a/atomic-forge/tools/fxmacrodata/pyproject.toml b/atomic-forge/tools/fxmacrodata/pyproject.toml
new file mode 100644
index 0000000..06d4dc8
--- /dev/null
+++ b/atomic-forge/tools/fxmacrodata/pyproject.toml
@@ -0,0 +1,34 @@
+[build-system]
+requires = ["hatchling"]
+build-backend = "hatchling.build"
+
+[tool.hatch.build.targets.wheel]
+packages = ["tool"]
+
+[project]
+name = "fxmacrodata-tool"
+version = "1.0.0"
+description = "Macroeconomic releases, release calendars, FX and COT data tool for Atomic Agents via the FXMacroData API"
+readme = "README.md"
+authors = [
+ { name = "Robert Tidball", email = "[email protected]" }
+]
+requires-python = ">=3.12"
+dependencies = [
+ "atomic-agents",
+ "pydantic>=2.10.3,<3.0.0",
+ "requests>=2.32.3,<3.0.0",
+]
+
+[dependency-groups]
+dev = [
+ "coverage>=7.6.1,<8.0.0",
+ "pytest>=8.3.3,<9.0.0",
+ "pytest-asyncio>=0.23.5,<1.0.0",
+ "pytest-cov>=5.0.0,<6.0.0",
+ "python-dotenv>=1.0.0,<2.0.0",
+ "rich>=13.7.0,<14.0.0",
+]
+
+[tool.uv.sources]
+atomic-agents = { workspace = true }
diff --git a/atomic-forge/tools/fxmacrodata/requirements.txt b/atomic-forge/tools/fxmacrodata/requirements.txt
new file mode 100644
index 0000000..b39dd01
--- /dev/null
+++ b/atomic-forge/tools/fxmacrodata/requirements.txt
@@ -0,0 +1,3 @@
+atomic-agents>=2.0.0,<3.0.0
+pydantic>=2.10.3,<3.0.0
+requests>=2.32.3,<3.0.0
diff --git a/atomic-forge/tools/fxmacrodata/tests/test_fxmacrodata.py b/atomic-forge/tools/fxmacrodata/tests/test_fxmacrodata.py
new file mode 100644
index 0000000..76760fb
--- /dev/null
+++ b/atomic-forge/tools/fxmacrodata/tests/test_fxmacrodata.py
@@ -0,0 +1,197 @@
+import os
+import sys
+from unittest.mock import MagicMock, patch
+
+import pytest
+import requests
+
+sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
+
+from tool.fxmacrodata import ( # noqa: E402
+ FXMacroDataTool,
+ FXMacroDataToolConfig,
+ FXMacroDataToolInputSchema,
+ FXMacroDataToolOutputSchema,
+)
+
+
+ANNOUNCEMENTS_PAYLOAD = {
+ "currency": "USD",
+ "indicator": "inflation",
+ "name": "Inflation (CPI)",
+ "source": "BLS",
+ "data": [
+ {"date": "2026-08-31", "val": 3.4, "announcement_datetime": 1789129800},
+ {"date": "2026-07-31", "val": 3.4, "announcement_datetime": 1786537800},
+ ],
+ "pagination": {"limit": 2, "offset": 0, "has_more": True, "next_offset": 2, "total_count": 3},
+}
+
+CALENDAR_PAYLOAD = {
+ "currency": "USD",
+ "timezone": "America/New_York",
+ "data": [
+ {
+ "release": "trade_balance",
+ "name": "Trade Balance",
+ "announcement_datetime": 1791289800,
+ "announcement_datetime_utc": "2026-10-06T12:30:00+00:00",
+ }
+ ],
+}
+
+CATALOGUE_PAYLOAD = {
+ "gdp": {"name": "GDP", "unit": "USD bn", "frequency": "Quarterly"},
+ "inflation": {"name": "Inflation (CPI)", "unit": "%", "frequency": "Monthly"},
+}
+
+
+def _response(status: int, payload, reason: str = "OK") -> MagicMock:
+ response = MagicMock()
+ response.status_code = status
+ response.reason = reason
+ response.json.return_value = payload
+ return response
+
+
+def tool(monkeypatch):
+ monkeypatch.delenv("FXMACRODATA_API_KEY", raising=False)
+ return FXMacroDataTool(FXMacroDataToolConfig())
+
+
+ "fields, path, query",
+ [
+ (
+ {"endpoint": "announcements", "currency": "USD", "indicator": "inflation", "limit": 5},
+ "/announcements/usd/inflation",
+ {"limit": "5"},
+ ),
+ ({"endpoint": "latest", "currency": "eur"}, "/announcements/eur/latest", {}),
+ (
+ {"endpoint": "calendar", "currency": "gbp", "indicator": "policy_rate"},
+ "/calendar/gbp",
+ {"indicator": "policy_rate"},
+ ),
+ ({"endpoint": "catalogue", "currency": "jpy"}, "/data_catalogue/jpy", {}),
+ (
+ {"endpoint": "forex", "currency": "eur", "quote": "USD", "start_date": "2026-01-01", "end_date": "2026-02-01"},
+ "/forex/eur/usd",
+ {"start_date": "2026-01-01", "end_date": "2026-02-01"},
+ ),
+ ({"endpoint": "cot", "currency": "aud", "offset": 20}, "/cot/aud", {"offset": "20"}),
+ ({"endpoint": "commodities", "indicator": "gold"}, "/commodities/gold", {}),
+ ],
+)
+def test_build_request(fields, path, query):
+ assert FXMacroDataTool.build_request(FXMacroDataToolInputSchema(**fields)) == (path, query)
+
+
+ "fields, message",
+ [
+ ({"endpoint": "announcements", "indicator": "inflation"}, "'currency'"),
+ ({"endpoint": "announcements", "currency": "usd"}, "'indicator'"),
+ ({"endpoint": "forex", "currency": "eur"}, "'quote'"),
+ ({"endpoint": "latest", "currency": "dollars"}, "'currency'"),
+ ({"endpoint": "announcements", "currency": "usd", "indicator": "../ping"}, "'indicator'"),
+ ({"endpoint": "calendar", "currency": "usd", "start_date": "01/02/2026"}, "'start_date'"),
+ ({"endpoint": "commodities"}, "'indicator'"),
+ ],
+)
+def test_invalid_input_returns_error_without_request(tool, fields, message):
+ with patch("tool.fxmacrodata.requests.get") as mock_get:
+ output = tool.run(FXMacroDataToolInputSchema(**fields))
+ mock_get.assert_not_called()
+ assert output.error and message in output.error
+ assert output.data == []
+
+
+def test_announcements_split_rows_pagination_and_metadata(tool):
+ with patch("tool.fxmacrodata.requests.get", return_value=_response(200, ANNOUNCEMENTS_PAYLOAD)) as mock_get:
+ output = tool.run(FXMacroDataToolInputSchema(endpoint="announcements", currency="usd", indicator="inflation", limit=2))
+
+ assert isinstance(output, FXMacroDataToolOutputSchema)
+ assert output.error is None
+ assert [row["val"] for row in output.data] == [3.4, 3.4]
+ assert output.data[0]["announcement_datetime"] == 1789129800
+ assert output.pagination["next_offset"] == 2
+ assert output.metadata == {"currency": "USD", "indicator": "inflation", "name": "Inflation (CPI)", "source": "BLS"}
+ assert output.url == "https://api.fxmacrodata.com/v1/announcements/usd/inflation?limit=2"
+
+ args, kwargs = mock_get.call_args
+ assert args[0] == "https://api.fxmacrodata.com/v1/announcements/usd/inflation"
+ assert kwargs["params"] == {"limit": "2"}
+ assert kwargs["timeout"] == 30.0
+ assert "X-API-Key" not in kwargs["headers"]
+
+
+def test_calendar_without_pagination(tool):
+ with patch("tool.fxmacrodata.requests.get", return_value=_response(200, CALENDAR_PAYLOAD)):
+ output = tool.run(FXMacroDataToolInputSchema(endpoint="calendar", currency="usd"))
+
+ assert output.data[0]["release"] == "trade_balance"
+ assert output.pagination is None
+ assert output.metadata == {"currency": "USD", "timezone": "America/New_York"}
+
+
+def test_catalogue_returns_mapping(tool):
+ with patch("tool.fxmacrodata.requests.get", return_value=_response(200, CATALOGUE_PAYLOAD)):
+ output = tool.run(FXMacroDataToolInputSchema(endpoint="catalogue", currency="usd"))
+
+ assert output.data == CATALOGUE_PAYLOAD
+ assert output.metadata == {}
+
+
+def test_api_key_from_config_is_sent_as_header():
+ tool = FXMacroDataTool(FXMacroDataToolConfig(api_key="test-key", base_url="https://example.test/v1/", timeout=5))
+ with patch("tool.fxmacrodata.requests.get", return_value=_response(200, CALENDAR_PAYLOAD)) as mock_get:
+ output = tool.run(FXMacroDataToolInputSchema(endpoint="calendar", currency="eur"))
+
+ args, kwargs = mock_get.call_args
+ assert args[0] == "https://example.test/v1/calendar/eur"
+ assert kwargs["headers"]["X-API-Key"] == "test-key"
+ assert kwargs["timeout"] == 5
+ assert "test-key" not in output.url
+
+
+def test_api_key_falls_back_to_environment(monkeypatch):
+ monkeypatch.setenv("FXMACRODATA_API_KEY", "env-key")
+ tool = FXMacroDataTool()
+ with patch("tool.fxmacrodata.requests.get", return_value=_response(200, CALENDAR_PAYLOAD)) as mock_get:
+ tool.run(FXMacroDataToolInputSchema(endpoint="calendar", currency="eur"))
+ assert mock_get.call_args[1]["headers"]["X-API-Key"] == "env-key"
+
+
+def test_http_error_surfaces_api_detail(tool):
+ body = {"detail": "This endpoint requires an Individual or Business API key.", "code": "api_key_required"}
+ with patch("tool.fxmacrodata.requests.get", return_value=_response(401, body, "Unauthorized")):
+ output = tool.run(FXMacroDataToolInputSchema(endpoint="forex", currency="eur", quote="usd"))
+
+ assert output.error == "FXMacroData returned 401: This endpoint requires an Individual or Business API key."
+ assert output.url == "https://api.fxmacrodata.com/v1/forex/eur/usd"
+ assert output.data == []
+
+
+def test_http_error_without_json_body(tool):
+ response = _response(502, None, "Bad Gateway")
+ response.json.side_effect = ValueError("not json")
+ with patch("tool.fxmacrodata.requests.get", return_value=response):
+ output = tool.run(FXMacroDataToolInputSchema(endpoint="latest", currency="usd"))
+ assert output.error == "FXMacroData returned 502 Bad Gateway"
+
+
+def test_network_error_is_reported(tool):
+ with patch("tool.fxmacrodata.requests.get", side_effect=requests.ConnectionError("connection refused")):
+ output = tool.run(FXMacroDataToolInputSchema(endpoint="latest", currency="usd"))
+ assert "connection refused" in output.error
+
+
+async def test_run_async(tool):
+ with patch("tool.fxmacrodata.requests.get", return_value=_response(200, ANNOUNCEMENTS_PAYLOAD)):
+ output = await tool.run_async(
+ FXMacroDataToolInputSchema(endpoint="announcements", currency="usd", indicator="inflation")
+ )
+ assert len(output.data) == 2
diff --git a/atomic-forge/tools/fxmacrodata/tool/fxmacrodata.py b/atomic-forge/tools/fxmacrodata/tool/fxmacrodata.py
new file mode 100644
index 0000000..56fcea6
--- /dev/null
+++ b/atomic-forge/tools/fxmacrodata/tool/fxmacrodata.py
@@ -0,0 +1,224 @@
+import asyncio
+import os
+import re
+from typing import Any, Dict, List, Literal, Optional, Tuple, Union
+
+import requests
+from pydantic import Field
+
+from atomic_agents import BaseIOSchema, BaseTool, BaseToolConfig
+
+
+_CURRENCY_RE = re.compile(r"^[A-Za-z]{3}$")
+_SLUG_RE = re.compile(r"^[A-Za-z0-9_]+$")
+_DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
+
+# Endpoints whose responses wrap rows in a "data" list next to metadata.
+_ROW_ENDPOINTS = {"announcements", "latest", "calendar", "forex", "cot", "commodities"}
+
+
+################
+# INPUT SCHEMA #
+################
+class FXMacroDataToolInputSchema(BaseIOSchema):
+ """
+ Look up official-source macroeconomic data from FXMacroData: economic releases with their
+ announcement timestamps (CPI, GDP, unemployment, payrolls, policy rates, bond yields and more),
+ the latest value of every indicator for a currency, upcoming release dates, the indicator
+ catalogue, FX spot history, CFTC Commitments of Traders positioning, and commodity prices.
+ USD releases work without an API key; other currencies, FX, COT and commodities need one.
+ """
+
+ endpoint: Literal["announcements", "latest", "calendar", "catalogue", "forex", "cot", "commodities"] = Field(
+ ...,
+ description=(
+ "'announcements' = release history for one indicator of a currency; 'latest' = most recent value of every"
+ " indicator for a currency; 'calendar' = upcoming release dates for a currency; 'catalogue' = available"
+ " indicator slugs for a currency (call this first if unsure of a slug); 'forex' = FX spot history for"
+ " currency/quote; 'cot' = CFTC positioning for a currency; 'commodities' = price history for a commodity"
+ " indicator."
+ ),
+ )
+ currency: Optional[str] = Field(
+ None,
+ description="Three-letter currency code, e.g. 'usd', 'eur', 'jpy'. Required for every endpoint except commodities."
+ " For 'forex' this is the base currency.",
+ )
+ indicator: Optional[str] = Field(
+ None,
+ description="Indicator slug, e.g. 'inflation', 'policy_rate', 'gdp', 'unemployment', 'non_farm_payrolls'."
+ " Required for 'announcements' and 'commodities' (e.g. 'gold'); optional filter for 'calendar'.",
+ )
+ quote: Optional[str] = Field(None, description="Quote currency for the 'forex' endpoint, e.g. 'usd' for EUR/USD.")
+ start_date: Optional[str] = Field(None, description="Start of the date range, YYYY-MM-DD.")
+ end_date: Optional[str] = Field(None, description="End of the date range, YYYY-MM-DD.")
+ limit: Optional[int] = Field(None, ge=1, le=100, description="Rows per page for history endpoints (API default 20).")
+ offset: Optional[int] = Field(None, ge=0, description="Row offset for paging through history endpoints.")
+
+
+####################
+# OUTPUT SCHEMA(S) #
+####################
+class FXMacroDataToolOutputSchema(BaseIOSchema):
+ """Output of the FXMacroData tool. Field names inside `data` are the API's own."""
+
+ endpoint: str = Field(..., description="The endpoint that was called.")
+ url: str = Field(..., description="The request URL, without the API key.")
+ data: Union[List[Dict[str, Any]], Dict[str, Any]] = Field(
+ default_factory=list,
+ description=(
+ "Rows returned by the API. Announcement rows carry 'date' (reference period), 'val', and"
+ " 'announcement_datetime' (Unix seconds of the official release). For 'catalogue' this is a mapping"
+ " of indicator slug to its metadata."
+ ),
+ )
+ pagination: Optional[Dict[str, Any]] = Field(
+ None, description="Paging info ('has_more', 'next_offset', 'total_count') when the endpoint pages."
+ )
+ metadata: Dict[str, Any] = Field(
+ default_factory=dict,
+ description="Remaining top-level response fields, such as source, units, provenance and data quality.",
+ )
+ error: Optional[str] = Field(None, description="Error message when the request failed.")
+
+
+#################
+# CONFIGURATION #
+#################
+class FXMacroDataToolConfig(BaseToolConfig):
+ """Configuration for the FXMacroDataTool."""
+
+ api_key: str = Field(
+ default="",
+ description="FXMacroData API key. Falls back to the FXMACRODATA_API_KEY environment variable. Optional for USD data.",
+ )
+ base_url: str = Field(default="https://api.fxmacrodata.com/v1", description="FXMacroData API base URL.")
+ timeout: float = Field(default=30.0, ge=1.0, le=120.0, description="HTTP request timeout in seconds.")
+
+
+#####################
+# MAIN TOOL & LOGIC #
+#####################
+class FXMacroDataTool(BaseTool[FXMacroDataToolInputSchema, FXMacroDataToolOutputSchema]):
+ """Tool for querying macroeconomic releases, release calendars, FX and positioning data from FXMacroData."""
+
+ def __init__(self, config: FXMacroDataToolConfig = FXMacroDataToolConfig()):
+ super().__init__(config)
+ self.api_key = config.api_key or os.getenv("FXMACRODATA_API_KEY", "")
+ self.base_url = config.base_url.rstrip("/")
+ self.timeout = config.timeout
+
+ @staticmethod
+ def _currency(value: Optional[str], name: str) -> str:
+ if not value or not _CURRENCY_RE.match(value.strip()):
+ raise ValueError(f"'{name}' must be a three-letter currency code such as 'usd' or 'eur'.")
+ return value.strip().lower()
+
+ @staticmethod
+ def _slug(value: Optional[str], name: str) -> str:
+ if not value or not _SLUG_RE.match(value.strip()):
+ raise ValueError(f"'{name}' must be an indicator slug such as 'inflation' or 'policy_rate'.")
+ return value.strip().lower()
+
+ @classmethod
+ def build_request(cls, params: FXMacroDataToolInputSchema) -> Tuple[str, Dict[str, str]]:
+ """Return the (path, query) pair for an input, validating the fields the endpoint needs."""
+ endpoint = params.endpoint
+ if endpoint == "commodities":
+ path = f"/commodities/{cls._slug(params.indicator, 'indicator')}"
+ else:
+ currency = cls._currency(params.currency, "currency")
+ if endpoint == "announcements":
+ path = f"/announcements/{currency}/{cls._slug(params.indicator, 'indicator')}"
+ elif endpoint == "latest":
+ path = f"/announcements/{currency}/latest"
+ elif endpoint == "calendar":
+ path = f"/calendar/{currency}"
+ elif endpoint == "catalogue":
+ path = f"/data_catalogue/{currency}"
+ elif endpoint == "forex":
+ path = f"/forex/{currency}/{cls._currency(params.quote, 'quote')}"
+ else:
+ path = f"/cot/{currency}"
+
+ query: Dict[str, str] = {}
+ for name in ("start_date", "end_date"):
+ value = getattr(params, name)
+ if value:
+ if not _DATE_RE.match(value):
+ raise ValueError(f"'{name}' must be formatted YYYY-MM-DD.")
+ query[name] = value
+ if params.limit is not None:
+ query["limit"] = str(params.limit)
+ if params.offset is not None:
+ query["offset"] = str(params.offset)
+ if endpoint == "calendar" and params.indicator:
+ query["indicator"] = cls._slug(params.indicator, "indicator")
+ return path, query
+
+ @staticmethod
+ def _error_message(response: requests.Response) -> str:
+ try:
+ body = response.json()
+ except ValueError:
+ body = None
+ detail = body.get("detail") if isinstance(body, dict) else None
+ if isinstance(detail, str) and detail:
+ return f"FXMacroData returned {response.status_code}: {detail}"
+ return f"FXMacroData returned {response.status_code} {response.reason}"
+
+ def _get(self, path: str, query: Dict[str, str]) -> Union[Dict[str, Any], List[Any]]:
+ headers = {"Accept": "application/json"}
+ if self.api_key:
+ headers["X-API-Key"] = self.api_key
+ response = requests.get(f"{self.base_url}{path}", params=query, headers=headers, timeout=self.timeout)
+ if response.status_code != 200:
+ raise RuntimeError(self._error_message(response))
+ return response.json()
+
+ def run(self, params: FXMacroDataToolInputSchema) -> FXMacroDataToolOutputSchema:
+ try:
+ path, query = self.build_request(params)
+ except ValueError as exc:
+ return FXMacroDataToolOutputSchema(endpoint=params.endpoint, url="", error=str(exc))
+
+ url = requests.Request("GET", f"{self.base_url}{path}", params=query).prepare().url
+ try:
+ payload = self._get(path, query)
+ except (requests.RequestException, RuntimeError, ValueError) as exc:
+ return FXMacroDataToolOutputSchema(endpoint=params.endpoint, url=url, error=str(exc))
+
+ if params.endpoint in _ROW_ENDPOINTS and isinstance(payload, dict):
+ metadata = {k: v for k, v in payload.items() if k not in ("data", "pagination")}
+ return FXMacroDataToolOutputSchema(
+ endpoint=params.endpoint,
+ url=url,
+ data=payload.get("data") or [],
+ pagination=payload.get("pagination"),
+ metadata=metadata,
+ )
+ return FXMacroDataToolOutputSchema(endpoint=params.endpoint, url=url, data=payload)
+
+ async def run_async(self, params: FXMacroDataToolInputSchema) -> FXMacroDataToolOutputSchema:
+ return await asyncio.to_thread(self.run, params)
+
+
+#################
+# EXAMPLE USAGE #
+#################
+if __name__ == "__main__": # pragma: no cover
+ from dotenv import load_dotenv
+ from rich.console import Console
+
+ load_dotenv()
+ console = Console()
+ tool = FXMacroDataTool()
+
+ output = tool.run(FXMacroDataToolInputSchema(endpoint="announcements", currency="usd", indicator="inflation", limit=3))
+ console.rule("[bold cyan]USD CPI")
+ console.print(output.error or [(row["date"], row["val"]) for row in output.data])
+
+ output = tool.run(FXMacroDataToolInputSchema(endpoint="calendar", currency="usd"))
+ console.rule("[bold cyan]Upcoming USD releases")
+ for row in output.data[:5]:
+ console.print(row.get("announcement_datetime_utc"), row.get("name"))
diff --git a/docs/guides/tools.md b/docs/guides/tools.md
index 5d29036..6c4aad9 100644
--- a/docs/guides/tools.md
+++ b/docs/guides/tools.md
@@ -150,6 +150,7 @@ The Atomic Forge ships with several pre-built tools:
- **Calculator**: Perform mathematical calculations
- **DateTime**: Timezone-aware now / parse / convert / shift / diff (no key required)
- **Fía Signals**: Crypto market intelligence — market regime, trading signals, DeFi yields, gas prices, Solana trending tokens, and wallet risk scoring
+- **FXMacroData**: Macroeconomic releases with official announcement times, release calendars, FX rates, and COT positioning (USD data needs no key)
- **Hacker News Search**: Search HN stories, comments, Show HN, Ask HN, polls (free Algolia API)
- **PDF Reader**: Extract text and metadata from local or remote PDFs, with page-range filtering
- **SearXNG Search**: Search the web using SearXNG
diff --git a/uv.lock b/uv.lock
index 6c39d50..64b4fff 100644
--- a/uv.lock
+++ b/uv.lock
@@ -21,6 +21,7 @@ members = [
"example-mcp-server",
"fastapi-memory",
"fia-signals",
+ "fxmacrodata-tool",
"hackernews-search",
"hooks-example",
"nested-multimodal",
@@ -1418,6 +1419,43 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/eb/02/a6b21098b1d5d6249b7c5ab69dde30108a71e4e819d4a9778f1de1d5b70d/fsspec-2025.10.0-py3-none-any.whl", hash = "sha256:7c7712353ae7d875407f97715f0e1ffcc21e33d5b24556cb1e090ae9409ec61d", size = 200966, upload-time = "2025-10-30T14:58:42.53Z" },
]
+[[package]]
+name = "fxmacrodata-tool"
+version = "1.0.0"
+source = { editable = "atomic-forge/tools/fxmacrodata" }
+dependencies = [
+ { name = "atomic-agents" },
+ { name = "pydantic" },
+ { name = "requests" },
+]
+
+[package.dev-dependencies]
+dev = [
+ { name = "coverage" },
+ { name = "pytest" },
+ { name = "pytest-asyncio" },
+ { name = "pytest-cov" },
+ { name = "python-dotenv" },
+ { name = "rich" },
+]
+
+[package.metadata]
+requires-dist = [
+ { name = "atomic-agents", editable = "." },
+ { name = "pydantic", specifier = ">=2.10.3,<3.0.0" },
+ { name = "requests", specifier = ">=2.32.3,<3.0.0" },
+]
+
+[package.metadata.requires-dev]
+dev = [
+ { name = "coverage", specifier = ">=7.6.1,<8.0.0" },
+ { name = "pytest", specifier = ">=8.3.3,<9.0.0" },
+ { name = "pytest-asyncio", specifier = ">=0.23.5,<1.0.0" },
+ { name = "pytest-cov", specifier = ">=5.0.0,<6.0.0" },
+ { name = "python-dotenv", specifier = ">=1.0.0,<2.0.0" },
+ { name = "rich", specifier = ">=13.7.0,<14.0.0" },
+]
+
[[package]]
name = "gepa"
version = "0.0.17"