Skip to content

160-tool MCP server for real-time global intelligence from free public APIs: markets, liquidity, prediction markets, SEC filings, conflict, military, aircraft-cohort early warning, migration and border flows, cyber, climate, news and more. Dated observation history, 29 research prompts, cited briefs, geofences, SSE dashboard. MIT, no paid API keys.

Liquidity: refuse a future ECB start, key rules from one constant, per-sort ranking rule, finite values

Phoenix Agent (mac-studio)cbbeb1659109
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8e5b1df..9deb112 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -60,15 +60,18 @@ responses say so. `limit=0` returns the full history.
included, is retried, counted as a breaker failure and takes the outage path.
An empty ECB response is one only when a start was requested;
without one it is an unexpected payload and takes the outage path, as does
- JSON that is not an object.
+ JSON that is not an object. An observation value that is not a finite number
+ makes the response a parse error.
Missing ECB roles and board rows are named; index bases, provisional status
and percentage-point change units are retained. ECB keys must specify every
- dimension and request at most 50 series combinations.
+ dimension, request at most 50 series combinations and be at most 200
+ characters long. An ECB start after today (UTC) is refused before any
+ request, so a caller's input is never counted as a source failure.
- CLI: `intel liquidity`, `intel net-liquidity`, `intel money-supply`,
`intel fed-liquidity`, `intel ecb-series`. Collector: `liquidity_board` and
`net_liquidity` (group `liquidity`). `intel liquidity` prints the ranking
- rule and each row's status; a terminal too narrow for the table gets one
- entry per indicator instead, so no value, date or unit is cut.
+ rule of the chosen sort and each row's status; a terminal too narrow for the
+ table gets one entry per indicator instead, so no value, date or unit is cut.
- Live reading 2026-10-17: net liquidity for Wednesday 2026-10-14 was
USD 5,869.615 billion (WALCL 6,755,639 million, WDTGAL 885,823 million,
RRPONTSYD 0.201 billion, all observed 2026-10-14).
diff --git a/src/world_intel_mcp/cli.py b/src/world_intel_mcp/cli.py
index ead935e..5fcc8ed 100644
--- a/src/world_intel_mcp/cli.py
+++ b/src/world_intel_mcp/cli.py
@@ -1782,7 +1782,7 @@ def fed_liquidity_cmd(ctx: click.Context, series_id: str, limit: int, start: str
@click.argument("key")
@click.option("--dataset", "-d", type=click.Choice(sorted(liquidity.ECB_DATASETS)), default="BSI")
@click.option("--limit", "-n", default=12, help="Newest points per series (0 = full history)")
[email protected]("--start", default=None, help="Only points on or after YYYY-MM-DD")
[email protected]("--start", default=None, help="Only points on or after YYYY-MM-DD, not after today (UTC)")
@click.pass_context
def ecb_series_cmd(
ctx: click.Context, key: str, dataset: str, limit: int, start: str | None
diff --git a/src/world_intel_mcp/sources/liquidity.py b/src/world_intel_mcp/sources/liquidity.py
index 4557c5b..6b8261a 100644
--- a/src/world_intel_mcp/sources/liquidity.py
+++ b/src/world_intel_mcp/sources/liquidity.py
@@ -253,14 +253,24 @@ ECB_DATASETS = {
}
_ECB_MAX_AGE_DAYS = {"M": 75, "W": 16, "D": 6, "Q": 200, "A": 500}
-_ECB_KEY_RE = re.compile(r"^[A-Za-z0-9_+.]{1,200}$")
+# A key is letters, digits and these separators, at most _ECB_KEY_MAX_LEN
+# characters; the regex, the refusals and ECB_KEY_RULES derive from both.
+_ECB_KEY_MAX_LEN = 200
+_ECB_KEY_PUNCTUATION = (".", "+", "_")
+_ECB_KEY_RE = re.compile(
+ f"^[A-Za-z0-9{''.join(re.escape(c) for c in _ECB_KEY_PUNCTUATION)}]{{1,{_ECB_KEY_MAX_LEN}}}$"
+)
+_ECB_KEY_CHARACTERS = (
+ "letters, digits, " + ", ".join(f"'{c}'" for c in _ECB_KEY_PUNCTUATION[:-1])
+ + f" and '{_ECB_KEY_PUNCTUATION[-1]}' only"
+)
# Dimensions a series key must give, per dataset, none left empty.
_ECB_KEY_DIMENSIONS = {"BSI": 11, "ILM": 6}
ECB_KEY_RULES = (
f"SDMX series key: every dimension given (BSI {_ECB_KEY_DIMENSIONS['BSI']}, "
f"ILM {_ECB_KEY_DIMENSIONS['ILM']}), none empty, so no wildcards; '+' selects "
f"several values in one dimension, at most {_MAX_ECB_SERIES} series combinations "
- "in all; letters, digits, '.', '+' and '_' only, up to 200 characters"
+ f"in all; {_ECB_KEY_CHARACTERS}, up to {_ECB_KEY_MAX_LEN} characters"
)
@@ -756,7 +766,12 @@ def _period_end(value: dict) -> date | None:
def parse_sdmx_json(data: dict, dataset: str) -> list[dict]:
- """Every series in an ECB SDMX-JSON 1.0 response, points oldest first."""
+ """Every series in an ECB SDMX-JSON 1.0 response, points oldest first.
+
+ An observation value that is not a finite number (infinity, NaN, or an
+ integer too large for a float) raises ValueError or OverflowError: the
+ response is a parse error, and no such value is ever returned.
+ """
structure = data["structure"]
dims = structure["dimensions"]["series"]
periods = structure["dimensions"]["observation"][0]["values"]
@@ -783,11 +798,14 @@ def parse_sdmx_json(data: dict, dataset: str) -> list[dict]:
if 0 <= ov[status_pos + 1] < len(values):
status = values[ov[status_pos + 1]].get("name")
end = _period_end(period)
+ value = float(ov[0])
+ if not math.isfinite(value):
+ raise ValueError(f"observation value for {period['id']} is not a finite number")
points.append(
{
"observed_at": period["id"],
"period_end": end.isoformat() if end else None,
- "value": float(ov[0]),
+ "value": value,
"units": units,
"status": status,
}
@@ -884,7 +902,7 @@ async def _ecb_fetch(
return None, f"ECB Data Portal returned no data for {dataset}/{key}: {failure}, no cached copy"
try:
series = parse_sdmx_json(data, dataset)
- except (KeyError, IndexError, TypeError, ValueError, AttributeError) as exc:
+ except (KeyError, IndexError, TypeError, ValueError, AttributeError, OverflowError) as exc:
if not fetched:
fetcher.cache.delete(cache_key)
return None, (
@@ -957,9 +975,14 @@ async def fetch_ecb_series(
"timestamp": _utc_now_iso(),
}
key = str(key or "").strip()
+ if len(key) > _ECB_KEY_MAX_LEN:
+ return {
+ "error": f"key must be at most {_ECB_KEY_MAX_LEN} characters, got {len(key)}",
+ "timestamp": _utc_now_iso(),
+ }
if not _ECB_KEY_RE.fullmatch(key):
return {
- "error": "key must be an SDMX series key: letters, digits, '.', '+' and '_' only",
+ "error": f"key must be an SDMX series key: {_ECB_KEY_CHARACTERS}",
"timestamp": _utc_now_iso(),
}
dimensions = key.split(".")
@@ -978,6 +1001,15 @@ async def fetch_ecb_series(
start_d = _validate_start(start)
except ValueError as exc:
return {"error": str(exc), "timestamp": _utc_now_iso()}
+ # The portal answers a start after its own date with an HTTP 400 block
+ # page (measured 2026-10-17). Refused here, before any request, so a
+ # caller's input is never retried or counted as a source failure.
+ today = _today()
+ if start_d is not None and start_d > today:
+ return {
+ "error": f"start must be on or before today ({today} UTC), got {start!r}",
+ "timestamp": _utc_now_iso(),
+ }
# One extra observation so the oldest returned point still has a change.
series, err = await _ecb_fetch(fetcher, ds, key, n + 1 if n else 0, start_d)
@@ -1159,6 +1191,20 @@ _BOARD_FRED = (
("us_m2", "M2SL"),
)
+# The order each board sort applies, returned as the payload's ranking_rule.
+_BOARD_RANKING_RULES = {
+ "biggest_move": (
+ "biggest_move ranks absolute changes in billions of each row currency; "
+ "no FX conversion, and observation horizons differ. Percentage changes "
+ "do not affect ranking."
+ ),
+ "newest": (
+ "newest orders rows by the period end of their latest observation, newest "
+ "first, and rows without a period end last; rows that tie are in reverse "
+ "alphabetical order of indicator. Changes do not affect the order."
+ ),
+}
+
def _board_move(row: dict) -> float:
divisor = 1000 if (row.get("units") or "").endswith(" millions") else 1
@@ -1168,7 +1214,7 @@ def _board_move(row: dict) -> float:
async def fetch_liquidity_board(fetcher: Fetcher, sort: str = "biggest_move") -> dict:
"""Latest reading and change per liquidity indicator across FRED and the ECB."""
sort = str(sort or "biggest_move").strip().lower()
- if sort not in ("biggest_move", "newest"):
+ if sort not in _BOARD_RANKING_RULES:
return {"error": f"sort must be biggest_move or newest, got {sort!r}", "timestamp": _utc_now_iso()}
fred_ids = [sid for _, sid in _BOARD_FRED]
@@ -1290,11 +1336,7 @@ async def fetch_liquidity_board(fetcher: Fetcher, sort: str = "biggest_move") ->
)
out: dict[str, Any] = {
"sort": sort,
- "ranking_rule": (
- "biggest_move ranks absolute changes in billions of each row currency; "
- "no FX conversion, and observation horizons differ. Percentage changes "
- "do not affect ranking."
- ),
+ "ranking_rule": _BOARD_RANKING_RULES[sort],
"count": len(rows),
"indicators": rows,
"unavailable": unavailable,
diff --git a/src/world_intel_mcp/tests/test_liquidity_docs_match_code.py b/src/world_intel_mcp/tests/test_liquidity_docs_match_code.py
index ff3c617..ff75050 100644
--- a/src/world_intel_mcp/tests/test_liquidity_docs_match_code.py
+++ b/src/world_intel_mcp/tests/test_liquidity_docs_match_code.py
@@ -1,7 +1,9 @@
-"""Liquidity docs say what the code does: the biggest_move rule, the
-`unknown` measure, the ECB key limits, the CLI board's ranking line and
-row status (whole at every terminal width from 40 to 200 columns), and
-the dated net liquidity measurement in the CHANGELOG.
+"""Liquidity docs say what the code does: the biggest_move rule and each
+board sort's ranking rule (payload and CLI), the `unknown` measure, the
+ECB key limits, the CLI board's ranking line and row status (whole at
+every terminal width from 40 to 200 columns), and the dated net liquidity
+measurement in the CHANGELOG. Every fetcher and cache a test opens is
+closed when it ends.
Gaps / not covered: README wording (counts and tables wait for the final
docs pass); the CHANGELOG figures themselves, which were measured live on
@@ -25,11 +27,50 @@ from world_intel_mcp.sources import liquidity
from world_intel_mcp.tests.test_liquidity_surfaces import (
_fake, _invoke, _isolation, _liquidity_tools, _payloads,
)
-from world_intel_mcp.tests.test_sources_liquidity import _mock_all, fetcher
+from world_intel_mcp.tests import test_liquidity_surfaces as _surfaces
+from world_intel_mcp.tests.test_sources_liquidity import _mock_all
_ROOT = Path(__file__).parents[3]
+async def fetcher(tmp_path):
+ """Like test_sources_liquidity's fetcher (no retries), but closes its client and cache."""
+ f = Fetcher(cache=Cache(db_path=tmp_path / "liq.db"), breaker=CircuitBreaker(), default_timeout=5.0,
+ max_retries=0)
+ yield f
+ await f.close()
+ f.cache.close()
+
+
[email protected](autouse=True)
+def _close_payload_and_cli_caches(_isolation, monkeypatch: pytest.MonkeyPatch):
+ """No sqlite connection outlives its test: the fetchers _payloads opens
+ are closed inside the loop that used them, and the cache of the CLI's
+ own fetcher (cli._get_fetcher) at teardown."""
+ real_fetcher, real_build = _surfaces._fetcher, _surfaces._build_payloads
+ opened: list[Fetcher] = []
+
+ def recording(tmp_path):
+ opened.append(real_fetcher(tmp_path))
+ return opened[-1]
+
+ async def build_then_close(tmp_path):
+ try:
+ return await real_build(tmp_path)
+ finally:
+ while opened:
+ f = opened.pop()
+ await f.close()
+ f.cache.close()
+
+ monkeypatch.setattr(_surfaces, "_fetcher", recording)
+ monkeypatch.setattr(_surfaces, "_build_payloads", build_then_close)
+ yield
+ if cli._fetcher is not None:
+ cli._fetcher.cache.close()
+
+
def _flat(text: str) -> str:
return " ".join(text.split())
@@ -190,3 +231,66 @@ def test_changelog_states_the_measured_net_liquidity_start():
assert int(early) + int(blank) + 1 == as_int(skipped) and late == last
assert first < start < "2013-09-23" < last
assert "ECB 404 and empty responses are final no-data answers" not in text
+
+
+_RANKING_RULES = {
+ "biggest_move": (
+ "biggest_move ranks absolute changes in billions of each row currency; no FX conversion, "
+ "and observation horizons differ. Percentage changes do not affect ranking."
+ ),
+ "newest": (
+ "newest orders rows by the period end of their latest observation, newest first, and rows "
+ "without a period end last; rows that tie are in reverse alphabetical order of indicator. "
+ "Changes do not affect the order."
+ ),
+}
+
+
+async def test_each_board_sort_states_the_order_it_applies(fetcher):
+ _mock_all()
+ by_move = await liquidity.fetch_liquidity_board(fetcher)
+ newest = await liquidity.fetch_liquidity_board(fetcher, sort="newest")
+
+ assert by_move["sort"] == "biggest_move" and by_move["ranking_rule"] == _RANKING_RULES["biggest_move"]
+ assert newest["sort"] == "newest" and newest["ranking_rule"] == _RANKING_RULES["newest"]
+ # Newest first; the three 2026-10-14 rows and the four 2026-08-31 rows tie.
+ assert [(r["indicator"], r["period_end"]) for r in newest["indicators"]] == [
+ ("reverse_repo", "2026-10-16"),
+ ("treasury_general_account", "2026-10-14"), ("net_liquidity", "2026-10-14"),
+ ("fed_total_assets", "2026-10-14"),
+ ("eurosystem_total_assets", "2026-10-11"),
+ ("us_m2", "2026-08-31"), ("euro_area_m3", "2026-08-31"), ("euro_area_m2", "2026-08-31"),
+ ("euro_area_m1", "2026-08-31"),
+ ]
+
+
+async def test_newest_puts_a_row_without_a_period_end_last(fetcher, monkeypatch):
+ """A weekly ECB period whose end the parser cannot read (patched here)."""
+ real = liquidity._period_end
+ monkeypatch.setattr(liquidity, "_period_end", lambda p: None if "-W" in str(p.get("id")) else real(p))
+ _mock_all()
+ newest = await liquidity.fetch_liquidity_board(fetcher, sort="newest")
+ rows = newest["indicators"]
+ assert rows[-1]["indicator"] == "eurosystem_total_assets" and rows[-1]["period_end"] is None
+ assert all(r["period_end"] for r in rows[:-1])
+
+
+def test_every_sort_the_surfaces_offer_has_a_ranking_rule():
+ tool_sorts = _tool("intel_liquidity_board").inputSchema["properties"]["sort"]["enum"]
+ cli_sorts = next(p for p in cli.liquidity_cmd.params if p.name == "sort").type.choices
+ assert set(tool_sorts) == set(cli_sorts) == set(liquidity._BOARD_RANKING_RULES) == set(_RANKING_RULES)
+ assert liquidity._BOARD_RANKING_RULES == _RANKING_RULES
+
+
[email protected]("sort", ["biggest_move", "newest"])
+def test_cli_board_prints_the_ranking_rule_of_its_sort(sort):
+ """End to end: CLI, source and payload, upstreams mocked."""
+ with respx.mock:
+ _mock_all()
+ out = _flat(_invoke("liquidity", "--sort", sort).output)
+ assert f"Liquidity board (sorted by {sort})" in out
+ assert f"Ranking: {_RANKING_RULES[sort]}" in out
+ (other,) = set(_RANKING_RULES) - {sort}
+ assert _RANKING_RULES[other] not in out
diff --git a/src/world_intel_mcp/tests/test_liquidity_ecb_inputs.py b/src/world_intel_mcp/tests/test_liquidity_ecb_inputs.py
new file mode 100644
index 0000000..8142e74
--- /dev/null
+++ b/src/world_intel_mcp/tests/test_liquidity_ecb_inputs.py
@@ -0,0 +1,205 @@
+"""ECB caller input outside the stated rules is refused before any request.
+
+The live portal answers a start after its own date with an HTTP 400 HTML
+block page (measured 2026-10-17 at 22:00 UTC: startPeriod 2026-10-19 and
+2030-01-01 drew 400, 2026-10-17 and 2026-10-18 drew 200 with an empty
+body; the portal clock runs at +02:00). Counted as an outage, three such
+calls opened the ECB circuit the liquidity board shares for 300 s. A
+start after today (UTC) is therefore refused locally, as is a key outside
+ECB_KEY_RULES, with the rule named, no request sent and no breaker
+failure recorded.
+
+Gaps / not covered: live portal answers (respx only); a 400 the portal
+sends for input these checks pass (a very large limit, a start in year 1)
+is still retried and counted as an outage; FRED tools filter a start
+locally and are not exercised here.
+"""
+
+import re
+import string
+from unittest.mock import AsyncMock
+
+import httpx
+import pytest
+import respx
+from click.testing import CliRunner
+
+from world_intel_mcp import cli
+from world_intel_mcp.cache import Cache
+from world_intel_mcp.circuit_breaker import CircuitBreaker
+from world_intel_mcp.fetcher import Fetcher
+from world_intel_mcp.sources import liquidity
+from world_intel_mcp.tests.test_liquidity_surfaces import _liquidity_tools
+from world_intel_mcp.tests.test_sources_liquidity import (
+ _BSI, _ECB_BSI_URL, _fixed_clock_and_no_throttle, _mock_all,
+)
+
+_ECB = "https://data-api.ecb.europa.eu/"
+_M3 = "M.U2.Y.V.M30.X.1.U2.2300.Z01.E" # 11 dimensions, 30 characters
+_ECB_ROWS = {"euro_area_m1", "euro_area_m2", "euro_area_m3", "eurosystem_total_assets"}
+# Abridged: the live page is 12,174 bytes of text/html with this text.
+_BLOCK_PAGE = (
+ "<html><head><title>European Central Bank</title></head><body>Your access has been "
+ "blocked due to security concerns. HTTP status code: 400</body></html>"
+)
+_DIMENSIONS = "key must specify every SDMX dimension ({n} for {ds}) without wildcards and at most 50 series combinations"
+
+
+async def fetcher(tmp_path):
+ """Like test_sources_liquidity's fetcher (no retries), but closes its client and cache."""
+ f = Fetcher(cache=Cache(db_path=tmp_path / "liq.db"), breaker=CircuitBreaker(), default_timeout=5.0,
+ max_retries=0)
+ yield f
+ await f.close()
+ f.cache.close()
+
+
+def sleep(monkeypatch: pytest.MonkeyPatch) -> AsyncMock:
+ mock = AsyncMock()
+ monkeypatch.setattr("world_intel_mcp.fetcher.asyncio.sleep", mock)
+ return mock
+
+
+def _ecb_failures(fetcher) -> int:
+ fetcher.breaker.is_available(liquidity.ECB_SOURCE) # registers the source if no request was ever sent
+ return fetcher.breaker.status()[liquidity.ECB_SOURCE]["total_failures"]
+
+
+# ---------------------------------------------------------------------------
+# A start after today
+# ---------------------------------------------------------------------------
+
+
[email protected]("start", ["2026-10-18", "2030-01-01"])
+async def test_a_future_start_is_refused_before_any_request(fetcher, sleep, start):
+ fetcher.max_retries = 2
+ route = respx.get(url__startswith=_ECB).respond(400, text=_BLOCK_PAGE, headers={"content-type": "text/html"})
+
+ out = await liquidity.fetch_ecb_series(fetcher, key=_M3, start=start)
+
+ assert out["error"] == f"start must be on or before today (2026-10-17 UTC), got {start!r}"
+ assert route.call_count == 0
+ sleep.assert_not_awaited()
+ assert _ecb_failures(fetcher) == 0
+
+
+async def test_a_start_of_today_is_still_sent(fetcher):
+ route = respx.get(url__startswith=_ECB).respond(200, content=b"")
+
+ out = await liquidity.fetch_ecb_series(fetcher, key=_M3, start="2026-10-17")
+
+ assert out["error"] == f"ECB Data Portal: no observations on or after 2026-10-17 for BSI/{_M3}"
+ assert route.call_count == 1
+ assert route.calls.last.request.url.params["startPeriod"] == "2026-10-17"
+
+
+async def test_future_starts_never_open_the_circuit_the_board_shares(fetcher, sleep):
+ """The reviewer's scenario: three calls with a future start, then the board."""
+ fetcher.max_retries = 2
+
+ def portal(request: httpx.Request) -> httpx.Response:
+ if request.url.params.get("startPeriod", "") > "2026-10-18":
+ return httpx.Response(400, text=_BLOCK_PAGE, headers={"content-type": "text/html"})
+ return httpx.Response(200, json=_BSI)
+
+ _mock_all()
+ bsi = respx.get(_ECB_BSI_URL).mock(side_effect=portal)
+ for _ in range(fetcher.breaker.failure_threshold):
+ out = await liquidity.fetch_ecb_series(fetcher, key=liquidity._ECB_MONEY_KEY, start="2030-01-01")
+ assert out["error"].startswith("start must be on or before today")
+ assert bsi.call_count == 0
+
+ board = await liquidity.fetch_liquidity_board(fetcher)
+
+ assert {r["indicator"] for r in board["indicators"] if r["source"] == liquidity.ECB_SOURCE} == _ECB_ROWS
+ assert board["unavailable"] == []
+ assert not any(r.get("served_from_stale_cache") for r in board["indicators"])
+ state = fetcher.breaker.status()[liquidity.ECB_SOURCE]
+ assert state["status"] == "closed" and state["total_failures"] == 0
+
+
+def cli_cache(tmp_path, monkeypatch: pytest.MonkeyPatch):
+ """The CLI's own fetcher on a temp cache, closed afterwards."""
+ monkeypatch.setenv("WORLD_INTEL_CACHE_DB", str(tmp_path / "cli-cache.db"))
+ monkeypatch.setenv("COLUMNS", "200")
+ monkeypatch.setattr(cli, "_fetcher", None)
+ yield
+ if cli._fetcher is not None:
+ cli._fetcher.cache.close()
+
+
+def test_cli_ecb_series_refuses_a_future_start_without_a_request(cli_cache):
+ with respx.mock:
+ route = respx.get(url__startswith=_ECB).respond(400, text=_BLOCK_PAGE, headers={"content-type": "text/html"})
+ result = CliRunner().invoke(cli.main, ["ecb-series", _M3, "--start", "2030-01-01"], catch_exceptions=False)
+
+ assert "Error: start must be on or before today (2026-10-17 UTC), got '2030-01-01'" in " ".join(result.output.split())
+ assert route.call_count == 0
+ assert _ecb_failures(cli._fetcher) == 0
+
+
+def test_the_ecb_surfaces_state_the_start_rule():
+ tool = next(t for t in _liquidity_tools().TOOLS if t.name == "intel_ecb_series")
+ assert "not after today (UTC)" in tool.inputSchema["properties"]["start"]["description"]
+ option = next(p for p in cli.ecb_series_cmd.params if p.name == "start")
+ assert "not after today (UTC)" in option.help
+
+
+# ---------------------------------------------------------------------------
+# Keys outside ECB_KEY_RULES
+# ---------------------------------------------------------------------------
+
+
[email protected]("dataset, key, error", [
+ pytest.param("BSI", _M3 + ".X", _DIMENSIONS.format(n=11, ds="BSI"), id="bsi-12-dimensions"),
+ pytest.param("BSI", "M.U2.Y.V.M30.X.1.U2.2300.Z01", _DIMENSIONS.format(n=11, ds="BSI"), id="bsi-10-dimensions"),
+ pytest.param("ILM", "W.U2.C.T000000.Z5", _DIMENSIONS.format(n=6, ds="ILM"), id="ilm-5-dimensions"),
+ pytest.param("ILM", "W.U2.C.T000000.Z5.Z01.X", _DIMENSIONS.format(n=6, ds="ILM"), id="ilm-7-dimensions"),
+ pytest.param("BSI", _M3.replace("M30", "M30" + "A" * 171), "key must be at most 200 characters, got 201",
+ id="201-characters"),
+ pytest.param("BSI", _M3 + "?x", "key must be an SDMX series key: letters, digits, '.', '+' and '_' only",
+ id="character-outside-the-set"),
+])
+async def test_a_key_outside_the_rules_is_refused_with_its_rule_and_no_request(fetcher, dataset, key, error):
+ with respx.mock:
+ route = respx.get(url__startswith=_ECB).respond(503)
+ out = await liquidity.fetch_ecb_series(fetcher, dataset=dataset, key=key)
+ assert out["error"] == error
+ assert route.call_count == 0
+ assert _ecb_failures(fetcher) == 0
+
+
[email protected]("dataset, key", [
+ pytest.param("BSI", _M3.replace("M30", "M30" + "A" * 170), id="200-characters"),
+ pytest.param("ILM", liquidity._ECB_EUROSYSTEM_KEY, id="ilm-6-dimensions"),
+])
+async def test_a_key_at_the_limits_is_sent(fetcher, dataset, key):
+ assert len(key) <= 200
+ with respx.mock:
+ route = respx.get(url__startswith=_ECB).respond(200, json=_BSI)
+ out = await liquidity.fetch_ecb_series(fetcher, dataset=dataset, key=key)
+ assert route.call_count == 1
+ assert not out.get("error", "").startswith("key must")
+
+
+def test_key_rules_state_the_characters_and_length_the_validator_applies():
+ """Drift check: read the characters and the length out of ECB_KEY_RULES
+ and hold the validator (and history tooling that full-matches
+ _ECB_KEY_RE) to exactly those."""
+ match = re.search(r"letters, digits, (.+) only, up to (\d+) characters$", liquidity.ECB_KEY_RULES)
+ assert match, liquidity.ECB_KEY_RULES
+ allowed = set(re.findall(r"'(.)'", match.group(1)))
+ longest = int(match.group(2))
+ assert allowed == {".", "+", "_"} and longest == 200
+ for c in string.printable:
+ accepted = bool(liquidity._ECB_KEY_RE.fullmatch(f"A{c}B"))
+ assert accepted is (c.isalnum() or c in allowed), repr(c)
+ assert liquidity._ECB_KEY_RE.fullmatch("A" * longest)
+ assert not liquidity._ECB_KEY_RE.fullmatch("A" * (longest + 1))
+ assert not liquidity._ECB_KEY_RE.fullmatch("")
diff --git a/src/world_intel_mcp/tests/test_liquidity_outage_paths.py b/src/world_intel_mcp/tests/test_liquidity_outage_paths.py
index d05db10..3592f92 100644
--- a/src/world_intel_mcp/tests/test_liquidity_outage_paths.py
+++ b/src/world_intel_mcp/tests/test_liquidity_outage_paths.py
@@ -1,32 +1,48 @@
"""Liquidity outage paths: what each failure kind does to a response.
Every failure that leaves a series without a fresh body is named in the
-response (HTTP status, no response, open circuit, unexpected payload,
-parse error); a stale copy is served marked, never re-cached as fresh,
+response (HTTP status, no response, open circuit, an oversized body,
+unexpected payload, parse error, including an observation that is not a
+finite number); a stale copy is served marked, never re-cached as fresh,
and counted on the circuit breaker. Also pins the ECB key cap and the
-"." blank in FRED CSVs.
+"." blank in FRED CSVs. Every fetcher a test opens is closed when it
+ends.
Gaps / not covered: live upstreams (fixtures and respx only); concurrent
requests racing the breaker threshold (each test drives one sequence).
"""
import copy
+import json
from datetime import date
import httpx
import pytest
import respx
+from world_intel_mcp.cache import Cache
+from world_intel_mcp.circuit_breaker import CircuitBreaker
+from world_intel_mcp.fetcher import BinaryResult, Fetcher
from world_intel_mcp.sources import liquidity
from world_intel_mcp.tests.test_sources_liquidity import (
_BSI, _ECB_BSI_URL, _ECB_ILM_URL, _FRED_URL,
- _fixed_clock_and_no_throttle, _fred_router, _mock_all, fetcher,
+ _fixed_clock_and_no_throttle, _fred_router, _mock_all,
)
_ECB_ROWS = {"euro_area_m1", "euro_area_m2", "euro_area_m3", "eurosystem_total_assets"}
_CIRCUIT_OPEN = "upstream fetch failed (circuit open: request not sent after repeated failures)"
+async def fetcher(tmp_path):
+ """Like test_sources_liquidity's fetcher (no retries), but closes its client and cache."""
+ f = Fetcher(cache=Cache(db_path=tmp_path / "liq.db"), breaker=CircuitBreaker(), default_timeout=5.0,
+ max_retries=0)
+ yield f
+ await f.close()
+ f.cache.close()
+
+
def _expire(fetcher, key=None):
conn = fetcher.cache._get_conn()
if key is None:
@@ -331,3 +347,89 @@ async def test_fred_dot_cell_is_a_missing_observation(fetcher):
out = await liquidity.fetch_fed_liquidity_series(fetcher, "RRPONTSYD", limit=0)
assert out["blank_observations"] == 2
assert [p["value"] for p in out["points"]] == [0.25, 1.5]
+
+
+# ---------------------------------------------------------------------------
+# A whitespace-only ECB body, an oversized body, a value that is no number
+# ---------------------------------------------------------------------------
+
+
+async def test_ecb_whitespace_only_body_reads_as_an_empty_one(fetcher):
+ key = liquidity._ECB_MONEY_KEY
+ empty = "unexpected payload (empty body, no start requested)"
+ route = respx.get(_ECB_BSI_URL).respond(200, content=b" \n")
+ with_start = await liquidity.fetch_ecb_series(fetcher, key=key, start="2026-10-01")
+ assert with_start["error"] == f"ECB Data Portal: no observations on or after 2026-10-01 for BSI/{key}"
+ cold = await liquidity.fetch_ecb_series(fetcher, key=key)
+ assert cold["error"] == f"ECB Data Portal returned no data for BSI/{key}: {empty}, no cached copy"
+
+ route.mock(return_value=httpx.Response(200, json=_BSI))
+ await liquidity.fetch_ecb_series(fetcher, key=key)
+ _expire(fetcher)
+ route.mock(return_value=httpx.Response(200, content=b" \n"))
+ warm = await liquidity.fetch_ecb_series(fetcher, key=key)
+ assert warm["series"] and all(s["served_from_stale_cache"] and s["fetch_failure"] == empty for s in warm["series"])
+ assert fetcher.breaker.status()[liquidity.ECB_SOURCE]["total_failures"] == 0
+
+
+ "body of 300 bytes exceeds cap 100",
+ "body exceeds cap 100: stopped after 300 decoded bytes", # the streamed read's wording on the cyclone branch
+])
+def test_an_oversized_body_is_named_with_its_cap(error):
+ assert liquidity._fetch_failure(BinaryResult(200, None, error)) == f"upstream fetch failed (HTTP 200, {error})"
+
+
+def _bsi_with_first_value(literal: str) -> bytes:
+ """The live BSI response with its first observation value written as ``literal``."""
+ data = copy.deepcopy(_BSI)
+ first = next(iter(data["dataSets"][0]["series"].values()))
+ first["observations"][next(iter(first["observations"]))][0] = 424242.25
+ text = json.dumps(data)
+ assert text.count("424242.25") == 1
+ return text.replace("424242.25", literal).encode()
+
+
+_NOT_FINITE = [
+ pytest.param(str(10**400), id="401-digit-integer"),
+ pytest.param("1e400", id="1e400"),
+ pytest.param("Infinity", id="infinity"),
+ pytest.param("-Infinity", id="minus-infinity"),
+ pytest.param("NaN", id="nan"),
+]
+
+
[email protected]("literal", _NOT_FINITE)
+async def test_an_ecb_value_that_is_not_a_finite_number_is_a_parse_error(fetcher, literal):
+ key = liquidity._ECB_MONEY_KEY
+ respx.get(_ECB_BSI_URL).respond(200, content=_bsi_with_first_value(literal))
+ out = await liquidity.fetch_ecb_series(fetcher, key=key)
+ assert out["error"].startswith(
+ f"ECB Data Portal response for BSI/{key} not in the expected SDMX-JSON shape (parse error: "
+ )
+ assert ("OverflowError" if literal.isdigit() else "is not a finite number") in out["error"]
+ assert out["data_gaps"] == [out["error"]]
+ assert fetcher.cache.get_stale(f"liquidity:ecb:BSI:{key}:25:None") is None # never cached
+ assert fetcher.breaker.status()[liquidity.ECB_SOURCE]["total_failures"] == 0
+
+
[email protected]("literal", _NOT_FINITE[:2])
+async def test_a_value_that_is_not_a_finite_number_drops_only_its_rows(fetcher, literal):
+ """It once raised out of the board and money supply (gather without
+ return_exceptions), losing the FRED and ILM rows too."""
+ _mock_all(bsi=httpx.Response(200, content=_bsi_with_first_value(literal)))
+ board = await liquidity.fetch_liquidity_board(fetcher)
+ assert {r["indicator"] for r in board["indicators"]} == {
+ "fed_total_assets", "treasury_general_account", "reverse_repo", "net_liquidity", "us_m2",
+ "eurosystem_total_assets",
+ }
+ missing = {u["indicator"]: u["error"] for u in board["unavailable"]}
+ assert set(missing) == {"euro_area_m1", "euro_area_m2", "euro_area_m3"}
+ assert all("SDMX-JSON shape (parse error: " in e for e in missing.values())
+
+ money = await liquidity.fetch_money_supply(fetcher)
+ assert "error" not in money and money["us"]["M2"]["latest"]
+ assert "SDMX-JSON shape (parse error: " in money["euro_area"]["error"]
diff --git a/src/world_intel_mcp/tools/liquidity.py b/src/world_intel_mcp/tools/liquidity.py
index 7fe2d2b..5ccee27 100644
--- a/src/world_intel_mcp/tools/liquidity.py
+++ b/src/world_intel_mcp/tools/liquidity.py
@@ -136,7 +136,13 @@ TOOLS: list[Tool] = [
"description": "Newest points per series (default 24); 0 returns the full history",
"default": 24,
},
- "start": _START,
+ "start": {
+ **_START,
+ "description": (
+ "Optional ISO date YYYY-MM-DD, not after today (UTC): only points observed "
+ "on or after it; a later date is refused without a request"
+ ),
+ },
},
"required": ["key"],
},