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.
Python ai-toolsai-watchanthropicclaudecybersecuritydashboardgeofencinggeopoliticalgeospatialintelligencemarketsmcpmigrationmilitarymodel-context-protocolnuclearosintreal-timespace-weatherthreat-intelligence
Instability index: reject codes it cannot name, mark every missing input
Phoenix Agent (mac-studio)812a0636ba5e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 73d2cae..a8c815e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -305,6 +305,20 @@ source here, and no proxy is substituted for any of these measures.and a failed download sets `match_count` to null with `error`,`degraded`, reason `sdn_unavailable` and a `data_gaps` entry. `inteldossier` prints "not screened" in that case.+- `intel_instability_index` for one country: a code outside its name+ table was sent upstream as-is and scored from inputs that never matched+ the place, and any string (a name, a typo, lower case) gave a low score+ with no error. Codes are now upper-cased, the 50 codes it can name are+ sent as English names, and any other input returns an error listing+ `accepted_codes`. Every input it could not obtain (ACLED, internet+ outages, military flights, GDELT, or a country with no military bounding+ box) is named in `data_gaps`, a component with no measured input is+ null, `index_is_lower_bound` marks a total that counts missing parts as+ zero, and with nothing measured the index is null and the risk level+ `unknown`. `ucdp_floor_basis` says the floor comes from a static table.+- `intel_internet_outages` returned an empty list with no marker when+ neither Cloudflare Radar nor IODA answered; it now carries `error`,+ `degraded` and reason `outages_unavailable`.### Added: tropical cyclone forecast tracks- `intel_cyclones` and `intel_jtwc_cyclones` take `include_forecast`diff --git a/src/world_intel_mcp/cli.py b/src/world_intel_mcp/cli.pyindex 7921b6a..59447e9 100644--- a/src/world_intel_mcp/cli.py+++ b/src/world_intel_mcp/cli.py@@ -1872,13 +1872,20 @@ def instability(ctx: click.Context, country_code: str | None) -> None:if country_code:idx = data.get("instability_index", 0)level = data.get("risk_level", "")+ # A null index or component was not measured; it is not zero.+ idx_text = "not measured" if idx is None else f"{idx}/100"console.print(- f"[bold]{country_code} Instability Index: {idx}/100 ({level})[/bold]\n"+ f"[bold]{country_code} Instability Index: {idx_text} ({level})[/bold]\n")components = data.get("components", {})for name, score in components.items():+ if score is None:+ console.print(f" {name:30s} not measured")+ continuebar = "█" * int(score) + "░" * (20 - int(score))console.print(f" {name:30s} {bar} {score:.1f}/20")+ for gap in data.get("data_gaps") or []:+ console.print(f" [yellow]gap:[/yellow] {escape(str(gap))}")else:table = Table(title="Instability Index (Focus Countries)", box=box.SIMPLE_HEAVY)table.add_column("Country", style="bold")diff --git a/src/world_intel_mcp/guide.py b/src/world_intel_mcp/guide.pyindex 39fc157..e0a634d 100644--- a/src/world_intel_mcp/guide.py+++ b/src/world_intel_mcp/guide.py@@ -394,8 +394,11 @@ caused the other.Escalation, instability, risk, macro composite and stress scores areweighted combinations of current inputs against stated baselines. They-summarize their inputs, they are not probabilities, and they hold no-information their inputs do not. Report the components with the score.+summarize their inputs and are not probabilities. Some add a fixed amount+from a static country table: the instability index's `ucdp_floor` and+`displacement_boost` come from a baseline risk table, not from current+data, so a floor score says nothing about this week. Report the+components with the score; a null component was not measured.## Missing data is not zero@@ -405,8 +408,8 @@ unknown, not none. Not every tool does: some return an empty list, azero count or a neutral score when every upstream request failed, so anempty list or a zero means nothing was returned, not that nothinghappened. Zero events from a fetch that worked, in a region the source-covers, is a measurement; zero events in a region it does not cover is-nothing at all.+covers and for a query that matched the place, is a measurement; zero+events in a region it does not cover is nothing at all."""diff --git a/src/world_intel_mcp/guide_prompts.py b/src/world_intel_mcp/guide_prompts.pyindex 8fa3853..2fbac99 100644--- a/src/world_intel_mcp/guide_prompts.py+++ b/src/world_intel_mcp/guide_prompts.py@@ -1244,7 +1244,11 @@ PROMPTS: tuple[ResearchPrompt, ...] = (),Step("intel_instability_index",- "the index with its four components",+ "the index with its four components. It takes 50 ISO alpha-3 "+ "codes and returns an error listing them for any other. Each "+ "input it could not obtain is named in data_gaps and its "+ "component is null; index_is_lower_bound then means the total "+ "counts the missing parts as zero",args=(("country_code", "{country}"),),),Step(@@ -1261,7 +1265,9 @@ PROMPTS: tuple[ResearchPrompt, ...] = (),limits=("The instability index is a weighted composite with country "- "multipliers. Quote its components, not only the total.",+ "multipliers. Quote its components, not only the total. Its "+ "ucdp_floor comes from a static baseline table, not from current "+ "UCDP data: a total at the floor says nothing about this month.","World Bank figures in the dossier are annual and often a year or ""more old. Give the year of each.",),diff --git a/src/world_intel_mcp/sources/infrastructure.py b/src/world_intel_mcp/sources/infrastructure.pyindex ae08e00..b2d9154 100644--- a/src/world_intel_mcp/sources/infrastructure.py+++ b/src/world_intel_mcp/sources/infrastructure.py@@ -267,12 +267,21 @@ async def fetch_internet_outages(fetcher: Fetcher) -> dict:if data is None:note = "Set CLOUDFLARE_API_TOKEN for detailed outage data" if not token else Nonelogger.warning("Internet outages: no data from Cloudflare or IODA")+ # No source answered: the empty list is missing data, not a quiet+ # week, so it carries an error marker.result: dict = {"outages": [],"ongoing_count": 0,"total_7d": 0,"source": "cloudflare-radar","timestamp": now_iso,+ "error": (+ "No internet outage source answered (Cloudflare Radar and IODA)"+ if token+ else "No internet outage source answered (IODA; Cloudflare Radar needs CLOUDFLARE_API_TOKEN)"+ ),+ "degraded": True,+ "reason": "outages_unavailable",}if note:result["note"] = notediff --git a/src/world_intel_mcp/sources/intelligence.py b/src/world_intel_mcp/sources/intelligence.pyindex 6fc7b45..f6fae64 100644--- a/src/world_intel_mcp/sources/intelligence.py+++ b/src/world_intel_mcp/sources/intelligence.py@@ -429,11 +429,44 @@ async def fetch_instability_index(now = datetime.now(timezone.utc)if country_code is not None:- return await _instability_single(fetcher, country_code, now)+ code = country_code.strip().upper()+ names = _instability_country_names()+ if code not in names:+ # A code the index cannot name would be sent upstream as-is and+ # score from inputs that never matched the place.+ return {+ "error": (+ f"Unknown or unsupported country code {country_code!r}: the "+ "instability index takes one of the ISO alpha-3 codes it can "+ "name, listed in accepted_codes"+ ),+ "accepted_codes": sorted(names),+ "source": "instability-index-v2",+ "timestamp": now.strftime("%Y-%m-%dT%H:%M:%SZ"),+ }+ return await _instability_single(fetcher, code, now)return await _instability_multi(fetcher, now)+# ACLED spells this one differently from the sanctions-list form the+# dossier's name table uses.+_ACLED_NAME_OVERRIDES = {"KOR": "South Korea"}+++def _instability_country_names() -> dict[str, str]:+ """ISO alpha-3 code -> English name for every country the single-country+ index can query: its own table, the tier-1 countries and the dossier's+ table."""+ from ..analysis.dossier import _EXTRA_COUNTRY_NAMES++ names = dict(_EXTRA_COUNTRY_NAMES)+ names.update({code: cfg["name"] for code, cfg in TIER1_COUNTRIES.items() if cfg.get("name")})+ names.update(_ISO3_TO_NAME)+ names.update(_ACLED_NAME_OVERRIDES)+ return names++async def _instability_single(fetcher: Fetcher,country_code: str,@@ -443,8 +476,13 @@ async def _instability_single(Uses 4 weighted domains: unrest, conflict, security, information.Applies country-specific event multiplier and UCDP/displacement boosts.++ Every input that could not be obtained is named in ``data_gaps``, and a+ component with no measured input is null rather than 0. The total then+ treats it as 0, so it is a lower bound (``index_is_lower_bound``); with+ no component measured the index is null and the risk level "unknown"."""- country_name = _ISO3_TO_NAME.get(country_code, country_code)+ country_name = _instability_country_names()[country_code]event_multiplier = get_event_multiplier(country_code)start_date = (now - timedelta(days=30)).strftime("%Y-%m-%d")end_date = now.strftime("%Y-%m-%d")@@ -469,11 +507,13 @@ async def _instability_single(events = data.get("data", []) if isinstance(data, dict) else []return events, None- async def _fetch_outages() -> int:+ async def _fetch_outages() -> tuple[int, str | None]:"""Count internet outages mentioning this country."""from . import infrastructureresult = await infrastructure.fetch_internet_outages(fetcher)+ if result.get("error"):+ return 0, f"internet outages: {result['error']}"count = 0for outage in result.get("outages", []):countries_list = outage.get("countries", [])@@ -481,9 +521,9 @@ async def _instability_single(for c in countries_list:if isinstance(c, str) and country_code.lower() in c.lower():count += 1- return count+ return count, None- async def _fetch_military() -> int:+ async def _fetch_military() -> tuple[int, str | None]:"""Count military aircraft near this country."""_COUNTRY_BBOX = {"SYR": "32,35,37,42",@@ -505,14 +545,19 @@ async def _instability_single(}bbox = _COUNTRY_BBOX.get(country_code)if bbox is None:- return 0+ return 0, (+ f"military aircraft: no bounding box for {country_code} (the index "+ f"has {len(_COUNTRY_BBOX)}), not measured"+ )from . import military as mil_modresult = await mil_mod.fetch_military_flights(fetcher, bbox=bbox)- return result.get("count", 0)+ if result.get("error"):+ return 0, f"military aircraft: {result['error']}"+ return result.get("count", 0), None- async def _fetch_news_velocity() -> int:+ async def _fetch_news_velocity() -> tuple[int, str | None]:"""Estimate news velocity from GDELT."""from . import news@@ -522,9 +567,16 @@ async def _instability_single(mode="artlist",limit=100,)- return result.get("count", 0)+ if result.get("error"):+ return 0, f"news velocity (GDELT): {result['error']}"+ return result.get("count", 0), None- (acled_events, acled_gap), outage_count, mil_count, news_vel = await asyncio.gather(+ (+ (acled_events, acled_gap),+ (outage_count, outage_gap),+ (mil_count, mil_gap),+ (news_vel, news_gap),+ ) = await asyncio.gather(_fetch_acled(),_fetch_outages(),_fetch_military(),@@ -582,6 +634,27 @@ async def _instability_single(displacement_boost=displacement_boost,)+ # A component with no measured input is unknown, not 0.+ unmeasured = []+ if acled_gap:+ unmeasured += ["unrest", "conflict"]+ if mil_gap and outage_gap:+ unmeasured.append("security")+ if news_gap:+ unmeasured.append("information")+ for name in unmeasured:+ cii["components"][name] = None+ if unmeasured or mil_gap or outage_gap:+ cii["index_is_lower_bound"] = True+ if len(unmeasured) == len(cii["components"]):+ cii["instability_index"] = None+ cii["risk_level"] = "unknown"+ if ucdp_floor is not None:+ cii["ucdp_floor_basis"] = (+ "static baseline_risk from the country table, not current UCDP data"+ )+ data_gaps = [g for g in (acled_gap, mil_gap, outage_gap, news_gap) if g]+return {"country_code": country_code,"country_name": country_name,@@ -596,7 +669,7 @@ async def _instability_single("internet_outages": outage_count,"news_articles": news_vel,},- "data_gaps": [acled_gap] if acled_gap else [],+ "data_gaps": data_gaps,"source": "instability-index-v2","timestamp": now.strftime("%Y-%m-%dT%H:%M:%SZ"),}diff --git a/src/world_intel_mcp/tests/test_sources_intelligence.py b/src/world_intel_mcp/tests/test_sources_intelligence.pyindex 426290f..492d29e 100644--- a/src/world_intel_mcp/tests/test_sources_intelligence.py+++ b/src/world_intel_mcp/tests/test_sources_intelligence.py@@ -314,6 +314,186 @@ async def test_fetch_instability_index_multi_unconfigured(assert result.get("degraded") is None+def _instability_inputs(monkeypatch, *, acled=None, outages=None, flights=None, gdelt=None):+ """Patch the four single-country inputs; record what each was asked."""+ sent: dict = {"acled": [], "gdelt": [], "bbox": []}++ async def _acled(fetcher, params, cache_key, cache_ttl=900):+ sent["acled"].append(params.get("country"))+ return acled++ async def _gdelt(fetcher, query="", mode="artlist", limit=100):+ sent["gdelt"].append(query)+ return gdelt if gdelt is not None else {"count": 40}++ async def _flights(fetcher, bbox=None):+ sent["bbox"].append(bbox)+ return flights if flights is not None else {"count": 10}++ monkeypatch.setattr(intelligence, "acled_query", _acled)+ monkeypatch.setattr(+ infrastructure,+ "fetch_internet_outages",+ _async_return(outages if outages is not None else {"outages": []}),+ )+ monkeypatch.setattr(military, "fetch_military_flights", _flights)+ monkeypatch.setattr(news, "fetch_gdelt_search", _gdelt)+ return sent+++async def test_instability_unknown_code_is_an_error_not_zero_low(+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch+) -> None:+ sent = _instability_inputs(monkeypatch, acled={"data": []})+ for bad in ("XYZ", "Sudan", ""):+ result = await intelligence.fetch_instability_index(fetcher, country_code=bad)+ assert "instability_index" not in result, bad+ assert result["error"].startswith("Unknown or unsupported country code"), bad+ assert {"SDN", "FRA", "BRA", "USA"} <= set(result["accepted_codes"])+ assert len(result["accepted_codes"]) == 50+ assert sent == {"acled": [], "gdelt": [], "bbox": []}+++async def test_instability_sends_the_country_name_upstream_and_ignores_case(+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch+) -> None:+ sent = _instability_inputs(monkeypatch, acled={"data": []})+ bra = await intelligence.fetch_instability_index(fetcher, country_code="BRA")+ syr = await intelligence.fetch_instability_index(fetcher, country_code=" syr ")+ assert sent["acled"] == ["Brazil", "Syria"]+ assert sent["gdelt"] == ["Brazil", "Syria"]+ assert (bra["country_code"], bra["country_name"]) == ("BRA", "Brazil")+ assert (syr["country_code"], syr["country_name"], syr["ucdp_floor"]) == ("SYR", "Syria", 70.0)+ assert syr["ucdp_floor_basis"].startswith("static baseline_risk")+ assert "ucdp_floor_basis" not in bra+++async def test_instability_names_every_input_it_could_not_obtain(+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch+) -> None:+ """ACLED unconfigured, outages, flights and GDELT all failed: nothing+ was measured, so there is no index and no risk level from the floor."""+ _instability_inputs(+ monkeypatch,+ acled=None,+ outages={"outages": [], "error": "No internet outage source answered"},+ flights={"count": 0, "source": "none", "error": "No military flight source available"},+ gdelt={"count": 0, "error": "GDELT fetch failed", "degraded": True},+ )+ monkeypatch.setattr(intelligence, "acled_failure_reason", _fake_reason("acled_unconfigured"))++ result = await intelligence.fetch_instability_index(fetcher, country_code="SDN")++ assert result["components"] == {"unrest": None, "conflict": None, "security": None, "information": None}+ assert (result["instability_index"], result["risk_level"]) == (None, "unknown")+ assert result["index_is_lower_bound"] is True+ assert result["data_gaps"] == [+ "acled_unconfigured",+ "military aircraft: No military flight source available",+ "internet outages: No internet outage source answered",+ "news velocity (GDELT): GDELT fetch failed",+ ]+++async def test_instability_without_a_bbox_says_military_was_not_measured(+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch+) -> None:+ """France has no military bounding box and GDELT failed: security rests+ on outages alone, information is unknown, and the total is a lower bound."""+ sent = _instability_inputs(+ monkeypatch,+ acled={"data": [{"event_type": "Protests", "fatalities": 0}] * 4},+ gdelt={"count": 0, "error": "GDELT fetch failed"},+ )++ result = await intelligence.fetch_instability_index(fetcher, country_code="FRA")++ assert sent["bbox"] == []+ assert result["components"]["information"] is None+ assert result["components"]["security"] == 0.0+ assert result["components"]["unrest"] is not None+ assert result["instability_index"] is not None+ assert result["index_is_lower_bound"] is True+ assert result["data_gaps"] == [+ "military aircraft: no bounding box for FRA (the index has 16), not measured",+ "news velocity (GDELT): GDELT fetch failed",+ ]+++async def test_instability_with_every_input_measured_has_no_gap(+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch+) -> None:+ _instability_inputs(monkeypatch, acled={"data": []})+ result = await intelligence.fetch_instability_index(fetcher, country_code="SYR")+ assert result["data_gaps"] == []+ assert "index_is_lower_bound" not in result+ assert None not in result["components"].values()+++async def test_instability_part_measured_security_makes_a_lower_bound(+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch+) -> None:+ """Only the military part is missing (no bounding box): every component+ has a value, but the total still leaves that part out."""+ _instability_inputs(monkeypatch, acled={"data": []})+ result = await intelligence.fetch_instability_index(fetcher, country_code="DEU")+ assert None not in result["components"].values()+ assert result["index_is_lower_bound"] is True+ assert result["data_gaps"] == [+ "military aircraft: no bounding box for DEU (the index has 16), not measured"+ ]+++async def test_internet_outages_with_no_source_answering_is_marked(+ cache, monkeypatch: pytest.MonkeyPatch+) -> None:+ from world_intel_mcp.circuit_breaker import CircuitBreaker++ monkeypatch.delenv("CLOUDFLARE_API_TOKEN", raising=False)+ quick = Fetcher(cache=cache, breaker=CircuitBreaker(), max_retries=0)+ try:+ with respx.mock(assert_all_called=False) as router:+ router.route().mock(return_value=httpx.Response(503))+ result = await infrastructure.fetch_internet_outages(quick)+ finally:+ await quick.close()+ assert (result["degraded"], result["reason"]) == (True, "outages_unavailable")+ assert result["error"].startswith("No internet outage source answered")+ assert (result["outages"], result["total_7d"]) == ([], 0)+++def test_cli_instability_prints_unmeasured_components(tmp_path, monkeypatch: pytest.MonkeyPatch) -> None:+ from click.testing import CliRunner++ from world_intel_mcp import cli++ monkeypatch.setenv("WORLD_INTEL_CACHE_DB", str(tmp_path / "cli-cache.db"))+ monkeypatch.setattr(cli, "_fetcher", None)+ monkeypatch.setattr(+ intelligence,+ "fetch_instability_index",+ _async_return({+ "instability_index": None,+ "risk_level": "unknown",+ "components": {"unrest": None, "information": 15.0},+ "data_gaps": ["news velocity (GDELT): GDELT fetch failed"],+ }),+ )+ result = CliRunner().invoke(cli.main, ["instability", "SDN"], env={"COLUMNS": "200"})+ assert result.exit_code == 0, result.output+ assert "SDN Instability Index: not measured (unknown)" in result.output+ assert "unrest" in result.output and "not measured" in result.output+ assert "15.0/20" in result.output+ assert "gap: news velocity (GDELT): GDELT fetch failed" in result.output++# ---------------------------------------------------------------------------# Function 4: fetch_signal_convergence# ---------------------------------------------------------------------------