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 and money: board, net liquidity, money supply, FRED and ECB series

Phoenix Agent (mac-studio)9d9389595d31
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6311734..51e9692 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,52 @@
# Changelog
+## Unreleased
+
+### Added: liquidity and money (Phase 29)
+Keyless sources only: the FRED graph CSV (`fred.stlouisfed.org/graph/fredgraph.csv`,
+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
+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.
+- `intel_net_liquidity`: weekly Fed total assets (WALCL) minus Treasury General
+ 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
+ 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).
+- `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
+ failed source becomes an `unavailable` row; net liquidity is dropped, not
+ computed with a zero term, when any of its components fails.
+- `intel_money_supply`: US M2 (FRED M2SL) and euro area M1, M2 and M3 from the ECB
+ BSI dataset (end-of-month stocks, monthly flows, annual growth rates), kept
+ separate and never summed. US M3 is reported as discontinued (FRED M3SL ends at
+ 2006-02-01).
+- `intel_fed_liquidity_series`: WALCL, WDTGAL, WTREGEN, RRPONTSYD or M2SL with full
+ history; blank source dates (2,833 for RRPONTSYD) are counted, not read as zero.
+- `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.
+- CLI: `intel liquidity`, `intel net-liquidity`, `intel money-supply`,
+ `intel fed-liquidity`, `intel ecb-series`. Collector: `liquidity_board` and
+ `net_liquidity` (group `liquidity`).
+- 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).
+
+Not added, measured 2026-10-17: ICI money market fund assets and ETF net issuance
+(403 on every path, robots.txt included); FINRA margin statistics (finra.org terms
+of use forbid robots and building a database from the site); BLS public API (keyless
+v1 answers, but api.bls.gov robots.txt disallows all paths and the terms page
+answers 403).
+
## 0.11.0 - 2026-10-12
Cross-border migration (MCP tools, CLI, collector and a dashboard
diff --git a/README.md b/README.md
index 77f7474..f380298 100644
--- a/README.md
+++ b/README.md
@@ -6,7 +6,7 @@
[![Python 3.11+](https://img.shields.io/badge/Python-3.11%2B-green)](https://python.org)
[![License](https://img.shields.io/badge/License-MIT-yellow)](LICENSE)
-Real-time global intelligence across **30+ domains** with **139 MCP tools**, a live ops-center dashboard, a CLI, and a **Qdrant vector store** for enterprise-grade semantic search across accumulated intelligence. All data comes from free, public APIs: no paid subscriptions required.
+Real-time global intelligence across **30+ domains** with **144 MCP tools**, a live ops-center dashboard, a CLI, and a **Qdrant vector store** for enterprise-grade semantic search across accumulated intelligence. All data comes from free, public APIs: no paid subscriptions required.
Built for AI agents that need world awareness: market conditions, geopolitical risk, military posture, aircraft-cohort early warning, refugee and migration flows, supply chain disruptions, cyber threats, and more — all queryable via the Model Context Protocol. The vector store enables natural language queries like *"military activity near Taiwan"* or *"cyber threats targeting healthcare"* across all historical data.
@@ -25,6 +25,7 @@ Built for AI agents that need world awareness: market conditions, geopolitical r
| **Macro Composite** | 1 | Weighted 6-signal market verdict (Fear&Greed, VIX, sectors, DXY, BTC, yields) |
| **Economic Indicators** | 6 | AAA fuel prices, EIA energy, FRED macro, World Bank |
| **Central Banks** | 1 | 15 central bank policy rates |
+| **Liquidity and Money** | 5 | Keyless FRED graph CSV (Fed balance sheet, Treasury General Account, overnight reverse repo, US M2) and ECB Data Portal (euro area M1/M2/M3 stocks, flows and growth, Eurosystem balance sheet); derived net liquidity with its formula, unit conversion and date alignment stated |
| **BTC Technicals** | 1 | SMA 50/200, golden/death cross, Mayer Multiple |
| **Natural Disasters** | 2 | USGS earthquakes, NASA FIRMS wildfires |
| **Environmental** | 2 | NASA EONET, GDACS disaster alerts |
@@ -64,7 +65,7 @@ Built for AI agents that need world awareness: market conditions, geopolitical r
| **Tropical Cyclones** | 2 | NHC (Atlantic, E/C Pacific) + JTWC (NW Pacific, N Indian, S Hemisphere) |
| **Situation Brief** | 1 | Cited situational awareness brief over MCP: bounded server-side overview synthesized via local Ollama, with a mechanically-cited fallback |
-**Total: 139 tools** across 30+ intelligence domains.
+**Total: 144 tools** across 30+ intelligence domains.
---
@@ -129,6 +130,8 @@ intel markets # stock indices
intel earthquakes --min-mag 5.0
intel migration-surges # year-over-year displacement jumps (UNHCR)
intel migration-flows -o Sudan
+intel liquidity # Fed balance sheet, TGA, RRP, net liquidity, US M2, euro area M1-M3
+intel net-liquidity -n 0 # full weekly history, components and RRP date per week
intel status # cache + circuit breaker health
```
@@ -147,7 +150,7 @@ collector.py (daemon) ─┘
- **CircuitBreaker**: Per-source tracking. 3 consecutive failures trips for 5 minutes. Each RSS feed gets its own breaker.
- **Cache**: SQLite WAL-mode TTL cache. `get()` returns live data, `get_stale()` returns expired data for fallback.
- **VectorStore**: Qdrant + FastEmbed (BAAI/bge-small-en-v1.5, 384-dim). Async background worker queue for non-blocking storage. Enables semantic search across all accumulated intelligence.
-- **Collector**: Standalone daemon that fetches all 55 sources in parallel and populates the vector store. Run once or as a daemon (default: 5-minute interval). Includes the AOI change sweep, so a running daemon continuously watches every defined geofence.
+- **Collector**: Standalone daemon that fetches all 57 sources in parallel and populates the vector store. Run once or as a daemon (default: 5-minute interval). Includes the AOI change sweep, so a running daemon continuously watches every defined geofence.
- **Sources** (`sources/*.py`): 30+ modules, each exports `async def fetch_*(fetcher, **kwargs) -> dict`.
- **Analysis** (`analysis/*.py`): Cross-domain synthesis — signal aggregation, instability indexing, NLP, company enrichment, macro composite.
- **Config** (`config/*.py`): Curated datasets — 22 hotspots, 70+ bases, 40 ports, 24 pipelines, 24 nuclear facilities, 34 cables, 48 datacenters, 27 spaceports, 82 exchanges.
@@ -218,6 +221,17 @@ 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.
+
+| 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` |
+| `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 |
+| `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 |
+| `intel_ecb_series` | ECB Data Portal series by SDMX key from BSI (monetary aggregates) or ILM (Eurosystem weekly financial statement), with units, scale and provisional flags from the response |
+
### BTC Technicals (1)
| Tool | Description |
|------|-------------|
@@ -665,7 +679,7 @@ Everything else uses free, unauthenticated public APIs.
```bash
pip install -e ".[dev]"
-pytest # 973 tests (991 total, 18 live-network smoke tests deselected by default)
+pytest # 1034 tests (1052 total, 18 live-network smoke tests deselected by default)
pytest --cov=world_intel_mcp # with coverage
pytest tests/test_forex.py -v # single module
```
diff --git a/ROADMAP.md b/ROADMAP.md
index 7249537..236a42d 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -577,7 +577,7 @@ dashboard.
| 1 | Research guide over MCP | MCP resources (guide generated from the live registry and source health, measures glossary, "what this server will not do") and MCP prompts (worked research questions, each naming the tools it needs and the limit to respect). Server exposed no prompts or resources before | :red_circle: |
| 1 | Hostility timeline | Per country pair or country, daily counts of threat / sanction / force / criticism coverage plus tone; sortable by most covered, most hostile, biggest change | :red_circle: |
| 1 | Story breadth | News clusters carry a distinct-outlet count; a top-stories view ranks by how many outlets carry a story | :red_circle: |
-| 1 | Liquidity and flows | Fed balance sheet, Treasury General Account, reverse repo and net liquidity (FRED keyless CSV), money supply (US M2, euro area M1/M2/M3, never summed), ECB, ICI fund flows and ETF net issuance, FINRA margin statistics, BLS series; amounts kept separate from flows | :red_circle: |
+| 1 | Liquidity and flows | Fed balance sheet, Treasury General Account, reverse repo and net liquidity (FRED keyless CSV), money supply (US M2, euro area M1/M2/M3, never summed), ECB, ICI fund flows and ETF net issuance, FINRA margin statistics, BLS series; amounts kept separate from flows | :yellow_circle: Built, unreleased: 5 tools (`intel_liquidity_board`, `intel_net_liquidity`, `intel_money_supply`, `intel_fed_liquidity_series`, `intel_ecb_series`), 5 CLI commands, 2 collector sources. FRED graph CSV and ECB Data Portal live-verified 2026-10-17. The TGA term is WDTGAL (Wednesday level): WTREGEN is a week average. Blocked, measured 2026-10-17: ICI (money market fund assets, ETF net issuance) answers 403 Akamai "Access Denied" on every path, robots.txt included; FINRA margin statistics XLSX answers 200, but finra.org terms of use forbid robots and building a database from the site, and the page says data feeds are not available; BLS public API v1 answers 200 without a key, but api.bls.gov robots.txt is `Disallow: /` and the terms page on www.bls.gov answers 403 to this server's User-Agent, so it is not used |
| 1 | Kalshi + cross-venue markets | Kalshi public market data next to Polymarket; same-event comparison with an explicit match confidence; settled markets scored against pre-settlement prices (Brier) | :red_circle: |
| 1 | News vs market reaction | Companies and countries named in story clusters mapped to tickers / country indices; same-day move against a benchmark | :red_circle: |
| 2 | Connections with timing offsets | Correlation between retained series over a shared sample, tested at leads and lags, with minimum sample size and false-discovery control; states that it does not prove causation | :red_circle: |
diff --git a/src/world_intel_mcp/cli.py b/src/world_intel_mcp/cli.py
index af3204c..056ef1f 100644
--- a/src/world_intel_mcp/cli.py
+++ b/src/world_intel_mcp/cli.py
@@ -68,6 +68,7 @@ from .sources.github_trending import fetch_trending_repos
from .sources.arxiv_papers import fetch_arxiv_papers
from .sources.usa_spending import fetch_usa_spending
from .sources import geospatial
+from .sources import liquidity
console = Console()
@@ -1574,6 +1575,181 @@ def central_banks_cmd(ctx: click.Context) -> None:
console.print(table)
+# ---------------------------------------------------------------------------
+# Liquidity and money (Phase 29)
+# ---------------------------------------------------------------------------
+
+
+def _liq_num(value: Any, signed: bool = False) -> str:
+ """Two decimals, rounded half-up on the value as reported: binary
+ float formatting would show 5869.615 as 5,869.61."""
+ if value is None:
+ return "n/a"
+ from decimal import ROUND_HALF_UP, Decimal
+
+ d = Decimal(repr(value)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
+ return f"{d:+,.2f}" if signed else f"{d:,.2f}"
+
+
+def _liq_points_table(title: str, points: list[dict], extra: tuple[str, ...] = ()) -> Table:
+ table = Table(title=title, box=box.SIMPLE_HEAVY)
+ table.add_column("Observed", style="bold")
+ table.add_column("Value", justify="right")
+ table.add_column("Units")
+ for col in extra:
+ table.add_column(col.replace("_", " ").title(), justify="right")
+ for p in points:
+ table.add_row(
+ _cell(p.get("observed_at", "")),
+ _liq_num(p.get("value")),
+ _cell(p.get("units") or ""),
+ *(
+ _liq_num(p.get(c)) if isinstance(p.get(c), (int, float)) else _cell(p.get(c) or "")
+ for c in extra
+ ),
+ )
+ return table
+
+
[email protected](name="liquidity")
+ "--sort", type=click.Choice(["biggest_move", "newest"]), default="biggest_move",
+ help="Order rows by absolute percent change or by newest period",
+)
+def liquidity_cmd(ctx: click.Context, sort: str) -> None:
+ """Liquidity board: Fed balance sheet, TGA, RRP, net liquidity, M2, euro M1-M3."""
+ 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")
+ 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", "")),
+ _liq_num(r.get("latest_value")),
+ _cell(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)
+ for u in data.get("unavailable", []):
+ console.print(
+ f"[red]Unavailable:[/red] {escape(str(u.get('indicator')))}: {escape(str(u.get('error')))}"
+ )
+ _print_data_gaps(data)
+
+
[email protected](name="net-liquidity")
[email protected]("--limit", "-n", default=12, help="Newest weeks (0 = full history)")
[email protected]("--start", default=None, help="Only weeks on or after YYYY-MM-DD")
+def net_liquidity_cmd(ctx: click.Context, limit: int, start: str | None) -> None:
+ """US net liquidity = WALCL - WDTGAL - RRPONTSYD, weekly, USD billions."""
+ data = _run(liquidity.fetch_net_liquidity(_get_fetcher(), limit=limit, start=start))
+ if _bail_on_error(ctx, data):
+ return
+ console.print(f"[bold]{escape(str(data.get('formula', '')))}[/bold]")
+ console.print(f"[dim]{escape(str(data.get('alignment', '')))}[/dim]\n")
+ console.print(
+ _liq_points_table(
+ "US net liquidity",
+ data.get("points", []),
+ ("fed_total_assets", "treasury_general_account", "reverse_repo", "reverse_repo_observed_at"),
+ )
+ )
+ _print_data_gaps(data)
+
+
[email protected](name="money-supply")
+ "--region", type=click.Choice(["all", "us", "euro_area"]), default="all",
+ help="US M2, euro area M1/M2/M3, or both",
+)
[email protected]("--limit", "-n", default=6, help="Newest months per series (0 = full history)")
+def money_supply_cmd(ctx: click.Context, region: str, limit: int) -> None:
+ """Money supply: US M2 and euro area M1/M2/M3, never summed."""
+ data = _run(liquidity.fetch_money_supply(_get_fetcher(), region=region, limit=limit))
+ if _bail_on_error(ctx, data):
+ return
+ us = data.get("us")
+ if us is not None:
+ m2 = us.get("M2", {})
+ if "error" in m2:
+ console.print(f"[red]US M2 unavailable:[/red] {escape(str(m2['error']))}")
+ else:
+ console.print(_liq_points_table("US M2 (FRED M2SL, seasonally adjusted)", m2.get("points", [])))
+ console.print(f"[dim]{escape(str(us.get('M3', {}).get('note', '')))}[/dim]")
+ ea = data.get("euro_area")
+ if ea is not None:
+ if "error" in ea:
+ console.print(f"[red]Euro area unavailable:[/red] {escape(str(ea['error']))}")
+ else:
+ for name, roles in ea.get("aggregates", {}).items():
+ for role, s in roles.items():
+ console.print(
+ _liq_points_table(f"Euro area {name} {role}", s.get("points", []), ("status",))
+ )
+ console.print(f"[dim]{escape(str(data.get('note', '')))}[/dim]")
+ _print_data_gaps(data)
+
+
[email protected](name="fed-liquidity")
[email protected]("series_id", type=click.Choice(sorted(liquidity.FRED_SERIES), case_sensitive=False))
[email protected]("--limit", "-n", default=20, help="Newest points (0 = full history)")
[email protected]("--start", default=None, help="Only points on or after YYYY-MM-DD")
+def fed_liquidity_cmd(ctx: click.Context, series_id: str, limit: int, start: str | None) -> None:
+ """One keyless FRED liquidity series (WALCL, WDTGAL, WTREGEN, RRPONTSYD, M2SL)."""
+ data = _run(
+ liquidity.fetch_fed_liquidity_series(
+ _get_fetcher(), series_id=series_id, limit=limit, start=start
+ )
+ )
+ if _bail_on_error(ctx, data):
+ return
+ console.print(
+ _liq_points_table(
+ f"{data.get('label')} ({data.get('series_id')}, {data.get('frequency')}, {data.get('measure')})",
+ data.get("points", []),
+ )
+ )
+ _print_data_gaps(data)
+
+
[email protected](name="ecb-series")
[email protected]("--dataset", "-d", type=click.Choice(sorted(liquidity.ECB_DATASETS)), default="BSI")
[email protected]("--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")
+def ecb_series_cmd(
+ ctx: click.Context, key: str, dataset: str, limit: int, start: str | None
+) -> None:
+ """ECB Data Portal series by SDMX key (BSI money, ILM Eurosystem balance sheet)."""
+ data = _run(
+ liquidity.fetch_ecb_series(_get_fetcher(), dataset=dataset, key=key, limit=limit, start=start)
+ )
+ if _bail_on_error(ctx, data):
+ return
+ for s in data.get("series", []):
+ # ECB titles are remote free text: escape them in the table title.
+ title = escape(f"{s.get('title') or s.get('key')} ({s.get('measure')})")
+ console.print(_liq_points_table(title, s.get("points", []), ("status",)))
+ _print_data_gaps(data)
+
+
@main.command(name="shipping")
@click.pass_context
def shipping_cmd(ctx: click.Context) -> None:
diff --git a/src/world_intel_mcp/collector.py b/src/world_intel_mcp/collector.py
index 4211562..37024ed 100644
--- a/src/world_intel_mcp/collector.py
+++ b/src/world_intel_mcp/collector.py
@@ -52,6 +52,13 @@ SOURCES = [
("residential_natgas", "sources.economic", "fetch_residential_natgas_prices", {}),
("electricity_rates", "sources.economic", "fetch_electricity_rates", {}),
("central_bank_rates", "sources.central_banks", "fetch_central_bank_rates", {}),
+ # Liquidity (2): FRED H.4.1 data are weekly (Thursday release), RRP
+ # daily, M2 and euro area M1-M3 monthly. The fetcher caches FRED CSVs
+ # 1 h and ECB responses 3 h, so a 5-minute daemon cycle reaches each
+ # upstream at most once per TTL; the response's freshness block, not
+ # the cycle, says whether the data are current.
+ ("liquidity_board", "sources.liquidity", "fetch_liquidity_board", {}),
+ ("net_liquidity", "sources.liquidity", "fetch_net_liquidity", {}),
# Natural Disasters & Hazards (5)
("earthquakes", "sources.seismology", "fetch_earthquakes", {}),
("wildfires", "sources.wildfire", "fetch_wildfires", {}),
@@ -148,6 +155,7 @@ DOMAIN_GROUPS = {
"electricity_rates",
"central_bank_rates",
],
+ "liquidity": ["liquidity_board", "net_liquidity"],
"natural": [
"earthquakes",
"wildfires",
diff --git a/src/world_intel_mcp/fetcher.py b/src/world_intel_mcp/fetcher.py
index 5b3afad..8bdd7e3 100644
--- a/src/world_intel_mcp/fetcher.py
+++ b/src/world_intel_mcp/fetcher.py
@@ -41,6 +41,7 @@ _SOURCE_RATE_LIMITS: dict[str, float] = {
"acled": 2.0, # API key based
"nga": 2.0, # govt API
"sec-edgar": 1.0, # SEC EDGAR — be polite
+ "fred-graph": 1.0, # fred.stlouisfed.org robots.txt: Crawl-delay: 1
# adsb.lol globe_history heatmaps are ~14 MB each; one at a time,
# spaced, so a cold baseline never bursts the community server.
"adsblol-history": 2.0,
diff --git a/src/world_intel_mcp/sources/liquidity.py b/src/world_intel_mcp/sources/liquidity.py
new file mode 100644
index 0000000..20ab858
--- /dev/null
+++ b/src/world_intel_mcp/sources/liquidity.py
@@ -0,0 +1,1037 @@
+"""Liquidity and money: Fed balance sheet, Treasury General Account,
+overnight reverse repo, net liquidity, US M2, euro area M1/M2/M3 and the
+Eurosystem balance sheet. Keyless sources only.
+
+- FRED graph CSV (``fred.stlouisfed.org/graph/fredgraph.csv``): the keyless
+ download behind every FRED chart; robots.txt allows it with
+ ``Crawl-delay: 1``, honored by the fetcher's ``fred-graph`` rate floor.
+ The CSV carries observation dates and values only, so units, frequency
+ and release come from ``FRED_SERIES`` below (each checked against the
+ series page on 2026-10-17) and ``published_at`` is always null.
+- ECB Data Portal SDMX-JSON (``data-api.ecb.europa.eu``): units, scale,
+ titles and provisional flags come from the response itself.
+
+Every point carries ``observed_at`` (the period the value describes),
+``value`` and ``units``; every series says whether it is an amount
+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.
+
+Blocked upstreams (measured 2026-10-17, see ROADMAP Phase 29): ICI money
+market fund assets and ETF net issuance answer 403 on every path,
+robots.txt included; FINRA margin statistics answer 200 but finra.org's
+terms of use forbid robots and building a database from the site.
+"""
+
+import asyncio
+import calendar
+import csv
+import io
+import logging
+import re
+from datetime import date, datetime, timezone
+from typing import Any
+
+from ..fetcher import Fetcher
+
+logger = logging.getLogger("world-intel-mcp.sources.liquidity")
+
+_FRED_GRAPH_URL = "https://fred.stlouisfed.org/graph/fredgraph.csv"
+_ECB_DATA_URL = "https://data-api.ecb.europa.eu/service/data/{dataset}/{key}"
+
+FRED_SOURCE = "fred-graph"
+ECB_SOURCE = "ecb-data-portal"
+
+# FRED drops connections that carry the Fetcher's generic default UA
+# (measured 2026-10-17: ReadTimeout after 18 s, 200 in 0.06 s with this
+# one), so both upstreams get the project's descriptive UA.
+_HEADERS = {"User-Agent": "world-intel-mcp (https://github.com/marc-shade/world-intel-mcp)"}
+
+_FRED_TTL = 3600
+_ECB_TTL = 3 * 3600
+
+DEFAULT_LIMIT = 52
+_MAX_ECB_SERIES = 50
+
+# Units, frequency and release as stated on each FRED series page
+# (checked 2026-10-17). ``max_age_days`` is how old the newest observation
+# may be before the response flags it stale: weekly H.4.1 data are as of
+# Wednesday and released the next day; RRP is daily on business days;
+# M2 for a month is released late in the following month.
+FRED_SERIES: dict[str, dict[str, Any]] = {
+ "WALCL": {
+ "label": "Federal Reserve total assets",
+ "detail": "Total assets less eliminations from consolidation, Wednesday level",
+ "units": "USD millions",
+ "scale": 1_000_000,
+ "frequency": "weekly, as of Wednesday",
+ "seasonal_adjustment": "not seasonally adjusted",
+ "measure": "amount_outstanding",
+ "release": "H.4.1 Factors Affecting Reserve Balances",
+ "max_age_days": 10,
+ },
+ "WDTGAL": {
+ "label": "Treasury General Account (Wednesday level)",
+ "detail": "U.S. Treasury, General Account deposits with F.R. Banks, Wednesday level",
+ "units": "USD millions",
+ "scale": 1_000_000,
+ "frequency": "weekly, as of Wednesday",
+ "seasonal_adjustment": "not seasonally adjusted",
+ "measure": "amount_outstanding",
+ "release": "H.4.1 Factors Affecting Reserve Balances",
+ "max_age_days": 10,
+ },
+ "WTREGEN": {
+ "label": "Treasury General Account (week average)",
+ "detail": "U.S. Treasury, General Account deposits with F.R. Banks, average of the week ending Wednesday",
+ "units": "USD millions",
+ "scale": 1_000_000,
+ "frequency": "weekly, ending Wednesday (week average)",
+ "seasonal_adjustment": "not seasonally adjusted",
+ "measure": "amount_outstanding",
+ "release": "H.4.1 Factors Affecting Reserve Balances",
+ "max_age_days": 10,
+ },
+ "RRPONTSYD": {
+ "label": "Fed overnight reverse repo",
+ "detail": (
+ "Treasury securities sold by the Federal Reserve in overnight reverse "
+ "repurchase operations; each matures the next business day, so a day's "
+ "take-up is the amount outstanding overnight"
+ ),
+ "units": "USD billions",
+ "scale": 1_000_000_000,
+ "frequency": "daily (business days)",
+ "seasonal_adjustment": "not seasonally adjusted",
+ "measure": "amount_outstanding",
+ "release": "Temporary Open Market Operations",
+ "max_age_days": 6,
+ },
+ "M2SL": {
+ "label": "US M2 money stock",
+ "detail": "M2, monthly average",
+ "units": "USD billions",
+ "scale": 1_000_000_000,
+ "frequency": "monthly",
+ "seasonal_adjustment": "seasonally adjusted",
+ "measure": "amount_outstanding",
+ "release": "H.6 Money Stock Measures",
+ "max_age_days": 100,
+ },
+}
+
+US_M3_NOTE = (
+ "US M3 is discontinued: the Federal Reserve stopped publishing it in 2006 "
+ "(FRED M3SL ends at 2006-02-01). There is no current US M3 series."
+)
+NESTING_NOTE = (
+ "M1 is contained in M2 and M2 in M3: the aggregates nest, so they are "
+ "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
+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"
+)
+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 "
+ "used. Weeks without an aligned TGA or RRP value are skipped and counted, "
+ "never filled with zero."
+)
+TGA_CHOICE_NOTE = (
+ "The Treasury General Account term is WDTGAL (Wednesday level), not "
+ "WTREGEN (week average), so all three terms describe the same Wednesday."
+)
+
+# ECB Data Portal series used by the money-supply view and the board.
+# Data types: 1 = outstanding amounts (stocks), 4 = transactions (flows),
+# I + suffix A = annual growth rate of the notional-stock index.
+_ECB_MONEY_KEY = "M.U2.Y.V.M10+M20+M30.X.1+4+I.U2.2300.Z01.E+A"
+_ECB_AGGREGATE_CODES = {"M10": "M1", "M20": "M2", "M30": "M3"}
+_ECB_EUROSYSTEM_KEY = "W.U2.C.T000000.Z5.Z01"
+ECB_DATASETS = {
+ "BSI": "Balance sheet items of euro area monetary financial institutions (monetary aggregates)",
+ "ILM": "Eurosystem weekly financial statement (internal liquidity management)",
+}
+_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}$")
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _utc_now_iso() -> str:
+ return datetime.now(timezone.utc).isoformat()
+
+
+def _today() -> date:
+ return datetime.now(timezone.utc).date()
+
+
+def _month_end(d: date) -> date:
+ return d.replace(day=calendar.monthrange(d.year, d.month)[1])
+
+
+def _round(value: float | None, ndigits: int = 3) -> float | None:
+ return None if value is None else round(value, ndigits)
+
+
+def _validate_limit(limit: Any) -> int:
+ """``limit`` newest points; 0 returns the full history."""
+ if isinstance(limit, bool) or not isinstance(limit, int) or limit < 0:
+ raise ValueError(f"limit must be a non-negative integer (0 = full history), got {limit!r}")
+ return limit
+
+
+def _validate_start(start: Any) -> date | None:
+ if start in (None, ""):
+ return None
+ if not isinstance(start, str):
+ raise ValueError(f"start must be an ISO date YYYY-MM-DD, got {start!r}")
+ try:
+ return date.fromisoformat(start)
+ except ValueError as exc:
+ raise ValueError(f"start must be an ISO date YYYY-MM-DD, got {start!r}") from exc
+
+
+def _change(latest: dict | None, previous: dict | None, relative: bool = True) -> dict | None:
+ """Change between the two newest observations (same units).
+
+ ``relative=False`` (growth rates) reports the absolute change only:
+ a percent change of a percent is not meaningful.
+ """
+ if not latest or not previous:
+ return None
+ a, b = latest["value"], previous["value"]
+ return {
+ "absolute": _round(a - b),
+ "pct": _round((a - b) / abs(b) * 100, 4) if b and relative else None,
+ "from": previous["observed_at"],
+ "to": latest["observed_at"],
+ "basis": "vs previous observation",
+ }
+
+
+def _freshness(period_end: date | None, max_age_days: int) -> dict:
+ if period_end is None:
+ return {"latest_age_days": None, "expected_max_age_days": max_age_days, "stale": None}
+ age = (_today() - period_end).days
+ return {
+ "latest_age_days": age,
+ "expected_max_age_days": max_age_days,
+ "stale": age > max_age_days,
+ }
+
+
+def _stale_gap(name: str, observed_at: str, fresh: dict) -> str | None:
+ if fresh.get("stale"):
+ return (
+ f"{name}: newest observation {observed_at} is {fresh['latest_age_days']} "
+ f"days old, past the expected {fresh['expected_max_age_days']} "
+ "(publisher delay, a served stale cache copy, or an outage)"
+ )
+ return None
+
+
+# ---------------------------------------------------------------------------
+# FRED graph CSV
+# ---------------------------------------------------------------------------
+
+
+def parse_fred_csv(text: str, series_id: str) -> list[tuple[date, float | None]]:
+ """Parse ``observation_date,<ID>`` rows, oldest first.
+
+ A blank (or ".") value is a missing observation and stays ``None``.
+ Anything else that is not a number, a header for another series, or
+ an HTML error page raises ``ValueError``.
+ """
+ reader = csv.reader(io.StringIO(text))
+ header = next(reader, None)
+ if header is None or [h.strip() for h in header] != ["observation_date", series_id]:
+ raise ValueError(f"unexpected header {header!r:.80}")
+ rows: list[tuple[date, float | None]] = []
+ for row in reader:
+ if not row:
+ continue
+ if len(row) != 2:
+ raise ValueError(f"unexpected row {row!r:.80}")
+ day = date.fromisoformat(row[0].strip())
+ raw = row[1].strip()
+ rows.append((day, None if raw in ("", ".") else float(raw)))
+ return rows
+
+
+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,
+ )
+ if text is None:
+ 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}"
+ 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
+
+
+def _fred_period_end(series_id: str, d: date) -> date:
+ return _month_end(d) if FRED_SERIES[series_id]["frequency"] == "monthly" else d
+
+
+def _build_fred_series(
+ series_id: str,
+ rows: list[tuple[date, float | None]],
+ limit: int,
+ start: date | None,
+) -> dict:
+ meta = FRED_SERIES[series_id]
+ units = meta["units"]
+ present = [(d, v) for d, v in rows if v is not None]
+ blank = len(rows) - len(present)
+ window = [(d, v) for d, v in present if start is None or d >= start]
+ newest_first = list(reversed(window))
+ if limit:
+ newest_first = newest_first[:limit]
+ points = [
+ {"observed_at": d.isoformat(), "value": v, "units": units} for d, v in newest_first
+ ]
+ latest_d, latest_v = present[-1]
+ latest = {"observed_at": latest_d.isoformat(), "value": latest_v, "units": units}
+ previous = (
+ {"observed_at": present[-2][0].isoformat(), "value": present[-2][1], "units": units}
+ if len(present) > 1
+ else None
+ )
+ fresh = _freshness(_fred_period_end(series_id, latest_d), meta["max_age_days"])
+ return {
+ "series_id": series_id,
+ "dataset": f"FRED {series_id}",
+ "label": meta["label"],
+ "detail": meta["detail"],
+ "units": units,
+ "scale": meta["scale"],
+ "frequency": meta["frequency"],
+ "seasonal_adjustment": meta["seasonal_adjustment"],
+ "measure": meta["measure"],
+ "release": meta["release"],
+ "published_at": None,
+ "latest": latest,
+ "previous": previous,
+ "change": _change(latest, previous),
+ "freshness": fresh,
+ "first_observed_at": present[0][0].isoformat(),
+ "blank_observations": blank,
+ "order": "newest_first",
+ "count": len(points),
+ "points": points,
+ }
+
+
+_FRED_GAP = (
+ "FRED's keyless CSV carries observation dates only: published_at is null, "
+ "and units/frequency come from the server's series catalog, not the payload."
+)
+
+
+async def fetch_fed_liquidity_series(
+ fetcher: Fetcher,
+ series_id: str = "WALCL",
+ limit: int = DEFAULT_LIMIT,
+ start: str | None = None,
+) -> dict:
+ """One FRED liquidity series (keyless), newest first; ``limit=0`` is full history."""
+ sid = str(series_id or "").strip().upper()
+ if sid not in FRED_SERIES:
+ return {
+ "error": f"unknown series {series_id!r}; choose one of {sorted(FRED_SERIES)}",
+ "series_available": sorted(FRED_SERIES),
+ "timestamp": _utc_now_iso(),
+ }
+ try:
+ n = _validate_limit(limit)
+ start_d = _validate_start(start)
+ except ValueError as exc:
+ return {"error": str(exc), "timestamp": _utc_now_iso()}
+
+ rows, err = await _fred_rows(fetcher, sid)
+ if rows is None:
+ return {
+ "error": err,
+ "series_id": sid,
+ "source": FRED_SOURCE,
+ "data_gaps": [err],
+ "timestamp": _utc_now_iso(),
+ }
+ series = _build_fred_series(sid, rows, n, start_d)
+ gaps = [_FRED_GAP]
+ stale = _stale_gap(sid, series["latest"]["observed_at"], series["freshness"])
+ if stale:
+ gaps.append(stale)
+ if series["blank_observations"]:
+ gaps.append(
+ f"{series['blank_observations']} blank {sid} dates in the source "
+ "(no value published) are omitted, not read as zero"
+ )
+ return {**series, "source": FRED_SOURCE, "data_gaps": gaps, "timestamp": _utc_now_iso()}
+
+
+# ---------------------------------------------------------------------------
+# Net liquidity
+# ---------------------------------------------------------------------------
+
+
+def compute_net_liquidity(
+ walcl: list[tuple[date, float | None]],
+ tga: list[tuple[date, float | None]],
+ rrp: list[tuple[date, float | None]],
+) -> tuple[list[dict], list[str]]:
+ """Aligned weekly net liquidity in USD billions, oldest first.
+
+ Returns ``(points, skipped)`` where ``skipped`` lists the WALCL dates
+ that had no aligned TGA or RRP value.
+ """
+ tga_by_day = {d: v for d, v in tga if v is not None}
+ rrp_days = sorted((d, v) for d, v in rrp if v is not None)
+ rrp_by_day = dict(rrp_days)
+ points: list[dict] = []
+ skipped: list[str] = []
+ for day, assets in walcl:
+ if assets is None:
+ continue
+ tga_v = tga_by_day.get(day)
+ rrp_day: date | None = None
+ for back in range(_NET_LIQUIDITY_RRP_LOOKBACK_DAYS + 1):
+ candidate = date.fromordinal(day.toordinal() - back)
+ if candidate in rrp_by_day:
+ rrp_day = candidate
+ break
+ if tga_v is None or rrp_day is None:
+ skipped.append(day.isoformat())
+ continue
+ assets_bn = assets / 1000.0
+ tga_bn = tga_v / 1000.0
+ rrp_bn = rrp_by_day[rrp_day]
+ points.append(
+ {
+ "observed_at": day.isoformat(),
+ "value": round(assets_bn - tga_bn - rrp_bn, 3),
+ "units": "USD billions",
+ "fed_total_assets": round(assets_bn, 3),
+ "treasury_general_account": round(tga_bn, 3),
+ "reverse_repo": round(rrp_bn, 3),
+ "reverse_repo_observed_at": rrp_day.isoformat(),
+ }
+ )
+ return points, skipped
+
+
+async def fetch_net_liquidity(
+ fetcher: Fetcher,
+ limit: int = DEFAULT_LIMIT,
+ start: str | None = None,
+) -> dict:
+ """Fed balance sheet minus TGA minus overnight RRP, weekly, newest first."""
+ try:
+ n = _validate_limit(limit)
+ start_d = _validate_start(start)
+ except ValueError as exc:
+ return {"error": str(exc), "timestamp": _utc_now_iso()}
+
+ 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}
+ base = {
+ "source": FRED_SOURCE,
+ "formula": NET_LIQUIDITY_FORMULA,
+ "alignment": NET_LIQUIDITY_ALIGNMENT,
+ "units": "USD billions",
+ "measure": "amount_outstanding",
+ "frequency": "weekly, as of Wednesday",
+ }
+ if failures:
+ gaps = list(failures.values())
+ return {
+ **base,
+ "error": (
+ "net liquidity not computed: missing component(s) "
+ f"{', '.join(sorted(failures))}; a missing term is never treated as zero"
+ ),
+ "components_failed": sorted(failures),
+ "data_gaps": gaps,
+ "timestamp": _utc_now_iso(),
+ }
+ walcl, tga, rrp = (rows for rows, _ in fetched)
+ all_points, skipped = compute_net_liquidity(walcl, tga, rrp)
+ if not all_points:
+ return {
+ **base,
+ "error": "net liquidity not computed: no week had all three components aligned",
+ "skipped_weeks": len(skipped),
+ "data_gaps": [f"{len(skipped)} WALCL weeks lacked an aligned TGA or RRP value"],
+ "timestamp": _utc_now_iso(),
+ }
+
+ latest = all_points[-1]
+ previous = all_points[-2] if len(all_points) > 1 else None
+ window = [p for p in all_points if start_d is None or p["observed_at"] >= start_d.isoformat()]
+ newest_first = list(reversed(window))
+ if n:
+ newest_first = newest_first[:n]
+ keep = ("label", "units", "frequency", "measure", "release", "latest", "freshness")
+ components = {}
+ for sid, rows in zip(ids, (walcl, tga, rrp)):
+ built = _build_fred_series(sid, rows, 1, None)
+ components[sid] = {k: built[k] for k in keep}
+ gaps = [_FRED_GAP, TGA_CHOICE_NOTE]
+ for sid, comp in components.items():
+ stale = _stale_gap(sid, comp["latest"]["observed_at"], comp["freshness"])
+ if stale:
+ gaps.append(stale)
+ if skipped:
+ gaps.append(
+ f"{len(skipped)} of {len(skipped) + len(all_points)} WALCL weeks skipped "
+ f"(no aligned TGA or RRP value), first {skipped[0]}, last {skipped[-1]}"
+ )
+ return {
+ **base,
+ "latest": latest,
+ "previous": previous,
+ "change": _change(latest, previous),
+ "components": components,
+ "first_observed_at": all_points[0]["observed_at"],
+ "skipped_weeks": len(skipped),
+ "order": "newest_first",
+ "count": len(newest_first),
+ "points": newest_first,
+ "published_at": None,
+ "data_gaps": gaps,
+ "timestamp": _utc_now_iso(),
+ }
+
+
+# ---------------------------------------------------------------------------
+# ECB Data Portal (SDMX-JSON)
+# ---------------------------------------------------------------------------
+
+
+def _attr_lookup(defs: list[dict], indexes: list[Any]) -> dict[str, dict]:
+ out: dict[str, dict] = {}
+ for pos, vi in enumerate(indexes):
+ if vi is None or pos >= len(defs):
+ continue
+ values = defs[pos].get("values") or []
+ if isinstance(vi, int) and 0 <= vi < len(values):
+ out[defs[pos]["id"]] = values[vi]
+ return out
+
+
+def _ecb_units(attrs: dict[str, dict]) -> tuple[str | None, int | None]:
+ unit = attrs.get("UNIT", {})
+ mult = attrs.get("UNIT_MULT", {})
+ unit_id = unit.get("id")
+ try:
+ exponent = int(mult.get("id")) if mult.get("id") is not None else None
+ except ValueError:
+ exponent = None
+ scale = 10**exponent if exponent is not None else None
+ if unit_id is None:
+ return None, scale
+ if unit_id == "PCCH":
+ return "percent", scale
+ mult_name = (mult.get("name") or "").lower()
+ if mult_name and mult_name != "units":
+ return f"{unit_id} {mult_name}", scale
+ return unit_id, scale
+
+
+def _ecb_measure(dataset: str, dims: dict[str, str]) -> str:
+ if dataset == "ILM":
+ return "amount_outstanding"
+ data_type = dims.get("DATA_TYPE")
+ if data_type == "1":
+ return "amount_outstanding"
+ if data_type == "4":
+ return "flow"
+ if data_type == "I":
+ return "growth_rate" if dims.get("BS_SUFFIX") == "A" else "index"
+ return "unknown"
+
+
+def _period_end(value: dict) -> date | None:
+ end = value.get("end")
+ if isinstance(end, str) and len(end) >= 10:
+ try:
+ return date.fromisoformat(end[:10])
+ except ValueError:
+ return None
+ return None
+
+
+def parse_sdmx_json(data: dict, dataset: str) -> list[dict]:
+ """Every series in an ECB SDMX-JSON 1.0 response, points oldest first."""
+ structure = data["structure"]
+ dims = structure["dimensions"]["series"]
+ periods = structure["dimensions"]["observation"][0]["values"]
+ series_attr_defs = structure["attributes"]["series"]
+ obs_attr_defs = structure["attributes"]["observation"]
+ status_pos = next(
+ (i for i, a in enumerate(obs_attr_defs) if a.get("id") == "OBS_STATUS"), None
+ )
+ out: list[dict] = []
+ for skey, body in data["dataSets"][0].get("series", {}).items():
+ idx = [int(i) for i in skey.split(":")]
+ dim_ids = {dims[i]["id"]: dims[i]["values"][j]["id"] for i, j in enumerate(idx)}
+ key = ".".join(dims[i]["values"][j]["id"] for i, j in enumerate(idx))
+ attrs = _attr_lookup(series_attr_defs, body.get("attributes", []))
+ units, scale = _ecb_units(attrs)
+ points = []
+ for oi, ov in body.get("observations", {}).items():
+ if not ov or ov[0] is None:
+ continue
+ period = periods[int(oi)]
+ status = None
+ if status_pos is not None and len(ov) > status_pos + 1 and ov[status_pos + 1] is not None:
+ values = obs_attr_defs[status_pos].get("values") or []
+ if 0 <= ov[status_pos + 1] < len(values):
+ status = values[ov[status_pos + 1]].get("name")
+ end = _period_end(period)
+ points.append(
+ {
+ "observed_at": period["id"],
+ "period_end": end.isoformat() if end else None,
+ "value": float(ov[0]),
+ "units": units,
+ "status": status,
+ }
+ )
+ points.sort(key=lambda p: (p["period_end"] or "", p["observed_at"]))
+ out.append(
+ {
+ "key": f"{dataset}.{key}",
+ "title": attrs.get("TITLE", {}).get("name"),
+ "title_full": attrs.get("TITLE_COMPL", {}).get("name"),
+ "dimensions": dim_ids,
+ "units": units,
+ "scale": scale,
+ "measure": _ecb_measure(dataset, dim_ids),
+ "frequency": dim_ids.get("FREQ"),
+ "points": points,
+ }
+ )
+ out.sort(key=lambda s: s["key"])
+ return out
+
+
+async def _ecb_fetch(
+ fetcher: Fetcher, dataset: str, key: str, last_n: int, start: date | None
+) -> tuple[list[dict] | None, str | None]:
+ params: dict[str, Any] = {"format": "jsondata"}
+ if last_n:
+ 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)"
+ )
+ try:
+ series = parse_sdmx_json(data, dataset)
+ except (KeyError, IndexError, TypeError, ValueError) as exc:
+ 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}"
+ return series, None
+
+
+def _finish_ecb_series(series: dict, limit: int) -> dict:
+ """Newest-first window plus latest/previous/change/freshness."""
+ pts = series["points"]
+ latest = pts[-1] if pts else None
+ previous = pts[-2] if len(pts) > 1 else None
+ end = date.fromisoformat(latest["period_end"]) if latest and latest["period_end"] else None
+ max_age = _ECB_MAX_AGE_DAYS.get(series.get("frequency") or "", 75)
+ newest_first = list(reversed(pts))
+ if limit:
+ newest_first = newest_first[:limit]
+ return {
+ **{k: v for k, v in series.items() if k != "points"},
+ "published_at": None,
+ "latest": latest,
+ "previous": previous,
+ # A change between two flows is not a liquidity change; growth
+ # rates change in percentage points, not percent.
+ "change": (
+ None
+ if series["measure"] == "flow"
+ else _change(latest, previous, relative=series["measure"] != "growth_rate")
+ ),
+ "freshness": _freshness(end, max_age),
+ "order": "newest_first",
+ "count": len(newest_first),
+ "points": newest_first,
+ }
+
+
+_ECB_GAP = (
+ "The ECB Data Portal response carries no release dates: published_at is "
+ "null; observation status (normal / provisional) is per point."
+)
+
+
+async def fetch_ecb_series(
+ fetcher: Fetcher,
+ dataset: str = "BSI",
+ key: str = "M.U2.Y.V.M30.X.1.U2.2300.Z01.E",
+ limit: int = 24,
+ start: str | None = None,
+) -> dict:
+ """ECB Data Portal series (BSI money and banking, ILM Eurosystem balance sheet)."""
+ ds = str(dataset or "").strip().upper()
+ if ds not in ECB_DATASETS:
+ return {
+ "error": f"dataset must be one of {sorted(ECB_DATASETS)}, got {dataset!r}",
+ "datasets": ECB_DATASETS,
+ "timestamp": _utc_now_iso(),
+ }
+ key = str(key or "").strip()
+ if not _ECB_KEY_RE.match(key):
+ return {
+ "error": "key must be an SDMX series key: letters, digits, '.', '+' and '_' only",
+ "timestamp": _utc_now_iso(),
+ }
+ try:
+ n = _validate_limit(limit)
+ start_d = _validate_start(start)
+ except ValueError as exc:
+ return {"error": str(exc), "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)
+ if series is None:
+ return {
+ "error": err,
+ "dataset": ds,
+ "key": key,
+ "source": ECB_SOURCE,
+ "data_gaps": [err],
+ "timestamp": _utc_now_iso(),
+ }
+ gaps = [_ECB_GAP]
+ if len(series) > _MAX_ECB_SERIES:
+ gaps.append(f"{len(series)} series matched; the first {_MAX_ECB_SERIES} by key are returned")
+ series = series[:_MAX_ECB_SERIES]
+ finished = [_finish_ecb_series(s, n) for s in series]
+ for s in finished:
+ if s["measure"] == "unknown":
+ gaps.append(f"{s['key']}: measure type not recognized (not typed as stock or flow)")
+ if s["latest"]:
+ stale = _stale_gap(s["key"], s["latest"]["observed_at"], s["freshness"])
+ if stale:
+ gaps.append(stale)
+ return {
+ "dataset": ds,
+ "dataset_description": ECB_DATASETS[ds],
+ "key": key,
+ "source": ECB_SOURCE,
+ "series_count": len(finished),
+ "series": finished,
+ "data_gaps": gaps,
+ "timestamp": _utc_now_iso(),
+ }
+
+
+# ---------------------------------------------------------------------------
+# Money supply
+# ---------------------------------------------------------------------------
+
+
+def _ecb_money_view(series: list[dict], limit: int) -> dict:
+ aggregates: dict[str, dict] = {}
+ for s in series:
+ name = _ECB_AGGREGATE_CODES.get(s["dimensions"].get("BS_ITEM", ""))
+ role = {
+ "amount_outstanding": "stock",
+ "flow": "flow",
+ "growth_rate": "annual_growth_rate",
+ }.get(s["measure"])
+ if name is None or role is None:
+ continue
+ aggregates.setdefault(name, {})[role] = _finish_ecb_series(s, limit)
+ return dict(sorted(aggregates.items()))
+
+
+async def fetch_money_supply(
+ fetcher: Fetcher,
+ region: str = "all",
+ limit: int = 13,
+) -> dict:
+ """US M2 (FRED) and euro area M1/M2/M3 (ECB), reported separately, never summed."""
+ reg = str(region or "all").strip().lower()
+ if reg not in ("all", "us", "euro_area"):
+ return {"error": f"region must be all, us or euro_area, got {region!r}", "timestamp": _utc_now_iso()}
+ try:
+ n = _validate_limit(limit)
+ except ValueError as exc:
+ return {"error": str(exc), "timestamp": _utc_now_iso()}
+
+ want_us = reg in ("all", "us")
+ want_ea = reg in ("all", "euro_area")
+
+ async def _none() -> tuple[None, None]:
+ return None, None
+
+ 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)
+
+ gaps: list[str] = []
+ out: dict[str, Any] = {"region": reg, "note": NESTING_NOTE}
+ if want_us:
+ us: dict[str, Any] = {"M3": {"available": False, "note": US_M3_NOTE}}
+ if us_rows is None:
+ us["M2"] = {"error": us_err}
+ gaps.append(us_err)
+ else:
+ m2 = _build_fred_series("M2SL", us_rows, n, None)
+ us["M2"] = {**m2, "source": FRED_SOURCE}
+ gaps.append(_FRED_GAP)
+ stale = _stale_gap("M2SL", m2["latest"]["observed_at"], m2["freshness"])
+ if stale:
+ gaps.append(stale)
+ out["us"] = us
+ if want_ea:
+ if ea_series is None:
+ out["euro_area"] = {"error": ea_err}
+ gaps.append(ea_err)
+ else:
+ aggregates = _ecb_money_view(ea_series, n)
+ out["euro_area"] = {
+ "source": ECB_SOURCE,
+ "key": f"BSI.{_ECB_MONEY_KEY}",
+ "aggregates": aggregates,
+ "note": (
+ "stock = outstanding amount at end of month; flow = transactions "
+ "during the month (excludes reclassifications and revaluations, so "
+ "stock changes differ from flows); annual_growth_rate = percent"
+ ),
+ }
+ gaps.append(_ECB_GAP)
+ for name, roles in aggregates.items():
+ for role, s in roles.items():
+ if s["latest"]:
+ 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}")
+
+ us_failed = want_us and "error" in out.get("us", {}).get("M2", {})
+ ea_failed = want_ea and "error" in out.get("euro_area", {})
+ if (not want_us or us_failed) and (not want_ea or ea_failed):
+ out["error"] = "money supply unavailable: " + "; ".join(gaps)
+ out["data_gaps"] = gaps
+ out["timestamp"] = _utc_now_iso()
+ return out
+
+
+# ---------------------------------------------------------------------------
+# Liquidity board
+# ---------------------------------------------------------------------------
+
+
+def _row(
+ indicator: str,
+ label: str,
+ dataset: str,
+ source: str,
+ measure: str,
+ frequency: str,
+ units: str | None,
+ latest: dict | None,
+ previous: dict | None,
+ period_end: date | None,
+ freshness: dict,
+) -> dict:
+ change = _change(latest, previous)
+ return {
+ "indicator": indicator,
+ "label": label,
+ "dataset": dataset,
+ "source": source,
+ "measure": measure,
+ "frequency": frequency,
+ "units": units,
+ "latest_value": latest["value"] if latest else None,
+ "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,
+ "previous_observed_at": previous["observed_at"] if previous else None,
+ "change": change["absolute"] if change else None,
+ "change_pct": change["pct"] if change else None,
+ "change_basis": "vs previous observation",
+ "freshness": freshness,
+ }
+
+
+_BOARD_FRED = (
+ ("fed_total_assets", "WALCL"),
+ ("treasury_general_account", "WDTGAL"),
+ ("reverse_repo", "RRPONTSYD"),
+ ("us_m2", "M2SL"),
+)
+
+
+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"):
+ 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]
+ results = await asyncio.gather(
+ *(_fred_rows(fetcher, sid) for sid in fred_ids),
+ _ecb_fetch(fetcher, "BSI", _ECB_MONEY_KEY, 2, None),
+ _ecb_fetch(fetcher, "ILM", _ECB_EUROSYSTEM_KEY, 2, None),
+ )
+ fred_results = dict(zip(fred_ids, results[: len(fred_ids)]))
+ (bsi, bsi_err), (ilm, ilm_err) = results[len(fred_ids):]
+
+ rows: list[dict] = []
+ unavailable: list[dict] = []
+ gaps: list[str] = []
+
+ for indicator, sid in _BOARD_FRED:
+ fr, err = 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)
+ rows.append(
+ _row(
+ indicator, s["label"], s["dataset"], FRED_SOURCE, s["measure"], s["frequency"],
+ s["units"], s["latest"], s["previous"],
+ _fred_period_end(sid, date.fromisoformat(s["latest"]["observed_at"])),
+ s["freshness"],
+ )
+ )
+
+ 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 points:
+ latest = points[-1]
+ previous = points[-2] if len(points) > 1 else None
+ end = date.fromisoformat(latest["observed_at"])
+ rows.append(
+ _row(
+ "net_liquidity", "US net liquidity (WALCL - WDTGAL - RRPONTSYD)",
+ "derived from FRED WALCL, WDTGAL, RRPONTSYD", FRED_SOURCE,
+ "amount_outstanding", "weekly, as of Wednesday", "USD billions",
+ {"observed_at": latest["observed_at"], "value": latest["value"]},
+ {"observed_at": previous["observed_at"], "value": previous["value"]} if previous else None,
+ end, _freshness(end, FRED_SERIES["WALCL"]["max_age_days"]),
+ )
+ )
+ else:
+ unavailable.append({"indicator": "net_liquidity", "error": "no aligned week"})
+ gaps.append("net liquidity: no week had all three components aligned")
+ else:
+ unavailable.append(
+ {"indicator": "net_liquidity", "error": "a component failed; never computed with a zero term"}
+ )
+ gaps.append("net liquidity not computed: a component series failed")
+
+ for err, payload, wanted in (
+ (bsi_err, bsi, "BSI"),
+ (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
+ for s in payload:
+ if wanted == "BSI":
+ agg = _ECB_AGGREGATE_CODES.get(s["dimensions"].get("BS_ITEM", ""))
+ if agg is None or s["measure"] != "amount_outstanding":
+ continue
+ indicator, label = f"euro_area_{agg.lower()}", f"Euro area {agg} (stock)"
+ else:
+ indicator, label = "eurosystem_total_assets", s["title"] or "Eurosystem total assets"
+ f = _finish_ecb_series(s, 1)
+ latest = f["latest"]
+ end = date.fromisoformat(latest["period_end"]) if latest and latest["period_end"] else None
+ rows.append(
+ _row(
+ indicator, label, s["key"], ECB_SOURCE, s["measure"],
+ {"M": "monthly", "W": "weekly"}.get(s["frequency"], s["frequency"]),
+ s["units"], latest, f["previous"], end, f["freshness"],
+ )
+ )
+
+ for r in rows:
+ stale = _stale_gap(r["indicator"], r["observed_at"], r["freshness"])
+ if stale:
+ gaps.append(stale)
+
+ 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"]))
+
+ gaps.append(
+ "Changes are vs each indicator's previous observation, so horizons differ "
+ "(daily RRP, weekly Fed and Eurosystem data, monthly money supply)."
+ )
+ gaps.append(
+ "published_at is null for every row: neither FRED's keyless CSV nor the "
+ "ECB payload carries release dates. FRED units come from the server's "
+ "series catalog; ECB units come from the response."
+ )
+ out: dict[str, Any] = {
+ "sort": sort,
+ "count": len(rows),
+ "indicators": rows,
+ "unavailable": unavailable,
+ "net_liquidity_formula": NET_LIQUIDITY_FORMULA,
+ "note": NESTING_NOTE,
+ "sources": [FRED_SOURCE, ECB_SOURCE],
+ "data_gaps": gaps,
+ "timestamp": _utc_now_iso(),
+ }
+ if not rows:
+ out["error"] = "liquidity board unavailable: every source failed"
+ return out
diff --git a/src/world_intel_mcp/tests/fixtures/liquidity/ecb_404_problem.json b/src/world_intel_mcp/tests/fixtures/liquidity/ecb_404_problem.json
new file mode 100644
index 0000000..44d36ef
--- /dev/null
+++ b/src/world_intel_mcp/tests/fixtures/liquidity/ecb_404_problem.json
@@ -0,0 +1 @@
+{"type":"/service/data/BSI/M.U2.Y.V.M99.X.1.U2.2300.Z01.E","title":"Not Found","status":404,"detail":"No Series was returned for the query: <?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><DataQuery dataflowId=\"BSI\" detail=\"FULL\" type=\"SINGLE_QUERY\" lastNObservations=\"2\" includeHistory=\"false\"><SeriesKeys><SeriesKey>M.U2.Y.V.M99.X.1.U2.2300.Z01.E</SeriesKey></SeriesKeys></DataQuery>","instance":"/service/data/BSI/M.U2.Y.V.M99.X.1.U2.2300.Z01.E"}
\ No newline at end of file
diff --git a/src/world_intel_mcp/tests/fixtures/liquidity/ecb_bsi_money.json b/src/world_intel_mcp/tests/fixtures/liquidity/ecb_bsi_money.json
new file mode 100644
index 0000000..27ee086
--- /dev/null
+++ b/src/world_intel_mcp/tests/fixtures/liquidity/ecb_bsi_money.json
@@ -0,0 +1 @@
+{"header":{"id":"788f23e5-ff33-42b9-9293-e5cd04380137","test":false,"prepared":"2026-10-17T18:23:32.306+02:00","sender":{"id":"ECB"}},"dataSets":[{"action":"Replace","validFrom":"2026-10-17T18:23:32.306+02:00","series":{"0:0:0:0:0:0:0:0:0:0:0":{"attributes":[0,null,0,null,null,null,null,null,null,null,null,0,null,null,0,0,0,0],"observations":{"0":[11324679,0,0,null,null],"1":[11291831,0,0,null,null],"2":[11293328,1,0,null,null]}},"0:0:0:0:0:0:1:0:0:0:0":{"attributes":[0,null,1,null,null,null,null,null,null,null,null,0,null,null,1,1,0,0],"observations":{"0":[22119,0,0,null,null],"1":[-31014,0,0,null,null],"2":[4054,1,0,null,null]}},"0:0:0:0:0:0:2:0:0:0:1":{"attributes":[0,null,0,null,null,null,null,null,null,null,null,1,null,null,2,2,1,1],"observations":{"0":[3.4655328619043413,0,0,null,null],"1":[3.139514565864854,0,0,null,null],"2":[2.85242102599661,1,0,null,null]}},"0:0:0:0:0:0:2:0:0:0:0":{"attributes":[0,null,0,null,null,null,null,null,null,0,null,2,null,null,3,3,0,1],"observations":{"0":[233.11594390735382,0,0,null,null],"1":[232.47752654224146,0,0,null,null],"2":[232.560996073444,1,0,null,null]}},"0:0:0:0:1:0:0:0:0:0:0":{"attributes":[0,null,0,null,null,null,null,null,null,null,null,0,null,null,4,4,0,0],"observations":{"0":[16416939,0,0,null,null],"1":[16434747,0,0,null,null],"2":[16447405,1,0,null,null]}},"0:0:0:0:1:0:1:0:0:0:0":{"attributes":[0,null,1,null,null,null,null,null,null,null,null,0,null,null,5,5,0,0],"observations":{"0":[58158,0,0,null,null],"1":[20673,0,0,null,null],"2":[14569,1,0,null,null]}},"0:0:0:0:1:0:2:0:0:0:1":{"attributes":[0,null,0,null,null,null,null,null,null,null,null,1,null,null,6,6,1,1],"observations":{"0":[3.2586326232093787,0,0,null,null],"1":[3.325985827488509,0,0,null,null],"2":[3.241497989111042,1,0,null,null]}},"0:0:0:0:1:0:2:0:0:0:0":{"attributes":[0,null,0,null,null,null,null,null,null,0,null,2,null,null,7,7,0,1],"observations":{"0":[189.26063611108376,0,0,null,null],"1":[189.49895630808982,0,0,null,null],"2":[189.66696551903985,1,0,null,null]}},"0:0:0:0:2:0:0:0:0:0:0":{"attributes":[0,null,0,null,null,null,null,null,null,null,null,0,null,null,8,8,0,0],"observations":{"0":[17611985,0,0,null,null],"1":[17615092,0,0,null,null],"2":[17646463,1,0,null,null]}},"0:0:0:0:2:0:1:0:0:0:0":{"attributes":[0,null,1,null,null,null,null,null,null,null,null,0,null,null,9,9,0,0],"observations":{"0":[80541,0,0,null,null],"1":[2242,0,0,null,null],"2":[33644,1,0,null,null]}},"0:0:0:0:2:0:2:0:0:0:1":{"attributes":[0,null,0,null,null,null,null,null,null,null,null,1,null,null,10,10,1,1],"observations":{"0":[3.302089255943752,0,0,null,null],"1":[3.374812706145436,0,0,null,null],"2":[3.489572442704003,1,0,null,null]}},"0:0:0:0:2:0:2:0:0:0:0":{"attributes":[0,null,0,null,null,null,null,null,null,0,null,2,null,null,11,11,0,1],"observations":{"0":[186.6522125415646,0,0,null,null],"1":[186.6759145693168,0,0,null,null],"2":[187.03246207321294,1,0,null,null]}}}}],"structure":{"links":[{"title":"Balance Sheet Items","rel":"dataflow","href":"https://data-api.ecb.europa.eu:443/service/dataflow/ECB/BSI/1.0"}],"name":"Balance Sheet Items","dimensions":{"series":[{"id":"FREQ","name":"Frequency","values":[{"id":"M","name":"Monthly"}]},{"id":"REF_AREA","name":"Reference area","values":[{"id":"U2","name":"Euro area (changing composition)"}]},{"id":"ADJUSTMENT","name":"Adjustment indicator","values":[{"id":"Y","name":"Working day and seasonally adjusted"}]},{"id":"BS_REP_SECTOR","name":"BS reference sector breakdown","values":[{"id":"V","name":"MFIs, central government and post office giro institutions"}]},{"id":"BS_ITEM","name":"Balance sheet item","values":[{"id":"M10","name":"Monetary aggregate M1"},{"id":"M20","name":"Monetary aggregate M2"},{"id":"M30","name":"Monetary aggregate M3"}]},{"id":"MATURITY_ORIG","name":"Original maturity","values":[{"id":"X","name":"Not applicable"}]},{"id":"DATA_TYPE","name":"Data type","values":[{"id":"1","name":"Outstanding amounts at the end of the period (stocks)"},{"id":"4","name":"Financial transactions (flows)"},{"id":"I","name":"Index of Notional Stocks"}]},{"id":"COUNT_AREA","name":"Counterpart area","values":[{"id":"U2","name":"Euro area (changing composition)"}]},{"id":"BS_COUNT_SECTOR","name":"BS counterpart sector","values":[{"id":"2300","name":"Non-MFIs excluding central government"}]},{"id":"CURRENCY_TRANS","name":"Currency of transaction","values":[{"id":"Z01","name":"All currencies combined"}]},{"id":"BS_SUFFIX","name":"Balance sheet suffix","values":[{"id":"E","name":"Euro"},{"id":"A","name":"Annual growth rate"}]}],"observation":[{"id":"TIME_PERIOD","name":"Time period or range","role":"time","values":[{"id":"2026-06","name":"2026-06","start":"2026-06-01T00:00:00.000+02:00","end":"2026-06-30T23:59:59.999+02:00"},{"id":"2026-07","name":"2026-07","start":"2026-07-01T00:00:00.000+02:00","end":"2026-07-31T23:59:59.999+02:00"},{"id":"2026-08","name":"2026-08","start":"2026-08-01T00:00:00.000+02:00","end":"2026-08-31T23:59:59.999+02:00"}]}]},"attributes":{"series":[{"id":"TIME_FORMAT","name":"Time format code","values":[{"name":"P1M"}]},{"id":"BREAKS","name":"Breaks","values":[]},{"id":"COLLECTION","name":"Collection indicator","values":[{"id":"E","name":"End of period"},{"id":"S","name":"Summed through period"}]},{"id":"COMPILING_ORG","name":"Compiling organisation","values":[]},{"id":"DISS_ORG","name":"Data dissemination organisation","values":[]},{"id":"DOM_SER_IDS","name":"Domestic series ids","values":[]},{"id":"PUBL_ECB","name":"Source publication (ECB only)","values":[]},{"id":"PUBL_MU","name":"Source publication (Euro area only)","values":[]},{"id":"PUBL_PUBLIC","name":"Source publication (public)","values":[]},{"id":"UNIT_INDEX_BASE","name":"Unit index base","values":[{"name":"Dec10 = 100"}]},{"id":"COMPILATION","name":"Compilation","values":[]},{"id":"DECIMALS","name":"Decimals","values":[{"id":"2","name":"Two"},{"id":"1","name":"One"},{"id":"5","name":"Five"}]},{"id":"NAT_TITLE","name":"National language title","values":[]},{"id":"SOURCE_AGENCY","name":"Source agency","values":[]},{"id":"TITLE","name":"Title","values":[{"name":"Monetary aggregate M1, Stocks"},{"name":"Monetary aggregate M1, Transactions"},{"name":"Monetary aggregate M1, Annual growth rate"},{"name":"Monetary aggregate M1, Index"},{"name":"Monetary aggregate M2, Stocks"},{"name":"Monetary aggregate M2, Transactions"},{"name":"Monetary aggregate M2, Annual growth rate"},{"name":"Monetary aggregate M2, Index"},{"name":"Monetary aggregate M3, Stocks"},{"name":"Monetary aggregate M3, Transactions"},{"name":"Monetary aggregate M3, Annual growth rate"},{"name":"Monetary aggregate M3, Index"}]},{"id":"TITLE_COMPL","name":"Title complement","values":[{"name":"Euro area (changing composition), Outstanding amounts at the end of the period (stocks), MFIs, central government and post office giro institutions reporting sector - Monetary aggregate M1, All currencies combined - Euro area (changing composition) counterpart, Non-MFIs excluding central government sector, denominated in Euro, data Working day and seasonally adjusted"},{"name":"Euro area (changing composition), Financial transactions (flows), MFIs, central government and post office giro institutions reporting sector - Monetary aggregate M1, All currencies combined - Euro area (changing composition) counterpart, Non-MFIs excluding central government sector, denominated in Euro, data Working day and seasonally adjusted"},{"name":"Euro area (changing composition), Index of Notional Stocks, MFIs, central government and post office giro institutions reporting sector - Monetary aggregate M1, All currencies combined - Euro area (changing composition) counterpart, Non-MFIs excluding central government sector, Annual growth rate, data Working day and seasonally adjusted"},{"name":"Euro area (changing composition), Index of Notional Stocks, MFIs, central government and post office giro institutions reporting sector - Monetary aggregate M1, All currencies combined - Euro area (changing composition) counterpart, Non-MFIs excluding central government sector, denominated in Euro, data Working day and seasonally adjusted"},{"name":"Euro area (changing composition), Outstanding amounts at the end of the period (stocks), MFIs, central government and post office giro institutions reporting sector - Monetary aggregate M2, All currencies combined - Euro area (changing composition) counterpart, Non-MFIs excluding central government sector, denominated in Euro, data Working day and seasonally adjusted"},{"name":"Euro area (changing composition), Financial transactions (flows), MFIs, central government and post office giro institutions reporting sector - Monetary aggregate M2, All currencies combined - Euro area (changing composition) counterpart, Non-MFIs excluding central government sector, denominated in Euro, data Working day and seasonally adjusted"},{"name":"Euro area (changing composition), Index of Notional Stocks, MFIs, central government and post office giro institutions reporting sector - Monetary aggregate M2, All currencies combined - Euro area (changing composition) counterpart, Non-MFIs excluding central government sector, Annual growth rate, data Working day and seasonally adjusted"},{"name":"Euro area (changing composition), Index of Notional Stocks, MFIs, central government and post office giro institutions reporting sector - Monetary aggregate M2, All currencies combined - Euro area (changing composition) counterpart, Non-MFIs excluding central government sector, denominated in Euro, data Working day and seasonally adjusted"},{"name":"Euro area (changing composition), Outstanding amounts at the end of the period (stocks), MFIs, central government and post office giro institutions reporting sector - Monetary aggregate M3, All currencies combined - Euro area (changing composition) counterpart, Non-MFIs excluding central government sector, denominated in Euro, data Working day and seasonally adjusted"},{"name":"Euro area (changing composition), Financial transactions (flows), MFIs, central government and post office giro institutions reporting sector - Monetary aggregate M3, All currencies combined - Euro area (changing composition) counterpart, Non-MFIs excluding central government sector, denominated in Euro, data Working day and seasonally adjusted"},{"name":"Euro area (changing composition), Index of Notional Stocks, MFIs, central government and post office giro institutions reporting sector - Monetary aggregate M3, All currencies combined - Euro area (changing composition) counterpart, Non-MFIs excluding central government sector, Annual growth rate, data Working day and seasonally adjusted"},{"name":"Euro area (changing composition), Index of Notional Stocks, MFIs, central government and post office giro institutions reporting sector - Monetary aggregate M3, All currencies combined - Euro area (changing composition) counterpart, Non-MFIs excluding central government sector, denominated in Euro, data Working day and seasonally adjusted"}]},{"id":"UNIT","name":"Unit","values":[{"id":"EUR","name":"Euro"},{"id":"PCCH","name":"Percentage change"}]},{"id":"UNIT_MULT","name":"Unit multiplier","values":[{"id":"6","name":"Millions"},{"id":"0","name":"Units"}]}],"observation":[{"id":"OBS_STATUS","name":"Observation status","values":[{"id":"A","name":"Normal value"},{"id":"P","name":"Provisional value"}]},{"id":"OBS_CONF","name":"Observation confidentiality","values":[{"id":"F","name":"Free"}]},{"id":"OBS_PRE_BREAK","name":"Pre-break observation value","values":[]},{"id":"OBS_COM","name":"Observation comment","values":[]}]}}}
\ No newline at end of file
diff --git a/src/world_intel_mcp/tests/fixtures/liquidity/ecb_ilm_total.json b/src/world_intel_mcp/tests/fixtures/liquidity/ecb_ilm_total.json
new file mode 100644
index 0000000..7790309
--- /dev/null
+++ b/src/world_intel_mcp/tests/fixtures/liquidity/ecb_ilm_total.json
@@ -0,0 +1 @@
+{"header":{"id":"5bc2d80a-82be-4326-bfa9-300183308fa3","test":false,"prepared":"2026-10-17T18:16:30.446+02:00","sender":{"id":"ECB"}},"dataSets":[{"action":"Replace","validFrom":"2026-10-17T18:16:30.446+02:00","series":{"0:0:0:0:0:0":{"attributes":[0,null,0,null,null,null,null,null,null,null,null,0,null,0,0,0,0],"observations":{"0":[5897262,0,0,null,null],"1":[5947826,0,0,null,null],"2":[5943911,0,0,null,null]}}}}],"structure":{"links":[{"title":"Internal Liquidity Management","rel":"dataflow","href":"https://data-api.ecb.europa.eu:443/service/dataflow/ECB/ILM/1.0"}],"name":"Internal Liquidity Management","dimensions":{"series":[{"id":"FREQ","name":"Frequency","values":[{"id":"W","name":"Weekly"}]},{"id":"REF_AREA","name":"Reference area","values":[{"id":"U2","name":"Euro area (changing composition)"}]},{"id":"BS_REP_SECTOR","name":"BS reference sector breakdown","values":[{"id":"C","name":"Eurosystem"}]},{"id":"BS_ITEM","name":"Balance sheet item","values":[{"id":"T000000","name":"Total assets/liabilities"}]},{"id":"COUNT_AREA","name":"Counterpart area","values":[{"id":"Z5","name":"World not allocated (geographically)"}]},{"id":"CURRENCY_TRANS","name":"Currency of transaction","values":[{"id":"Z01","name":"All currencies combined"}]}],"observation":[{"id":"TIME_PERIOD","name":"Time period or range","role":"time","values":[{"id":"2026-W39","name":"2026-W39","start":"2026-09-21T00:00:00.000+02:00","end":"2026-09-27T23:59:59.999+02:00"},{"id":"2026-W40","name":"2026-W40","start":"2026-09-28T00:00:00.000+02:00","end":"2026-10-04T23:59:59.999+02:00"},{"id":"2026-W41","name":"2026-W41","start":"2026-10-05T00:00:00.000+02:00","end":"2026-10-11T23:59:59.999+02:00"}]}]},"attributes":{"series":[{"id":"TIME_FORMAT","name":"Time format code","values":[{"name":"P7D"}]},{"id":"BREAKS","name":"Breaks","values":[]},{"id":"COLLECTION","name":"Collection indicator","values":[{"id":"E","name":"End of period"}]},{"id":"COMPILING_ORG","name":"Compiling organisation","values":[]},{"id":"DISS_ORG","name":"Data dissemination organisation","values":[]},{"id":"PUBL_ECB","name":"Source publication (ECB only)","values":[]},{"id":"PUBL_MU","name":"Source publication (Euro area only)","values":[]},{"id":"PUBL_PUBLIC","name":"Source publication (public)","values":[]},{"id":"AGG_EQUN","name":"Aggregation equations","values":[]},{"id":"COMPILATION","name":"Compilation","values":[]},{"id":"COVERAGE","name":"Coverage","values":[]},{"id":"DECIMALS","name":"Decimals","values":[{"id":"0","name":"Zero"}]},{"id":"SOURCE_AGENCY","name":"Source agency","values":[]},{"id":"TITLE","name":"Title","values":[{"name":"Total assets/liabilities - Eurosystem"}]},{"id":"TITLE_COMPL","name":"Title complement","values":[{"name":"Euro area (changing composition), Eurosystem reporting sector - Total assets/liabilities, All currencies combined - World not allocated (geographically) counterpart"}]},{"id":"UNIT","name":"Unit","values":[{"id":"EUR","name":"Euro"}]},{"id":"UNIT_MULT","name":"Unit multiplier","values":[{"id":"6","name":"Millions"}]}],"observation":[{"id":"OBS_STATUS","name":"Observation status","values":[{"id":"A","name":"Normal value"}]},{"id":"OBS_CONF","name":"Observation confidentiality","values":[{"id":"F","name":"Free"}]},{"id":"OBS_PRE_BREAK","name":"Pre-break observation value","values":[]},{"id":"OBS_COM","name":"Observation comment","values":[]}]}}}
\ No newline at end of file
diff --git a/src/world_intel_mcp/tests/fixtures/liquidity/fred_M2SL.csv b/src/world_intel_mcp/tests/fixtures/liquidity/fred_M2SL.csv
new file mode 100644
index 0000000..a5f3b4d
--- /dev/null
+++ b/src/world_intel_mcp/tests/fixtures/liquidity/fred_M2SL.csv
@@ -0,0 +1,15 @@
+observation_date,M2SL
+2025-07-01,22025.6
+2025-08-01,22092.6
+2025-09-01,22176.1
+2025-10-01,22249.8
+2025-11-01,22279.8
+2025-12-01,22355.3
+2026-01-01,22413.4
+2026-02-01,22598.7
+2026-03-01,22640.3
+2026-04-01,22756.6
+2026-05-01,23013.7
+2026-06-01,23114.9
+2026-07-01,23217.9
+2026-08-01,23342.8
diff --git a/src/world_intel_mcp/tests/fixtures/liquidity/fred_RRPONTSYD.csv b/src/world_intel_mcp/tests/fixtures/liquidity/fred_RRPONTSYD.csv
new file mode 100644
index 0000000..82c08c3
--- /dev/null
+++ b/src/world_intel_mcp/tests/fixtures/liquidity/fred_RRPONTSYD.csv
@@ -0,0 +1,46 @@
+observation_date,RRPONTSYD
+2026-08-17,0.255
+2026-08-18,0.155
+2026-08-19,0.317
+2026-08-20,0.225
+2026-08-21,0.200
+2026-08-24,0.380
+2026-08-25,0.405
+2026-08-26,0.702
+2026-08-27,0.456
+2026-08-28,0.175
+2026-08-31,6.726
+2026-09-01,0.725
+2026-09-02,0.525
+2026-09-03,0.702
+2026-09-04,0.675
+2026-09-07,
+2026-09-08,0.626
+2026-09-09,0.432
+2026-09-10,4.736
+2026-09-11,5.255
+2026-09-14,1.420
+2026-09-15,0.700
+2026-09-16,5.375
+2026-09-17,0.276
+2026-09-18,0.576
+2026-09-21,0.582
+2026-09-22,0.453
+2026-09-23,0.461
+2026-09-24,0.630
+2026-09-25,0.576
+2026-09-28,0.851
+2026-09-29,11.446
+2026-09-30,11.539
+2026-10-01,0.350
+2026-10-02,1.501
+2026-10-05,1.004
+2026-10-06,0.414
+2026-10-07,2.338
+2026-10-08,0.335
+2026-10-09,0.300
+2026-10-12,
+2026-10-13,0.275
+2026-10-14,0.201
+2026-10-15,1.201
+2026-10-16,0.100
diff --git a/src/world_intel_mcp/tests/fixtures/liquidity/fred_WALCL.csv b/src/world_intel_mcp/tests/fixtures/liquidity/fred_WALCL.csv
new file mode 100644
index 0000000..d2f20d6
--- /dev/null
+++ b/src/world_intel_mcp/tests/fixtures/liquidity/fred_WALCL.csv
@@ -0,0 +1,10 @@
+observation_date,WALCL
+2026-08-19,6745699
+2026-08-26,6730912
+2026-09-02,6737204
+2026-09-09,6740619
+2026-09-16,6746548
+2026-09-23,6747704
+2026-09-30,6743031
+2026-10-07,6747560
+2026-10-14,6755639
diff --git a/src/world_intel_mcp/tests/fixtures/liquidity/fred_WDTGAL.csv b/src/world_intel_mcp/tests/fixtures/liquidity/fred_WDTGAL.csv
new file mode 100644
index 0000000..60f32ca
--- /dev/null
+++ b/src/world_intel_mcp/tests/fixtures/liquidity/fred_WDTGAL.csv
@@ -0,0 +1,10 @@
+observation_date,WDTGAL
+2026-08-19,936406
+2026-08-26,959435
+2026-09-02,944364
+2026-09-09,843705
+2026-09-16,991708
+2026-09-23,947317
+2026-09-30,984046
+2026-10-07,885783
+2026-10-14,885823
diff --git a/src/world_intel_mcp/tests/test_liquidity_surfaces.py b/src/world_intel_mcp/tests/test_liquidity_surfaces.py
new file mode 100644
index 0000000..aa930ea
--- /dev/null
+++ b/src/world_intel_mcp/tests/test_liquidity_surfaces.py
@@ -0,0 +1,244 @@
+"""Liquidity tools and CLI commands (Phase 29): MCP handlers pass their
+arguments through, and every CLI command renders values, surfaces an
+upstream error as one red line, and passes raw JSON in --json-output mode.
+
+Payloads are produced by the real source functions from the live-captured
+fixtures, so the CLI renders the shapes the tools return.
+
+Gaps / not covered: the MCP stdio transport itself (test_server_registry
+covers dispatch); terminal widths below 200 columns.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+from datetime import date
+from pathlib import Path
+
+import httpx
+import pytest
+import respx
+from click.testing import CliRunner
+
+import world_intel_mcp.fetcher as fetcher_mod
+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 .test_sources_liquidity import _mock_all
+
+
+def _liquidity_tools():
+ """Import tools/liquidity.py under test_server_registry's temp cache.
+
+ Importing any tools module imports runtime, which opens a live Cache
+ at import; the shared temp path keeps it off the developer's cache and
+ keeps test_server_cache_landed_in_temp_path true whichever test file
+ imports runtime first (same pattern as test_aoi._tools_registry)."""
+ import importlib
+ import os
+
+ from .test_server_registry import _TMP_CACHE
+
+ prior = os.environ.get("WORLD_INTEL_CACHE_DB")
+ os.environ["WORLD_INTEL_CACHE_DB"] = str(_TMP_CACHE)
+ try:
+ importlib.import_module("world_intel_mcp.tools")
+ return importlib.import_module("world_intel_mcp.tools.liquidity")
+ finally:
+ if prior is None:
+ os.environ.pop("WORLD_INTEL_CACHE_DB", None)
+ else:
+ os.environ["WORLD_INTEL_CACHE_DB"] = prior
+
+
[email protected](autouse=True)
+def _isolation(tmp_path, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("WORLD_INTEL_CACHE_DB", str(tmp_path / "cli-cache.db"))
+ monkeypatch.setenv("COLUMNS", "200")
+ monkeypatch.setattr(cli, "_fetcher", None)
+ monkeypatch.setattr(liquidity, "_today", lambda: date(2026, 10, 17))
+ monkeypatch.setitem(fetcher_mod._SOURCE_RATE_LIMITS, liquidity.FRED_SOURCE, 0.0)
+
+
+def _fetcher(tmp_path: Path) -> Fetcher:
+ return Fetcher(cache=Cache(db_path=tmp_path / "f.db"), breaker=CircuitBreaker(), max_retries=0)
+
+
+async def _build_payloads(tmp_path: Path) -> dict:
+ f = _fetcher(tmp_path)
+ with respx.mock:
+ _mock_all()
+ ecb_key = "M.U2.Y.V.M10+M20+M30.X.1+4+I.U2.2300.Z01.E+A"
+ respx.get(f"https://data-api.ecb.europa.eu/service/data/BSI/{ecb_key}").mock(
+ return_value=httpx.Response(200, json=json.loads(
+ (Path(__file__).parent / "fixtures" / "liquidity" / "ecb_bsi_money.json").read_text()
+ ))
+ )
+ return {
+ "board": await liquidity.fetch_liquidity_board(f),
+ "net": await liquidity.fetch_net_liquidity(f, limit=3),
+ "money": await liquidity.fetch_money_supply(f, limit=2),
+ "fed": await liquidity.fetch_fed_liquidity_series(f, "WALCL", limit=2),
+ "ecb": await liquidity.fetch_ecb_series(f, key=ecb_key, limit=1),
+ }
+
+
+def _payloads(tmp_path: Path) -> dict:
+ """Built outside any running loop: the CLI calls asyncio.run itself."""
+ return asyncio.run(_build_payloads(tmp_path))
+
+
+def _fake(payload, calls: list | None = None):
+ async def _f(*args, **kwargs):
+ if calls is not None:
+ calls.append(kwargs)
+ return payload
+
+ return _f
+
+
+def _invoke(*args: str):
+ return CliRunner().invoke(cli.main, list(args), catch_exceptions=False)
+
+
+# ---------------------------------------------------------------------------
+# MCP handlers
+# ---------------------------------------------------------------------------
+
+
+def test_registry_has_five_liquidity_tools() -> None:
+ liquidity_tools = _liquidity_tools()
+ names = [t.name for t in liquidity_tools.TOOLS]
+ assert names == [
+ "intel_liquidity_board",
+ "intel_net_liquidity",
+ "intel_money_supply",
+ "intel_fed_liquidity_series",
+ "intel_ecb_series",
+ ]
+ schema = {t.name: t.inputSchema for t in liquidity_tools.TOOLS}
+ assert schema["intel_fed_liquidity_series"]["properties"]["series_id"]["enum"] == sorted(liquidity.FRED_SERIES)
+ assert schema["intel_ecb_series"]["required"] == ["key"]
+
+
+ "tool, fn, args, expected",
+ [
+ ("intel_liquidity_board", "fetch_liquidity_board", {"sort": "newest"}, {"sort": "newest"}),
+ ("intel_liquidity_board", "fetch_liquidity_board", {}, {"sort": "biggest_move"}),
+ ("intel_net_liquidity", "fetch_net_liquidity", {"limit": 0, "start": "2020-01-01"},
+ {"limit": 0, "start": "2020-01-01"}),
+ ("intel_net_liquidity", "fetch_net_liquidity", {}, {"limit": 52, "start": None}),
+ ("intel_money_supply", "fetch_money_supply", {"region": "us"}, {"region": "us", "limit": 13}),
+ ("intel_fed_liquidity_series", "fetch_fed_liquidity_series", {"series_id": "M2SL", "limit": 5},
+ {"series_id": "M2SL", "limit": 5, "start": None}),
+ ("intel_ecb_series", "fetch_ecb_series", {"key": "W.U2.C.T000000.Z5.Z01", "dataset": "ILM"},
+ {"dataset": "ILM", "key": "W.U2.C.T000000.Z5.Z01", "limit": 24, "start": None}),
+ ],
+)
+async def test_handlers_pass_arguments(monkeypatch, tool, fn, args, expected) -> None:
+ calls: list = []
+ monkeypatch.setattr(liquidity, fn, _fake({"ok": tool}, calls))
+ out = await _liquidity_tools().HANDLERS[tool](args)
+ assert out == {"ok": tool}
+ assert calls == [expected]
+
+
+# ---------------------------------------------------------------------------
+# CLI
+# ---------------------------------------------------------------------------
+
+
+def test_cli_liquidity_board_renders_rows_and_gaps(tmp_path, monkeypatch) -> None:
+ payload = _payloads(tmp_path)["board"]
+ calls: list = []
+ monkeypatch.setattr(cli.liquidity, "fetch_liquidity_board", _fake(payload, calls))
+ out = _invoke("liquidity", "--sort", "newest").output
+ assert calls == [{"sort": "newest"}]
+ assert "net_liquidity" in out and "5,869.62" in out
+ assert "eurosystem_total_assets" in out and "2026-W41" in out
+ assert "Gap:" in out
+
+
+def test_cli_liquidity_board_marks_stale_and_unavailable(tmp_path, monkeypatch) -> None:
+ payload = _payloads(tmp_path)["board"]
+ payload["indicators"][0]["freshness"]["stale"] = True
+ payload["unavailable"] = [{"indicator": "us_m2", "error": "FRED graph CSV for M2SL unavailable"}]
+ monkeypatch.setattr(cli.liquidity, "fetch_liquidity_board", _fake(payload))
+ out = _invoke("liquidity").output
+ assert "(stale)" in out
+ assert "Unavailable: us_m2: FRED graph CSV for M2SL unavailable" in out
+
+
+ "command, fn",
+ [
+ (["liquidity"], "fetch_liquidity_board"),
+ (["net-liquidity"], "fetch_net_liquidity"),
+ (["money-supply"], "fetch_money_supply"),
+ (["fed-liquidity", "WALCL"], "fetch_fed_liquidity_series"),
+ (["ecb-series", "M.U2.Y.V.M30.X.1.U2.2300.Z01.E"], "fetch_ecb_series"),
+ ],
+)
+def test_cli_error_is_one_red_line_and_json_mode_is_raw(monkeypatch, command, fn) -> None:
+ err = {"error": "net liquidity not computed: missing component(s) WDTGAL", "data_gaps": ["x"]}
+ monkeypatch.setattr(cli.liquidity, fn, _fake(err))
+ out = _invoke(*command).output
+ assert out.strip() == "Error: net liquidity not computed: missing component(s) WDTGAL"
+ raw = _invoke("--json-output", *command).output
+ assert json.loads(raw) == err
+
+
+def test_cli_net_liquidity_shows_formula_and_components(tmp_path, monkeypatch) -> None:
+ payload = _payloads(tmp_path)["net"]
+ calls: list = []
+ monkeypatch.setattr(cli.liquidity, "fetch_net_liquidity", _fake(payload, calls))
+ out = _invoke("net-liquidity", "-n", "3", "--start", "2026-09-01").output
+ assert calls == [{"limit": 3, "start": "2026-09-01"}]
+ assert "net_liquidity = WALCL - WDTGAL - RRPONTSYD" in out
+ assert "6,755.64" in out and "885.82" in out and "0.20" in out
+ assert "2026-10-14" in out
+
+
+def test_cli_money_supply_renders_both_regions(tmp_path, monkeypatch) -> None:
+ payload = _payloads(tmp_path)["money"]
+ monkeypatch.setattr(cli.liquidity, "fetch_money_supply", _fake(payload))
+ out = _invoke("money-supply").output
+ assert "US M2" in out and "23,342.80" in out
+ assert "US M3 is discontinued" in out
+ assert "Euro area M3 stock" in out and "17,646,463.00" in out
+ assert "Provisional value" in out
+ assert "never added together" in out
+
+
+def test_cli_money_supply_partial_failures(monkeypatch) -> None:
+ payload = {
+ "region": "all",
+ "note": liquidity.NESTING_NOTE,
+ "us": {"M2": {"error": "FRED graph CSV for M2SL unavailable"}, "M3": {"note": liquidity.US_M3_NOTE}},
+ "euro_area": {"error": "ECB Data Portal returned no data"},
+ "data_gaps": [],
+ }
+ monkeypatch.setattr(cli.liquidity, "fetch_money_supply", _fake(payload))
+ out = _invoke("money-supply").output
+ assert "US M2 unavailable: FRED graph CSV for M2SL unavailable" in out
+ assert "Euro area unavailable: ECB Data Portal returned no data" in out
+
+
+def test_cli_fed_liquidity_and_ecb_series_render(tmp_path, monkeypatch) -> None:
+ payloads = _payloads(tmp_path)
+ calls: list = []
+ monkeypatch.setattr(cli.liquidity, "fetch_fed_liquidity_series", _fake(payloads["fed"], calls))
+ out = _invoke("fed-liquidity", "walcl", "-n", "2").output
+ assert calls == [{"series_id": "WALCL", "limit": 2, "start": None}]
+ assert "6,755,639.00" in out and "USD millions" in out
+ ecb_calls: list = []
+ monkeypatch.setattr(cli.liquidity, "fetch_ecb_series", _fake(payloads["ecb"], ecb_calls))
+ out = _invoke("ecb-series", "M.U2.Y.V.M30.X.1.U2.2300.Z01.E", "-d", "BSI", "-n", "1").output
+ assert ecb_calls == [{"dataset": "BSI", "key": "M.U2.Y.V.M30.X.1.U2.2300.Z01.E", "limit": 1, "start": None}]
+ assert "Monetary aggregate M3, Stocks (amount_outstanding)" in out
+ assert "(growth_rate)" in out
diff --git a/src/world_intel_mcp/tests/test_sources_liquidity.py b/src/world_intel_mcp/tests/test_sources_liquidity.py
new file mode 100644
index 0000000..ac0247c
--- /dev/null
+++ b/src/world_intel_mcp/tests/test_sources_liquidity.py
@@ -0,0 +1,499 @@
+"""Tests for sources/liquidity.py (FRED graph CSV, ECB Data Portal SDMX-JSON).
+
+Fixtures under fixtures/liquidity/ are live responses captured 2026-10-17:
+the FRED CSVs are the newest rows of each series' full download (header
+unchanged; RRPONTSYD keeps its real blank cells for 2026-09-07 and
+2026-10-12), the ECB files are complete responses for the keys the
+module queries, and ecb_404_problem.json is the portal's real answer to
+a key that matches no series.
+
+Gaps / not covered: live calls (run by hand, see the CHANGELOG entry);
+ECB responses with more than 50 series; FRED full-history downloads
+(the arithmetic is the same per week, pinned here on real weeks).
+"""
+
+from __future__ import annotations
+
+import json
+from datetime import date
+from pathlib import Path
+
+import httpx
+import pytest
+import respx
+
+import world_intel_mcp.fetcher as fetcher_mod
+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
+
+_FIX = Path(__file__).parent / "fixtures" / "liquidity"
+_FRED = {sid: (_FIX / f"fred_{sid}.csv").read_text() for sid in ("WALCL", "WDTGAL", "RRPONTSYD", "M2SL")}
+_BSI = json.loads((_FIX / "ecb_bsi_money.json").read_text())
+_ILM = json.loads((_FIX / "ecb_ilm_total.json").read_text())
+_ECB_404 = (_FIX / "ecb_404_problem.json").read_text()
+_FRED_FLOOR_AT_IMPORT = fetcher_mod._SOURCE_RATE_LIMITS.get(liquidity.FRED_SOURCE)
+
+_FRED_URL = "https://fred.stlouisfed.org/graph/fredgraph.csv"
+_ECB_BSI_URL = f"https://data-api.ecb.europa.eu/service/data/BSI/{liquidity._ECB_MONEY_KEY}"
+_ECB_ILM_URL = f"https://data-api.ecb.europa.eu/service/data/ILM/{liquidity._ECB_EUROSYSTEM_KEY}"
+
+
[email protected](autouse=True)
+def _fixed_clock_and_no_throttle(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(liquidity, "_today", lambda: date(2026, 10, 17))
+ monkeypatch.setitem(fetcher_mod._SOURCE_RATE_LIMITS, liquidity.FRED_SOURCE, 0.0)
+
+
+def fetcher(tmp_path: Path) -> Fetcher:
+ return Fetcher(
+ cache=Cache(db_path=tmp_path / "liq.db"),
+ breaker=CircuitBreaker(),
+ default_timeout=5.0,
+ max_retries=0,
+ )
+
+
+def _fred_router(overrides: dict[str, httpx.Response] | None = None):
+ overrides = overrides or {}
+
+ def _route(request: httpx.Request) -> httpx.Response:
+ sid = request.url.params.get("id")
+ if sid in overrides:
+ return overrides[sid]
+ if sid in _FRED:
+ return httpx.Response(200, text=_FRED[sid], headers={"content-type": "application/csv"})
+ return httpx.Response(404, text="<html>Error - St. Louis Fed</html>")
+
+ return _route
+
+
+def _mock_all(fred_overrides=None, bsi=None, ilm=None) -> None:
+ respx.get(_FRED_URL).mock(side_effect=_fred_router(fred_overrides))
+ respx.get(_ECB_BSI_URL).mock(return_value=bsi or httpx.Response(200, json=_BSI))
+ respx.get(_ECB_ILM_URL).mock(return_value=ilm or httpx.Response(200, json=_ILM))
+
+
+def _rows(text: str, sid: str):
+ return liquidity.parse_fred_csv(text, sid)
+
+
+# ---------------------------------------------------------------------------
+# FRED CSV parsing
+# ---------------------------------------------------------------------------
+
+
+def test_parse_fred_csv_keeps_blank_cells_missing_not_zero() -> None:
+ rows = dict(_rows(_FRED["RRPONTSYD"], "RRPONTSYD"))
+ assert rows[date(2026, 10, 12)] is None # Columbus Day: blank in the live CSV
+ assert rows[date(2026, 9, 7)] is None # Labor Day
+ assert rows[date(2026, 10, 14)] == 0.201
+
+
+ "text",
+ [
+ "observation_date,WDTGAL\n2026-10-14,885823\n", # another series' header
+ "<!DOCTYPE html><html><title>Error - St. Louis Fed</title></html>",
+ "observation_date,WALCL\n2026-10-14,n/a\n",
+ "",
+ ],
+)
+def test_parse_fred_csv_rejects_wrong_shapes(text: str) -> None:
+ with pytest.raises(ValueError):
+ liquidity.parse_fred_csv(text, "WALCL")
+
+
+# ---------------------------------------------------------------------------
+# Net liquidity arithmetic, unit conversion, alignment
+# ---------------------------------------------------------------------------
+
+
+def test_compute_net_liquidity_known_week_and_unit_conversion() -> None:
+ points, skipped = liquidity.compute_net_liquidity(
+ _rows(_FRED["WALCL"], "WALCL"),
+ _rows(_FRED["WDTGAL"], "WDTGAL"),
+ _rows(_FRED["RRPONTSYD"], "RRPONTSYD"),
+ )
+ by_day = {p["observed_at"]: p for p in points}
+ week = by_day["2026-10-14"]
+ # WALCL 6,755,639 and WDTGAL 885,823 are USD millions; RRP 0.201 is USD billions.
+ assert week["fed_total_assets"] == 6755.639
+ assert week["treasury_general_account"] == 885.823
+ assert week["reverse_repo"] == 0.201
+ assert week["value"] == 5869.615
+ assert week["units"] == "USD billions"
+ assert week["reverse_repo_observed_at"] == "2026-10-14"
+ # Quarter-end week: RRP 11.539 on 2026-09-30.
+ assert by_day["2026-09-30"]["value"] == round(6743.031 - 984.046 - 11.539, 3)
+ assert skipped == []
+ assert [p["observed_at"] for p in points] == sorted(by_day)
+
+
+def test_rrp_blank_on_the_wednesday_uses_latest_earlier_day_and_names_it() -> None:
+ rrp = [(d, None if d == date(2026, 10, 7) else v) for d, v in _rows(_FRED["RRPONTSYD"], "RRPONTSYD")]
+ points, _ = liquidity.compute_net_liquidity(
+ _rows(_FRED["WALCL"], "WALCL"), _rows(_FRED["WDTGAL"], "WDTGAL"), rrp
+ )
+ week = {p["observed_at"]: p for p in points}["2026-10-07"]
+ assert week["reverse_repo_observed_at"] == "2026-10-06"
+ assert week["reverse_repo"] == 0.414
+ assert week["value"] == round(6747.560 - 885.783 - 0.414, 3)
+
+
+def test_rrp_is_never_taken_from_after_the_wednesday_and_gaps_are_skipped() -> None:
+ walcl = [(date(2026, 10, 14), 6755639.0)]
+ tga = [(date(2026, 10, 14), 885823.0)]
+ later_only = [(date(2026, 10, 15), 1.201)]
+ points, skipped = liquidity.compute_net_liquidity(walcl, tga, later_only)
+ assert points == [] and skipped == ["2026-10-14"]
+ # TGA missing for the week: skipped, not treated as a zero TGA.
+ points, skipped = liquidity.compute_net_liquidity(walcl, [(date(2026, 10, 7), 885783.0)], [(date(2026, 10, 14), 0.201)])
+ assert points == [] and skipped == ["2026-10-14"]
+
+
+async def test_fetch_net_liquidity_states_formula_and_returns_newest_first(fetcher: Fetcher) -> None:
+ respx.get(_FRED_URL).mock(side_effect=_fred_router())
+ out = await liquidity.fetch_net_liquidity(fetcher, limit=3)
+ assert "error" not in out
+ assert out["formula"].startswith("net_liquidity = WALCL - WDTGAL - RRPONTSYD")
+ assert "divided by 1,000" in out["formula"]
+ assert "never filled with zero" in out["alignment"]
+ assert [p["observed_at"] for p in out["points"]] == ["2026-10-14", "2026-10-07", "2026-09-30"]
+ assert out["latest"]["value"] == 5869.615
+ assert out["change"]["absolute"] == round(5869.615 - (6747.560 - 885.783 - 2.338), 3)
+ assert out["change"]["from"] == "2026-10-07"
+ assert out["components"]["WALCL"]["units"] == "USD millions"
+ assert out["components"]["RRPONTSYD"]["units"] == "USD billions"
+ assert out["published_at"] is None
+ assert any("WDTGAL (Wednesday level), not" in g for g in out["data_gaps"])
+ # start filter and full history
+ since = await liquidity.fetch_net_liquidity(fetcher, limit=0, start="2026-09-23")
+ assert [p["observed_at"] for p in since["points"]] == ["2026-10-14", "2026-10-07", "2026-09-30", "2026-09-23"]
+ full = await liquidity.fetch_net_liquidity(fetcher, limit=0)
+ assert full["count"] == 9 and full["first_observed_at"] == "2026-08-19"
+
+
[email protected]("failing", ["WALCL", "WDTGAL", "RRPONTSYD"])
+async def test_net_liquidity_component_outage_is_an_error_never_a_zero_term(
+ fetcher: Fetcher, failing: str
+) -> None:
+ respx.get(_FRED_URL).mock(side_effect=_fred_router({failing: httpx.Response(503)}))
+ out = await liquidity.fetch_net_liquidity(fetcher)
+ assert "error" in out
+ assert out["components_failed"] == [failing]
+ assert "never treated as zero" in out["error"]
+ assert "points" not in out and "latest" not in out
+ assert any(failing in g for g in out["data_gaps"])
+
+
+async def test_fred_html_error_page_is_an_error_not_data(fetcher: Fetcher) -> None:
+ html = httpx.Response(200, text="<!DOCTYPE html><title>Error</title>", headers={"content-type": "text/html"})
+ respx.get(_FRED_URL).mock(side_effect=_fred_router({"WALCL": html}))
+ out = await liquidity.fetch_fed_liquidity_series(fetcher, "WALCL")
+ assert "not in the expected format" in out["error"]
+ assert "points" not in out
+
+
+async def test_net_liquidity_with_no_aligned_week_is_an_error(fetcher: Fetcher) -> None:
+ only_later_rrp = "observation_date,RRPONTSYD\n2026-12-01,0.5\n"
+ respx.get(_FRED_URL).mock(
+ side_effect=_fred_router({"RRPONTSYD": httpx.Response(200, text=only_later_rrp)})
+ )
+ out = await liquidity.fetch_net_liquidity(fetcher)
+ assert "no week had all three components aligned" in out["error"]
+ assert out["skipped_weeks"] == 9
+
+
+# ---------------------------------------------------------------------------
+# One FRED series
+# ---------------------------------------------------------------------------
+
+
+async def test_fed_liquidity_series_points_carry_units_and_blank_count(fetcher: Fetcher) -> None:
+ respx.get(_FRED_URL).mock(side_effect=_fred_router())
+ out = await liquidity.fetch_fed_liquidity_series(fetcher, "rrpontsyd", limit=4)
+ assert out["series_id"] == "RRPONTSYD"
+ assert out["points"] == [
+ {"observed_at": "2026-10-16", "value": 0.1, "units": "USD billions"},
+ {"observed_at": "2026-10-15", "value": 1.201, "units": "USD billions"},
+ {"observed_at": "2026-10-14", "value": 0.201, "units": "USD billions"},
+ {"observed_at": "2026-10-13", "value": 0.275, "units": "USD billions"},
+ ]
+ assert out["blank_observations"] == 2
+ assert any("2 blank RRPONTSYD dates" in g for g in out["data_gaps"])
+ assert out["measure"] == "amount_outstanding" and out["published_at"] is None
+ assert out["freshness"] == {"latest_age_days": 1, "expected_max_age_days": 6, "stale": False}
+ assert out["change"]["absolute"] == round(0.1 - 1.201, 3)
+
+
+async def test_monthly_series_freshness_uses_period_end_and_flags_stale(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ respx.get(_FRED_URL).mock(side_effect=_fred_router())
+ out = await liquidity.fetch_fed_liquidity_series(fetcher, "M2SL", limit=0, start="2026-06-01")
+ assert [p["observed_at"] for p in out["points"]] == ["2026-08-01", "2026-07-01", "2026-06-01"]
+ assert out["freshness"]["latest_age_days"] == (date(2026, 10, 17) - date(2026, 8, 31)).days
+ assert out["freshness"]["stale"] is False
+ monkeypatch.setattr(liquidity, "_today", lambda: date(2027, 1, 15))
+ out = await liquidity.fetch_fed_liquidity_series(fetcher, "M2SL")
+ assert out["freshness"]["stale"] is True
+ assert any("M2SL: newest observation 2026-08-01 is" in g for g in out["data_gaps"])
+
+
+ "kwargs, message",
+ [
+ ({"series_id": "GDP"}, "unknown series"),
+ ({"series_id": "WALCL", "limit": -1}, "limit must be"),
+ ({"series_id": "WALCL", "limit": True}, "limit must be"),
+ ({"series_id": "WALCL", "start": "17/10/2026"}, "start must be"),
+ ({"series_id": "WALCL", "start": 20261017}, "start must be"),
+ ],
+)
+async def test_fed_liquidity_series_validation(fetcher: Fetcher, kwargs: dict, message: str) -> None:
+ out = await liquidity.fetch_fed_liquidity_series(fetcher, **kwargs)
+ assert message in out["error"]
+
+
+async def test_net_liquidity_validation(fetcher: Fetcher) -> None:
+ assert "limit must be" in (await liquidity.fetch_net_liquidity(fetcher, limit="5"))["error"]
+ assert "start must be" in (await liquidity.fetch_net_liquidity(fetcher, start="yesterday"))["error"]
+
+
+# ---------------------------------------------------------------------------
+# ECB SDMX-JSON
+# ---------------------------------------------------------------------------
+
+
+def test_parse_sdmx_money_units_measures_and_status() -> None:
+ series = {s["key"]: s for s in liquidity.parse_sdmx_json(_BSI, "BSI")}
+ m3 = series["BSI.M.U2.Y.V.M30.X.1.U2.2300.Z01.E"]
+ assert m3["units"] == "EUR millions" and m3["scale"] == 1_000_000
+ assert m3["measure"] == "amount_outstanding"
+ assert m3["title"] == "Monetary aggregate M3, Stocks"
+ assert m3["points"][-1] == {
+ "observed_at": "2026-08",
+ "period_end": "2026-08-31",
+ "value": 17646463.0,
+ "units": "EUR millions",
+ "status": "Provisional value",
+ }
+ assert series["BSI.M.U2.Y.V.M30.X.4.U2.2300.Z01.E"]["measure"] == "flow"
+ growth = series["BSI.M.U2.Y.V.M30.X.I.U2.2300.Z01.A"]
+ assert growth["measure"] == "growth_rate" and growth["units"] == "percent" and growth["scale"] == 1
+ assert series["BSI.M.U2.Y.V.M30.X.I.U2.2300.Z01.E"]["measure"] == "index"
+ assert len(series) == 12
+
+
+def test_parse_sdmx_eurosystem_weekly() -> None:
+ (s,) = liquidity.parse_sdmx_json(_ILM, "ILM")
+ assert s["measure"] == "amount_outstanding" and s["frequency"] == "W"
+ assert [p["observed_at"] for p in s["points"]] == ["2026-W39", "2026-W40", "2026-W41"]
+ assert s["points"][-1]["period_end"] == "2026-10-11"
+ assert s["points"][-1]["value"] == 5943911.0
+
+
+async def test_fetch_ecb_series_growth_rate_change_is_points_not_percent(fetcher: Fetcher) -> None:
+ key = "M.U2.Y.V.M10+M20+M30.X.1+4+I.U2.2300.Z01.E+A"
+ respx.get(f"https://data-api.ecb.europa.eu/service/data/BSI/{key}").mock(
+ return_value=httpx.Response(200, json=_BSI)
+ )
+ out = await liquidity.fetch_ecb_series(fetcher, dataset="bsi", key=key, limit=2)
+ by_key = {s["key"]: s for s in out["series"]}
+ growth = by_key["BSI.M.U2.Y.V.M10.X.I.U2.2300.Z01.A"]
+ assert growth["change"]["pct"] is None
+ assert growth["count"] == 2
+ flow = by_key["BSI.M.U2.Y.V.M10.X.4.U2.2300.Z01.E"]
+ assert flow["change"] is None # differences of flows are not reported as changes
+ stock = by_key["BSI.M.U2.Y.V.M10.X.1.U2.2300.Z01.E"]
+ assert stock["change"]["absolute"] == 11293328.0 - 11291831.0
+ assert respx.calls.last.request.url.params["lastNObservations"] == "3"
+
+
+async def test_ecb_404_and_outage_are_errors(fetcher: Fetcher) -> None:
+ key = "M.U2.Y.V.M99.X.1.U2.2300.Z01.E"
+ respx.get(f"https://data-api.ecb.europa.eu/service/data/BSI/{key}").mock(
+ return_value=httpx.Response(404, text=_ECB_404, headers={"content-type": "application/problem+json"})
+ )
+ out = await liquidity.fetch_ecb_series(fetcher, key=key)
+ assert "no series matches the key" in out["error"]
+ assert "series" not in out
+
+
+async def test_ecb_unexpected_shape_is_an_error(fetcher: Fetcher) -> None:
+ key = "W.U2.C.T000000.Z5.Z01"
+ respx.get(f"https://data-api.ecb.europa.eu/service/data/ILM/{key}").mock(
+ return_value=httpx.Response(200, json={"header": {}, "dataSets": []})
+ )
+ out = await liquidity.fetch_ecb_series(fetcher, dataset="ILM", key=key)
+ assert "expected SDMX-JSON shape" in out["error"]
+
+
+ "kwargs, message",
+ [
+ ({"dataset": "EXR", "key": "D.USD.EUR.SP00.A"}, "dataset must be one of"),
+ ({"key": "../../etc"}, "key must be an SDMX series key"),
+ ({"key": "M.U2?x=1"}, "key must be an SDMX series key"),
+ ({"key": "M.U2.Y.V.M30.X.1.U2.2300.Z01.E", "limit": -3}, "limit must be"),
+ ],
+)
+async def test_ecb_series_validation(fetcher: Fetcher, kwargs: dict, message: str) -> None:
+ out = await liquidity.fetch_ecb_series(fetcher, **kwargs)
+ assert message in out["error"]
+
+
+# ---------------------------------------------------------------------------
+# Money supply
+# ---------------------------------------------------------------------------
+
+
+async def test_money_supply_keeps_aggregates_separate_and_never_sums(fetcher: Fetcher) -> None:
+ _mock_all()
+ out = await liquidity.fetch_money_supply(fetcher, limit=2)
+ assert "error" not in out
+ ea = out["euro_area"]["aggregates"]
+ assert set(ea) == {"M1", "M2", "M3"}
+ for roles in ea.values():
+ assert set(roles) == {"stock", "flow", "annual_growth_rate"}
+ stocks = {name: roles["stock"]["latest"]["value"] for name, roles in ea.items()}
+ assert stocks == {"M1": 11293328.0, "M2": 16447405.0, "M3": 17646463.0}
+ assert stocks["M1"] < stocks["M2"] < stocks["M3"] # nested, as published
+ # No figure anywhere equals a sum of the aggregates.
+ flat = json.dumps(out)
+ assert str(sum(stocks.values())) not in flat
+ assert not any(k in ea for k in ("total", "sum", "combined"))
+ assert "never added together" in out["note"]
+ assert ea["M3"]["flow"]["measure"] == "flow"
+ assert ea["M3"]["annual_growth_rate"]["latest"]["units"] == "percent"
+ us = out["us"]
+ assert us["M2"]["latest"] == {"observed_at": "2026-08-01", "value": 23342.8, "units": "USD billions"}
+ assert us["M2"]["count"] == 2
+ assert us["M3"]["available"] is False and "discontinued" in us["M3"]["note"]
+
+
+async def test_money_supply_partial_outage_names_the_gap(fetcher: Fetcher) -> None:
+ _mock_all(bsi=httpx.Response(503))
+ out = await liquidity.fetch_money_supply(fetcher)
+ assert "error" not in out # US M2 still answered
+ assert "error" in out["euro_area"] and "aggregates" not in out["euro_area"]
+ assert any("ECB Data Portal returned no data" in g for g in out["data_gaps"])
+
+
+async def test_money_supply_total_outage_is_an_error(fetcher: Fetcher) -> None:
+ _mock_all(fred_overrides={"M2SL": httpx.Response(500)}, bsi=httpx.Response(503))
+ out = await liquidity.fetch_money_supply(fetcher)
+ assert out["error"].startswith("money supply unavailable")
+ us_only = await liquidity.fetch_money_supply(fetcher, region="us")
+ assert "error" in us_only and "euro_area" not in us_only
+
+
+async def test_money_supply_validation(fetcher: Fetcher) -> None:
+ assert "region must be" in (await liquidity.fetch_money_supply(fetcher, region="uk"))["error"]
+ assert "limit must be" in (await liquidity.fetch_money_supply(fetcher, limit=-1))["error"]
+
+
+# ---------------------------------------------------------------------------
+# Board
+# ---------------------------------------------------------------------------
+
+
+async def test_board_rows_values_and_sorting(fetcher: Fetcher) -> None:
+ _mock_all()
+ out = await liquidity.fetch_liquidity_board(fetcher)
+ assert out["unavailable"] == [] and "error" not in out
+ rows = {r["indicator"]: r for r in out["indicators"]}
+ assert set(rows) == {
+ "fed_total_assets", "treasury_general_account", "reverse_repo", "net_liquidity",
+ "us_m2", "euro_area_m1", "euro_area_m2", "euro_area_m3", "eurosystem_total_assets",
+ }
+ nl = rows["net_liquidity"]
+ assert nl["latest_value"] == 5869.615 and nl["units"] == "USD billions"
+ assert nl["previous_observed_at"] == "2026-10-07"
+ assert rows["fed_total_assets"]["change"] == 6755639.0 - 6747560.0
+ assert rows["eurosystem_total_assets"]["change"] == 5943911.0 - 5947826.0
+ assert rows["eurosystem_total_assets"]["period_end"] == "2026-10-11"
+ assert rows["us_m2"]["period_end"] == "2026-08-31"
+ assert all(r["measure"] == "amount_outstanding" for r in rows.values())
+ moves = [abs(r["change_pct"]) for r in out["indicators"]]
+ assert moves == sorted(moves, reverse=True)
+ assert out["indicators"][0]["indicator"] == "reverse_repo"
+
+ newest = await liquidity.fetch_liquidity_board(fetcher, sort="newest")
+ ends = [r["period_end"] for r in newest["indicators"]]
+ assert ends == sorted(ends, reverse=True)
+ assert newest["indicators"][0]["indicator"] == "reverse_repo" # 2026-10-16
+
+
+async def test_board_component_outage_drops_net_liquidity_instead_of_zeroing(fetcher: Fetcher) -> None:
+ _mock_all(fred_overrides={"WDTGAL": httpx.Response(503)}, ilm=httpx.Response(500))
+ out = await liquidity.fetch_liquidity_board(fetcher)
+ names = {r["indicator"] for r in out["indicators"]}
+ assert "net_liquidity" not in names and "treasury_general_account" not in names
+ assert "eurosystem_total_assets" not in names
+ missing = {u["indicator"] for u in out["unavailable"]}
+ assert {"treasury_general_account", "net_liquidity", "Eurosystem total assets"} <= missing
+ assert any("never computed with a zero term" in u["error"] for u in out["unavailable"])
+ assert "error" not in out # the rest of the board is real
+
+
+async def test_board_total_outage_is_an_error(fetcher: Fetcher) -> None:
+ respx.get(_FRED_URL).mock(return_value=httpx.Response(503))
+ respx.get(_ECB_BSI_URL).mock(return_value=httpx.Response(503))
+ respx.get(_ECB_ILM_URL).mock(return_value=httpx.Response(503))
+ out = await liquidity.fetch_liquidity_board(fetcher)
+ assert out["error"] == "liquidity board unavailable: every source failed"
+ assert out["indicators"] == [] and len(out["unavailable"]) == 7
+
+
+async def test_board_flags_stale_rows(fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch) -> None:
+ _mock_all()
+ monkeypatch.setattr(liquidity, "_today", lambda: date(2026, 11, 20))
+ out = await liquidity.fetch_liquidity_board(fetcher, sort="newest")
+ rows = {r["indicator"]: r for r in out["indicators"]}
+ assert rows["fed_total_assets"]["freshness"]["stale"] is True
+ assert rows["us_m2"]["freshness"]["stale"] is False # monthly allowance
+ assert any(g.startswith("fed_total_assets: newest observation 2026-10-14") for g in out["data_gaps"])
+
+
+async def test_board_validation(fetcher: Fetcher) -> None:
+ assert "sort must be" in (await liquidity.fetch_liquidity_board(fetcher, sort="loudest"))["error"]
+
+
+# ---------------------------------------------------------------------------
+# Request shape
+# ---------------------------------------------------------------------------
+
+
+async def test_requests_send_descriptive_user_agent(fetcher: Fetcher) -> None:
+ _mock_all()
+ await liquidity.fetch_liquidity_board(fetcher)
+ agents = {c.request.headers["user-agent"] for c in respx.calls}
+ assert agents == {"world-intel-mcp (https://github.com/marc-shade/world-intel-mcp)"}
+ ids = sorted(c.request.url.params["id"] for c in respx.calls if c.request.url.host == "fred.stlouisfed.org")
+ assert ids == ["M2SL", "RRPONTSYD", "WALCL", "WDTGAL"]
+
+
+def test_fred_rate_floor_matches_robots_crawl_delay() -> None:
+ # Read at import time: the autouse fixture zeroes it for speed.
+ assert _FRED_FLOOR_AT_IMPORT == 1.0
diff --git a/src/world_intel_mcp/tools/__init__.py b/src/world_intel_mcp/tools/__init__.py
index d1b68a7..29be168 100644
--- a/src/world_intel_mcp/tools/__init__.py
+++ b/src/world_intel_mcp/tools/__init__.py
@@ -30,6 +30,7 @@ from . import ( # noqa: E402
hazards,
infrastructure,
intelligence,
+ liquidity,
markets,
society,
synthesis,
@@ -49,6 +50,7 @@ _MODULES = [
geospatial,
synthesis,
finance,
+ liquidity,
vector,
aoi,
system,
diff --git a/src/world_intel_mcp/tools/liquidity.py b/src/world_intel_mcp/tools/liquidity.py
new file mode 100644
index 0000000..024dda5
--- /dev/null
+++ b/src/world_intel_mcp/tools/liquidity.py
@@ -0,0 +1,190 @@
+"""Liquidity and money tools: liquidity board, net liquidity, money supply,
+and keyless series access to FRED liquidity series and the ECB Data
+Portal (Phase 29). See sources/liquidity.py for units, alignment and the
+blocked upstreams (ICI fund flows, FINRA margin statistics).
+"""
+
+from typing import Any
+
+from mcp.types import Tool
+
+from .. import runtime
+from ..sources import liquidity
+
+_LIMIT = {
+ "type": "integer",
+ "minimum": 0,
+ "description": "Newest points to return (default 52); 0 returns the full history",
+ "default": liquidity.DEFAULT_LIMIT,
+}
+_START = {
+ "type": "string",
+ "description": "Optional ISO date YYYY-MM-DD: only points observed on or after it",
+}
+
+TOOLS: list[Tool] = [
+ Tool(
+ name="intel_liquidity_board",
+ description=(
+ "Liquidity board: latest reading and change vs the previous observation for "
+ "the Fed balance sheet (WALCL), Treasury General Account (WDTGAL), overnight "
+ "reverse repo (RRPONTSYD), US net liquidity, US M2, euro area M1/M2/M3 and "
+ "Eurosystem total assets. Each row names its units, observation date, "
+ "frequency and staleness. Keyless (FRED graph CSV + ECB Data Portal)."
+ ),
+ inputSchema={
+ "type": "object",
+ "properties": {
+ "sort": {
+ "type": "string",
+ "enum": ["biggest_move", "newest"],
+ "description": "biggest_move (absolute percent change) or newest (latest period end)",
+ "default": "biggest_move",
+ },
+ },
+ },
+ ),
+ Tool(
+ name="intel_net_liquidity",
+ description=(
+ "US net liquidity, weekly: Fed total assets (WALCL) minus Treasury General "
+ "Account (WDTGAL, Wednesday level) minus overnight reverse repo (RRPONTSYD), "
+ "all converted to USD billions and aligned on the WALCL Wednesday. Every point "
+ "carries its components and the RRP date used; the response states the "
+ "formula, unit conversion and alignment rule."
+ ),
+ inputSchema={
+ "type": "object",
+ "properties": {"limit": _LIMIT, "start": _START},
+ },
+ ),
+ Tool(
+ name="intel_money_supply",
+ description=(
+ "Money supply: US M2 (FRED M2SL, USD billions, monthly, seasonally adjusted) and "
+ "euro area M1, M2 and M3 (ECB BSI: end-of-month stocks, monthly flows and annual "
+ "growth rates). Aggregates nest and are never summed; US M3 is discontinued "
+ "and says so."
+ ),
+ inputSchema={
+ "type": "object",
+ "properties": {
+ "region": {
+ "type": "string",
+ "enum": ["all", "us", "euro_area"],
+ "description": "Which region (default: all)",
+ "default": "all",
+ },
+ "limit": {
+ **_LIMIT,
+ "description": "Newest points per series (default 13); 0 returns the full history",
+ "default": 13,
+ },
+ },
+ },
+ ),
+ Tool(
+ name="intel_fed_liquidity_series",
+ description=(
+ "One keyless FRED liquidity series with full history available: WALCL (Fed "
+ "total assets), WDTGAL (TGA, Wednesday level), WTREGEN (TGA, week average), "
+ "RRPONTSYD (overnight reverse repo), M2SL (US M2). Points carry observation "
+ "date, value and units; blank source dates are counted, never read as zero."
+ ),
+ inputSchema={
+ "type": "object",
+ "properties": {
+ "series_id": {
+ "type": "string",
+ "enum": sorted(liquidity.FRED_SERIES),
+ "description": "FRED series id",
+ },
+ "limit": _LIMIT,
+ "start": _START,
+ },
+ "required": ["series_id"],
+ },
+ ),
+ Tool(
+ name="intel_ecb_series",
+ description=(
+ "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. "
+ "Example key: BSI M.U2.Y.V.M30.X.1.U2.2300.Z01.E (euro area M3 stock)."
+ ),
+ inputSchema={
+ "type": "object",
+ "properties": {
+ "dataset": {
+ "type": "string",
+ "enum": sorted(liquidity.ECB_DATASETS),
+ "description": "ECB dataset (dataflow) id",
+ "default": "BSI",
+ },
+ "key": {
+ "type": "string",
+ "description": "SDMX series key; '+' selects several values in one dimension",
+ },
+ "limit": {
+ **_LIMIT,
+ "description": "Newest points per series (default 24); 0 returns the full history",
+ "default": 24,
+ },
+ "start": _START,
+ },
+ "required": ["key"],
+ },
+ ),
+]
+
+
+async def _liquidity_board(arguments: dict[str, Any]) -> Any:
+ return await liquidity.fetch_liquidity_board(
+ runtime.fetcher, sort=arguments.get("sort", "biggest_move")
+ )
+
+
+async def _net_liquidity(arguments: dict[str, Any]) -> Any:
+ return await liquidity.fetch_net_liquidity(
+ runtime.fetcher,
+ limit=arguments.get("limit", liquidity.DEFAULT_LIMIT),
+ start=arguments.get("start"),
+ )
+
+
+async def _money_supply(arguments: dict[str, Any]) -> Any:
+ return await liquidity.fetch_money_supply(
+ runtime.fetcher,
+ region=arguments.get("region", "all"),
+ limit=arguments.get("limit", 13),
+ )
+
+
+async def _fed_liquidity_series(arguments: dict[str, Any]) -> Any:
+ return await liquidity.fetch_fed_liquidity_series(
+ runtime.fetcher,
+ series_id=arguments.get("series_id", ""),
+ limit=arguments.get("limit", liquidity.DEFAULT_LIMIT),
+ start=arguments.get("start"),
+ )
+
+
+async def _ecb_series(arguments: dict[str, Any]) -> Any:
+ return await liquidity.fetch_ecb_series(
+ runtime.fetcher,
+ dataset=arguments.get("dataset", "BSI"),
+ key=arguments.get("key", ""),
+ limit=arguments.get("limit", 24),
+ start=arguments.get("start"),
+ )
+
+
+HANDLERS = {
+ "intel_liquidity_board": _liquidity_board,
+ "intel_net_liquidity": _net_liquidity,
+ "intel_money_supply": _money_supply,
+ "intel_fed_liquidity_series": _fed_liquidity_series,
+ "intel_ecb_series": _ecb_series,
+}