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
intel_aoi_digest: the change sweep across every AOI in one call (+1 = 129)
Phoenix Agent (Marcs-Mac-Studio)31de74f8cd58
diff --git a/src/world_intel_mcp/analysis/aoi.py b/src/world_intel_mcp/analysis/aoi.pyindex 9623a71..684d631 100644--- a/src/world_intel_mcp/analysis/aoi.py+++ b/src/world_intel_mcp/analysis/aoi.py@@ -1768,3 +1768,110 @@ async def fetch_aoi_changes(fetcher, store: AOIStore, name: Any) -> dict:"source": "aoi-changes","timestamp": _utc_now_iso(),}+++# ---------------------------------------------------------------------------+# intel_aoi_digest: one-call change sweep across all AOIs+# ---------------------------------------------------------------------------++_DIGEST_CONCURRENCY = 3+++async def fetch_aoi_digest(fetcher, store: AOIStore, names: Any = None) -> dict:+ """Run the change sweep (``fetch_aoi_changes``) across every defined+ AOI - or the named subset - in one call, and compose a cross-AOI+ digest. This IS a sweep: each AOI's change snapshot advances, so a+ scheduler can call this one tool on an interval and get "what+ entered or left each of my areas since last time".++ Concurrency is capped (upstream fetches for the shared global+ domains hit the cache across AOIs; per-AOI fetches like military+ bboxes and news queries do not). Honest shapes throughout: no AOIs+ is a note, not an error; unknown requested names ARE an error; a+ domain failure stays inside that AOI's ``data_gaps``.+ """+ all_aois = store.list_all()+ if names is not None:+ if not isinstance(names, list) or not all(+ isinstance(n, str) and n.strip() for n in names+ ):+ return {"error": "names must be a list of non-empty strings."}+ by_key = {a["name"].strip().lower(): a for a in all_aois}+ missing = [n for n in names if n.strip().lower() not in by_key]+ if missing:+ return {+ "error": "Unknown AOI name(s): "+ + ", ".join(sorted(missing))+ + ". Use intel_aoi_list to see defined areas."+ }+ selected = [by_key[n.strip().lower()] for n in names]+ else:+ selected = all_aois++ if not selected:+ return {+ "aois": [],+ "count": 0,+ "note": "No AOIs defined. Use intel_aoi_define (or the polygon/"+ "corridor variants) to create one.",+ "source": "aoi-digest",+ "timestamp": _utc_now_iso(),+ }++ semaphore = asyncio.Semaphore(_DIGEST_CONCURRENCY)++ async def _sweep(row: dict) -> dict:+ async with semaphore:+ return await fetch_aoi_changes(fetcher, store, row["name"])++ results = await asyncio.gather(*[_sweep(row) for row in selected])++ entries: list[dict] = []+ total_new = total_departed = 0+ md_parts = ["# AOI Digest", ""]+ for row, result in zip(selected, results):+ if "error" in result and "changes" not in result:+ # A per-AOI hard failure (e.g. deleted concurrently): keep+ # it visible without sinking the whole digest.+ entries.append({"name": row["name"], "error": result["error"]})+ md_parts += [f"## {row['name']}", f"_Error: {result['error']}_", ""]+ continue+ new_count = sum(len(c["new"]) for c in result["changes"].values())+ departed_count = sum(len(c["departed"]) for c in result["changes"].values())+ total_new += new_count+ total_departed += departed_count+ entries.append(+ {+ "name": result["aoi"]["name"],+ "kind": result["aoi"]["kind"],+ "baseline": result["baseline"],+ "counts": result["counts"],+ "changes": result["changes"],+ "data_gaps": result["data_gaps"],+ }+ )+ md_parts.append(f"## {result['aoi']['name']} ({result['aoi']['kind']})")+ if result["baseline"]:+ md_parts.append(+ "_Baseline established; changes will report from the next sweep._"+ )+ elif new_count == 0 and departed_count == 0:+ md_parts.append("_No changes since the last sweep._")+ else:+ for domain, change in result["changes"].items():+ for item in change["new"]:+ md_parts.append(f"- NEW [{domain}] {item['summary']}")+ for item in change["departed"]:+ md_parts.append(f"- DEPARTED [{domain}] {item['summary']}")+ for gap in result["data_gaps"]:+ md_parts.append(f"- data gap: {gap}")+ md_parts.append("")++ return {+ "aois": entries,+ "count": len(entries),+ "totals": {"new_items": total_new, "departed_items": total_departed},+ "markdown": "\n".join(md_parts),+ "source": "aoi-digest",+ "timestamp": _utc_now_iso(),+ }diff --git a/src/world_intel_mcp/tests/test_aoi.py b/src/world_intel_mcp/tests/test_aoi.pyindex e545816..5f00e6f 100644--- a/src/world_intel_mcp/tests/test_aoi.py+++ b/src/world_intel_mcp/tests/test_aoi.py@@ -641,6 +641,7 @@ def _tools_registry():("intel_aoi_delete", "aoi.delete_aoi"),("intel_aoi_brief", "aoi.fetch_aoi_brief"),("intel_aoi_escalation", "aoi.fetch_aoi_escalation"),+ ("intel_aoi_digest", "aoi.fetch_aoi_digest"),],)def test_aoi_tools_registered_and_dispatched(tool_name: str, fn_name: str) -> None:@@ -1672,3 +1673,100 @@ def test_store_migrates_pre_shape_schema(tmp_path: Path) -> None:# And new shapes write fine into the migrated table.assert "error" not in aoi.define_polygon_aoi(s, "PGH Square", _PGH_SQUARE)s.close()+++# ---------------------------------------------------------------------------+# intel_aoi_digest: one-call change sweep across all AOIs+# ---------------------------------------------------------------------------+++async def test_aoi_digest_no_aois_is_honest_empty(fetcher, store: AOIStore) -> None:+ result = await aoi.fetch_aoi_digest(fetcher, store)+ assert "error" not in result+ assert result["aois"] == []+ assert result["count"] == 0+ assert "No AOIs defined" in result["note"]+++async def test_aoi_digest_sweeps_all_aois_and_totals(+ fetcher, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ _patch_all_domains(monkeypatch)+ s = AOIStore(tmp_path / "digest.db")+ aoi.define_aoi(s, "Pittsburgh", _PGH_LAT, _PGH_LON, _PGH_RADIUS_KM)+ aoi.define_polygon_aoi(s, "PGH Square", _PGH_SQUARE)++ first = await aoi.fetch_aoi_digest(fetcher, s)+ assert first["count"] == 2+ assert all(entry["baseline"] for entry in first["aois"])+ assert first["totals"]["new_items"] == 0+ assert first["totals"]["departed_items"] == 0+ # Per-AOI sections in the digest markdown.+ assert "Pittsburgh" in first["markdown"]+ assert "PGH Square" in first["markdown"]++ # Second sweep: quake near1 replaced by near2 -> 1 new + 1 departed+ # per AOI that contains both points.+ async def _second_earthquakes(fetcher_, **kwargs):+ return {+ "earthquakes": [+ {+ "id": "near2",+ "magnitude": 4.1,+ "place": "near Pittsburgh again",+ "latitude": _NEAR_LAT,+ "longitude": _NEAR_LON,+ }+ ]+ }++ monkeypatch.setattr(seismology, "fetch_earthquakes", _second_earthquakes)+ second = await aoi.fetch_aoi_digest(fetcher, s)+ assert not any(entry["baseline"] for entry in second["aois"])+ assert second["totals"]["new_items"] == 2 # near2 entered both AOIs+ assert second["totals"]["departed_items"] == 2 # near1 left both+ pgh = next(e for e in second["aois"] if e["name"] == "Pittsburgh")+ assert pgh["changes"]["earthquakes"]["new"][0]["key"] == "near2"+ s.close()+++async def test_aoi_digest_names_filter_and_unknown_name(+ fetcher, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ _patch_all_domains(monkeypatch)+ s = AOIStore(tmp_path / "digest2.db")+ aoi.define_aoi(s, "Pittsburgh", _PGH_LAT, _PGH_LON, _PGH_RADIUS_KM)+ aoi.define_aoi(s, "Austin", 30.27, -97.74, 40.0)++ only = await aoi.fetch_aoi_digest(fetcher, s, names=["pittsburgh"])+ assert [e["name"] for e in only["aois"]] == ["Pittsburgh"]++ missing = await aoi.fetch_aoi_digest(fetcher, s, names=["Nowhere"])+ assert "error" in missing+ assert "Nowhere" in missing["error"]+ s.close()+++async def test_aoi_digest_domain_error_stays_per_aoi(+ fetcher, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """A failing domain shows up in that AOI's data_gaps without+ contaminating the other AOIs' results."""+ _patch_all_domains(monkeypatch)++ async def _broken_earthquakes(fetcher_, **kwargs):+ return {"error": "USGS down"}++ monkeypatch.setattr(seismology, "fetch_earthquakes", _broken_earthquakes)+ s = AOIStore(tmp_path / "digest3.db")+ aoi.define_aoi(s, "Pittsburgh", _PGH_LAT, _PGH_LON, _PGH_RADIUS_KM)++ result = await aoi.fetch_aoi_digest(fetcher, s)+ entry = result["aois"][0]+ assert any("Earthquakes" in g for g in entry["data_gaps"])+ assert "error" not in result # the digest itself succeeded+ s.close()diff --git a/src/world_intel_mcp/tools/aoi.py b/src/world_intel_mcp/tools/aoi.pyindex 431000d..7cb4f38 100644--- a/src/world_intel_mcp/tools/aoi.py+++ b/src/world_intel_mcp/tools/aoi.py@@ -181,6 +181,20 @@ TOOLS: list[Tool] = [},),# --- Situation Brief (1 tool) ---+ Tool(+ name="intel_aoi_digest",+ description="Run the change sweep across every defined AOI (or a named subset) in one call: per-AOI new/departed/unchanged items, counts, data_gaps, and a combined markdown digest. This IS a sweep - each AOI's change snapshot advances - so a scheduler can call this one tool on an interval to learn what entered or left all watched areas. First-ever sweep per AOI is an explicit baseline. Optional: names (list of AOI names; unknown names are an error, no AOIs defined is a note).",+ inputSchema={+ "type": "object",+ "properties": {+ "names": {+ "type": "array",+ "description": "Optional subset of AOI names to sweep",+ "items": {"type": "string"},+ },+ },+ },+ ),Tool(name="intel_situation_brief",description="Cited situational awareness brief, generated on demand over MCP (previously reachable only through the dashboard). Gathers a bounded server-side overview (earthquakes, military flights, ACLED conflict events, wildfires, cyber threats, disease outbreaks, news headlines, space weather, strategic posture, alert digest; not the dashboard's full 47-source fan-out), then synthesizes a 3-paragraph brief via local Ollama, or a mechanically-cited fallback summary when Ollama is unreachable. Returns brief, ai_generated, model, metrics_snapshot, a numbered sources list, and a cited flag that is true only when the brief text references a real source number.",@@ -278,6 +292,12 @@ async def _aoi_define_corridor(arguments: dict[str, Any]) -> Any:)+async def _aoi_digest(arguments: dict[str, Any]) -> Any:+ return await aoi.fetch_aoi_digest(+ runtime.fetcher, runtime.aoi_store, names=arguments.get("names")+ )++async def _aoi_changes(arguments: dict[str, Any]) -> Any:return await aoi.fetch_aoi_changes(runtime.fetcher, runtime.aoi_store, name=arguments.get("name")@@ -312,6 +332,7 @@ HANDLERS = {"intel_aoi_define_polygon": _aoi_define_polygon,"intel_aoi_define_corridor": _aoi_define_corridor,"intel_aoi_changes": _aoi_changes,+ "intel_aoi_digest": _aoi_digest,"intel_situation_brief": _situation_brief,"intel_generate_report": _generate_report,}