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: review fixes for stale copies, RRP alignment and ECB no-data

Phoenix Agent (mac-studio)c9de357ec13f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 629a2fa..7312f75 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,7 +7,7 @@ Keyless sources only: the FRED graph CSV (`fred.stlouisfed.org/graph/fredgraph.c
allowed by robots.txt with `Crawl-delay: 1`, honored by a 1 s `fred-graph` rate
floor) and the ECB Data Portal (SDMX-JSON). Every point carries `observed_at`,
`value` and `units`; every series is typed `amount_outstanding`, `flow`,
-`growth_rate` or `index` and carries a freshness block that flags data older than
+`growth_rate`, `index` or `unknown` and carries a freshness block that flags data older than
its publication cadence allows (a served stale cache copy or an outage shows up
there). `published_at` is null: neither payload carries release dates, and the
responses say so. `limit=0` returns the full history.
@@ -15,9 +15,9 @@ responses say so. `limit=0` returns the full history.
Account (WDTGAL) minus overnight reverse repo (RRPONTSYD), in USD billions.
WALCL and WDTGAL are USD millions and are divided by 1,000; RRPONTSYD is already
USD billions. One point per WALCL Wednesday; the TGA must be reported for that
- Wednesday; RRP comes from that day or, when that day is blank (a holiday), the
- latest earlier business day within 5 days, and each point names the RRP date
- used. Weeks without aligned components are skipped and counted, never filled
+ Wednesday; RRP comes from that day or, when blank on or after 2013-09-23,
+ Tuesday only. Before that date a blank Wednesday has no fallback. Each point
+ names the RRP date used. Weeks without aligned components are skipped and counted, never filled
with zero, and a failed component makes the whole response an error. The TGA
term is the Wednesday level (WDTGAL), not the week average (WTREGEN). A
`method` block, returned with errors too, states each term's observation basis
@@ -25,7 +25,10 @@ responses say so. `limit=0` returns the full history.
billions), its conversion, the RRP alignment and why WTREGEN is not used.
- `intel_liquidity_board`: latest reading and change vs the previous observation
for the Fed balance sheet, TGA, RRP, net liquidity, US M2, euro area M1/M2/M3
- stocks and Eurosystem total assets, sortable by `biggest_move` or `newest`. A
+ stocks and Eurosystem total assets, sortable by `biggest_move` or `newest`.
+ `biggest_move` ranks absolute changes in billions of each row currency, with
+ no FX conversion; observation horizons differ. Percentage changes do not
+ affect ranking. A
failed source becomes an `unavailable` row; net liquidity is dropped, not
computed with a zero term, when any of its components fails. A `blocked` list
names each measure not covered with its publisher and the status measured on
@@ -37,11 +40,15 @@ responses say so. `limit=0` returns the full history.
- `intel_fed_liquidity_series`: WALCL, WDTGAL, WTREGEN, RRPONTSYD or M2SL with full
history; blank source dates (2,833 for RRPONTSYD on 2026-10-17, 2,679 of them
before 2013-09-23, when daily values begin) are counted, not read as zero.
- Net liquidity therefore starts at 2003-02-12 with 523 earlier or unaligned
- weeks skipped and counted, the last of them 2013-09-18.
- `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 is
reported 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.
+ 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.
- CLI: `intel liquidity`, `intel net-liquidity`, `intel money-supply`,
`intel fed-liquidity`, `intel ecb-series`. Collector: `liquidity_board` and
`net_liquidity` (group `liquidity`).
diff --git a/README.md b/README.md
index b88d20f..2ab29fe 100644
--- a/README.md
+++ b/README.md
@@ -222,11 +222,11 @@ collector.py (daemon) ─┘
| `intel_central_bank_rates` | Policy rates for 15 major central banks |
### Liquidity and Money (5)
-Keyless: FRED graph CSV and the ECB Data Portal. Every point carries its observation date, value and units; every series is typed `amount_outstanding`, `flow`, `growth_rate` or `index`, and carries a freshness block (age of the newest observation against its publication cadence). `limit=0` returns the full history. A failed upstream is an error or an `unavailable` row, never a zero.
+Keyless: FRED graph CSV and the ECB Data Portal. Every point carries its observation date, value and units; every series is typed `amount_outstanding`, `flow`, `growth_rate`, `index` or `unknown`, and carries a freshness block (age of the newest observation against its publication cadence). `limit=0` returns the full history. A failed upstream is an error or an `unavailable` row, never a zero.
| Tool | Description |
|------|-------------|
-| `intel_liquidity_board` | Latest reading and change vs the previous observation for the Fed balance sheet, TGA, overnight reverse repo, net liquidity, US M2, euro area M1/M2/M3 and Eurosystem total assets; sort by `biggest_move` or `newest`; a `blocked` list names the measures not covered (ICI fund flows and ETF net issuance, FINRA margin statistics, BLS) with the upstream status measured, and no proxy stands in for them |
+| `intel_liquidity_board` | Latest reading and change vs the previous observation for the Fed balance sheet, TGA, overnight reverse repo, net liquidity, US M2, euro area M1/M2/M3 and Eurosystem total assets; sort by `biggest_move` (absolute change in billions of each row currency, no FX conversion; horizons differ) or `newest`; a `blocked` list names the measures not covered (ICI fund flows and ETF net issuance, FINRA margin statistics, BLS) with the upstream status measured, and no proxy stands in for them |
| `intel_net_liquidity` | Weekly WALCL minus WDTGAL minus RRPONTSYD in USD billions (millions divided by 1,000), aligned on the WALCL Wednesday; each point names its components and the RRP date used; unaligned weeks are skipped and counted; a `method` block states each term's observation basis, units, conversion and RRP alignment |
| `intel_money_supply` | US M2 (FRED M2SL) and euro area M1, M2, M3 (ECB BSI stocks, monthly flows, annual growth rates), reported separately and never summed; US M3 is reported as discontinued |
| `intel_fed_liquidity_series` | One FRED liquidity series (WALCL, WDTGAL, WTREGEN, RRPONTSYD, M2SL) with full history; blank source dates are counted, not read as zero |
diff --git a/src/world_intel_mcp/sources/liquidity.py b/src/world_intel_mcp/sources/liquidity.py
index 962be75..53e566e 100644
--- a/src/world_intel_mcp/sources/liquidity.py
+++ b/src/world_intel_mcp/sources/liquidity.py
@@ -16,6 +16,9 @@ Every point carries ``observed_at`` (the period the value describes),
outstanding, 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.
+RRP uses the Wednesday value; a blank Wednesday on or after 2013-09-23
+may use Tuesday only. Earlier blank Wednesdays and missing Tuesdays are
+skipped and counted, never filled.
Blocked upstreams (measured 2026-10-17, see ROADMAP Phase 29 and
``BLOCKED_SOURCES``): ICI money market fund assets and ETF net issuance
@@ -31,10 +34,14 @@ import calendar
import copy
import csv
import io
+import json
import logging
+import math
import re
+import time
from datetime import date, datetime, timezone
from typing import Any
+from urllib.parse import urlencode
from ..fetcher import Fetcher
@@ -133,10 +140,7 @@ NESTING_NOTE = (
"never added together."
)
-# Net liquidity components and the unit each is converted to before the
-# subtraction. RRP may come from up to this many days before the
-# Wednesday (a holiday leaves a blank FRED cell); never from after it.
-_NET_LIQUIDITY_RRP_LOOKBACK_DAYS = 5
+_DAILY_RRP_START = date(2013, 9, 23)
NET_LIQUIDITY_FORMULA = (
"net_liquidity = WALCL - WDTGAL - RRPONTSYD, in USD billions: WALCL and "
"WDTGAL are USD millions divided by 1,000; RRPONTSYD is already USD billions"
@@ -144,8 +148,8 @@ NET_LIQUIDITY_FORMULA = (
NET_LIQUIDITY_ALIGNMENT = (
"One point per WALCL Wednesday. WDTGAL must be reported for that same "
"Wednesday. RRPONTSYD is taken from that Wednesday, or when that day is "
- f"blank, from the latest earlier business day within "
- f"{_NET_LIQUIDITY_RRP_LOOKBACK_DAYS} days; each point names the RRP date "
+ "blank on or after 2013-09-23, from Tuesday only; before that date a "
+ "blank Wednesday has no fallback. Each point names the RRP date "
"used. Weeks without an aligned TGA or RRP value are skipped and counted, "
"never filled with zero."
)
@@ -182,9 +186,9 @@ NET_LIQUIDITY_METHOD: dict[str, Any] = {
"units": "USD billions",
"conversion": "none: already USD billions",
"alignment": (
- "the value for the WALCL Wednesday; when that day is blank, the "
- f"latest earlier day within {_NET_LIQUIDITY_RRP_LOOKBACK_DAYS} days, "
- "reported per point as reverse_repo_observed_at; never a later day"
+ "the value for the WALCL Wednesday; when blank on or after "
+ "2013-09-23, Tuesday only; no fallback before that date. "
+ "Reported per point as reverse_repo_observed_at; never a later day"
),
},
},
@@ -248,7 +252,6 @@ 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}$")
-_FRED_ID_RE = re.compile(r"^[A-Z0-9]{2,30}$")
# ---------------------------------------------------------------------------
@@ -301,6 +304,7 @@ def _change(latest: dict | None, previous: dict | None, relative: bool = True) -
a, b = latest["value"], previous["value"]
return {
"absolute": _round(a - b),
+ "units": latest.get("units") if relative else "percentage points",
"pct": _round((a - b) / abs(b) * 100, 4) if b and relative else None,
"from": previous["observed_at"],
"to": latest["observed_at"],
@@ -320,6 +324,11 @@ 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"({fresh['cache_age_seconds']} seconds old)"
+ )
if fresh.get("stale"):
return (
f"{name}: newest observation {observed_at} is {fresh['latest_age_days']} "
@@ -357,27 +366,53 @@ 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 _mark_cached(series: dict, meta: dict) -> dict:
+ if meta:
+ series.update(meta)
+ series.setdefault("freshness", {}).update(meta, stale=True)
+ return series
+
+
async def _fred_rows(
fetcher: Fetcher, series_id: str
-) -> tuple[list[tuple[date, float | None]] | None, str | None]:
- text = await fetcher.get_text(
- _FRED_GRAPH_URL,
- source=FRED_SOURCE,
- cache_key=f"liquidity:fred:{series_id}",
- cache_ttl=_FRED_TTL,
- headers=_HEADERS,
- params={"id": series_id},
- timeout=20.0,
- )
+) -> tuple[list[tuple[date, float | None]] | None, str | None, dict]:
+ key = f"liquidity:fred:{series_id}"
+ text = fetcher.cache.get(key)
+ meta = {}
+ fetched = text is None
+ if fetched:
+ result = await fetcher.get_bytes(
+ f"{_FRED_GRAPH_URL}?{urlencode({'id': series_id})}",
+ source=FRED_SOURCE, headers=_HEADERS, timeout=20.0,
+ )
+ 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)"
+ return None, f"FRED graph CSV for {series_id} unavailable (fetch failed, no cached copy)", {}
try:
rows = parse_fred_csv(text, series_id)
- except ValueError as exc:
- return None, f"FRED graph CSV for {series_id} not in the expected format: {exc}"
+ 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}", {}
if not any(v is not None for _, v in rows):
- return None, f"FRED graph CSV for {series_id} has no observations"
- return rows, None
+ return None, f"FRED graph CSV for {series_id} has no observations", {}
+ if fetched and not meta:
+ fetcher.cache.set(key, text, _FRED_TTL)
+ return rows, None, meta
def _fred_period_end(series_id: str, d: date) -> date:
@@ -459,7 +494,7 @@ async def fetch_fed_liquidity_series(
except ValueError as exc:
return {"error": str(exc), "timestamp": _utc_now_iso()}
- rows, err = await _fred_rows(fetcher, sid)
+ rows, err, cache_meta = await _fred_rows(fetcher, sid)
if rows is None:
return {
"error": err,
@@ -468,7 +503,7 @@ async def fetch_fed_liquidity_series(
"data_gaps": [err],
"timestamp": _utc_now_iso(),
}
- series = _build_fred_series(sid, rows, n, start_d)
+ series = _mark_cached(_build_fred_series(sid, rows, n, start_d), cache_meta)
gaps = [_FRED_GAP]
stale = _stale_gap(sid, series["latest"]["observed_at"], series["freshness"])
if stale:
@@ -506,7 +541,7 @@ def compute_net_liquidity(
continue
tga_v = tga_by_day.get(day)
rrp_day: date | None = None
- for back in range(_NET_LIQUIDITY_RRP_LOOKBACK_DAYS + 1):
+ for back in range(2 if day >= _DAILY_RRP_START else 1):
candidate = date.fromordinal(day.toordinal() - back)
if candidate in rrp_by_day:
rrp_day = candidate
@@ -545,7 +580,7 @@ async def fetch_net_liquidity(
ids = ("WALCL", "WDTGAL", "RRPONTSYD")
fetched = await asyncio.gather(*(_fred_rows(fetcher, sid) for sid in ids))
- failures = {sid: err for sid, (rows, err) in zip(ids, fetched) if rows is None}
+ failures = {sid: err for sid, (rows, err, _) in zip(ids, fetched) if rows is None}
base = {
"source": FRED_SOURCE,
"formula": NET_LIQUIDITY_FORMULA,
@@ -567,7 +602,7 @@ async def fetch_net_liquidity(
"data_gaps": gaps,
"timestamp": _utc_now_iso(),
}
- walcl, tga, rrp = (rows for rows, _ in fetched)
+ walcl, tga, rrp = (rows for rows, _, _ in fetched)
all_points, skipped = compute_net_liquidity(walcl, tga, rrp)
if not all_points:
return {
@@ -586,9 +621,12 @@ async def fetch_net_liquidity(
newest_first = newest_first[:n]
keep = ("label", "units", "frequency", "measure", "release", "latest", "freshness")
components = {}
- for sid, rows in zip(ids, (walcl, tga, rrp)):
+ for sid, (rows, _, cache_meta) in zip(ids, fetched):
built = _build_fred_series(sid, rows, 1, None)
- components[sid] = {k: built[k] for k in keep}
+ components[sid] = _mark_cached({k: built[k] for k in keep}, cache_meta)
+ stale_components = [meta for _, _, meta in fetched if meta]
+ if stale_components:
+ _mark_cached(base, max(stale_components, key=lambda m: m["cache_age_seconds"]))
gaps = [_FRED_GAP, TGA_CHOICE_NOTE]
for sid, comp in components.items():
stale = _stale_gap(sid, comp["latest"]["observed_at"], comp["freshness"])
@@ -633,6 +671,9 @@ def _attr_lookup(defs: list[dict], indexes: list[Any]) -> dict[str, dict]:
def _ecb_units(attrs: dict[str, dict]) -> tuple[str | None, int | None]:
+ base = attrs.get("UNIT_INDEX_BASE")
+ if base:
+ return f"index ({base.get('name') or base.get('id')})", 1
unit = attrs.get("UNIT", {})
mult = attrs.get("UNIT_MULT", {})
unit_id = unit.get("id")
@@ -737,26 +778,41 @@ async def _ecb_fetch(
params["lastNObservations"] = last_n
if start is not None:
params["startPeriod"] = start.isoformat()
- data = await fetcher.get_json(
- _ECB_DATA_URL.format(dataset=dataset, key=key),
- source=ECB_SOURCE,
- cache_key=f"liquidity:ecb:{dataset}:{key}:{last_n}:{start}",
- cache_ttl=_ECB_TTL,
- headers=_HEADERS,
- params=params,
- timeout=30.0,
- )
- if not isinstance(data, dict):
- return None, (
- f"ECB Data Portal returned no data for {dataset}/{key} "
- "(outage, or no series matches the key)"
+ cache_key = f"liquidity:ecb:{dataset}:{key}:{last_n}:{start}"
+ data = fetcher.cache.get(cache_key)
+ cache_meta = {}
+ fetched = data is None
+ if fetched:
+ result = await fetcher.get_bytes(
+ f"{_ECB_DATA_URL.format(dataset=dataset, key=key)}?{urlencode(params)}",
+ source=ECB_SOURCE, headers=_HEADERS, timeout=30.0,
)
+ 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:
+ 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)"
try:
series = parse_sdmx_json(data, dataset)
- except (KeyError, IndexError, TypeError, ValueError) as exc:
+ 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}"
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)
+ for item in series:
+ item.update(cache_meta)
return series, None
@@ -782,7 +838,12 @@ def _finish_ecb_series(series: dict, limit: int) -> dict:
if series["measure"] == "flow"
else _change(latest, previous, relative=series["measure"] != "growth_rate")
),
- "freshness": _freshness(end, max_age),
+ "freshness": {
+ **_freshness(end, max_age),
+ **({"stale": True, "served_from_stale_cache": True,
+ "cache_age_seconds": series["cache_age_seconds"]}
+ if series.get("served_from_stale_cache") else {}),
+ },
"order": "newest_first",
"count": len(newest_first),
"points": newest_first,
@@ -811,11 +872,19 @@ async def fetch_ecb_series(
"timestamp": _utc_now_iso(),
}
key = str(key or "").strip()
- if not _ECB_KEY_RE.match(key):
+ if not _ECB_KEY_RE.fullmatch(key):
return {
"error": "key must be an SDMX series key: letters, digits, '.', '+' and '_' only",
"timestamp": _utc_now_iso(),
}
+ dimensions = key.split(".")
+ if (len(dimensions) != {"BSI": 11, "ILM": 6}[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",
+ "timestamp": _utc_now_iso(),
+ }
try:
n = _validate_limit(limit)
start_d = _validate_start(start)
@@ -894,12 +963,12 @@ async def fetch_money_supply(
want_us = reg in ("all", "us")
want_ea = reg in ("all", "euro_area")
- async def _none() -> tuple[None, None]:
- return None, None
+ async def _none(value):
+ return value
- us_task = _fred_rows(fetcher, "M2SL") if want_us else _none()
- ea_task = _ecb_fetch(fetcher, "BSI", _ECB_MONEY_KEY, n + 1 if n else 0, None) if want_ea else _none()
- (us_rows, us_err), (ea_series, ea_err) = await asyncio.gather(us_task, ea_task)
+ us_task = _fred_rows(fetcher, "M2SL") if want_us else _none((None, None, {}))
+ ea_task = _ecb_fetch(fetcher, "BSI", _ECB_MONEY_KEY, n + 1 if n else 0, None) if want_ea else _none((None, None))
+ (us_rows, us_err, us_cache), (ea_series, ea_err) = await asyncio.gather(us_task, ea_task)
gaps: list[str] = []
out: dict[str, Any] = {"region": reg, "note": NESTING_NOTE}
@@ -909,7 +978,7 @@ async def fetch_money_supply(
us["M2"] = {"error": us_err}
gaps.append(us_err)
else:
- m2 = _build_fred_series("M2SL", us_rows, n, None)
+ m2 = _mark_cached(_build_fred_series("M2SL", us_rows, n, None), us_cache)
us["M2"] = {**m2, "source": FRED_SOURCE}
gaps.append(_FRED_GAP)
stale = _stale_gap("M2SL", m2["latest"]["observed_at"], m2["freshness"])
@@ -939,9 +1008,10 @@ async def fetch_money_supply(
stale = _stale_gap(f"euro area {name} {role}", s["latest"]["observed_at"], s["freshness"])
if stale:
gaps.append(stale)
- missing = sorted(set(_ECB_AGGREGATE_CODES.values()) - set(aggregates))
- if missing:
- gaps.append(f"euro area aggregates missing from the ECB response: {missing}")
+ for name in _ECB_AGGREGATE_CODES.values():
+ for role in ("stock", "flow", "annual_growth_rate"):
+ if not aggregates.get(name, {}).get(role, {}).get("latest"):
+ gaps.append(f"euro area {name} {role}: missing observations from the ECB response")
us_failed = want_us and "error" in out.get("us", {}).get("M2", {})
ea_failed = want_ea and "error" in out.get("euro_area", {})
@@ -980,6 +1050,9 @@ def _row(
"frequency": frequency,
"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")}
+ 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,
"previous_value": previous["value"] if previous else None,
@@ -999,6 +1072,11 @@ _BOARD_FRED = (
)
+def _board_move(row: dict) -> float:
+ divisor = 1000 if (row.get("units") or "").endswith(" millions") else 1
+ return abs(row["change"] or 0.0) / divisor
+
+
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()
@@ -1019,12 +1097,12 @@ async def fetch_liquidity_board(fetcher: Fetcher, sort: str = "biggest_move") ->
gaps: list[str] = []
for indicator, sid in _BOARD_FRED:
- fr, err = fred_results[sid]
+ fr, err, cache_meta = fred_results[sid]
if fr is None:
unavailable.append({"indicator": indicator, "dataset": f"FRED {sid}", "error": err})
gaps.append(err)
continue
- s = _build_fred_series(sid, fr, 1, None)
+ s = _mark_cached(_build_fred_series(sid, fr, 1, None), cache_meta)
rows.append(
_row(
indicator, s["label"], s["dataset"], FRED_SOURCE, s["measure"], s["frequency"],
@@ -1035,8 +1113,8 @@ async def fetch_liquidity_board(fetcher: Fetcher, sort: str = "biggest_move") ->
)
nl_parts = [fred_results[s] for s in ("WALCL", "WDTGAL", "RRPONTSYD")]
- if all(rows_ is not None for rows_, _ in nl_parts):
- points, _ = compute_net_liquidity(*(rows_ for rows_, _ in nl_parts))
+ if all(rows_ is not None for rows_, _, _ in nl_parts):
+ points, _ = compute_net_liquidity(*(rows_ for rows_, _, _ in nl_parts))
if points:
latest = points[-1]
previous = points[-2] if len(points) > 1 else None
@@ -1051,6 +1129,9 @@ async def fetch_liquidity_board(fetcher: Fetcher, sort: str = "biggest_move") ->
end, _freshness(end, FRED_SERIES["WALCL"]["max_age_days"]),
)
)
+ stale_parts = [meta for _, _, meta in nl_parts if meta]
+ if stale_parts:
+ _mark_cached(rows[-1], max(stale_parts, key=lambda m: m["cache_age_seconds"]))
else:
unavailable.append({"indicator": "net_liquidity", "error": "no aligned week"})
gaps.append("net liquidity: no week had all three components aligned")
@@ -1065,10 +1146,7 @@ async def fetch_liquidity_board(fetcher: Fetcher, sort: str = "biggest_move") ->
(ilm_err, ilm, "ILM"),
):
if payload is None:
- name = "euro area M1/M2/M3" if wanted == "BSI" else "Eurosystem total assets"
- unavailable.append({"indicator": name, "dataset": f"ECB {wanted}", "error": err})
- gaps.append(err)
- continue
+ payload = []
for s in payload:
if wanted == "BSI":
agg = _ECB_AGGREGATE_CODES.get(s["dimensions"].get("BS_ITEM", ""))
@@ -1079,6 +1157,8 @@ async def fetch_liquidity_board(fetcher: Fetcher, sort: str = "biggest_move") ->
indicator, label = "eurosystem_total_assets", s["title"] or "Eurosystem total assets"
f = _finish_ecb_series(s, 1)
latest = f["latest"]
+ if latest is None:
+ continue
end = date.fromisoformat(latest["period_end"]) if latest and latest["period_end"] else None
rows.append(
_row(
@@ -1088,6 +1168,14 @@ async def fetch_liquidity_board(fetcher: Fetcher, sort: str = "biggest_move") ->
)
)
+ expected = ("euro_area_m1", "euro_area_m2", "euro_area_m3") if wanted == "BSI" else ("eurosystem_total_assets",)
+ present = {r["indicator"] for r in rows}
+ for indicator in expected:
+ if indicator not in present:
+ reason = err or "missing stock observations from the ECB response"
+ unavailable.append({"indicator": indicator, "dataset": f"ECB {wanted}", "error": reason})
+ gaps.append(f"{indicator}: {reason}")
+
for r in rows:
stale = _stale_gap(r["indicator"], r["observed_at"], r["freshness"])
if stale:
@@ -1096,7 +1184,7 @@ async def fetch_liquidity_board(fetcher: Fetcher, sort: str = "biggest_move") ->
if sort == "newest":
rows.sort(key=lambda r: (r["period_end"] or "", r["indicator"]), reverse=True)
else:
- rows.sort(key=lambda r: (r["change_pct"] is None, -abs(r["change_pct"] or 0.0), r["indicator"]))
+ rows.sort(key=lambda r: (r["change"] is None, -_board_move(r), r["indicator"]))
gaps.append(
"Changes are vs each indicator's previous observation, so horizons differ "
@@ -1114,6 +1202,11 @@ 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."
+ ),
"count": len(rows),
"indicators": rows,
"unavailable": unavailable,
diff --git a/src/world_intel_mcp/tests/test_liquidity_regressions.py b/src/world_intel_mcp/tests/test_liquidity_regressions.py
new file mode 100644
index 0000000..c6ffc3d
--- /dev/null
+++ b/src/world_intel_mcp/tests/test_liquidity_regressions.py
@@ -0,0 +1,327 @@
+"""Mocked regressions for liquidity data honesty and bounded requests."""
+
+import copy
+import csv
+from datetime import date
+from pathlib import Path
+from unittest.mock import AsyncMock
+
+import httpx
+import pytest
+import respx
+
+from world_intel_mcp.sources import liquidity
+from world_intel_mcp.tests.test_sources_liquidity import (
+ _BSI, _FRED, _FRED_URL, _ECB_BSI_URL, _ECB_ILM_URL,
+ _fixed_clock_and_no_throttle, _fred_router, _mock_all, fetcher,
+)
+
+
+def _expire(fetcher):
+ conn = fetcher.cache._get_conn()
+ conn.execute("UPDATE cache SET expires_at = ?, created_at = ?", (1, 1))
+ conn.commit()
+
+
+async def test_stale_cache_markers_reach_every_surface(fetcher):
+ _mock_all()
+ await liquidity.fetch_liquidity_board(fetcher)
+ await liquidity.fetch_net_liquidity(fetcher)
+ await liquidity.fetch_money_supply(fetcher)
+ await liquidity.fetch_ecb_series(fetcher, key=liquidity._ECB_MONEY_KEY)
+ _expire(fetcher)
+ respx.get(_FRED_URL).respond(503)
+ respx.get(_ECB_BSI_URL).respond(503)
+ respx.get(_ECB_ILM_URL).respond(503)
+ single = await liquidity.fetch_fed_liquidity_series(fetcher)
+ net = await liquidity.fetch_net_liquidity(fetcher)
+ money = await liquidity.fetch_money_supply(fetcher)
+ ecb = await liquidity.fetch_ecb_series(fetcher, key=liquidity._ECB_MONEY_KEY)
+ board = await liquidity.fetch_liquidity_board(fetcher)
+ series = [single, net, *net["components"].values(), money["us"]["M2"],
+ *ecb["series"], *board["indicators"]]
+ series += [s for roles in money["euro_area"]["aggregates"].values() for s in roles.values()]
+ for s in series:
+ assert s["served_from_stale_cache"] is True
+ assert s["cache_age_seconds"] > 3600
+ assert s["freshness"]["stale"] is True
+ for out in (single, net, money, ecb, board):
+ assert any("upstream fetch failed" in gap for gap in out["data_gaps"])
+
+
[email protected]("wednesday, earlier, expected", [
+ ("2024-12-25", "2024-12-24", True),
+ ("2003-02-12", "2003-02-07", False),
+ ("2013-09-18", "2013-09-17", False),
+ ("2024-12-25", "2024-12-23", False),
+])
+def test_rrp_only_tuesday_after_daily_operations_begin(wednesday, earlier, expected):
+ day = date.fromisoformat(wednesday)
+ points, skipped = liquidity.compute_net_liquidity(
+ [(day, 10000)], [(day, 1000)],
+ [(date.fromisoformat(earlier), 2), (day, None)],
+ )
+ assert bool(points) is expected
+ assert skipped == ([] if expected else [wednesday])
+ if expected:
+ assert points[0]["reverse_repo_observed_at"] == earlier
+ assert points[0]["value"] == 7
+
+
+def test_alignment_documentation_states_cutoff_and_tuesday():
+ for text in (liquidity.__doc__, liquidity.NET_LIQUIDITY_ALIGNMENT,
+ liquidity.NET_LIQUIDITY_METHOD["components"]["RRPONTSYD"]["alignment"]):
+ assert "2013-09-23" in text and "Tuesday" in text
+ changelog = (Path(__file__).parents[3] / "CHANGELOG.md").read_text()
+ assert "Tuesday only" in changelog
+ assert "Net liquidity therefore starts at 2003-02-12" not in changelog
+
+
[email protected]("status, body, message", [
+ (404, b'{"title":"No results"}', "no series matches the key"),
+ (200, b"", "no observations on or after 2026-10-01"),
+])
+async def test_ecb_no_data_never_retries_or_trips_breaker(fetcher, monkeypatch, status, body, message):
+ fetcher.max_retries = 2
+ sleep = AsyncMock()
+ monkeypatch.setattr("world_intel_mcp.fetcher.asyncio.sleep", sleep)
+ route = respx.get(_ECB_BSI_URL).respond(status, content=body)
+ for _ in range(4):
+ out = await liquidity.fetch_ecb_series(fetcher, key=liquidity._ECB_MONEY_KEY, start="2026-10-01")
+ assert message in out["error"]
+ assert "outage" not in out["error"]
+ assert route.call_count == 4
+ sleep.assert_not_awaited()
+ state = fetcher.breaker.status()[liquidity.ECB_SOURCE]
+ assert state["total_failures"] == 0 and state["status"] == "closed"
+ _mock_all()
+ board = await liquidity.fetch_liquidity_board(fetcher)
+ assert {r["indicator"] for r in board["indicators"]} >= {"euro_area_m1", "eurosystem_total_assets"}
+
+
[email protected]("failure", [503, "timeout", "connection"])
+async def test_ecb_real_outages_retry_and_trip(fetcher, monkeypatch, failure):
+ fetcher.max_retries = 1
+ monkeypatch.setattr("world_intel_mcp.fetcher.asyncio.sleep", AsyncMock())
+ route = respx.get(_ECB_BSI_URL)
+ if failure == 503:
+ route.respond(503)
+ else:
+ route.mock(side_effect=httpx.ReadTimeout("offline") if failure == "timeout" else httpx.ConnectError("offline"))
+ for _ in range(3):
+ out = await liquidity.fetch_ecb_series(fetcher, key=liquidity._ECB_MONEY_KEY)
+ assert "upstream fetch failed" in out["error"]
+ assert route.call_count == 6
+ assert fetcher.breaker.status()[liquidity.ECB_SOURCE]["status"] == "open"
+
+
[email protected]("missing_role", [None, "1", "4", "I"])
+async def test_partial_ecb_names_each_missing_role_and_board_row(fetcher, missing_role):
+ data = copy.deepcopy(_BSI)
+ dims = data["structure"]["dimensions"]["series"]
+ for key in list(data["dataSets"][0]["series"]):
+ codes = {d["id"]: d["values"][int(i)]["id"] for d, i in zip(dims, key.split(":"))}
+ if codes["BS_ITEM"] == "M30" and (missing_role is None or codes["DATA_TYPE"] == missing_role):
+ del data["dataSets"][0]["series"][key]
+ _mock_all(bsi=httpx.Response(200, json=data))
+ money = await liquidity.fetch_money_supply(fetcher, region="euro_area")
+ role = {"1": "stock", "4": "flow", "I": "annual_growth_rate"}.get(missing_role)
+ for expected in ([role] if role else ["stock", "flow", "annual_growth_rate"]):
+ assert any(f"M3 {expected}: missing" in gap for gap in money["data_gaps"])
+ board = await liquidity.fetch_liquidity_board(fetcher)
+ if missing_role in (None, "1"):
+ assert any(r["indicator"] == "euro_area_m3" and r["error"] for r in board["unavailable"])
+ assert any("euro_area_m3" in gap for gap in board["data_gaps"])
+
+
+async def test_all_expected_board_rows_accounted_for_on_outage(fetcher):
+ _mock_all(bsi=httpx.Response(503), ilm=httpx.Response(503))
+ board = await liquidity.fetch_liquidity_board(fetcher)
+ assert {r["indicator"] for r in board["indicators"] + board["unavailable"]} == {
+ "fed_total_assets", "treasury_general_account", "reverse_repo", "net_liquidity",
+ "us_m2", "euro_area_m1", "euro_area_m2", "euro_area_m3", "eurosystem_total_assets",
+ }
+
+
+def test_index_base_overrides_currency():
+ series = liquidity.parse_sdmx_json(_BSI, "BSI")
+ indexes = [s for s in series if s["measure"] == "index"]
+ assert indexes
+ for s in indexes:
+ assert s["units"] == "index (Dec10 = 100)"
+ assert all(p["units"] == s["units"] for p in s["points"])
+
+
+async def test_fred_bad_body_refetches_and_preserves_last_good(fetcher):
+ route = respx.get(_FRED_URL).mock(side_effect=_fred_router())
+ good = await liquidity.fetch_fed_liquidity_series(fetcher)
+ _expire(fetcher)
+ key = "liquidity:fred:WALCL"
+ original = fetcher.cache.get_stale_meta(key)
+ route.respond(200, text="<html>Unavailable</html>")
+ assert "error" in await liquidity.fetch_fed_liquidity_series(fetcher)
+ assert fetcher.cache.get(key) is None
+ assert fetcher.cache.get_stale_meta(key) == original
+ route.respond(503)
+ stale = await liquidity.fetch_fed_liquidity_series(fetcher)
+ assert stale["latest"] == good["latest"] and stale["served_from_stale_cache"]
+ route.mock(side_effect=_fred_router())
+ recovered = await liquidity.fetch_fed_liquidity_series(fetcher)
+ assert "error" not in recovered and not recovered.get("served_from_stale_cache")
+ assert route.call_count == 4
+
+
+async def test_fred_cold_html_does_not_poison_cache(fetcher):
+ route = respx.get(_FRED_URL).respond(200, text="<html>Unavailable</html>")
+ assert "error" in await liquidity.fetch_fed_liquidity_series(fetcher)
+ assert fetcher.cache.get_stale("liquidity:fred:WALCL") is None
+ route.mock(side_effect=_fred_router())
+ assert "latest" in await liquidity.fetch_fed_liquidity_series(fetcher)
+ assert route.call_count == 2
+
+
+async def test_malformed_csv_and_ecb_series_are_isolated_on_board(fetcher):
+ data = copy.deepcopy(_BSI)
+ data["dataSets"][0]["series"] = []
+ oversized = "observation_date,WALCL\n2026-10-14," + "9" * (csv.field_size_limit() + 1)
+ _mock_all(fred_overrides={"WALCL": httpx.Response(200, text=oversized)}, bsi=httpx.Response(200, json=data))
+ board = await liquidity.fetch_liquidity_board(fetcher)
+ missing = {r["indicator"]: r["error"] for r in board["unavailable"]}
+ assert "expected format" in missing["fed_total_assets"]
+ assert "SDMX-JSON shape" in missing["euro_area_m1"]
+ assert any(r["indicator"] == "us_m2" for r in board["indicators"])
+
+
+async def test_biggest_move_uses_amount_not_near_zero_percent(fetcher):
+ _mock_all()
+ board = await liquidity.fetch_liquidity_board(fetcher)
+ rows = board["indicators"]
+ amounts = [abs(r["change"]) / (1000 if r["units"].endswith(" millions") else 1) for r in rows]
+ assert amounts == sorted(amounts, reverse=True)
+ assert rows[0]["indicator"] != "reverse_repo"
+ assert "billions" in board["ranking_rule"] and "no FX conversion" in board["ranking_rule"]
+
+
+async def test_board_status_and_growth_change_units(fetcher):
+ _mock_all()
+ board = await liquidity.fetch_liquidity_board(fetcher)
+ for row in board["indicators"]:
+ if row["indicator"].startswith("euro_area_m"):
+ assert row["status"] == "Provisional value"
+ money = await liquidity.fetch_money_supply(fetcher, region="euro_area")
+ for roles in money["euro_area"]["aggregates"].values():
+ assert roles["annual_growth_rate"]["change"]["units"] == "percentage points"
+ assert roles["stock"]["change"]["units"] == "EUR millions"
+
+
+def test_unknown_measure_documented_and_unused_regex_removed():
+ root = Path(__file__).parents[3]
+ assert "`unknown`" in (root / "README.md").read_text()
+ assert not hasattr(liquidity, "_FRED_ID_RE")
+ assert liquidity._ecb_measure("BSI", {}) == "unknown"
+
+
+ "M.U2..........", "M.U2.Y.V.M30.X.1.U2.2300.Z01.",
+ "M.U2.Y.V.M30+.X.1.U2.2300.Z01.E", "M.U2",
+ "M.U2.Y.V." + "+".join(f"M{i}" for i in range(51)) + ".X.1.U2.2300.Z01.E",
+ "M.U2.Y.V.A+B+C+D.X.1+4+I.U2.2300.Z01.A+B+C+D+E",
+])
+async def test_unbounded_ecb_keys_rejected_before_request(fetcher, key):
+ route = respx.get(url__startswith="https://data-api.ecb.europa.eu/").respond(503)
+ out = await liquidity.fetch_ecb_series(fetcher, key=key)
+ assert "key must" in out["error"]
+ assert route.call_count == 0
+
+
+async def test_empty_ecb_stock_is_unavailable_and_missing_per_role(fetcher):
+ data = copy.deepcopy(_BSI)
+ dims = data["structure"]["dimensions"]["series"]
+ for key, body in data["dataSets"][0]["series"].items():
+ codes = {d["id"]: d["values"][int(i)]["id"] for d, i in zip(dims, key.split(":"))}
+ if codes["BS_ITEM"] == "M30" and codes["DATA_TYPE"] == "1":
+ body["observations"] = {}
+ _mock_all(bsi=httpx.Response(200, json=data))
+ board = await liquidity.fetch_liquidity_board(fetcher)
+ assert "euro_area_m3" not in {r["indicator"] for r in board["indicators"]}
+ assert "euro_area_m3" in {r["indicator"] for r in board["unavailable"]}
+ money = await liquidity.fetch_money_supply(fetcher, region="euro_area")
+ assert any("M3 stock: missing" in g for g in money["data_gaps"])
+
+
+async def test_only_failed_component_marks_net_stale_without_restamping(fetcher):
+ _mock_all()
+ await liquidity.fetch_liquidity_board(fetcher)
+ key = "liquidity:fred:WALCL"
+ conn = fetcher.cache._get_conn()
+ conn.execute("UPDATE cache SET expires_at = ?, created_at = ? WHERE key = ?", (1, 1, key))
+ conn.commit()
+ original = fetcher.cache.get_stale_meta(key)
+ respx.get(_FRED_URL).mock(side_effect=_fred_router({"WALCL": httpx.Response(503)}))
+ board = await liquidity.fetch_liquidity_board(fetcher)
+ for row in board["indicators"]:
+ assert bool(row.get("served_from_stale_cache")) == (row["indicator"] in ("fed_total_assets", "net_liquidity"))
+ net = await liquidity.fetch_net_liquidity(fetcher)
+ assert net["served_from_stale_cache"] is True
+ assert not net["components"]["WDTGAL"].get("served_from_stale_cache")
+ assert fetcher.cache.get_stale_meta(key) == original
+
+
+async def test_ecb_no_data_does_not_serve_an_old_cached_answer(fetcher):
+ _mock_all()
+ await liquidity.fetch_ecb_series(fetcher, key=liquidity._ECB_MONEY_KEY, start="2026-10-01")
+ _expire(fetcher)
+ 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 "no observations on or after 2026-10-01" in out["error"]
+ assert "series" not in out
+
+
+async def test_cached_invalid_bodies_are_evicted(fetcher):
+ key = "liquidity:fred:WALCL"
+ fetcher.cache.set(key, "<html>old error</html>", 3600)
+ assert "error" in await liquidity.fetch_fed_liquidity_series(fetcher)
+ assert fetcher.cache.get_stale(key) is None
+ ecb_key = f"liquidity:ecb:BSI:{liquidity._ECB_MONEY_KEY}:25:None"
+ fetcher.cache.set(ecb_key, {"bad": "shape"}, 3600)
+ assert "error" in await liquidity.fetch_ecb_series(fetcher, key=liquidity._ECB_MONEY_KEY)
+ assert fetcher.cache.get_stale(ecb_key) is None
+
+
+async def test_ecb_invalid_json_is_a_series_error(fetcher):
+ _mock_all(bsi=httpx.Response(200, content=b"{broken"))
+ out = await liquidity.fetch_ecb_series(fetcher, key=liquidity._ECB_MONEY_KEY)
+ assert "expected SDMX-JSON shape" in out["error"]
+ assert fetcher.cache.get_stale(f"liquidity:ecb:BSI:{liquidity._ECB_MONEY_KEY}:25:None") is None
+
+
[email protected]("status", [404, 200])
[email protected]("metric", ["attempts", "breaker"])
+async def test_ecb_no_data_transport_metrics(fetcher, monkeypatch, status, metric):
+ fetcher.max_retries = 2
+ monkeypatch.setattr("world_intel_mcp.fetcher.asyncio.sleep", AsyncMock())
+ route = respx.get(_ECB_BSI_URL).respond(status, content=b"")
+ for _ in range(4):
+ await liquidity.fetch_ecb_series(fetcher, key=liquidity._ECB_MONEY_KEY)
+ if metric == "attempts":
+ assert route.call_count == 4
+ else:
+ assert fetcher.breaker.status()[liquidity.ECB_SOURCE]["total_failures"] == 0
+ assert fetcher.breaker.is_available(liquidity.ECB_SOURCE)