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.
Python ai-toolsai-watchanthropicclaudecybersecuritydashboardgeofencinggeopoliticalgeospatialintelligencemarketsmcpmigrationmilitarymodel-context-protocolnuclearosintreal-timespace-weatherthreat-intelligence
Liquidity: name each fetch failure, count stale serves, ECB payload checks
Phoenix Agent (mac-studio)d13e816a7e0f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7312f75..a95abe5 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -40,18 +40,31 @@ responses say so. `limit=0` returns the full history.- `intel_fed_liquidity_series`: WALCL, WDTGAL, WTREGEN, RRPONTSYD or M2SL with fullhistory; blank source dates (2,833 for RRPONTSYD on 2026-10-17, 2,679 of thembefore 2013-09-23, when daily values begin) are counted, not read as zero.+ Net liquidity therefore starts at 2003-03-19: of 1,244 WALCL weeks, 705 align+ and 539 are skipped and counted (first 2002-12-18, last 2018-12-05): 8 before+ RRPONTSYD begins on 2003-02-07, 530 with a blank Wednesday before 2013-09-23,+ and 2018-12-05, when RRPONTSYD is blank on both the Tuesday and the Wednesday.+ 10 points use the Tuesday value, all on holiday Wednesdays (measured+ 2026-10-17).- `intel_ecb_series`: any ECB BSI or ILM series by SDMX key, with units, scale,titles and provisional flags taken from the response. A growth rate's change isreported in points, not as a percent of a percent.-- Stale cache responses carry `served_from_stale_cache` and `cache_age_seconds`,- and name the upstream failure in `data_gaps`. Only parsed bodies enter the cache.- ECB 404 and empty responses are final no-data answers, without outage retries.+- Stale cache responses carry `served_from_stale_cache`, `cache_age_seconds` and+ `fetch_failure`, and name the failure in `data_gaps`: the HTTP status, no+ response, an open circuit or an unexpected payload. Each stale copy served+ counts in the circuit breaker's `total_stale_serves` (`intel_status`), and none+ is re-cached as fresh. Only parsed bodies enter the cache. ECB 404 responses+ are final no-data answers, without outage retries. 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.Missing ECB roles and board rows are named; index bases, provisional statusand percentage-point change units are retained. ECB keys must specify everydimension and request at most 50 series combinations.- CLI: `intel liquidity`, `intel net-liquidity`, `intel money-supply`,`intel fed-liquidity`, `intel ecb-series`. Collector: `liquidity_board` and- `net_liquidity` (group `liquidity`).+ `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.- Live reading 2026-10-17: net liquidity for Wednesday 2026-10-14 wasUSD 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.pyindex 7edf247..ead935e 100644--- a/src/world_intel_mcp/cli.py+++ b/src/world_intel_mcp/cli.py@@ -24,8 +24,10 @@ from datetime import datetime, timezonefrom typing import Anyimport click+from rich.cells import cell_lenfrom rich.console import Consolefrom rich.markup import escape+from rich.padding import Paddingfrom rich.table import Tablefrom rich.text import Textfrom rich.panel import Panel@@ -1611,10 +1613,35 @@ def _liq_points_table(title: str, points: list[dict], extra: tuple[str, ...] = (return table+# Board columns: (header, justify, whole). A whole column holds dates,+# numbers or units and is never wrapped or cut; the text columns fold.+_LIQ_BOARD_COLUMNS = (+ ("Indicator", "left", False), ("Observed", "left", True), ("Latest", "right", True),+ ("Units", "left", True), ("Change", "right", True), ("Change %", "right", True),+ ("Measure", "left", False), ("Status", "left", False),+)+_LIQ_TEXT_MIN_WIDTH = 12+++def _liq_board_fits(rows: list[list[str]], width: int) -> bool:+ """Whether the board table fits ``width`` with its whole columns intact+ and each text column at least _LIQ_TEXT_MIN_WIDTH wide (or its full+ width). Narrower, Rich would cut cells or drop text columns (at 80+ columns it dropped Indicator), so the board is printed as a list."""+ need = len(_LIQ_BOARD_COLUMNS) + 1 # table edges and column separators+ for i, (header, _, whole) in enumerate(_LIQ_BOARD_COLUMNS):+ natural = max([cell_len(header)] + [cell_len(row[i]) for row in rows])+ need += (natural if whole else min(natural, _LIQ_TEXT_MIN_WIDTH)) + 2 # cell padding+ return need <= width++@main.command(name="liquidity")@click.option("--sort", type=click.Choice(["biggest_move", "newest"]), default="biggest_move",- help="Order rows by absolute percent change or by newest period",+ help=(+ "biggest_move: largest absolute change, in billions of each row's currency "+ "(no FX conversion; percent change does not rank); newest: latest period end"+ ),)@click.pass_contextdef liquidity_cmd(ctx: click.Context, sort: str) -> None:@@ -1622,27 +1649,45 @@ def liquidity_cmd(ctx: click.Context, sort: str) -> None:data = _run(liquidity.fetch_liquidity_board(_get_fetcher(), sort=sort))if _bail_on_error(ctx, data):return- table = Table(title=f"Liquidity board (sorted by {sort})", box=box.SIMPLE_HEAVY)- table.add_column("Indicator", style="bold")- table.add_column("Observed")- table.add_column("Latest", justify="right")- table.add_column("Units")- table.add_column("Change", justify="right")- table.add_column("Change %", justify="right")- table.add_column("Measure")+ rows, stale = [], []for r in data.get("indicators", []):- stale = (r.get("freshness") or {}).get("stale")measure = r.get("measure", "")- table.add_row(- _cell(r.get("indicator", "")),- Text(f"{r.get('observed_at')} (stale)", style="yellow") if stale else _cell(r.get("observed_at", "")),+ stale.append(bool((r.get("freshness") or {}).get("stale")))+ rows.append([+ str(r.get("indicator", "")),+ f"{r.get('observed_at')} (stale)" if stale[-1] else str(r.get("observed_at", "")),_liq_num(r.get("latest_value")),- _cell(r.get("units") or ""),+ str(r.get("units") or ""),_liq_num(r.get("change"), signed=True),_liq_num(r.get("change_pct"), signed=True),- _cell("stock" if measure == "amount_outstanding" else measure),- )- console.print(table)+ "stock" if measure == "amount_outstanding" else str(measure),+ str(r.get("status") or ""),+ ])+ title = f"Liquidity board (sorted by {sort})"+ if _liq_board_fits(rows, console.width):+ table = Table(title=title, box=box.SIMPLE_HEAVY)+ for header, justify, whole in _LIQ_BOARD_COLUMNS:+ table.add_column(+ header, justify=justify, no_wrap=whole, overflow="fold",+ style="bold" if header == "Indicator" else None,+ )+ for row, is_stale in zip(rows, stale):+ cells = [_cell(value) for value in row]+ if is_stale:+ cells[1].stylize("yellow")+ table.add_row(*cells)+ console.print(table)+ else:+ console.print(Text(title, style="bold"))+ for row, is_stale in zip(rows, stale):+ indicator, observed, latest, units, change, change_pct, measure, status = row+ console.print(Text(indicator, style="bold"))+ console.print(Padding(Text.assemble(+ f"{latest} {units}, observed ", (observed, "yellow" if is_stale else ""),+ f", change {change} ({change_pct}%), {measure}", f", {status}" if status else "",+ ), (0, 0, 0, 2)))+ if data.get("ranking_rule"):+ console.print(f"[dim]Ranking: {escape(str(data['ranking_rule']))}[/dim]")for u in data.get("unavailable", []):console.print(f"[red]Unavailable:[/red] {escape(str(u.get('indicator')))}: {escape(str(u.get('error')))}"diff --git a/src/world_intel_mcp/sources/liquidity.py b/src/world_intel_mcp/sources/liquidity.pyindex 53e566e..fd24f27 100644--- a/src/world_intel_mcp/sources/liquidity.py+++ b/src/world_intel_mcp/sources/liquidity.py@@ -14,8 +14,10 @@ Eurosystem balance sheet. Keyless sources only.Every point carries ``observed_at`` (the period the value describes),``value`` and ``units``; every series says whether it is an amountoutstanding, a flow (transactions within the period), a growth rate or an-index. A blank FRED cell is a missing observation, never a zero, and a-failed component is an error, never a zero term in the net liquidity sum.+index, or is typed ``unknown`` (named in ``data_gaps``) when the ECB data+type is not one of those. A blank FRED cell is a missing observation, never+a zero, and a failed component is an error, never a zero term in the net+liquidity sum.RRP uses the Wednesday value; a blank Wednesday on or after 2013-09-23may use Tuesday only. Earlier blank Wednesdays and missing Tuesdays areskipped and counted, never filled.@@ -43,7 +45,7 @@ from datetime import date, datetime, timezonefrom typing import Anyfrom urllib.parse import urlencode-from ..fetcher import Fetcher+from ..fetcher import BinaryResult, Fetcherlogger = logging.getLogger("world-intel-mcp.sources.liquidity")@@ -252,6 +254,14 @@ 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}$")+# 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"+)# ---------------------------------------------------------------------------@@ -326,7 +336,7 @@ def _freshness(period_end: date | None, max_age_days: int) -> dict:def _stale_gap(name: str, observed_at: str, fresh: dict) -> str | None:if fresh.get("served_from_stale_cache"):return (- f"{name}: upstream fetch failed or circuit open; served from stale cache "+ f"{name}: {fresh['fetch_failure']}; served from stale cache "f"({fresh['cache_age_seconds']} seconds old)")if fresh.get("stale"):@@ -338,6 +348,33 @@ def _stale_gap(name: str, observed_at: str, fresh: dict) -> str | None:return None+def _fetch_failure(result: BinaryResult) -> str:+ """Why ``get_bytes`` returned no body: the HTTP status, a request that+ got no response, or an open circuit (no request sent)."""+ error = result.error or ""+ if result.status is None and error.startswith("circuit open"):+ return "upstream fetch failed (circuit open: request not sent after repeated failures)"+ kind = error.split(":", 1)[0]+ if result.status is not None and kind in ("", "HTTPStatusError"):+ return f"upstream fetch failed (HTTP {result.status})"+ if "exceeds cap" in error:+ return f"upstream fetch failed (HTTP {result.status}, {error})"+ return f"upstream fetch failed (no response: {kind or 'unknown error'})"+++def _stale_copy(fetcher: Fetcher, key: str, failure: str) -> tuple[Any, dict]:+ """The last good copy under ``key`` and the markers that travel with it."""+ hit = fetcher.cache.get_stale_meta(key)+ if hit is None:+ return None, {}+ value, created_at = hit+ return value, {+ "served_from_stale_cache": True,+ "cache_age_seconds": round(max(0.0, time.time() - created_at), 1),+ "fetch_failure": failure,+ }++# ---------------------------------------------------------------------------# FRED graph CSV# ---------------------------------------------------------------------------@@ -366,14 +403,17 @@ def parse_fred_csv(text: str, series_id: str) -> list[tuple[date, float | None]]return rows-def _cache_meta(fetcher: Fetcher, key: str) -> dict:- meta = fetcher.cache.get_stale_meta(key)- if meta is None:- return {}- return {- "served_from_stale_cache": True,- "cache_age_seconds": round(max(0.0, time.time() - meta[1]), 1),- }+def _keep_or_count(fetcher: Fetcher, key: str, value: Any, ttl: int, source: str, meta: dict) -> None:+ """After a body parsed: cache a fresh one, or count a stale copy served.++ A stale copy is never written back (that would restamp old data as+ fresh); each one served counts on the circuit breaker's+ ``total_stale_serves``, which intel_status and the dashboard show.+ """+ if meta:+ fetcher.breaker.record_stale_serve(source)+ else:+ fetcher.cache.set(key, value, ttl)def _mark_cached(series: dict, meta: dict) -> dict:@@ -388,7 +428,7 @@ async def _fred_rows() -> tuple[list[tuple[date, float | None]] | None, str | None, dict]:key = f"liquidity:fred:{series_id}"text = fetcher.cache.get(key)- meta = {}+ meta: dict = {}fetched = text is Noneif fetched:result = await fetcher.get_bytes(@@ -398,20 +438,20 @@ async def _fred_rows(if result.ok:text = result.content.decode("utf-8", errors="replace")else:- text = fetcher.cache.get_stale(key)- meta = _cache_meta(fetcher, key)- if text is None:- return None, f"FRED graph CSV for {series_id} unavailable (fetch failed, no cached copy)", {}+ failure = _fetch_failure(result)+ text, meta = _stale_copy(fetcher, key, failure)+ if text is None:+ return None, f"FRED graph CSV for {series_id} unavailable: {failure}, no cached copy", {}try:rows = parse_fred_csv(text, series_id)except (ValueError, csv.Error) as exc:if not fetched:fetcher.cache.delete(key)- return None, f"FRED graph CSV for {series_id} not in the expected format: {exc}", {}+ return None, f"FRED graph CSV for {series_id} not in the expected format (parse error: {exc})", {}if not any(v is not None for _, v in rows):return None, f"FRED graph CSV for {series_id} has no observations", {}- if fetched and not meta:- fetcher.cache.set(key, text, _FRED_TTL)+ if fetched:+ _keep_or_count(fetcher, key, text, _FRED_TTL, FRED_SOURCE, meta)return rows, None, meta@@ -770,6 +810,9 @@ def parse_sdmx_json(data: dict, dataset: str) -> list[dict]:return out+_JSON_KINDS = {list: "array", str: "string", int: "number", float: "number", bool: "boolean", type(None): "null"}++async def _ecb_fetch(fetcher: Fetcher, dataset: str, key: str, last_n: int, start: date | None) -> tuple[list[dict] | None, str | None]:@@ -780,7 +823,7 @@ async def _ecb_fetch(params["startPeriod"] = start.isoformat()cache_key = f"liquidity:ecb:{dataset}:{key}:{last_n}:{start}"data = fetcher.cache.get(cache_key)- cache_meta = {}+ cache_meta: dict = {}fetched = data is Noneif fetched:result = await fetcher.get_bytes(@@ -789,28 +832,44 @@ async def _ecb_fetch()if result.status == 404:return None, f"ECB Data Portal: no series matches the key {dataset}/{key}"- if result.ok and not result.content.strip():- return None, f"ECB Data Portal: no observations on or after {start or 'the requested start'} for {dataset}/{key}"- if result.ok:+ # An unexpected payload takes the outage path (last good copy,+ # marked) without a circuit-breaker failure: the transport worked.+ failure = None+ if not result.ok:+ failure = _fetch_failure(result)+ elif not result.content.strip():+ # Empty is the portal's answer when nothing is observed on or+ # after startPeriod; with no start sent it answers nothing.+ if start is not None:+ return None, f"ECB Data Portal: no observations on or after {start} for {dataset}/{key}"+ failure = "unexpected payload (empty body, no start requested)"+ else:try:data = json.loads(result.content)except (ValueError, UnicodeError) as exc:- return None, f"ECB Data Portal response not in the expected SDMX-JSON shape: {exc!r:.80}"- else:- data = fetcher.cache.get_stale(cache_key)- cache_meta = _cache_meta(fetcher, cache_key)- if not isinstance(data, dict):- return None, f"ECB Data Portal returned no data for {dataset}/{key} (upstream fetch failed or circuit open)"+ return None, (+ "ECB Data Portal response not in the expected SDMX-JSON shape "+ f"(parse error: {exc!r:.80})"+ )+ if not isinstance(data, dict):+ failure = f"unexpected payload (JSON {_JSON_KINDS.get(type(data), type(data).__name__)}, not an object)"+ if failure is not None:+ data, cache_meta = _stale_copy(fetcher, cache_key, failure)+ if data is None:+ 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:if not fetched:fetcher.cache.delete(cache_key)- return None, f"ECB Data Portal response for {dataset}/{key} not in the expected SDMX-JSON shape: {exc!r:.80}"+ return None, (+ f"ECB Data Portal response for {dataset}/{key} not in the expected SDMX-JSON shape "+ f"(parse error: {exc!r:.80})"+ )if not any(s["points"] for s in series):return None, f"ECB Data Portal returned no observations for {dataset}/{key}"- if fetched and not cache_meta:- fetcher.cache.set(cache_key, data, _ECB_TTL)+ if fetched:+ _keep_or_count(fetcher, cache_key, data, _ECB_TTL, ECB_SOURCE, cache_meta)for item in series:item.update(cache_meta)return series, None@@ -841,7 +900,8 @@ def _finish_ecb_series(series: dict, limit: int) -> dict:"freshness": {**_freshness(end, max_age),**({"stale": True, "served_from_stale_cache": True,- "cache_age_seconds": series["cache_age_seconds"]}+ "cache_age_seconds": series["cache_age_seconds"],+ "fetch_failure": series["fetch_failure"]}if series.get("served_from_stale_cache") else {}),},"order": "newest_first",@@ -878,11 +938,14 @@ async def fetch_ecb_series("timestamp": _utc_now_iso(),}dimensions = key.split(".")- if (len(dimensions) != {"BSI": 11, "ILM": 6}[ds]+ if (len(dimensions) != _ECB_KEY_DIMENSIONS[ds]or any(not code for dim in dimensions for code in dim.split("+"))or math.prod(len(dim.split("+")) for dim in dimensions) > _MAX_ECB_SERIES):return {- "error": "key must specify every SDMX dimension without wildcards and at most 50 series combinations",+ "error": (+ f"key must specify every SDMX dimension ({_ECB_KEY_DIMENSIONS[ds]} for {ds}) "+ f"without wildcards and at most {_MAX_ECB_SERIES} series combinations"+ ),"timestamp": _utc_now_iso(),}try:@@ -1051,7 +1114,7 @@ def _row("units": units,"latest_value": latest["value"] if latest else None,"status": latest.get("status") if latest else None,- **({k: freshness[k] for k in ("served_from_stale_cache", "cache_age_seconds")}+ **({k: freshness[k] for k in ("served_from_stale_cache", "cache_age_seconds", "fetch_failure")}if freshness.get("served_from_stale_cache") else {}),"observed_at": latest["observed_at"] if latest else None,"period_end": period_end.isoformat() if period_end else None,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.pynew file mode 100644index 0000000..ff3c617--- /dev/null+++ b/src/world_intel_mcp/tests/test_liquidity_docs_match_code.py@@ -0,0 +1,192 @@+"""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.++Gaps / not covered: README wording (counts and tables wait for the final+docs pass); the CHANGELOG figures themselves, which were measured live on+2026-10-17 and cannot be recomputed from the truncated fixtures (only+their internal consistency is checked here); terminals under 40 columns;+a real terminal (Rich renders to CliRunner's buffer at COLUMNS).+"""++import asyncio+import re+from pathlib import Path++import pytest+import respx++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 (+ _fake, _invoke, _isolation, _liquidity_tools, _payloads,+)+from world_intel_mcp.tests.test_sources_liquidity import _mock_all, fetcher++_ROOT = Path(__file__).parents[3]+++def _flat(text: str) -> str:+ return " ".join(text.split())+++def _tool(name: str):+ return next(t for t in _liquidity_tools().TOOLS if t.name == name)+++def test_biggest_move_is_described_as_the_ranking_the_code_applies():+ sort = _tool("intel_liquidity_board").inputSchema["properties"]["sort"]["description"]+ help_text = _flat(_invoke("liquidity", "--help").output)+ for text in (sort, help_text):+ assert "percent change)" not in text and "absolute percent" not in text+ assert "billions" in text and "no FX conversion" in text and "percent change does not rank" in text+++def test_unknown_measure_is_documented_where_measures_are_listed():+ assert "``unknown``" in liquidity.__doc__+ assert "growth_rate, index or unknown" in _tool("intel_ecb_series").description+ assert liquidity._ecb_measure("BSI", {"DATA_TYPE": "Z"}) == "unknown"++[email protected]("bad_key, why", [+ ("M.U2.Y.V.M30.X.1.U2.2300.Z01", "BSI 11"), # 10 dimensions+ ("M.U2.Y.V.M30.X.1.U2..Z01.E", "none empty, so no wildcards"),+ ("M.U2.Y.V.A+B+C+D.X.1+4+I.U2.2300.Z01.A+B+C+D+E", "at most 50 series combinations"), # 60+ ("M.U2.Y.V.M30.X.1.U2.2300.Z01.E?x", "letters, digits, '.', '+' and '_' only"),+])+async def test_ecb_key_description_states_the_limits_the_validator_applies(fetcher, bad_key, why):+ rules = _tool("intel_ecb_series").inputSchema["properties"]["key"]["description"]+ assert rules == liquidity.ECB_KEY_RULES+ assert why in rules+ assert "ILM 6" in rules and "up to 200 characters" in rules+ with respx.mock:+ route = respx.get(url__startswith="https://data-api.ecb.europa.eu/").respond(503)+ out = await liquidity.fetch_ecb_series(fetcher, key=bad_key)+ assert out["error"].startswith("key must") and route.call_count == 0+++def test_cli_board_prints_ranking_rule_and_row_status(tmp_path, monkeypatch):+ payload = _payloads(tmp_path)["board"]+ monkeypatch.setattr(liquidity, "fetch_liquidity_board", _fake(payload))+ out = _invoke("liquidity").output+ assert f"Ranking: {payload['ranking_rule']}" in _flat(out)+ rows = {r["indicator"]: r for r in payload["indicators"]}+ assert rows["euro_area_m3"]["status"] == "Provisional value"+ assert rows["eurosystem_total_assets"]["status"] == "Normal value"+ lines = {line.split()[0]: line for line in out.splitlines() if line.strip()}+ assert "Provisional value" in lines["euro_area_m3"]+ assert "Normal value" in lines["eurosystem_total_assets"]+ assert "value" not in lines["fed_total_assets"] # FRED rows carry no status+++def test_cli_board_from_stale_copies_keeps_values_dates_and_units_whole(tmp_path, monkeypatch):+ """At 100 columns (a list there: too narrow for the table) the stale+ board cuts no value, date, unit or change; the Status column once+ pushed Units into "USD billi…"."""+ async def build():+ f = Fetcher(cache=Cache(db_path=tmp_path / "stale.db"),+ breaker=CircuitBreaker(failure_threshold=99), max_retries=0)+ with respx.mock:+ _mock_all()+ await liquidity.fetch_liquidity_board(f)+ conn = f.cache._get_conn()+ conn.execute("UPDATE cache SET expires_at = ?", (1,))+ conn.commit()+ with respx.mock:+ respx.get(url__startswith="https://fred.stlouisfed.org/").respond(503)+ respx.get(url__startswith="https://data-api.ecb.europa.eu/").respond(500)+ board = await liquidity.fetch_liquidity_board(f)+ await f.close()+ f.cache.close()+ return board++ payload = asyncio.run(build())+ assert len(payload["indicators"]) == 9+ assert all(r["served_from_stale_cache"] for r in payload["indicators"])+ monkeypatch.setattr(liquidity, "fetch_liquidity_board", _fake(payload))+ monkeypatch.setenv("COLUMNS", "100")+ table = _invoke("liquidity").output.split("Ranking:")[0]+ assert "…" not in table+ for r in payload["indicators"]:+ assert f"{r['observed_at']} (stale)" in table+ assert r["units"] in table+ assert cli._liq_num(r["latest_value"]) in table+ assert cli._liq_num(r["change"], signed=True) in table+++def _stale_board(tmp_path) -> dict:+ """The board served from stale copies: a fresh fetch, every cache row+ expired, then FRED answering 503 and the ECB 500."""+ async def build():+ f = Fetcher(cache=Cache(db_path=tmp_path / "stale-sweep.db"),+ breaker=CircuitBreaker(failure_threshold=99), max_retries=0)+ with respx.mock:+ _mock_all()+ await liquidity.fetch_liquidity_board(f)+ conn = f.cache._get_conn()+ conn.execute("UPDATE cache SET expires_at = ?", (1,))+ conn.commit()+ with respx.mock:+ respx.get(url__startswith="https://fred.stlouisfed.org/").respond(503)+ respx.get(url__startswith="https://data-api.ecb.europa.eu/").respond(500)+ board = await liquidity.fetch_liquidity_board(f)+ await f.close()+ f.cache.close()+ return board++ return asyncio.run(build())++[email protected]("served", ["fresh", "stale"])+def test_cli_board_cuts_no_value_and_drops_no_column_at_any_width(tmp_path, monkeypatch, served):+ """From 40 to 200 columns: the table where it fits, else one entry per+ indicator. No ellipsis, no line past the width, and every row keeps its+ value, units, change, date and status (at 80 columns the table once+ dropped Indicator, Measure and Status; at 90 it folded names to one+ letter); a listed row names its indicator whole on its own line."""+ payload = _stale_board(tmp_path) if served == "stale" else _payloads(tmp_path)["board"]+ assert len(payload["indicators"]) == 9+ assert all(bool(r.get("served_from_stale_cache")) == (served == "stale") for r in payload["indicators"])+ monkeypatch.setattr(liquidity, "fetch_liquidity_board", _fake(payload))+ layouts = {}+ for width in range(40, 201):+ monkeypatch.setenv("COLUMNS", str(width))+ board = _invoke("liquidity").output.split("Ranking:")[0]+ assert "…" not in board, width+ assert max(len(line) for line in board.splitlines()) <= width, width+ flat = _flat(board)+ listed = "Change %" not in board+ layouts.setdefault("list" if listed else "table", []).append(width)+ lines = [line.strip() for line in board.splitlines()]+ for r in payload["indicators"]:+ observed = f"{r['observed_at']} (stale)" if served == "stale" else r["observed_at"]+ for whole in (observed, cli._liq_num(r["latest_value"]), r["units"],+ cli._liq_num(r["change"], signed=True), r["status"] or ""):+ assert whole in flat, (width, whole)+ if listed:+ assert r["indicator"] in lines, width+ assert min(layouts["table"]) > max(layouts["list"])+ assert max(layouts["list"]) >= 100 and min(layouts["table"]) <= 120+++def test_changelog_states_the_measured_net_liquidity_start():+ text = _flat((_ROOT / "CHANGELOG.md").read_text())+ match = re.search(+ r"Net liquidity therefore starts at (\d{4}-\d\d-\d\d): of ([\d,]+) WALCL weeks, ([\d,]+) align "+ r"and ([\d,]+) are skipped and counted \(first (\S+), last (\S+)\): (\d+) before RRPONTSYD begins "+ r"on \S+, (\d+) with a blank Wednesday before 2013-09-23, and (\S+), when RRPONTSYD is blank on "+ r"both the Tuesday and the Wednesday\. (\d+) points use the Tuesday value, all on holiday "+ r"Wednesdays \(measured 2026-10-17\)\.",+ text,+ )+ assert match, "dated net liquidity start missing from the CHANGELOG"+ start, total, aligned, skipped, first, last, early, blank, late, tuesday = match.groups()+ as_int = lambda s: int(s.replace(",", "")) # noqa: E731+ assert as_int(aligned) + as_int(skipped) == as_int(total)+ 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 textdiff --git a/src/world_intel_mcp/tests/test_liquidity_outage_paths.py b/src/world_intel_mcp/tests/test_liquidity_outage_paths.pynew file mode 100644index 0000000..d05db10--- /dev/null+++ b/src/world_intel_mcp/tests/test_liquidity_outage_paths.py@@ -0,0 +1,333 @@+"""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,+and counted on the circuit breaker. Also pins the ECB key cap and the+"." blank in FRED CSVs.++Gaps / not covered: live upstreams (fixtures and respx only); concurrent+requests racing the breaker threshold (each test drives one sequence).+"""++import copy+from datetime import date++import httpx+import pytest+import respx++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,+)++_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)"+++def _expire(fetcher, key=None):+ conn = fetcher.cache._get_conn()+ if key is None:+ conn.execute("UPDATE cache SET expires_at = ?, created_at = ?", (1, 1))+ else:+ conn.execute("UPDATE cache SET expires_at = ?, created_at = ? WHERE key = ?", (1, 1, key))+ conn.commit()+++def _respond(route, failure):+ if isinstance(failure, Exception):+ route.mock(side_effect=failure)+ else:+ route.mock(return_value=failure)+++# ---------------------------------------------------------------------------+# A stale ECB copy is never restamped (twin of the FRED rule)+# ---------------------------------------------------------------------------+++async def test_only_failed_ecb_dataset_is_stale_and_never_restamped(fetcher):+ _mock_all()+ await liquidity.fetch_liquidity_board(fetcher)+ key = f"liquidity:ecb:BSI:{liquidity._ECB_MONEY_KEY}:2:None"+ _expire(fetcher, key)+ original = fetcher.cache.get_stale_meta(key)+ respx.get(_ECB_BSI_URL).respond(503)+ # Twice: a copy re-cached as fresh on the first call would read as+ # fresh, unmarked data on the second.+ for _ in range(2):+ board = await liquidity.fetch_liquidity_board(fetcher)+ for row in board["indicators"]:+ stale = row["indicator"] in ("euro_area_m1", "euro_area_m2", "euro_area_m3")+ assert bool(row.get("served_from_stale_cache")) is stale, row["indicator"]+ assert fetcher.cache.get_stale_meta(key) == original+++# ---------------------------------------------------------------------------+# An empty ECB answer means "no data" only when a start was sent+# ---------------------------------------------------------------------------+++async def test_ecb_empty_answer_without_start_is_an_unexpected_payload(fetcher):+ respx.get(_ECB_BSI_URL).respond(200, content=b"")+ cold = await liquidity.fetch_ecb_series(fetcher, key=liquidity._ECB_MONEY_KEY)+ assert cold["error"] == (+ f"ECB Data Portal returned no data for BSI/{liquidity._ECB_MONEY_KEY}: "+ "unexpected payload (empty body, no start requested), no cached copy"+ )+ assert "no observations on or after" not in cold["error"]++ # The board sends no start: an empty answer there takes the outage path+ # and serves the last good copy, marked, instead of dropping the rows.+ _mock_all()+ await liquidity.fetch_liquidity_board(fetcher)+ _expire(fetcher)+ respx.get(_ECB_BSI_URL).respond(200, content=b"")+ respx.get(_ECB_ILM_URL).respond(200, content=b"")+ board = await liquidity.fetch_liquidity_board(fetcher)+ rows = {r["indicator"]: r for r in board["indicators"] if r["source"] == liquidity.ECB_SOURCE}+ assert set(rows) == _ECB_ROWS+ assert board["unavailable"] == []+ for row in rows.values():+ assert row["served_from_stale_cache"] is True and row["freshness"]["stale"] is True+ assert row["fetch_failure"] == "unexpected payload (empty body, no start requested)"+ assert any(+ g.startswith("euro_area_m1: unexpected payload (empty body, no start requested); served from stale cache (")+ for g in board["data_gaps"]+ )+++async def test_ecb_empty_answer_with_start_stays_a_final_no_data_answer(fetcher):+ route = respx.get(_ECB_BSI_URL).respond(200, content=b"")+ out = await liquidity.fetch_ecb_series(fetcher, key=liquidity._ECB_MONEY_KEY, start="2026-10-01")+ assert out["error"] == (+ f"ECB Data Portal: no observations on or after 2026-10-01 for BSI/{liquidity._ECB_MONEY_KEY}"+ )+ assert route.calls.last.request.url.params["startPeriod"] == "2026-10-01"+++# ---------------------------------------------------------------------------+# JSON that is not an object is an unexpected payload, not an outage+# ---------------------------------------------------------------------------++[email protected]("body, kind", [(b"[]", "array"), (b"null", "null"), (b'"text"', "string"), (b"7", "number")])+async def test_ecb_json_that_is_not_an_object_is_an_unexpected_payload(fetcher, body, kind):+ respx.get(_ECB_BSI_URL).respond(200, content=body)+ failure = f"unexpected payload (JSON {kind}, not an object)"+ cold = await liquidity.fetch_ecb_series(fetcher, key=liquidity._ECB_MONEY_KEY)+ assert cold["error"] == (+ f"ECB Data Portal returned no data for BSI/{liquidity._ECB_MONEY_KEY}: {failure}, no cached copy"+ )+ assert "circuit open" not in cold["error"] and cold["data_gaps"] == [cold["error"]]++ # With a last good copy it is served marked, and the gap says why.+ respx.get(_ECB_BSI_URL).respond(200, json=_BSI)+ await liquidity.fetch_ecb_series(fetcher, key=liquidity._ECB_MONEY_KEY)+ _expire(fetcher)+ respx.get(_ECB_BSI_URL).respond(200, content=body)+ warm = await liquidity.fetch_ecb_series(fetcher, key=liquidity._ECB_MONEY_KEY)+ assert warm["series"] and all(s["served_from_stale_cache"] and s["fetch_failure"] == failure+ for s in warm["series"])+ assert any(f": {failure}; served from stale cache (" in g for g in warm["data_gaps"])+++# ---------------------------------------------------------------------------+# Every stale serve counts on the circuit breaker+# ---------------------------------------------------------------------------+++async def test_every_stale_serve_counts_on_the_breaker(fetcher):+ _mock_all()+ await liquidity.fetch_liquidity_board(fetcher)+ counts = lambda: {src: fetcher.breaker.status()[src]["total_stale_serves"] # noqa: E731+ for src in (liquidity.FRED_SOURCE, liquidity.ECB_SOURCE)}+ assert counts() == {liquidity.FRED_SOURCE: 0, liquidity.ECB_SOURCE: 0}+ _expire(fetcher)+ respx.get(_FRED_URL).respond(503)+ respx.get(_ECB_BSI_URL).respond(503)+ respx.get(_ECB_ILM_URL).respond(503)+ board = await liquidity.fetch_liquidity_board(fetcher)+ assert all(r["served_from_stale_cache"] for r in board["indicators"])+ # WALCL, WDTGAL, RRPONTSYD and M2SL; BSI and ILM.+ assert counts() == {liquidity.FRED_SOURCE: 4, liquidity.ECB_SOURCE: 2}+ # Copies served behind an open circuit count too.+ for _ in range(3):+ fetcher.breaker.record_failure(liquidity.FRED_SOURCE)+ assert not fetcher.breaker.is_available(liquidity.FRED_SOURCE)+ single = await liquidity.fetch_fed_liquidity_series(fetcher, "WALCL")+ assert single["served_from_stale_cache"] is True+ assert counts()[liquidity.FRED_SOURCE] == 5+++async def test_fresh_answers_and_unserved_copies_do_not_count(fetcher):+ _mock_all()+ await liquidity.fetch_net_liquidity(fetcher)+ await liquidity.fetch_ecb_series(fetcher, key=liquidity._ECB_MONEY_KEY)+ respx.get(_FRED_URL).respond(503)+ cold = await liquidity.fetch_fed_liquidity_series(fetcher, "M2SL") # nothing cached for M2SL+ assert "no cached copy" in cold["error"]+ assert fetcher.breaker.status()[liquidity.FRED_SOURCE]["total_stale_serves"] == 0+ assert fetcher.breaker.status()[liquidity.ECB_SOURCE]["total_stale_serves"] == 0+++# ---------------------------------------------------------------------------+# Gaps and errors name the failure kind+# ---------------------------------------------------------------------------++[email protected]("failure, named", [+ (httpx.Response(503), "upstream fetch failed (HTTP 503)"),+ (httpx.Response(404, text="<html>Not Found</html>"), "upstream fetch failed (HTTP 404)"),+ (httpx.ReadTimeout("offline"), "upstream fetch failed (no response: ReadTimeout)"),+ (httpx.ConnectError("offline"), "upstream fetch failed (no response: ConnectError)"),+])+async def test_fred_failure_kind_is_named_cold_and_stale(fetcher, failure, named):+ route = respx.get(_FRED_URL)+ _respond(route, failure)+ cold = await liquidity.fetch_fed_liquidity_series(fetcher, "WALCL")+ assert cold["error"] == f"FRED graph CSV for WALCL unavailable: {named}, no cached copy"+ assert cold["data_gaps"] == [cold["error"]]++ route.mock(side_effect=_fred_router())+ await liquidity.fetch_fed_liquidity_series(fetcher, "WALCL")+ _expire(fetcher)+ _respond(route, failure)+ warm = await liquidity.fetch_fed_liquidity_series(fetcher, "WALCL")+ assert warm["served_from_stale_cache"] is True and warm["fetch_failure"] == named+ assert warm["freshness"]["fetch_failure"] == named+ assert any(g.startswith(f"WALCL: {named}; served from stale cache (") for g in warm["data_gaps"])++[email protected]("failure, named", [+ (httpx.Response(503), "upstream fetch failed (HTTP 503)"),+ (httpx.Response(500), "upstream fetch failed (HTTP 500)"),+ (httpx.ReadTimeout("offline"), "upstream fetch failed (no response: ReadTimeout)"),+])+async def test_ecb_failure_kind_is_named_cold_and_stale(fetcher, failure, named):+ route = respx.get(_ECB_BSI_URL)+ _respond(route, failure)+ cold = await liquidity.fetch_ecb_series(fetcher, key=liquidity._ECB_MONEY_KEY)+ assert cold["error"] == (+ f"ECB Data Portal returned no data for BSI/{liquidity._ECB_MONEY_KEY}: {named}, no cached copy"+ )+ route.mock(return_value=httpx.Response(200, json=_BSI))+ await liquidity.fetch_money_supply(fetcher, region="euro_area")+ _expire(fetcher)+ _respond(route, failure)+ money = await liquidity.fetch_money_supply(fetcher, region="euro_area")+ for roles in money["euro_area"]["aggregates"].values():+ for s in roles.values():+ assert s["fetch_failure"] == named and s["freshness"]["fetch_failure"] == named+ assert any(g.startswith(f"euro area M3 stock: {named}; served from stale cache (") for g in money["data_gaps"])+++async def test_open_circuit_is_named_on_every_surface(fetcher):+ _mock_all()+ await liquidity.fetch_liquidity_board(fetcher)+ await liquidity.fetch_net_liquidity(fetcher)+ _expire(fetcher)+ for _ in range(3):+ fetcher.breaker.record_failure(liquidity.FRED_SOURCE)+ fetcher.breaker.record_failure(liquidity.ECB_SOURCE)+ routes = [respx.get(url).respond(503) for url in (_FRED_URL, _ECB_BSI_URL, _ECB_ILM_URL)]+ sent_before = sum(r.call_count for r in routes)+ board = await liquidity.fetch_liquidity_board(fetcher)+ net = await liquidity.fetch_net_liquidity(fetcher)+ assert sum(r.call_count for r in routes) == sent_before # nothing sent while open+ assert {r["indicator"] for r in board["indicators"]} >= _ECB_ROWS | {"net_liquidity"}+ for row in board["indicators"]:+ assert row["fetch_failure"] == _CIRCUIT_OPEN and row["freshness"]["fetch_failure"] == _CIRCUIT_OPEN+ assert net["fetch_failure"] == _CIRCUIT_OPEN+ assert all(c["fetch_failure"] == _CIRCUIT_OPEN for c in net["components"].values())+ for out in (board, net):+ stale_gaps = [g for g in out["data_gaps"] if "served from stale cache" in g]+ assert stale_gaps and all(f": {_CIRCUIT_OPEN}; served from stale cache (" in g for g in stale_gaps)+++async def test_no_gap_says_the_cause_is_unknown(fetcher):+ """The generic "fetch failed or circuit open" sentence named no cause."""+ _mock_all()+ await liquidity.fetch_liquidity_board(fetcher)+ await liquidity.fetch_net_liquidity(fetcher)+ await liquidity.fetch_money_supply(fetcher)+ _expire(fetcher)+ respx.get(_FRED_URL).respond(503)+ respx.get(_ECB_BSI_URL).respond(503)+ respx.get(_ECB_ILM_URL).respond(503)+ outputs = [+ await liquidity.fetch_fed_liquidity_series(fetcher, "M2SL"),+ await liquidity.fetch_net_liquidity(fetcher),+ await liquidity.fetch_money_supply(fetcher),+ await liquidity.fetch_ecb_series(fetcher, key=liquidity._ECB_MONEY_KEY),+ await liquidity.fetch_liquidity_board(fetcher),+ ]+ for out in outputs:+ texts = list(out["data_gaps"]) + [out.get("error") or ""]+ assert not any("or circuit open" in t or "fetch failed, no cached copy" in t for t in texts)+ assert any("(HTTP 503)" in t or "(circuit open:" in t for t in texts)+++async def test_parse_errors_are_named(fetcher):+ respx.get(_FRED_URL).mock(side_effect=_fred_router({"WALCL": httpx.Response(200, text="<html>Maintenance</html>")}))+ fred = await liquidity.fetch_fed_liquidity_series(fetcher, "WALCL")+ assert fred["error"].startswith("FRED graph CSV for WALCL not in the expected format (parse error: unexpected header")+ respx.get(_ECB_BSI_URL).respond(200, content=b"{broken")+ ecb = await liquidity.fetch_ecb_series(fetcher, key=liquidity._ECB_MONEY_KEY)+ assert ecb["error"].startswith("ECB Data Portal response not in the expected SDMX-JSON shape (parse error: JSONDecodeError(")+ shape = copy.deepcopy(_BSI)+ del shape["structure"]+ respx.get(_ECB_BSI_URL).respond(200, json=shape)+ ecb = await liquidity.fetch_ecb_series(fetcher, key=liquidity._ECB_MONEY_KEY)+ assert ecb["error"] == (+ f"ECB Data Portal response for BSI/{liquidity._ECB_MONEY_KEY} not in the expected "+ "SDMX-JSON shape (parse error: KeyError('structure'))"+ )+++# ---------------------------------------------------------------------------+# Boundaries the earlier tests left open+# ---------------------------------------------------------------------------+++async def test_ecb_key_cap_is_exactly_fifty_combinations(fetcher):+ route = respx.get(url__startswith="https://data-api.ecb.europa.eu/").respond(200, json=_BSI)+ items = lambda n: "+".join(f"M{i}" for i in range(n)) # noqa: E731+ fifty = f"M.U2.Y.V.{items(25)}.X.1+4.U2.2300.Z01.E" # 25 x 2+ fifty_one = f"M.U2.Y.V.{items(17)}.X.1+4+I.U2.2300.Z01.E" # 17 x 3+ assert len(fifty) <= 200 and len(fifty_one) <= 200 # the cap, not the length rule, decides+ accepted = await liquidity.fetch_ecb_series(fetcher, key=fifty)+ assert "error" not in accepted and accepted["series_count"] == 12+ assert route.call_count == 1+ refused = await liquidity.fetch_ecb_series(fetcher, key=fifty_one)+ assert refused["error"] == (+ "key must specify every SDMX dimension (11 for BSI) without wildcards and at most 50 series combinations"+ )+ assert route.call_count == 1+++async def test_fred_dot_cell_is_a_missing_observation(fetcher):+ text = "observation_date,RRPONTSYD\n2013-09-20,.\n2013-09-23,1.5\n2013-09-24,\n2013-09-25,0.25\n"+ assert liquidity.parse_fred_csv(text, "RRPONTSYD") == [+ (date(2013, 9, 20), None), (date(2013, 9, 23), 1.5),+ (date(2013, 9, 24), None), (date(2013, 9, 25), 0.25),+ ]+ respx.get(_FRED_URL).respond(200, text=text)+ 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]diff --git a/src/world_intel_mcp/tools/liquidity.py b/src/world_intel_mcp/tools/liquidity.pyindex 024dda5..7fe2d2b 100644--- a/src/world_intel_mcp/tools/liquidity.py+++ b/src/world_intel_mcp/tools/liquidity.py@@ -38,7 +38,10 @@ TOOLS: list[Tool] = ["sort": {"type": "string","enum": ["biggest_move", "newest"],- "description": "biggest_move (absolute percent change) or newest (latest period end)",+ "description": (+ "biggest_move (largest absolute change, in billions of each row's currency, "+ "no FX conversion; percent change does not rank) or newest (latest period end)"+ ),"default": "biggest_move",},},@@ -111,7 +114,8 @@ TOOLS: list[Tool] = ["ECB Data Portal series by SDMX key, keyless: BSI (euro area monetary ""aggregates and MFI balance sheets) or ILM (Eurosystem weekly financial ""statement). Units, scale and provisional flags come from the response; each "- "series is typed as amount_outstanding, flow, growth_rate or index. "+ "series is typed as amount_outstanding, flow, growth_rate, index or unknown "+ "(a data type not recognized, named in data_gaps). ""Example key: BSI M.U2.Y.V.M30.X.1.U2.2300.Z01.E (euro area M3 stock)."),inputSchema={@@ -125,7 +129,7 @@ TOOLS: list[Tool] = [},"key": {"type": "string",- "description": "SDMX series key; '+' selects several values in one dimension",+ "description": liquidity.ECB_KEY_RULES,},"limit": {**_LIMIT,