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.

Merge feat/day-timeline: one UTC day's captures and observations from the history store (Phase 29)

Phoenix Agent (mac-studio)a91bee9d7778
diff --cc README.md
index 98473ba,274b516..a3b943a
--- a/README.md
+++ b/README.md
@@@ -6,7 -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 **158 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 **153 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 **159 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.
@@@ -66,10 -66,9 +66,10 @@@
| **Volcanoes** | 1 | Smithsonian GVP weekly activity report |
| **Tropical Cyclones** | 2 | NHC (Atlantic, E/C Pacific) + JTWC (NW Pacific, N Indian, S Hemisphere), with opt-in forecast tracks: positions, UTC valid times and intensities, plus NHC's cone of uncertainty |
| **Situation Brief** | 1 | Cited situational awareness brief over MCP: bounded server-side overview synthesized via local Ollama, with a mechanically-cited fallback |
- | **Collection History** | 4 | Collector run log (per-source health, overdue and failing sources), saved captures with change detection and replay, dated observation series, revisions |
+ | **Collection History** | 5 | Collector run log (per-source health, overdue and failing sources), saved captures with change detection and replay, dated observation series, revisions, and one UTC day's timeline by collection or observation date |
+| **Connections Between Series** | 1 | Correlation between stored series at leads and lags, with a minimum sample, false-discovery control and what it cannot prove |
- **Total: 158 tools** across 30+ intelligence domains.
-**Total: 153 tools** across 30+ intelligence domains.
++**Total: 159 tools** across 30+ intelligence domains.
---
@@@ -146,8 -142,7 +146,9 @@@ intel prediction-settled # Brier scor
intel status # cache + circuit breaker health
intel guide # the research guide (also served as intel://guide)
intel history health # per-source collection health from the collector's run log
+intel history connections central_bank_rates:federal_funds_rate central_bank_rates:boe_bank_rate_sonia
+ # correlation at leads and lags between stored series (day grid by default)
+ intel history day 2026-10-17 --by observed # values observed on one UTC day (default: captures that day)
```
---
@@@ -628,14 -606,8 +629,15 @@@ History accrues only while the collecto
| `intel_capture_history` | A source's earlier captures (ok / degraded / error with reason, duration, record count) and whether each changed from the previous one; `capture_id` replays one stored payload |
| `intel_series_history` | One series' observations with all three dates, or the list of available series |
| `intel_revisions` | Values for the same `observed_at` that a later capture changed (USGS magnitude revisions, NOAA Kp updates) |
+ | `intel_day_timeline` | What the history store holds for one UTC day (`YYYY-MM-DD`; a future day is an error). `by=collected` (default): per source, that day's captures (attempts, ok / degraded / error with reasons, changed vs unchanged payloads, first and last capture, observations stored), and for a source with no capture whether the collector did not run that day, ran without it, never ran it, or the day is past run-log retention. `by=observed`: values whose `observed_at` falls on the day; month and year values containing the day are listed apart as period values, and undated observations are counted and excluded. Every item carries `observed_at`, `published_at` and `collected_at`; pruned records are named, never read as a quiet day; per-source and total caps with truncation disclosed. Read-only, never fetches |
+### Connections Between Series (1)
+Reads the history store only, so the sample is what the collector saved, not each series' full history. A connection is a correlation in that sample: it does not show causation, and a lead does not show causal direction.
+
+| Tool | Description |
+|------|-------------|
+| `intel_lagged_connections` | Correlation between 2 to 8 stored series (keys as `intel_series_history` lists them) on a UTC day, week or month grid, tested at every lag from `-max_lag` to `+max_lag` (default 5, at most 30, at most 1,000 tests a call). Default transform is period-over-period changes, because levels of trending series correlate spuriously; `levels` on request. Per pair: the lag with the smallest p, with Pearson r, overlap n, two-sided p from Student's t and the Benjamini-Hochberg q across every test in the call (significant at q <= 0.05 by default). Lag +k compares A at period t with B at t+k, so A leads B by k. Pair/lag overlaps under 30 points are listed as not tested with their n; revised points use the latest vintage; rows without `observed_at` (Yahoo quotes) are not used. Each strongest result also carries an AR(1) effective sample size as a serial-correlation diagnostic |
+
---
## Watching your own area (geofences/AOIs)
diff --cc ROADMAP.md
index 3bbc0c8,75608db..06e0df1
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@@ -594,10 -578,10 +594,10 @@@ dashboard
| 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 | :white_check_mark: Built 2026-10-17, unreleased: `intel_hostility_timeline` (GDELT DOC 2.0 `timelinevolraw` + `timelinetone`, one call per category, failed calls and missing days null) and `intel_situations` (RSS headlines, ranked by covered / hostile / change, change defined over feeds whose history spans both windows). Measured 2026-10-17: timeline modes answer (HTTP 200, `date_resolution` `hour` for `timespan=7d` and `15m` for `3d`, explicit zero buckets, `norm` = all monitored articles), but a `timespan=7d` request returned 54 hours (2026-10-15T10Z onward), and about half of calls drew 429 even 30 s apart (later probes, 16:51 to 16:53Z, 4 of 4 drew 429, so the resolution for 14 days and coverage before 2026-10-15T10Z are unmeasured; 30 days was not probed; a live MCP run at 17:00Z got 4 of 6 columns after the retry pass, one at 17:20Z got 1 of 6, consistent with the server's breaker opening after 3 failed calls, which also skips the retry pass). The fetcher now spaces every live GDELT call at least 5 s apart, per process. Artlist was not used for daily counts: 250 records sorted by date covered 15 minutes. Situations see only the 22-country entity table |
| 1 | Story breadth | News clusters carry a distinct-outlet count; a top-stories view ranks by how many outlets carry a story | :white_check_mark: Built 2026-10-17, unreleased: clusters gain `outlets` / `outlet_count` (sister feeds of one publisher count once); `intel_top_stories` ranks by outlet count with an attention list (countries and organizations by mention growth). Found on the way: cluster `sources` was empty in every live cluster (key mismatch, `feed_name` vs `source_name`) and RSS times were shifted by the host UTC offset; both fixed. Concurrent RSS reads now share one request per feed (a live collector news-group cycle: 119 requests for 119 feeds) |
| 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, USD millions): WTREGEN is a week average; the net liquidity `method` block states each term's units, conversion and how RRPONTSYD (daily, USD billions) is aligned to the Wednesday. Blocked, measured 2026-10-17, and listed in the board's `blocked` field; no proxy is substituted, so fund flows and ETF net issuance have no source: ICI (money market fund assets at /research/stats/mmf, ETF net issuance at /research/stats/etf) answers 403 Akamai "Access Denied" on every path, robots.txt included; FINRA margin statistics XLSX answers 200, but the finra.org Terms of Use (Restrictions d and e) forbid building a database from the site and data mining, scraping or harvesting tools, robots included, and the page says data feeds are not available; BLS public API v1 answers 200 without a key (CPI-U, payrolls), 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 | :white_check_mark: Built 2026-10-17, unreleased: `intel_news_market_reaction` and `intel news-reaction`. Company rows: stock, benchmark (SPY, or the exchange country's index) and excess return on the story's session; country rows: index return with a trailing z-score. Session rule in the exchange's timezone (after close = next session; weekends and holidays read from the listing's own bars). Open: `^TASI` and `^TA125` (Saudi and Israel in the country-index table) return 404 on Yahoo, so those benchmarks are data gaps; story times inherit `sources/news.py`'s RSS timestamp offset until that is fixed |
-| 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: |
+| 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) | :white_check_mark: Unreleased: `intel_kalshi_markets`, `intel_prediction_compare`, `intel_prediction_settled` (`sources/kalshi.py`, `sources/prediction_cross.py`, `analysis/prediction_matching.py`), CLI and 2 collector sources. Kalshi endpoints measured 2026-10-17, all HTTP 200 without an account: `/events` (nested markets), `/series` (`include_volume`), `/markets?status=settled`, `/markets/candlesticks` (batch, capped at 10,000 candles per call), `/historical/cutoff`. The `/events` `category` parameter is ignored by the API, so categories resolve through `/series?category=`, whose filter is loose too (7 of the 869 series it returned for Economics were other categories), so series are matched exactly; an unknown category answers `{"series": null}` and is reported as a gap, not an outage. The exchange-wide settled listing is intraday sports (1,000 rows covered about 40 minutes; none open 24h), so settled samples default to the Economics category's top series. Polymarket Gamma caps a page at 100 rows. Matching is deliberately conservative: live 2026-10-17 it matched the Fed 25 bps hike/cut pairs for October and December and rejected 25 vs 50+ bps, 2026 vs 2027, and the Fed-hold pair ("no change" vs "Hike 0bps": a known false negative). Team and person aliases are not resolved, so most sports pairs stay unmatched. Kalshi requests are spaced 0.2 s apart in-process: the two collector sources scanning the same series at once drew HTTP 429, and at 0.1 s a 26-request category scan still drew one (none at 0.2 s in one live run). Settled samples are the most recently settled markets and cluster in time (one football match supplied 11 of 25 Polymarket markets in a live run), so a Brier score describes its sample, not a venue's skill. Every number a caller passes has a range stated in the input schema (at most 25 Kalshi series or pages per scan), so one call cannot fan out into unbounded upstream requests |
+| 1 | News vs market reaction | Companies and countries named in story clusters mapped to tickers / country indices; same-day move against a benchmark | :yellow_circle: Built 2026-10-17, unreleased; 7 test expectations await correction at merge: `intel_news_market_reaction` and `intel news-reaction`. Company rows: stock, benchmark (SPY, or the exchange country's index) and excess return on the story's session; country rows: index return with a trailing z-score. Session rule in the exchange's timezone (after close = next session; weekends and holidays read from the listing's own bars); a last bar Yahoo has not finalized is pending. Open: `^TASI` and `^TA125` (Saudi and Israel in the country-index table) return 404 on Yahoo, so those benchmarks are data gaps; story times inherit `sources/news.py`'s RSS timestamp offset until that is fixed |
+| 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 | :white_check_mark: Built 2026-10-17, unreleased: `intel_lagged_connections` and `intel history connections`. Pearson r on a UTC day, week or month grid at every lag from -max_lag to +max_lag (default 5, cap 30, at most 1,000 tests a call), period-over-period changes by default, p from Student's t (regularized incomplete beta, standard library), Benjamini-Hochberg q across the call (default 0.05), a 30-point minimum with every untested pair and lag listed with its n, latest vintage, rows without `observed_at` refused with the reason, an AR(1) effective sample size as a diagnostic, and a `cannot_prove` list. p-values match scipy to 3.3e-13 relative error. Verified 2026-10-17 over a live MCP stdio session and the CLI on four real FRED series loaded into an isolated store. Not done: rank correlation, prewhitening |
- | 2 | Day timeline | What every retained source recorded for a given day, by observation date or collection date | :red_circle: |
+ | 2 | Day timeline | What every retained source recorded for a given day, by observation date or collection date | :white_check_mark: Built 2026-10-17, unreleased: `intel_day_timeline` and `intel history day` (`history_timeline.py`; read-only `mode=ro` connection, never fetches). by=collected: per-source run-log state (changed, unchanged, answered, degraded, failed, not_attempted, collector_did_not_run, never_run, unknown_past_retention) with attempts, status counts, reasons and payload changes; by=observed: date and UTC-instant values on the day, month and year values listed apart as period values, undated observations counted and excluded. Retention is stated per record kind for the day. Measured 2026-10-17: two live collector cycles of 6 sources four minutes apart (12 captures: ok 8, degraded 2, error 2; every payload in the second cycle matched the first) read back over a live MCP stdio session and the CLI; 2026-10-16 in the same store reads `collector_did_not_run` (context `before_first_capture`). On a synthetic store (475,200 captures, 1.75 million observations, 10,982 series) one call took 24 to 46 ms, and no statement full-scans a history table under SQLite 3.45.3, 3.53.4 and 3.54.0. Not measured: a live store with weeks of history |
| 3 | Dashboard views | Liquidity board, situations, top stories, collection health panels | :red_circle: |
Considered and not planned:
diff --cc src/world_intel_mcp/cli.py
index 459bf6e,240cf9f..9074957
--- a/src/world_intel_mcp/cli.py
+++ b/src/world_intel_mcp/cli.py
@@@ -3581,105 -3318,201 +3581,301 @@@ def history_revisions
console.print(f"[yellow]Cannot prove:[/yellow] {escape(line)}")
+from .analysis import lagged_connections as _lagged # noqa: E402
+
+
+def _p_text(value: float) -> str:
+ return "<1e-300" if value == 0 else f"{value:.2g}"
+
+
+@history_group.command(name="connections")
[email protected]("series_keys", nargs=-1, required=True)
[email protected]("--grid", type=click.Choice(_lagged.GRIDS), default=_lagged.DEFAULT_GRID,
+ show_default=True, help="UTC calendar grid (weeks run Monday to Sunday)")
[email protected]("--transform", type=click.Choice(_lagged.TRANSFORMS),
+ default=_lagged.DEFAULT_TRANSFORM, show_default=True,
+ help="changes (period-over-period) or levels")
[email protected]("--max-lag", type=int, default=_lagged.DEFAULT_MAX_LAG, show_default=True,
+ help=f"Largest lead or lag in grid periods (0 to {_lagged.MAX_LAG_CAP})")
[email protected]("--min-overlap", type=int, default=_lagged.DEFAULT_MIN_OVERLAP, show_default=True,
+ help=f"Fewest overlapping periods a test needs (at least {_lagged.MIN_OVERLAP_FLOOR})")
[email protected]("--q", "q", type=float, default=_lagged.DEFAULT_Q, show_default=True,
+ help="False discovery rate threshold (Benjamini-Hochberg)")
[email protected]("--start", default=None, help="First date YYYY-MM-DD")
[email protected]("--end", default=None, help="Last date YYYY-MM-DD")
+def history_connections(
+ ctx: click.Context, series_keys: tuple[str, ...], grid: str, transform: str,
+ max_lag: int, min_overlap: int, q: float, start: str | None, end: str | None,
+) -> None:
+ """Correlation between stored series at leads and lags.
+
+ Lag +k compares the first series of a pair at period t with the second
+ at t+k, so the first leads by k. A connection is not a cause.
+ """
+ data = _with_history_store(
+ lambda s: _lagged.lagged_connections(
+ s, list(series_keys), grid=grid, transform=transform, max_lag=max_lag,
+ min_overlap=min_overlap, q=q, start=start, end=end,
+ )
+ )
+ if _bail_on_error(ctx, data):
+ return
+
+ method = data["method"]
+ lo, hi = method["lags"]
+ table = Table(
+ title=f"Connections ({method['grid']} grid, {method['transform']}, lags {lo:+d} to "
+ f"{hi:+d}, {data['tests_run']} tests, BH q <= {method['q_threshold']:g})",
+ box=box.SIMPLE_HEAVY,
+ )
+ for name in ("A", "B", "Lag", "Timing", "r", "n", "n_eff", "p", "q", "Significant"):
+ justify = "right" if name in ("Lag", "r", "n", "n_eff", "p", "q") else "left"
+ table.add_column(name, justify=justify)
+ for pair in data["pairs"]:
+ if not pair["strongest"]:
+ table.add_row(_cell(pair["a"]), _cell(pair["b"]), "-",
+ Text("not tested", style="dim"), "-", "-", "-", "-", "-", "-")
+ for entry in pair["strongest"]:
+ n_eff = entry.get("n_effective_ar1")
+ table.add_row(
+ _cell(pair["a"]), _cell(pair["b"]), f"{entry['lag']:+d}", entry["timing"],
+ f"{entry['r']:+.3f}", str(entry["n"]), "-" if n_eff is None else f"{n_eff:g}",
+ _p_text(entry["p"]), _p_text(entry["q"]),
+ Text("yes", style="green") if entry["significant"] else Text("no"),
+ )
+ console.print(table)
+ console.print(escape(data["summary"]))
+ console.print(
+ "n_eff: AR(1) effective sample size from the two series' lag-1 autocorrelations, "
+ "a diagnostic only: p and q use n."
+ )
+ console.print(f"Lag convention: {escape(method['lag_convention'])}")
+ console.print(
+ f"Transform: {escape(method['transform_rule'])} {escape(method['why_changes_default'])}"
+ )
+ for pair in data["pairs"]:
+ best = {e["lag"] for e in pair["strongest"]}
+ others = [e for e in pair["significant"] if e["lag"] not in best]
+ if others:
+ listed = ", ".join(
+ f"lag {e['lag']:+d} (r {e['r']:+.3f}, q {_p_text(e['q'])})" for e in others
+ )
+ console.print(f"Also significant: {escape(pair['a'])} / {escape(pair['b'])}: {listed}")
+ if pair["not_tested"]:
+ listed = ", ".join(
+ f"lag {nt['lag']:+d} (n {nt['n']}"
+ + (", no variation)" if nt["reason"] == "no_variation" else ")")
+ for nt in pair["not_tested"]
+ )
+ console.print(
+ f"[yellow]Not tested[/yellow] (minimum {method['min_overlap']} overlapping "
+ f"periods): {escape(pair['a'])} / {escape(pair['b'])}: {listed}"
+ )
+ for item in data["excluded_series"]:
+ console.print(
+ f"[yellow]Excluded:[/yellow] {escape(item['series_key'])}: {escape(item['reason'])}"
+ )
+ _print_data_gaps(data)
+ for line in data["cannot_prove"]:
+ console.print(f"[yellow]Cannot prove:[/yellow] {escape(line)}")
+
+
+ @history_group.command(name="day")
+ @click.argument("day")
+ @click.option(
+ "--by",
+ type=click.Choice(["collected", "observed"]),
+ default="collected",
+ show_default=True,
+ help="collected: what was captured that day; observed: values whose observed_at is that day",
+ )
+ @click.option("--source", default=None, help="One collector source name")
+ @click.option("--limit", default=None, type=int, help="Most items listed in all")
+ @click.option("--per-source", "per_source", default=None, type=int, help="Most items listed per source")
+ @click.pass_context
+ def history_day(
+ ctx: click.Context,
+ day: str,
+ by: str,
+ source: str | None,
+ limit: int | None,
+ per_source: int | None,
+ ) -> None:
+ """What the history store recorded for one UTC day (YYYY-MM-DD)."""
+ import time
+
+ from .collector import SOURCES
+ from .history_timeline import (
+ DEFAULT_LIMIT,
+ DEFAULT_PER_SOURCE_LIMIT,
+ day_timeline,
+ parse_day,
+ )
+
+ now = time.time()
+ _, problem = parse_day(day, now)
+ if problem:
+ raise click.BadParameter(problem, param_hint="DAY")
+ data = day_timeline(
+ _get_fetcher().cache.db_path,
+ day,
+ by=by,
+ source=source,
+ roster=[name for name, _, _, _ in SOURCES],
+ limit=DEFAULT_LIMIT if limit is None else limit,
+ per_source_limit=DEFAULT_PER_SOURCE_LIMIT if per_source is None else per_source,
+ now=now,
+ )
+ if _bail_on_error(ctx, data):
+ return
+
+ window = data["window"]
+ span = f"{window['start']} to {window['end']} (end exclusive)"
+ if not window["complete"]:
+ span += f", in progress through {window['through']}"
+ console.print(f"[bold]{data['day']}[/bold] (UTC) by {data['by']} date: {span}")
+ if by == "collected":
+ _print_day_collected(data)
+ else:
+ _print_day_observed(data)
+ _print_data_gaps(data)
+ for line in data["cannot_prove"]:
+ console.print(f"[yellow]Cannot prove:[/yellow] {escape(line)}")
+
+
+ def _print_day_collected(data: dict) -> None:
+ c = data["collector"]
+ if c["state"] == "ran":
+ console.print(
+ f"Collector: ran, {c['captures']:,} captures of {c['sources_captured']} "
+ f"source(s), {c['first_capture_at']} to {c['last_capture_at']}; longest gap "
+ f"{c['longest_gap_s']:,.0f} s ({c['longest_gap_from']} to {c['longest_gap_to']})"
+ )
+ else:
+ console.print(f"Collector: [yellow]{c['state']}[/yellow]. {escape(c['explanation'])}")
+
+ styles = {"changed": "green", "unchanged": "green", "answered": "green",
+ "failed": "red", "never_run": "dim"}
+ table = Table(title=f"Sources on {data['day']}", box=box.SIMPLE_HEAVY)
+ for name in ("Source", "State", "Tries", "OK", "Degr", "Err", "Changed", "Same",
+ "First", "Last", "Obs", "Reason / context"):
+ table.add_column(name, justify="right" if name in {
+ "Tries", "OK", "Degr", "Err", "Changed", "Same", "Obs"} else "left")
+ for row in data["sources"]:
+ counts = row.get("status_counts") or {}
+ changes = row.get("payload_changes") or {}
+ if row["attempts"]:
+ top = (row.get("reasons") or [None])[0]
+ context = f"{top['reason']} (x{top['count']})" if top else ""
+ if row.get("more_reasons"):
+ context += f" +{row['more_reasons']} more"
+ stored = row.get("observations_stored")
+ obs = "-" if stored is None else str(stored)
+ else:
+ parts = []
+ if row.get("last_capture_before"):
+ parts.append(f"last before {row['last_capture_before']}")
+ if row.get("next_capture_after"):
+ parts.append(f"next after {row['next_capture_after']}")
+ context = ", ".join(parts)
+ obs = str(row["observations_retained"]) if row["observations_retained"] else "-"
+ table.add_row(
+ _cell(row["source"]),
+ Text(row["day_state"], style=styles.get(row["day_state"], "yellow")),
+ str(row["attempts"]),
+ str(counts.get("ok", "-")),
+ str(counts.get("degraded", "-")),
+ str(counts.get("error", "-")),
+ (f"{changes['changed']}" + (f" +{changes['first']} first" if changes["first"] else ""))
+ if changes else "-",
+ str(changes.get("unchanged", "-")),
+ _cell(row.get("first_capture_at") or "-"),
+ _cell(row.get("last_capture_at") or "-"),
+ obs,
+ _cell(context),
+ )
+ console.print(table)
+ states = ", ".join(f"{k} {v}" for k, v in sorted(data["state_counts"].items()))
+ console.print(f"States: {states}.")
+
+ items = data["observations"]
+ trunc = data["truncation"]
+ if items:
+ obs_table = Table(
+ title=f"Observations saved that day ({trunc['returned']:,} of {trunc['matched']:,})",
+ box=box.SIMPLE_HEAVY,
+ )
+ for name in ("Collected", "Source", "Series", "Observed", "Published", "Value", "Unit"):
+ obs_table.add_column(name, justify="right" if name == "Value" else "left")
+ for item in items:
+ obs_table.add_row(
+ item["collected_at"],
+ _cell(item["source"]),
+ _cell(item["series_key"]),
+ _cell(item["observed_at"] or "unknown"),
+ _cell(item["published_at"] or "unknown"),
+ f"{item['value']:g}",
+ _cell(item.get("unit") or ""),
+ )
+ console.print(obs_table)
+ else:
+ console.print("[dim]No observations saved that day.[/dim]")
+
+
+ def _print_day_observed(data: dict) -> None:
+ def _points_table(title: str, points: list[dict]) -> Table:
+ table = Table(title=title, box=box.SIMPLE_HEAVY)
+ for name in ("Observed", "Precision", "Series", "Value", "Unit", "Published",
+ "Collected", "Stored"):
+ table.add_column(name, justify="right" if name in {"Value", "Stored"} else "left")
+ for point in points:
+ stored = str(point["stored_values"])
+ if point["stored_values"] > 1:
+ stored += f" (first {point['first_value']:g} at {point['first_collected_at']})"
+ table.add_row(
+ _cell(point["observed_at"]),
+ point["precision"],
+ _cell(point["series_key"]),
+ f"{point['value']:g}",
+ _cell(point.get("unit") or ""),
+ _cell(point["published_at"] or "unknown"),
+ point["collected_at"],
+ stored,
+ )
+ return table
+
+ day_trunc = data["truncation"]["day_values"]
+ if data["day_values"]:
+ console.print(_points_table(
+ f"Values observed on {data['day']} ({day_trunc['returned']:,} of "
+ f"{day_trunc['matched']:,})",
+ data["day_values"],
+ ))
+ else:
+ console.print(f"[yellow]No stored value is observed on {data['day']}.[/yellow]")
+ if data["period_values"]:
+ period_trunc = data["truncation"]["period_values"]
+ console.print(_points_table(
+ f"Period values containing the day, not values for it "
+ f"({period_trunc['returned']:,} of {period_trunc['matched']:,})",
+ data["period_values"],
+ ))
+ console.print(f"[dim]{escape(data['period_values_note'])}[/dim]")
+ if data["sources"]:
+ table = Table(title="By source", box=box.SIMPLE_HEAVY)
+ for name in ("Source", "Day values", "Revised", "Period values", "No observed_at"):
+ table.add_column(name, justify="left" if name == "Source" else "right")
+ for row in data["sources"]:
+ table.add_row(
+ _cell(row["source"]),
+ str(row["day_values"]),
+ str(row["day_values_revised"]),
+ str(row["period_values"]),
+ str(row["without_observed_at_collected_that_day"]),
+ )
+ console.print(table)
+
+
if __name__ == "__main__":
main()
diff --cc src/world_intel_mcp/tools/__init__.py
index e44a23d,7c18d63..82119e2
--- a/src/world_intel_mcp/tools/__init__.py
+++ b/src/world_intel_mcp/tools/__init__.py
@@@ -62,7 -60,7 +63,8 @@@ _MODULES =
vector,
aoi,
history,
+ lagged_connections,
+ day_timeline,
system,
]