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.

tests: regression tests for issues #3-#7

Phoenix Agent (Marcs-Mac-Studio)b4c942a5e42d
diff --git a/src/world_intel_mcp/tests/test_analysis.py b/src/world_intel_mcp/tests/test_analysis.py
index 963f228..6a67e1b 100644
--- a/src/world_intel_mcp/tests/test_analysis.py
+++ b/src/world_intel_mcp/tests/test_analysis.py
@@ -2,8 +2,8 @@
import time
-import pytest
+from world_intel_mcp.analysis.escalation import score_hotspot
from world_intel_mcp.circuit_breaker import CircuitBreaker
@@ -57,3 +57,74 @@ def test_independent_sources() -> None:
cb.record_failure("source_a")
assert not cb.is_available("source_a")
assert cb.is_available("source_b") # independent
+
+
+def test_circuit_reopens_on_failed_probe_after_cooldown() -> None:
+ """Issue #7: is_available() lets a single probe through once cooldown
+ elapses, but record_failure() previously only re-tripped the breaker
+ when it was closed — so a failed probe left tripped_at stuck at the
+ original trip time. Every subsequent is_available() call then saw the
+ (stale) cooldown as already elapsed and let calls straight through:
+ "half-open forever," backoff never re-enforced against a source that
+ is still failing."""
+ cb = CircuitBreaker(failure_threshold=1, cooldown_seconds=0.2)
+
+ cb.record_failure("src") # trips
+ assert not cb.is_available("src")
+
+ time.sleep(0.25) # cooldown elapses — single probe allowed
+ assert cb.is_available("src")
+
+ cb.record_failure("src") # the probe itself failed (source still down)
+
+ # A real backoff must block again immediately, not fall straight
+ # through — that's the "half-open forever" bug.
+ assert not cb.is_available("src")
+ assert cb.status()["src"]["status"] == "open"
+ assert cb.status()["src"]["cooldown_remaining_s"] > 0
+
+ time.sleep(0.25) # second cooldown elapses
+ assert cb.is_available("src") # probe allowed again, as expected
+
+
+def test_score_hotspot_unavailable_signals_are_null_and_renormalized() -> None:
+ """Issue #6: news_mentions and convergence_score were hardcoded to 0
+ for every hotspot on every call (real per-hotspot signals were never
+ wired), which permanently zeroed up to 20 of 100 points and was
+ indistinguishable from a genuinely quiet news cycle. An active hotspot
+ with every OTHER signal maxed out could never structurally exceed
+ 80/100 — Kyiv, an active war zone, scored 20.0 ("watch", the lowest
+ tier)."""
+ hotspot_config = {"baseline_escalation": 5, "lat": 0.0, "lon": 0.0}
+
+ result = score_hotspot(
+ hotspot_config,
+ news_mentions=None, # unavailable — NOT measured, not "zero mentions"
+ military_count=100, # maxes the military component (20)
+ conflict_events=100, # maxes the conflict component (20)
+ convergence_score=None, # unavailable
+ fatalities=1000,
+ protests=100, # maxes the social_unrest component (12)
+ )
+
+ assert result["components"]["news"] is None
+ assert result["components"]["convergence"] is None
+ assert result["unavailable_components"] == ["news", "convergence"]
+ # Renormalized over the 72 points actually measured (baseline 20 +
+ # military 20 + conflict 20 + social_unrest 12), all of which are
+ # maxed out here — so the score reaches 100, not a value structurally
+ # capped by two components that were never real signals to begin with.
+ assert result["score"] == 100.0
+ assert result["level"] == "critical"
+
+
+def test_score_hotspot_measured_zero_is_not_unavailable() -> None:
+ """A genuinely measured zero (the signal was queried and found quiet)
+ must still be reported as 0.0, not conflated with "not measured"."""
+ hotspot_config = {"baseline_escalation": 0, "lat": 0.0, "lon": 0.0}
+
+ result = score_hotspot(hotspot_config, news_mentions=0, convergence_score=0.0)
+
+ assert result["components"]["news"] == 0.0
+ assert result["components"]["convergence"] == 0.0
+ assert result["unavailable_components"] == []
diff --git a/src/world_intel_mcp/tests/test_fetcher.py b/src/world_intel_mcp/tests/test_fetcher.py
new file mode 100644
index 0000000..3622398
--- /dev/null
+++ b/src/world_intel_mcp/tests/test_fetcher.py
@@ -0,0 +1,62 @@
+"""Tests for Fetcher — stale-cache fallback honesty (issue #4).
+
+fetcher.py's module docstring promises that a stale-cache fallback is
+marked with ``_stale=True`` so dashboards/callers never mistake old data
+for fresh data. Prior to the fix, ``_stale_fallback`` returned the cached
+value completely unmodified — the marker was documented but never set.
+"""
+
+from pathlib import Path
+
+import pytest
+
+from world_intel_mcp.cache import Cache
+from world_intel_mcp.circuit_breaker import CircuitBreaker
+from world_intel_mcp.fetcher import Fetcher
+
+
+def cache(tmp_path: Path) -> Cache:
+ return Cache(db_path=tmp_path / "test_cache.db")
+
+
+def breaker() -> CircuitBreaker:
+ return CircuitBreaker()
+
+
+def fetcher(cache: Cache, breaker: CircuitBreaker) -> Fetcher:
+ return Fetcher(cache=cache, breaker=breaker, default_timeout=5.0)
+
+
+def test_stale_fallback_marks_dict_responses(fetcher: Fetcher) -> None:
+ key = "test:stale:dict"
+ fetcher.cache.set(key, {"value": 42}, ttl_seconds=-10) # already expired
+
+ result = fetcher._stale_fallback(key, "test-source")
+
+ assert result is not None
+ assert result["value"] == 42
+ assert result["_stale"] is True
+ assert isinstance(result["_stale_age_seconds"], (int, float))
+ assert result["_stale_age_seconds"] >= 0
+
+
+def test_stale_fallback_counts_non_dict_responses(
+ fetcher: Fetcher, breaker: CircuitBreaker
+) -> None:
+ """Non-dict payloads (raw text/XML, lists) can't carry an inline
+ marker, so the failure must surface via the breaker's stale-serve
+ counter instead of vanishing silently."""
+ key = "test:stale:list"
+ fetcher.cache.set(key, [1, 2, 3], ttl_seconds=-10)
+
+ result = fetcher._stale_fallback(key, "test-source")
+
+ assert result == [1, 2, 3]
+ assert breaker.status()["test-source"]["total_stale_serves"] == 1
+
+
+def test_stale_fallback_returns_none_when_nothing_cached(fetcher: Fetcher) -> None:
+ assert fetcher._stale_fallback("test:missing", "test-source") is None
diff --git a/src/world_intel_mcp/tests/test_intelligence.py b/src/world_intel_mcp/tests/test_intelligence.py
new file mode 100644
index 0000000..562e5e5
--- /dev/null
+++ b/src/world_intel_mcp/tests/test_intelligence.py
@@ -0,0 +1,101 @@
+"""Tests for sources/intelligence.py — downstream ACLED-failure honesty (issue #3)."""
+
+from pathlib import Path
+
+import pytest
+
+from world_intel_mcp.cache import Cache
+from world_intel_mcp.circuit_breaker import CircuitBreaker
+from world_intel_mcp.fetcher import Fetcher
+
+
+def cache(tmp_path: Path) -> Cache:
+ return Cache(db_path=tmp_path / "test_cache.db")
+
+
+def fetcher(cache: Cache) -> Fetcher:
+ breaker = CircuitBreaker()
+ return Fetcher(cache=cache, breaker=breaker, default_timeout=5.0)
+
+
+async def test_fetch_risk_scores_distinguishes_fetch_failure_from_unconfigured(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Issue #3 (downstream consumer audit): fetch_risk_scores previously
+ reported "ACLED credentials not configured" for ANY acled_query()
+ failure, even when credentials were fine and only the live fetch
+ failed (rate limit, 500, malformed payload) — misdiagnosing a
+ transient outage as a config problem an operator can't fix."""
+ from world_intel_mcp.sources import conflict, intelligence
+
+ async def _fake_token() -> str:
+ return "fake-token"
+
+ async def _fake_get_json(*args, **kwargs):
+ return None
+
+ monkeypatch.setattr(conflict, "_acled_get_token", _fake_token)
+ monkeypatch.setattr(fetcher, "get_json", _fake_get_json)
+
+ result = await intelligence.fetch_risk_scores(fetcher)
+
+ assert result.get("error") is not None
+ assert "not configured" not in result["error"]
+ assert result.get("degraded") is True
+
+
+async def test_fetch_risk_scores_unconfigured_still_reports_unconfigured(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The original "not configured" message must still fire when
+ credentials really are missing — only the misdiagnosis is fixed."""
+ from world_intel_mcp.sources import conflict, intelligence
+
+ async def _no_token() -> None:
+ return None
+
+ monkeypatch.setattr(conflict, "_acled_get_token", _no_token)
+ monkeypatch.delenv("ACLED_EMAIL", raising=False)
+ monkeypatch.delenv("ACLED_PASSWORD", raising=False)
+
+ result = await intelligence.fetch_risk_scores(fetcher)
+
+ assert result.get("error") is not None
+ assert "not configured" in result["error"]
+ assert result.get("degraded") is None
+
+
+async def test_fetch_hotspot_escalation_reports_unavailable_components(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Issue #6 at the tool level: intel_hotspot_escalation must disclose
+ that news/convergence are not wired up rather than silently scoring
+ every hotspot as if those signals were measured and quiet."""
+ from world_intel_mcp.sources import conflict, intelligence, military
+
+ async def _fake_token() -> str:
+ return "fake-token"
+
+ async def _fake_get_json(*args, **kwargs):
+ return {"data": []}
+
+ async def _fake_theater_posture(*args, **kwargs):
+ return {"theaters": {}}
+
+ monkeypatch.setattr(conflict, "_acled_get_token", _fake_token)
+ monkeypatch.setattr(fetcher, "get_json", _fake_get_json)
+ monkeypatch.setattr(military, "fetch_theater_posture", _fake_theater_posture)
+
+ result = await intelligence.fetch_hotspot_escalation(fetcher)
+
+ assert result["unavailable_components"] == ["news", "convergence"]
+ assert result["data_gaps"] == []
+ assert result["count"] > 0
+ for hotspot in result["hotspots"]:
+ assert hotspot["components"]["news"] is None
+ assert hotspot["components"]["convergence"] is None
diff --git a/src/world_intel_mcp/tests/test_sources.py b/src/world_intel_mcp/tests/test_sources.py
index 8d68324..fac26f0 100644
--- a/src/world_intel_mcp/tests/test_sources.py
+++ b/src/world_intel_mcp/tests/test_sources.py
@@ -282,6 +282,50 @@ async def test_fetch_gas_prices_no_data(
assert result["prices"] == {}
+async def test_fetch_gas_prices_stale_fallback_preserves_original_fetch_time(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Issue #5: on live-fetch failure, stale cached gas prices must keep
+ their ORIGINAL fetch timestamp and carry a _stale marker instead of
+ being restamped with datetime.now() — which made 3-day-old prices
+ look like they were fetched seconds ago."""
+ import json
+ import time as time_mod
+ from datetime import datetime, timezone
+
+ from world_intel_mcp.sources import economic
+
+ # Seed a cache entry whose created_at is 3 days in the past (Cache.set
+ # always uses now(), so write the row directly to backdate it).
+ conn = fetcher.cache._get_conn()
+ old_created_at = time_mod.time() - 3 * 86400
+ conn.execute(
+ "INSERT OR REPLACE INTO cache (key, value, expires_at, created_at) VALUES (?, ?, ?, ?)",
+ (
+ "economic:gas_prices:aaa",
+ json.dumps(_AAA_HTML),
+ old_created_at + 1800, # expired long ago
+ old_created_at,
+ ),
+ )
+ conn.commit()
+
+ # _fetch_aaa_html() swallows its own errors and returns None on a real
+ # failure (e.g. AAA's Cloudflare 403) rather than raising.
+ monkeypatch.setattr(economic, "_fetch_aaa_html", lambda: None)
+
+ result = await economic.fetch_gas_prices(fetcher)
+
+ assert result["_stale"] is True
+ assert result["_stale_age_seconds"] > 2.9 * 86400
+ fetched_at = datetime.fromisoformat(result["fetched_at"])
+ age_days = (datetime.now(timezone.utc) - fetched_at).total_seconds() / 86400
+ assert age_days > 2.9, "fetched_at must preserve the original (stale) fetch time"
+ # The stale payload still parses normally.
+ assert result["prices"]["regular"]["price_per_gallon"] == 3.450
+
+
@respx.mock
@pytest.mark.asyncio
async def test_fetch_residential_natgas(fetcher: Fetcher) -> None:
@@ -709,6 +753,62 @@ async def test_fetch_ucdp_events(fetcher: Fetcher) -> None:
assert result["total_fatalities_best"] == 5
+async def test_fetch_acled_events_distinguishes_fetch_failure_from_zero_events(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Issue #3: a post-auth ACLED fetch failure (rate limit, 500,
+ malformed payload) must not be byte-identical to a genuine zero-match
+ result. Repro per the issue: patch the OAuth token to succeed and
+ get_json to return None (the post-auth failure path)."""
+ from world_intel_mcp.sources import conflict
+
+ async def _fake_token() -> str:
+ return "fake-token"
+
+ async def _fake_get_json(*args, **kwargs):
+ return None
+
+ monkeypatch.setattr(conflict, "_acled_get_token", _fake_token)
+ monkeypatch.setattr(fetcher, "get_json", _fake_get_json)
+
+ result = await conflict.fetch_acled_events(fetcher, country="Sudan", days=7)
+
+ assert result.get("error") is not None
+ assert result.get("degraded") is True
+ assert result.get("reason") == "acled_fetch_failed"
+ # Additive-only: events/count keep their normal shape (empty list / 0,
+ # not None) so existing callers that don't check "error" or "degraded"
+ # still iterate an empty list instead of crashing.
+ assert result["events"] == []
+ assert result["count"] == 0
+
+
+async def test_fetch_acled_events_genuine_zero_has_no_error(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A real zero-match query (fetch succeeds, API returns no data) must
+ NOT be flagged as degraded — only actual fetch failures are."""
+ from world_intel_mcp.sources import conflict
+
+ async def _fake_token() -> str:
+ return "fake-token"
+
+ async def _fake_get_json(*args, **kwargs):
+ return {"data": []}
+
+ monkeypatch.setattr(conflict, "_acled_get_token", _fake_token)
+ monkeypatch.setattr(fetcher, "get_json", _fake_get_json)
+
+ result = await conflict.fetch_acled_events(fetcher, country="Iceland", days=7)
+
+ assert result.get("error") is None
+ assert result.get("degraded") is None
+ assert result["events"] == []
+ assert result["count"] == 0
+
+
# ---------------------------------------------------------------------------
# Hacker News
# ---------------------------------------------------------------------------