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.

CLI honesty: table cells render remote data literally; 17 legacy commands join the shared error surface

Phoenix Agent (Marcs-Mac-Studio)5aa3e9685336
diff --git a/src/world_intel_mcp/cli.py b/src/world_intel_mcp/cli.py
index 791aef3..609503e 100644
--- a/src/world_intel_mcp/cli.py
+++ b/src/world_intel_mcp/cli.py
@@ -3,6 +3,19 @@
intel — CLI for World Intelligence MCP.
Calls source functions directly (no MCP protocol overhead).
+
+Two rendering conventions keep the output honest:
+
+- Every data command routes upstream failures through _bail_on_error:
+ one red "Error:" line in table mode, the raw dict in --json-output
+ mode. An outage never renders as a healthy empty table or a raw JSON
+ dump at a table-mode user.
+- Remote free text (names, titles, places, descriptions) is
+ injection-safe: table cells go through _cell (rich.text.Text renders
+ literally), console lines through rich.markup.escape, and values
+ deliberately styled with markup escape only the interpolated part.
+ Config/enum-derived scalars (region keys, static dataset fields) and
+ numerically formatted values stay as-is.
"""
import asyncio
@@ -13,6 +26,7 @@ import click
from rich.console import Console
from rich.markup import escape
from rich.table import Table
+from rich.text import Text
from rich.panel import Panel
from rich import box
@@ -96,6 +110,19 @@ def _bail_on_error(ctx: click.Context, data: dict) -> bool:
return False
+def _cell(value: Any) -> Text:
+ """Table cell for remote data: renders literally, never as markup.
+
+ A bracketed sequence in an upstream value ("Coast of [/] Chile",
+ "[red]fake[/red]") must neither vanish into Rich's markup parser nor
+ raise MarkupError. Column-level style/justify still apply to Text
+ cells; only content-embedded markup is neutralized. Cells that
+ deliberately wrap a remote value in markup keep the markup and
+ escape() the interpolated value instead.
+ """
+ return Text(str(value))
+
+
# ---------------------------------------------------------------------------
# Root group
# ---------------------------------------------------------------------------
@@ -143,10 +170,10 @@ def markets_cmd(ctx: click.Context, symbols: tuple[str, ...]) -> None:
price = q.get("price") or 0
style = "green" if chg >= 0 else "red"
table.add_row(
- q.get("symbol", "?"),
+ _cell(q.get("symbol", "?")),
f"{price:,.2f}",
f"[{style}]{chg:+.2f}%[/{style}]",
- q.get("currency", ""),
+ _cell(q.get("currency", "")),
)
console.print(table)
@@ -180,7 +207,7 @@ def crypto(ctx: click.Context, limit: int) -> None:
mcap = c.get("market_cap", 0) or 0
table.add_row(
str(i),
- c.get("symbol", "?").upper(),
+ _cell(c.get("symbol", "?").upper()),
f"${c.get('current_price', 0):,.2f}",
f"[{style}]{chg:+.2f}%[/{style}]",
f"${mcap:,.0f}",
@@ -206,13 +233,13 @@ def macro(ctx: click.Context) -> None:
for name, info in signals.items():
if info is None:
- table.add_row(name, "[dim]unavailable[/dim]", "")
+ table.add_row(_cell(name), "[dim]unavailable[/dim]", "")
elif isinstance(info, dict):
val = info.get("value", info.get("price", "?"))
detail = info.get("classification", info.get("label", ""))
- table.add_row(name, str(val), str(detail))
+ table.add_row(_cell(name), _cell(val), _cell(detail))
else:
- table.add_row(name, str(info), "")
+ table.add_row(_cell(name), _cell(info), "")
console.print(table)
@@ -228,8 +255,7 @@ def energy(ctx: click.Context) -> None:
f = _get_fetcher()
data = _run(economic.fetch_energy_prices(f))
- if ctx.obj.get("json") or "error" in data:
- _print_json(data)
+ if _bail_on_error(ctx, data):
return
oil = data.get("oil", {})
@@ -245,7 +271,9 @@ def energy(ctx: click.Context) -> None:
("Natural Gas", gas),
]:
if info and isinstance(info, dict):
- table.add_row(name, f"${info.get('price', '?')}", str(info.get("date", "")))
+ table.add_row(
+ name, _cell(f"${info.get('price', '?')}"), _cell(info.get("date", ""))
+ )
console.print(table)
@@ -256,8 +284,7 @@ def gas_prices(ctx: click.Context) -> None:
f = _get_fetcher()
data = _run(economic.fetch_gas_prices(f))
- if ctx.obj.get("json") or "error" in data:
- _print_json(data)
+ if _bail_on_error(ctx, data):
return
prices = data.get("prices", {})
@@ -300,8 +327,7 @@ def natgas(ctx: click.Context) -> None:
f = _get_fetcher()
data = _run(economic.fetch_residential_natgas_prices(f))
- if ctx.obj.get("json") or "error" in data:
- _print_json(data)
+ if _bail_on_error(ctx, data):
return
prices = data.get("prices", [])
@@ -310,7 +336,7 @@ def natgas(ctx: click.Context) -> None:
table.add_column("$/MCF", justify="right")
for entry in prices:
- table.add_row(str(entry.get("period", "")), f"${entry.get('price', '?'):.2f}")
+ table.add_row(_cell(entry.get("period", "")), f"${entry.get('price', '?'):.2f}")
console.print(table)
@@ -322,13 +348,14 @@ def electricity(ctx: click.Context, state: str | None) -> None:
f = _get_fetcher()
data = _run(economic.fetch_electricity_rates(f, state=state))
- if ctx.obj.get("json") or "error" in data:
- _print_json(data)
+ if _bail_on_error(ctx, data):
return
rates = data.get("rates", {})
label = data.get("state", "US")
- table = Table(title=f"Electricity Rates — {label}", box=box.SIMPLE_HEAVY)
+ table = Table(
+ title=f"Electricity Rates — {escape(str(label))}", box=box.SIMPLE_HEAVY
+ )
table.add_column("Sector", style="bold")
table.add_column("cents/kWh", justify="right")
table.add_column("Period")
@@ -339,7 +366,7 @@ def electricity(ctx: click.Context, state: str | None) -> None:
table.add_row(
sector.replace("_", " ").title(),
f"{info.get('price_cents_kwh', '?'):.2f}",
- str(info.get("period", "")),
+ _cell(info.get("period", "")),
)
console.print(table)
@@ -353,18 +380,19 @@ def fred(ctx: click.Context, series_id: str, limit: int) -> None:
f = _get_fetcher()
data = _run(economic.fetch_fred_series(f, series_id=series_id, limit=limit))
- if ctx.obj.get("json") or "error" in data:
- _print_json(data)
+ if _bail_on_error(ctx, data):
return
obs = data.get("observations", [])
title = data.get("title", series_id)
- table = Table(title=f"FRED: {title}", box=box.SIMPLE_HEAVY)
+ # FRED series titles are remote free text — the table title is a
+ # markup surface too.
+ table = Table(title=f"FRED: {escape(str(title))}", box=box.SIMPLE_HEAVY)
table.add_column("Date", style="bold")
table.add_column("Value", justify="right")
for o in obs[:20]:
- table.add_row(o.get("date", ""), str(o.get("value", "")))
+ table.add_row(_cell(o.get("date", "")), _cell(o.get("value", "")))
console.print(table)
@@ -403,10 +431,10 @@ def earthquakes(ctx: click.Context, min_mag: float, hours: int) -> None:
alert = q.get("alert_level") or ""
table.add_row(
f"[{style}]{mag:.1f}[/{style}]" if style else f"{mag:.1f}",
- q.get("place", "Unknown"),
+ _cell(q.get("place", "Unknown")),
f"{q.get('depth_km', 0):.1f}",
- q.get("time", "")[:19],
- alert,
+ _cell(q.get("time", "")[:19]),
+ _cell(alert),
)
console.print(table)
@@ -419,8 +447,7 @@ def fires(ctx: click.Context, region: str | None) -> None:
f = _get_fetcher()
data = _run(wildfire.fetch_wildfires(f, region=region))
- if ctx.obj.get("json") or "error" in data:
- _print_json(data)
+ if _bail_on_error(ctx, data):
return
console.print(
@@ -453,8 +480,7 @@ def conflicts(ctx: click.Context, country: str | None, days: int) -> None:
f = _get_fetcher()
data = _run(conflict.fetch_acled_events(f, country=country, days=days))
- if ctx.obj.get("json") or "error" in data:
- _print_json(data)
+ if _bail_on_error(ctx, data):
return
events = data.get("events", [])
@@ -474,10 +500,10 @@ def conflicts(ctx: click.Context, country: str | None, days: int) -> None:
style = "red bold" if fat >= 10 else "yellow" if fat > 0 else ""
fat_str = f"[{style}]{fat}[/{style}]" if style else str(fat)
table.add_row(
- str(e.get("event_date", ""))[:10],
- e.get("event_type", ""),
- e.get("country", ""),
- e.get("location", ""),
+ _cell(str(e.get("event_date", ""))[:10]),
+ _cell(e.get("event_type", "")),
+ _cell(e.get("country", "")),
+ _cell(e.get("location", "")),
fat_str,
)
console.print(table)
@@ -513,9 +539,9 @@ def flights(ctx: click.Context, bbox: str | None) -> None:
for a in aircraft[:30]:
table.add_row(
- a.get("callsign", "?"),
- a.get("icao24", ""),
- a.get("origin_country", ""),
+ _cell(a.get("callsign", "?")),
+ _cell(a.get("icao24", "")),
+ _cell(a.get("origin_country", "")),
f"{a.get('altitude_m') or 0:,.0f}",
f"{a.get('velocity_ms') or 0:.0f}",
)
@@ -550,8 +576,8 @@ def posture(ctx: click.Context) -> None:
table.add_row(
name.replace("_", " ").title(),
count_str,
- ", ".join(info.get("countries", [])[:5]),
- ", ".join(info.get("sample_callsigns", [])[:3]),
+ _cell(", ".join(info.get("countries", [])[:5])),
+ _cell(", ".join(info.get("sample_callsigns", [])[:3])),
)
console.print(table)
@@ -613,7 +639,7 @@ def cables(ctx: click.Context) -> None:
table.add_row(
name.replace("_", " ").title(),
status_labels.get(score, str(score)),
- ", ".join(info.get("cables", [])[:3]),
+ _cell(", ".join(info.get("cables", [])[:3])),
str(len(info.get("relevant_warnings", []))),
)
console.print(table)
@@ -692,7 +718,7 @@ def climate_cmd(ctx: click.Context) -> None:
t_str = (
f"[{t_style}]{temp_a:+.1f}C[/{t_style}]" if t_style else f"{temp_a:+.1f}C"
)
- table.add_row(z.get("name", key), t_str, f"{prec_a:+.0f}%", flag)
+ table.add_row(_cell(z.get("name", key)), t_str, f"{prec_a:+.0f}%", flag)
console.print(table)
@@ -790,7 +816,7 @@ def trending(ctx: click.Context, min_count: int) -> None:
table.add_column("Count", justify="right")
for i, kw in enumerate(keywords[:30], 1):
- table.add_row(str(i), kw["word"], str(kw["count"]))
+ table.add_row(str(i), _cell(kw["word"]), str(kw["count"]))
console.print(table)
@@ -814,7 +840,7 @@ def gdelt(ctx: click.Context, query: str, mode: str, limit: int) -> None:
console.print(f"[bold]{len(articles)} articles[/bold] for '{query}'\n")
for a in articles[:20]:
title = escape(a.get("title", "")[:80])
- domain = a.get("domain", "")
+ domain = escape(a.get("domain", ""))
console.print(f" [bold]{title}[/bold] ({domain})")
else:
console.print(f"[bold]Timeline volume for '{query}'[/bold]")
@@ -856,9 +882,9 @@ def predictions(ctx: click.Context, limit: int) -> None:
"green" if "yes" in sentiment else "red" if "no" in sentiment else "yellow"
)
table.add_row(
- (m.get("question", "")[:50]),
+ _cell(m.get("question", "")[:50]),
f"{yes_pct:.0f}%",
- f"[{s_style}]{sentiment}[/{s_style}]",
+ f"[{s_style}]{escape(str(sentiment))}[/{s_style}]",
f"${vol:,.0f}",
)
console.print(table)
@@ -893,7 +919,7 @@ def displacement_cmd(ctx: click.Context, year: int | None) -> None:
for c in by_origin[:15]:
table.add_row(
- c.get("country", ""),
+ _cell(c.get("country", "")),
f"{c.get('total_displaced', 0):,}",
f"{c.get('refugees', 0):,}",
f"{c.get('internally_displaced', 0):,}",
@@ -941,7 +967,9 @@ def delays(ctx: click.Context) -> None:
if statuses
else "Details unavailable"
)
- table.add_row(d.get("code", ""), d.get("name", ""), info[:80])
+ table.add_row(
+ _cell(d.get("code", "")), _cell(d.get("name", "")), _cell(info[:80])
+ )
console.print(table)
@@ -988,13 +1016,17 @@ def threats(ctx: click.Context, limit: int) -> None:
"medium": "",
"low": "dim",
}.get(sev, "")
- sev_str = f"[{sev_style}]{sev}[/{sev_style}]" if sev_style else sev
+ sev_str = (
+ f"[{sev_style}]{escape(str(sev))}[/{sev_style}]"
+ if sev_style
+ else _cell(sev)
+ )
table.add_row(
sev_str,
- t.get("type", ""),
- (t.get("indicator", ""))[:40],
- (t.get("threat", ""))[:30],
- t.get("source_feed", ""),
+ _cell(t.get("type", "")),
+ _cell((t.get("indicator", ""))[:40]),
+ _cell((t.get("threat", ""))[:30]),
+ _cell(t.get("source_feed", "")),
)
console.print(table)
@@ -1043,8 +1075,7 @@ def dossier(ctx: click.Context, country: str) -> None:
f = _get_fetcher()
data = _run(fetch_country_dossier(f, country=country))
- if ctx.obj.get("json") or "error" in data:
- _print_json(data)
+ if _bail_on_error(ctx, data):
return
overview = data.get("overview", {})
@@ -1079,8 +1110,8 @@ def dossier(ctx: click.Context, country: str) -> None:
if upcoming:
next_e = upcoming[0]
console.print(
- f"[yellow]Elections:[/yellow] {next_e.get('election_type')} on {next_e.get('date')} "
- f"(risk: {next_e.get('risk_score', 0):.0f})"
+ f"[yellow]Elections:[/yellow] {escape(str(next_e.get('election_type')))} "
+ f"on {next_e.get('date')} (risk: {next_e.get('risk_score', 0):.0f})"
)
# Sanctions
@@ -1114,8 +1145,7 @@ def risk(ctx: click.Context, limit: int) -> None:
f = _get_fetcher()
data = _run(intelligence.fetch_risk_scores(f, limit=limit))
- if ctx.obj.get("json") or "error" in data:
- _print_json(data)
+ if _bail_on_error(ctx, data):
return
table = Table(title="Country Risk Scores", box=box.SIMPLE_HEAVY)
@@ -1133,11 +1163,13 @@ def risk(ctx: click.Context, limit: int) -> None:
"moderate": "",
"low": "dim",
}.get(level, "")
- l_str = f"[{l_style}]{level}[/{l_style}]" if l_style else level
+ l_str = (
+ f"[{l_style}]{escape(str(level))}[/{l_style}]" if l_style else _cell(level)
+ )
table.add_row(
str(i),
- c.get("country", ""),
- str(c.get("events_30d", 0)),
+ _cell(c.get("country", "")),
+ _cell(c.get("events_30d", 0)),
f"{c.get('risk_score', 0):.0f}",
l_str,
)
@@ -1152,8 +1184,7 @@ def instability(ctx: click.Context, country_code: str | None) -> None:
f = _get_fetcher()
data = _run(intelligence.fetch_instability_index(f, country_code=country_code))
- if ctx.obj.get("json") or "error" in data:
- _print_json(data)
+ if _bail_on_error(ctx, data):
return
if country_code:
@@ -1181,11 +1212,15 @@ def instability(ctx: click.Context, country_code: str | None) -> None:
"medium": "",
"low": "dim",
}.get(level, "")
- l_str = f"[{l_style}]{level}[/{l_style}]" if l_style else level
+ l_str = (
+ f"[{l_style}]{escape(str(level))}[/{l_style}]"
+ if l_style
+ else _cell(level)
+ )
table.add_row(
- f"{c.get('country_name', '')} ({c.get('country_code', '')})",
+ _cell(f"{c.get('country_name', '')} ({c.get('country_code', '')})"),
f"{c.get('instability_index', 0):.0f}",
- str(c.get("events_30d", 0)),
+ _cell(c.get("events_30d", 0)),
l_str,
)
console.print(table)
@@ -1203,8 +1238,7 @@ def btc(ctx: click.Context) -> None:
f = _get_fetcher()
data = _run(markets.fetch_btc_technicals(f))
- if ctx.obj.get("json") or "error" in data:
- _print_json(data)
+ if _bail_on_error(ctx, data):
return
console.print(f"[bold]BTC Technicals[/bold] price: ${data.get('price', 0):,.2f}\n")
@@ -1225,7 +1259,8 @@ def btc(ctx: click.Context) -> None:
"green" if cross == "golden_cross" else "red" if cross == "death_cross" else ""
)
table.add_row(
- "Cross Signal", f"[{c_style}]{cross}[/{c_style}]" if c_style else cross
+ "Cross Signal",
+ f"[{c_style}]{escape(str(cross))}[/{c_style}]" if c_style else _cell(cross),
)
table.add_row("ATH Distance", f"{data.get('ath_distance_pct', 0):.1f}%")
table.add_row(
@@ -1279,7 +1314,10 @@ def central_banks_cmd(ctx: click.Context) -> None:
)
rate_str = f"[{style}]{rate:.2f}[/{style}]" if style else f"{rate:.2f}"
table.add_row(
- r.get("bank", ""), r.get("country", ""), rate_str, r.get("as_of", "")
+ _cell(r.get("bank", "")),
+ _cell(r.get("country", "")),
+ rate_str,
+ _cell(r.get("as_of", "")),
)
console.print(table)
@@ -1308,7 +1346,7 @@ def shipping_cmd(ctx: click.Context) -> None:
chg = q.get("change_pct") or 0
style = "green" if chg >= 0 else "red"
table.add_row(
- q.get("symbol", ""),
+ _cell(q.get("symbol", "")),
f"${q.get('price', 0):,.2f}",
f"[{style}]{chg:+.2f}%[/{style}]",
)
@@ -1392,10 +1430,10 @@ def elections_cmd(ctx: click.Context, country: str | None) -> None:
r_style = "red bold" if risk >= 4 else "yellow" if risk >= 2 else ""
r_str = f"[{r_style}]{risk:.1f}[/{r_style}]" if r_style else f"{risk:.1f}"
table.add_row(
- e.get("date", ""),
- e.get("country", ""),
- e.get("type", ""),
- str(e.get("days_until", "")),
+ _cell(e.get("date", "")),
+ _cell(e.get("country", "")),
+ _cell(e.get("type", "")),
+ _cell(e.get("days_until", "")),
r_str,
)
console.print(table)
@@ -1453,7 +1491,7 @@ def space_cmd(ctx: click.Context) -> None:
):
val = data.get(key)
if val is not None:
- table.add_row(key.replace("_", " ").title(), str(val))
+ table.add_row(key.replace("_", " ").title(), _cell(val))
console.print(table)
@@ -1510,8 +1548,7 @@ def fleet_cmd(ctx: click.Context) -> None:
f = _get_fetcher()
data = _run(fetch_usni_fleet(f))
- if ctx.obj.get("json") or "error" in data:
- _print_json(data)
+ if _bail_on_error(ctx, data):
return
console.print(f"[bold]{escape(data.get('report_title', 'Fleet Report'))}[/bold]\n")
@@ -1538,10 +1575,10 @@ def fleet_cmd(ctx: click.Context) -> None:
table.add_column("Region")
for s in ships[:20]:
table.add_row(
- s.get("name", ""),
- s.get("hull_number", ""),
- s.get("type", ""),
- s.get("region", ""),
+ _cell(s.get("name", "")),
+ _cell(s.get("hull_number", "")),
+ _cell(s.get("type", "")),
+ _cell(s.get("region", "")),
)
console.print(table)
@@ -1626,7 +1663,9 @@ def spending_cmd(ctx: click.Context, limit: int) -> None:
budget = a.get("budget_authority", 0) or 0
obligated = a.get("obligated", 0) or 0
table.add_row(
- a.get("name", ""), f"${budget / 1e9:,.1f}B", f"${obligated / 1e9:,.1f}B"
+ _cell(a.get("name", "")),
+ f"${budget / 1e9:,.1f}B",
+ f"${obligated / 1e9:,.1f}B",
)
console.print(table)
@@ -1716,8 +1755,7 @@ def traffic(ctx: click.Context) -> None:
f = _get_fetcher()
data = _run(fetch_traffic_flow(f))
- if ctx.obj.get("json") or "error" in data:
- _print_json(data)
+ if _bail_on_error(ctx, data):
return
console.print(
@@ -1738,7 +1776,7 @@ def traffic(ctx: click.Context) -> None:
c.get("name", ""),
c.get("country", ""),
f"[{style}]{cong}%[/{style}]",
- str(c.get("current_speed_kmh", "")),
+ _cell(c.get("current_speed_kmh", "")),
)
console.print(table)
@@ -1752,8 +1790,7 @@ def incidents(ctx: click.Context) -> None:
f = _get_fetcher()
data = _run(fetch_traffic_incidents(f))
- if ctx.obj.get("json") or "error" in data:
- _print_json(data)
+ if _bail_on_error(ctx, data):
return
console.print(
@@ -1771,9 +1808,9 @@ def incidents(ctx: click.Context) -> None:
delay_min = round(inc.get("delay_seconds", 0) / 60)
table.add_row(
inc.get("region", ""),
- inc.get("description", "")[:40],
+ _cell(inc.get("description", "")[:40]),
str(delay_min) if delay_min else "-",
- inc.get("from_road", "")[:30],
+ _cell(inc.get("from_road", "")[:30]),
)
console.print(table)
@@ -1785,8 +1822,7 @@ def air_traffic_cmd(ctx: click.Context) -> None:
f = _get_fetcher()
data = _run(aviation.fetch_domestic_flights(f))
- if ctx.obj.get("json") or "error" in data:
- _print_json(data)
+ if _bail_on_error(ctx, data):
return
console.print(
@@ -1810,7 +1846,7 @@ def air_traffic_cmd(ctx: click.Context) -> None:
if data.get("busiest_origins"):
console.print("\n[bold]Busiest Origins:[/bold]")
for o in data["busiest_origins"][:10]:
- console.print(f" {o['country']}: {o['count']}")
+ console.print(f" {escape(str(o['country']))}: {o['count']}")
@main.command()
@@ -1824,8 +1860,7 @@ def webcams_cmd(ctx: click.Context, category: str, limit: int) -> None:
f = _get_fetcher()
data = _run(fetch_webcams(f, category=category, limit=limit))
- if ctx.obj.get("json") or "error" in data:
- _print_json(data)
+ if _bail_on_error(ctx, data):
return
console.print(
@@ -1840,10 +1875,10 @@ def webcams_cmd(ctx: click.Context, category: str, limit: int) -> None:
for cam in data.get("cameras", []):
table.add_row(
- cam.get("title", "")[:30],
- cam.get("city", ""),
- cam.get("country", ""),
- cam.get("status", ""),
+ _cell(cam.get("title", "")[:30]),
+ _cell(cam.get("city", "")),
+ _cell(cam.get("country", "")),
+ _cell(cam.get("status", "")),
)
console.print(table)
@@ -1946,8 +1981,13 @@ def dashboard(port: int, host: str) -> None:
@click.option(
"--sections", "-s", default=None, help="Comma-separated section names to include"
)
def report(
- output: str | None, title: str | None, fmt: str, sections: str | None
+ ctx: click.Context,
+ output: str | None,
+ title: str | None,
+ fmt: str,
+ sections: str | None,
) -> None:
"""Generate a PDF or HTML intelligence report."""
from .reports import generate_report
@@ -1962,9 +2002,8 @@ def report(
)
)
- if "error" in result:
- console.print(f"[red]Error:[/red] {escape(str(result['error']))}")
- if "fallback" in result:
+ if _bail_on_error(ctx, result):
+ if "fallback" in result and not ctx.obj.get("json"):
# escape keeps the literal "[pdf]" in the install hint from
# being eaten as a markup tag — the printed command must be
# runnable verbatim.
diff --git a/src/world_intel_mcp/tests/test_cli.py b/src/world_intel_mcp/tests/test_cli.py
index fb65f39..edf912e 100644
--- a/src/world_intel_mcp/tests/test_cli.py
+++ b/src/world_intel_mcp/tests/test_cli.py
@@ -8,28 +8,37 @@ options reach the fetch functions with the right names.
Two former cli.py bug classes are now covered by honest-contract tests
(they were pinned here as characterization tests until fixed):
-1. Error surfacing: every data command bails via ``cli._bail_on_error``,
- so an upstream {"error": ...} prints the error text in red instead of
- rendering as a healthy-looking empty table ("0 earthquakes", "No
- market data available"). In --json-output mode the raw dict (error
- included) is printed unchanged. An outage must never be
+1. Error surfacing: every data command — the ``report`` command
+ included — bails via ``cli._bail_on_error``, so an upstream
+ {"error": ...} prints one consistent red ``Error:`` line in table
+ mode instead of rendering as a healthy-looking empty table ("0
+ earthquakes") or dumping raw JSON at a table-mode user. In
+ --json-output mode the raw dict (error included) is printed
+ unchanged with no extra rendering. An outage must never be
shape-identical to a quiet world. See the *_error_dict tests and the
- parametrized test_error_dict_reaches_table_output sweep.
+ parametrized test_error_dict_reaches_table_output sweep, which now
+ covers the 17 commands that used to dump raw JSON in table mode.
2. Rich markup escaping: values interpolated into ``[...]`` label
constructs (news category, sanctions entity_type, ai-watch source,
gh-trending language) and remote free text (titles, descriptions,
feed names, the report command's literal ``[pdf]`` install hint) are
- escaped with rich.markup.escape, so lowercase bracketed labels render
- literally instead of parsing as markup tags, and bracketed sequences
- inside remote data neither vanish nor raise MarkupError. See the
- *_label_renders tests, test_report_error_with_fallback_hint, and
- test_news_bracketed_remote_title_survives.
+ escaped with rich.markup.escape, and remote values rendered inside
+ Rich Table cells go through ``cli._cell`` (rich.text.Text), so
+ bracketed sequences inside remote data render literally instead of
+ being swallowed as markup tags or raising MarkupError. See the
+ *_label_renders tests, test_report_error_with_fallback_hint,
+ test_news_bracketed_remote_title_survives, and the "Markup injection
+ via table cells" section.
"""
import pytest
from click.testing import CliRunner
+import world_intel_mcp.analysis.dossier as dossier_analysis
+import world_intel_mcp.reports as reports_mod
+import world_intel_mcp.sources.traffic as traffic_src
+import world_intel_mcp.sources.webcams as webcams_src
from world_intel_mcp import cli
@@ -268,13 +277,15 @@ def test_btc_technicals_values_and_na_branches(
assert "N/A" in result.output # sma_200 / mayer / 30d all None
-def test_btc_error_dict_is_surfaced_as_json(monkeypatch: pytest.MonkeyPatch) -> None:
+def test_btc_error_dict_prints_error_line(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(
cli.markets, "fetch_btc_technicals", _fake({"error": "coingecko down"})
)
result = _invoke("btc")
assert result.exit_code == 0
+ assert "Error:" in result.output
assert "coingecko down" in result.output
+ assert '"error"' not in result.output # no raw JSON dump at a table-mode user
# ---------------------------------------------------------------------------
@@ -298,7 +309,7 @@ def test_energy_renders_oil_and_gas(monkeypatch: pytest.MonkeyPatch) -> None:
assert "$2.9" in result.output
-def test_energy_error_dict_is_surfaced_as_json(
+def test_energy_error_dict_prints_error_line(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr(
@@ -306,7 +317,9 @@ def test_energy_error_dict_is_surfaced_as_json(
)
result = _invoke("energy")
assert result.exit_code == 0
+ assert "Error:" in result.output
assert "EIA_API_KEY missing" in result.output
+ assert '"error"' not in result.output
def test_gas_prices_renders_changes_and_em_dash_for_missing(
@@ -379,13 +392,15 @@ def test_fred_passes_series_and_limit(monkeypatch: pytest.MonkeyPatch) -> None:
assert "4.2" in result.output
-def test_fred_error_dict_is_surfaced_as_json(monkeypatch: pytest.MonkeyPatch) -> None:
+def test_fred_error_dict_prints_error_line(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(
cli.economic, "fetch_fred_series", _fake({"error": "series not found"})
)
result = _invoke("fred", "NOPE")
assert result.exit_code == 0
+ assert "Error:" in result.output
assert "series not found" in result.output
+ assert '"error"' not in result.output
def test_central_banks_renders_rates_and_fred_tag(
@@ -494,13 +509,15 @@ def test_fires_renders_regions_and_skips_zero_counts(
assert "europe" not in result.output # zero-count regions skipped
-def test_fires_error_dict_is_surfaced_as_json(monkeypatch: pytest.MonkeyPatch) -> None:
+def test_fires_error_dict_prints_error_line(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(
cli.wildfire, "fetch_wildfires", _fake({"error": "FIRMS key missing"})
)
result = _invoke("fires")
assert result.exit_code == 0
+ assert "Error:" in result.output
assert "FIRMS key missing" in result.output
+ assert '"error"' not in result.output
def test_climate_renders_anomalies_and_sig_flag(
@@ -590,7 +607,7 @@ def test_conflicts_passes_options_and_renders_events(
assert "12" in result.output
-def test_conflicts_error_dict_is_surfaced_as_json(
+def test_conflicts_error_dict_prints_error_line(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr(
@@ -598,7 +615,9 @@ def test_conflicts_error_dict_is_surfaced_as_json(
)
result = _invoke("conflicts")
assert result.exit_code == 0
+ assert "Error:" in result.output
assert "ACLED token missing" in result.output
+ assert '"error"' not in result.output
def test_flights_passes_bbox_and_renders_aircraft(
@@ -1127,17 +1146,19 @@ def test_dossier_renders_all_sections(monkeypatch: pytest.MonkeyPatch) -> None:
assert "Baseline risk: 78/100" in result.output
-def test_dossier_error_dict_is_surfaced_as_json(
+def test_dossier_error_dict_prints_error_line(
monkeypatch: pytest.MonkeyPatch,
) -> None:
- import world_intel_mcp.analysis.dossier as dossier_mod
-
monkeypatch.setattr(
- dossier_mod, "fetch_country_dossier", _fake({"error": "unknown country XX"})
+ dossier_analysis,
+ "fetch_country_dossier",
+ _fake({"error": "unknown country XX"}),
)
result = _invoke("dossier", "-c", "XX")
assert result.exit_code == 0
+ assert "Error:" in result.output
assert "unknown country XX" in result.output
+ assert '"error"' not in result.output
# ---------------------------------------------------------------------------
@@ -1323,13 +1344,15 @@ def test_fleet_renders_totals_and_ships(monkeypatch: pytest.MonkeyPatch) -> None
assert "CVN-78" in result.output
-def test_fleet_error_dict_is_surfaced_as_json(monkeypatch: pytest.MonkeyPatch) -> None:
+def test_fleet_error_dict_prints_error_line(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(
cli, "fetch_usni_fleet", _fake({"error": "USNI page structure changed"})
)
result = _invoke("fleet")
assert result.exit_code == 0
+ assert "Error:" in result.output
assert "USNI page structure changed" in result.output
+ assert '"error"' not in result.output
def test_hn_renders_stories(monkeypatch: pytest.MonkeyPatch) -> None:
@@ -1511,17 +1534,17 @@ def test_traffic_renders_cities(monkeypatch: pytest.MonkeyPatch) -> None:
assert "18" in result.output
-def test_traffic_error_dict_is_surfaced_as_json(
+def test_traffic_error_dict_prints_error_line(
monkeypatch: pytest.MonkeyPatch,
) -> None:
- import world_intel_mcp.sources.traffic as traffic_mod
-
monkeypatch.setattr(
- traffic_mod, "fetch_traffic_flow", _fake({"error": "TOMTOM key missing"})
+ traffic_src, "fetch_traffic_flow", _fake({"error": "TOMTOM key missing"})
)
result = _invoke("traffic")
assert result.exit_code == 0
+ assert "Error:" in result.output
assert "TOMTOM key missing" in result.output
+ assert '"error"' not in result.output
def test_incidents_renders_delays_and_dash_for_zero(
@@ -1647,8 +1670,6 @@ def test_sync_with_source_reports_not_implemented() -> None:
def test_report_success_panel_and_option_passthrough(
monkeypatch: pytest.MonkeyPatch,
) -> None:
- import world_intel_mcp.reports as reports_mod
-
calls: list = []
payload = {
"path": "/tmp/r.html",
@@ -1680,8 +1701,6 @@ def test_report_success_panel_and_option_passthrough(
def test_report_error_with_fallback_hint(monkeypatch: pytest.MonkeyPatch) -> None:
- import world_intel_mcp.reports as reports_mod
-
payload = {
"error": "WeasyPrint not installed",
"fallback": "pip install -e '.[pdf]'",
@@ -1697,6 +1716,286 @@ def test_report_error_with_fallback_hint(monkeypatch: pytest.MonkeyPatch) -> Non
assert "pip install -e '.[pdf]'" in result.output
+def test_report_error_json_mode_passes_raw_dict(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # report joins the shared _bail_on_error contract: --json-output gets
+ # the raw dict (fallback hint included as data), no error rendering.
+ payload = {
+ "error": "WeasyPrint not installed",
+ "fallback": "pip install -e '.[pdf]'",
+ }
+ monkeypatch.setattr(reports_mod, "generate_report", _fake(payload))
+ result = _invoke("--json-output", "report")
+ assert result.exit_code == 0
+ assert '"error"' in result.output
+ assert '"fallback"' in result.output
+ assert "Error:" not in result.output
+
+
+def test_report_success_json_mode_passes_raw_dict(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ payload = {
+ "path": "/tmp/r.html",
+ "format": "html",
+ "size_bytes": 123_456,
+ "sections_included": ["markets"],
+ "sections_failed": [],
+ "generation_seconds": 4.2,
+ }
+ monkeypatch.setattr(reports_mod, "generate_report", _fake(payload))
+ result = _invoke("--json-output", "report")
+ assert result.exit_code == 0
+ assert '"path"' in result.output
+ assert "Report generated" not in result.output
+
+
+# ---------------------------------------------------------------------------
+# Markup injection via table cells: remote data must render literally
+# ---------------------------------------------------------------------------
+
+# Two failure modes, both must be dead: a well-formed tag pair like
+# "[red]fake[/red]" is silently swallowed (styled, tags eaten), and a
+# stray closing tag like "[/]" raises MarkupError and crashes the
+# command. Remote values inside Rich Table cells go through cli._cell
+# (rich.text.Text), which renders content literally while column-level
+# style/justify still apply.
+
+
+def test_earthquakes_bracketed_place_renders_literally(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ payload = {
+ "count": 2,
+ "earthquakes": [
+ {
+ "magnitude": 5.1,
+ "place": "Coast of [/] Chile",
+ "depth_km": 10.0,
+ "time": "2026-08-31T12:00:00.000Z",
+ "alert_level": None,
+ },
+ {
+ "magnitude": 4.6,
+ "place": "[red]fake[/red] quake zone",
+ "depth_km": 5.2,
+ "time": "2026-08-31T13:00:00.000Z",
+ "alert_level": None,
+ },
+ ],
+ }
+ monkeypatch.setattr(cli.seismology, "fetch_earthquakes", _fake(payload))
+ result = _invoke("earthquakes")
+ assert result.exit_code == 0
+ assert "Coast of [/] Chile" in result.output
+ assert "[red]fake[/red] quake zone" in result.output
+
+
+def test_threats_bracketed_indicator_renders_literally(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ payload = {
+ "count": 1,
+ "feeds_successful": 1,
+ "feeds_attempted": 1,
+ "by_severity": {"critical": 1, "high": 0, "medium": 0, "low": 0},
+ "threats": [
+ {
+ "severity": "critical",
+ "type": "ip",
+ "indicator": "[red]fake[/red] indicator",
+ "threat": "botnet [/] C2",
+ "source_feed": "feodo",
+ }
+ ],
+ }
+ monkeypatch.setattr(cli.cyber, "fetch_cyber_threats", _fake(payload))
+ result = _invoke("threats")
+ assert result.exit_code == 0
+ assert "[red]fake[/red] indicator" in result.output
+ assert "botnet [/] C2" in result.output
+
+
+def test_conflicts_bracketed_location_renders_literally(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ payload = {
+ "count": 1,
+ "events": [
+ {
+ "event_date": "2026-08-30",
+ "event_type": "[bold]Battles[/bold]",
+ "country": "Ukraine",
+ "location": "Kharkiv [/] oblast",
+ "fatalities": 0,
+ }
+ ],
+ }
+ monkeypatch.setattr(cli.conflict, "fetch_acled_events", _fake(payload))
+ result = _invoke("conflicts")
+ assert result.exit_code == 0
+ assert "[bold]Battles[/bold]" in result.output
+ assert "Kharkiv [/] oblast" in result.output
+
+
+def test_flights_bracketed_callsign_renders_literally(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ payload = {
+ "count": 1,
+ "aircraft": [
+ {
+ "callsign": "[dim]RCH123[/dim]",
+ "icao24": "ae1234",
+ "origin_country": "Neverland [/]",
+ "altitude_m": 10_000,
+ "velocity_ms": 250.0,
+ }
+ ],
+ }
+ monkeypatch.setattr(cli.military, "fetch_military_flights", _fake(payload))
+ result = _invoke("flights")
+ assert result.exit_code == 0
+ assert "[dim]RCH123[/dim]" in result.output
+ assert "Neverland [/]" in result.output
+
+
+def test_predictions_bracketed_question_renders_literally(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ payload = {
+ "markets": [
+ {
+ "question": "Will [/] X happen",
+ "yes_probability": 0.62,
+ "sentiment": "likely_yes",
+ "volume_24h": 1_000,
+ }
+ ]
+ }
+ monkeypatch.setattr(cli.prediction, "fetch_prediction_markets", _fake(payload))
+ result = _invoke("predictions")
+ assert result.exit_code == 0
+ assert "Will [/] X happen" in result.output
+
+
+def test_elections_bracketed_country_renders_literally(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ payload = {
+ "elections": [
+ {
+ "date": "2026-10-04",
+ "country": "[green]Fake[/green]land",
+ "type": "general [/] vote",
+ "days_until": 33,
+ "risk_score": 1.0,
+ }
+ ]
+ }
+ monkeypatch.setattr(cli.elections, "fetch_election_calendar", _fake(payload))
+ result = _invoke("elections")
+ assert result.exit_code == 0
+ assert "[green]Fake[/green]land" in result.output
+ assert "general [/] vote" in result.output
+
+
+def test_central_banks_bracketed_bank_renders_literally(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ payload = {
+ "count": 1,
+ "fred_available": False,
+ "rates": [
+ {
+ "bank": "Bank [/] of Testland",
+ "country": "[red]TL[/red]",
+ "rate": 4.25,
+ "as_of": "2026-08-01",
+ }
+ ],
+ }
+ monkeypatch.setattr(cli, "fetch_central_bank_rates", _fake(payload))
+ result = _invoke("central-banks")
+ assert result.exit_code == 0
+ assert "Bank [/] of Testland" in result.output
+ assert "[red]TL[/red]" in result.output
+
+
+def test_fleet_bracketed_ship_name_renders_literally(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ payload = {
+ "report_title": "Fleet Report",
+ "force_totals": {},
+ "ships": [
+ {
+ "name": "USS [red]Fake[/red]",
+ "hull_number": "CVN-00",
+ "type": "carrier",
+ "region": "Pacific [/] Fleet",
+ }
+ ],
+ }
+ monkeypatch.setattr(cli, "fetch_usni_fleet", _fake(payload))
+ result = _invoke("fleet")
+ assert result.exit_code == 0
+ assert "USS [red]Fake[/red]" in result.output
+ assert "Pacific [/] Fleet" in result.output
+
+
+def test_webcams_bracketed_title_renders_literally(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ payload = {
+ "count": 1,
+ "cameras": [
+ {
+ "title": "Harbor [/] Cam",
+ "city": "[red]Rotterdam[/red]",
+ "country": "Netherlands",
+ "status": "active",
+ }
+ ],
+ }
+ monkeypatch.setattr(webcams_src, "fetch_webcams", _fake(payload))
+ result = _invoke("webcams")
+ assert result.exit_code == 0
+ assert "Harbor [/] Cam" in result.output
+ assert "[red]Rotterdam[/red]" in result.output
+
+
+def test_macro_bracketed_signal_renders_literally(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ payload = {
+ "signals": {
+ "vix [/] proxy": {"value": 18.2, "classification": "regime [/] shift"},
+ }
+ }
+ monkeypatch.setattr(cli.markets, "fetch_macro_signals", _fake(payload))
+ result = _invoke("macro")
+ assert result.exit_code == 0
+ assert "vix [/] proxy" in result.output
+ assert "regime [/] shift" in result.output
+
+
+def test_fred_bracketed_series_title_renders_literally(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # The table TITLE is a markup surface too: FRED series titles are
+ # remote free text.
+ payload = {
+ "title": "Rate[/]s",
+ "observations": [{"date": "2026-07-01", "value": "4.2"}],
+ }
+ monkeypatch.setattr(cli.economic, "fetch_fred_series", _fake(payload))
+ result = _invoke("fred", "UNRATE")
+ assert result.exit_code == 0
+ assert "Rate[/]s" in result.output
+
+
# ---------------------------------------------------------------------------
# Error-surfacing sweep: every data command converted to _bail_on_error
# ---------------------------------------------------------------------------
@@ -1738,6 +2037,25 @@ _ERROR_SWEEP = [
(("spending",), cli, "fetch_usa_spending"),
(("bases",), cli.geospatial, "fetch_military_bases"),
(("exchanges",), cli.geospatial, "fetch_stock_exchanges"),
+ # The 17 legacy commands that used to dump raw JSON at table-mode
+ # users on upstream error, unified onto _bail_on_error:
+ (("energy",), cli.economic, "fetch_energy_prices"),
+ (("gas-prices",), cli.economic, "fetch_gas_prices"),
+ (("natgas",), cli.economic, "fetch_residential_natgas_prices"),
+ (("electricity",), cli.economic, "fetch_electricity_rates"),
+ (("fred", "UNRATE"), cli.economic, "fetch_fred_series"),
+ (("fires",), cli.wildfire, "fetch_wildfires"),
+ (("conflicts",), cli.conflict, "fetch_acled_events"),
+ (("dossier",), dossier_analysis, "fetch_country_dossier"),
+ (("risk",), cli.intelligence, "fetch_risk_scores"),
+ (("instability",), cli.intelligence, "fetch_instability_index"),
+ (("btc",), cli.markets, "fetch_btc_technicals"),
+ (("fleet",), cli, "fetch_usni_fleet"),
+ (("traffic",), traffic_src, "fetch_traffic_flow"),
+ (("incidents",), traffic_src, "fetch_traffic_incidents"),
+ (("air-traffic",), cli.aviation, "fetch_domestic_flights"),
+ (("webcams",), webcams_src, "fetch_webcams"),
+ (("report",), reports_mod, "generate_report"),
]
@@ -1755,4 +2073,8 @@ def test_error_dict_reaches_table_output(
monkeypatch.setattr(module, attr, _fake({"error": "upstream exploded"}))
result = _invoke(*args)
assert result.exit_code == 0
+ # One consistent human-readable surface in table mode: the shared
+ # red "Error:" line, never a raw JSON dump.
+ assert "Error:" in result.output
assert "upstream exploded" in result.output
+ assert '"error"' not in result.output