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.

Implements #16: user-defined AOI geofences

Phoenix Agent (Marcs-Mac-Studio)a9e5b1ef7dc6
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f802e69..1b16bd1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,6 +3,27 @@
## Unreleased
### Added
+- User-defined areas of interest (AOIs/geofences): `intel_aoi_define`,
+ `intel_aoi_list`, `intel_aoi_delete`, `intel_aoi_brief`, and
+ `intel_aoi_escalation` (+5 = 119 tools). Before this, only
+ `intel_signal_convergence` accepted a real point-plus-radius,
+ `intel_military_flights` took a bbox, and hotspot escalation scoring was
+ restricted to the 22 hardcoded `INTEL_HOTSPOTS`. `intel_aoi_define`
+ persists a named point-radius area (validated: lat -90..90, lon
+ -180..180, radius_km 1..2000) in a dedicated `aois` table inside the
+ existing SQLite cache database, rejecting a duplicate (case-insensitive)
+ name by echoing the existing definition back instead of overwriting it.
+ `intel_aoi_brief` composes a cited view of earthquakes, military flights
+ (bbox derived from the radius), wildfires (region-mapped, since NASA
+ FIRMS has no point+radius query), ACLED conflict events, sampled
+ aviation traffic, nearby static infrastructure (bases, ports, pipelines,
+ nuclear facilities, undersea cables, datacenters, spaceports) with
+ distances in km, and news headline mentions of the AOI name, all
+ filtered to the AOI's radius, with `data_gaps` naming every domain that
+ couldn't be geographically scoped. `intel_aoi_escalation` reuses the
+ existing `score_hotspot` scoring engine unmodified, scoped to the AOI's
+ own radius rather than the fixed 2-degree window used for the 22
+ built-in hotspots (#16).
- Situation briefs now cite their sources. `fetch_situation_brief` builds a
numbered `sources` list while walking the overview data: domain, a short
description or headline, a URL when the upstream item carries one, and a
diff --git a/CLAUDE.md b/CLAUDE.md
index 18c0c30..7ae8c57 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -4,7 +4,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
## What This Is
-World Intelligence MCP Server: 114 tools across 30+ domains providing real-time global intelligence from free public APIs. Serves four interfaces: MCP stdio (for Claude Code/Cursor), a live Starlette dashboard with SSE, a Click CLI with Rich output, and a collector daemon for 24/7 vector store population. Python 3.11+, built with hatchling.
+World Intelligence MCP Server: 119 tools across 30+ domains providing real-time global intelligence from free public APIs. Serves four interfaces: MCP stdio (for Claude Code/Cursor), a live Starlette dashboard with SSE, a Click CLI with Rich output, and a collector daemon for 24/7 vector store population. Python 3.11+, built with hatchling.
## Commands
diff --git a/README.md b/README.md
index 04e2576..7c47f9b 100644
--- a/README.md
+++ b/README.md
@@ -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 **114 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 **119 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, 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.
@@ -57,8 +57,9 @@ Built for AI agents that need world awareness: market conditions, geopolitical r
| **Cross-Domain Analytics** | 3 | Correlation, domain summary, trend detection |
| **Reports** | 1 | PDF/HTML multi-domain intelligence reports |
| **Daily Digest** | 1 | Cited markdown morning brief: top events, headlines, trends, and timeline |
+| **AOI Geofences** | 5 | User-defined areas of interest: define/list/delete, a cited multi-domain brief, and hotspot escalation scoring for a user's own area |
-**Total: 114 tools** across 30+ intelligence domains.
+**Total: 119 tools** across 30+ intelligence domains.
---
@@ -426,6 +427,58 @@ collector.py (daemon) ─┘
|------|-------------|
| `intel_generate_report` | Generate a PDF or HTML intelligence report covering 18 domains in parallel |
+### AOI Geofences (5)
+| Tool | Description |
+|------|-------------|
+| `intel_aoi_define` | Define a named area of interest: point + radius in km (1-2000) |
+| `intel_aoi_list` | List all user-defined AOIs |
+| `intel_aoi_delete` | Delete a user-defined AOI by name |
+| `intel_aoi_brief` | Cited brief for an AOI: earthquakes, military flights, wildfires, conflict events, aviation, nearby infrastructure, and news mentions, all filtered to the AOI's radius |
+| `intel_aoi_escalation` | Hotspot escalation scoring (same engine as the 22 built-in hotspots) applied to a user AOI |
+
+---
+
+## Watching your own area (geofences/AOIs)
+
+28 of the 119 tools take some geographic parameter, but before the AOI
+family only `intel_signal_convergence` accepted a real point-plus-radius,
+`intel_military_flights` took a bbox, and hotspot escalation scoring was
+restricted to the 22 hardcoded `INTEL_HOTSPOTS`. The `intel_aoi_*` tools
+let you name your own area (a city, a border region, a facility) and get
+the same cited, multi-domain treatment.
+
+Define an AOI once, then brief and score it on demand:
+
+```
+intel_aoi_define(name="Pittsburgh", lat=40.4406, lon=-79.9959, radius_km=50)
+intel_aoi_brief(name="Pittsburgh")
+intel_aoi_escalation(name="Pittsburgh")
+```
+
+`intel_aoi_brief` filters every geo-capable domain to the 50 km radius
+around Pittsburgh: earthquakes, military flights (bbox derived from the
+radius), wildfires (region-mapped, since NASA FIRMS has no point+radius
+query), ACLED conflict events, a sample of nearby aviation traffic,
+nearby static infrastructure (military bases, ports, pipelines, nuclear
+facilities, undersea cables, datacenters, spaceports) with distances in
+km, and news headline mentions of "Pittsburgh". Every item in the
+response carries a `[n]` citation into a numbered `sources` list, and
+`data_gaps` names any domain that couldn't be scoped to the AOI (for
+example, wildfires when the AOI falls outside NASA FIRMS's coverage
+regions, or conflict events when ACLED credentials aren't configured)
+instead of silently omitting it.
+
+`intel_aoi_escalation` runs the same baseline/military/conflict/social-
+unrest scoring engine that powers `intel_hotspot_escalation` for the 22
+built-in hotspots, but scoped to your AOI's own radius instead of a fixed
+2-degree window.
+
+AOIs persist in a dedicated table inside the same SQLite cache database
+the server already uses (`~/.cache/world-intel-mcp/cache.db` by default,
+or `$WORLD_INTEL_CACHE_DB`), so a scheduled agent can watch any named
+area across restarts with `intel_aoi_list` / `intel_aoi_delete` to manage
+them.
+
---
## Vector Store
diff --git a/ROADMAP.md b/ROADMAP.md
index 1a83e5f..a4618b1 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -2,7 +2,7 @@
**Benchmark**: [koala73/worldmonitor](https://github.com/koala73/worldmonitor)
**Updated**: 2026-06-04
-**Current tools**: 114 (113 intel + 1 status)
+**Current tools**: 119 (118 intel + 1 status)
---
@@ -20,7 +20,7 @@
| Area | Finding | Status | Action |
|------|---------|--------|--------|
-| MCP tool parity | 114 tools declared in `TOOLS`; 114 routed in `_dispatch()` | :white_check_mark: | Keep as an invariant |
+| MCP tool parity | 119 tools declared in `TOOLS`; 119 routed in `_dispatch()` | :white_check_mark: | Keep as an invariant |
| Optional vector runtime | Missing `qdrant-client` / `fastembed` previously surfaced as runtime failures | :white_check_mark: Fixed | Vector features now degrade cleanly and report availability |
| Base-environment test run | `pytest -q` fails collection without dev extras because `respx` is not installed | :yellow_circle: | Run `pip install -e ".[dev]"` before full-suite validation |
| Core verification | 226 non-smoke tests pass with dev extras installed | :white_check_mark: | Full default `pytest` run |
@@ -444,17 +444,34 @@ store is installed, recent trend detection and a timeline, degrading via
`data_gaps` rather than an empty section when the vector store isn't
available.
+### Phase 20: AOI Geofences (+5 = 119 tools)
+`intel_aoi_define`, `intel_aoi_list`, `intel_aoi_delete`, `intel_aoi_brief`, `intel_aoi_escalation`
+
+User-defined areas of interest (AOIs), the intel-community term for what
+consumer software calls a geofence. Before this phase, only
+`intel_signal_convergence` accepted a real point-plus-radius, only
+`intel_military_flights` took a bbox, and hotspot escalation scoring was
+restricted to the 22 hardcoded `INTEL_HOTSPOTS`. `intel_aoi_define`
+persists a named point-radius area in a dedicated table inside the
+existing SQLite cache database; `intel_aoi_brief` composes a cited view
+of earthquakes, military flights (bbox-derived), wildfires
+(region-mapped), ACLED conflict events, sampled aviation, nearby static
+infrastructure with distances in km, and news headline mentions, all
+filtered to the AOI's radius, with `data_gaps` for domains that can't be
+geographically scoped. `intel_aoi_escalation` reuses the existing
+`score_hotspot` scoring engine unmodified for a user AOI (#16).
+
---
## Summary
| Category | Current | Notes |
|----------|---------|-------|
-| Total MCP tools | 114 | 113 intelligence tools + `intel_status` |
-| Tool parity | 114 / 114 | `TOOLS` and `_dispatch()` are aligned |
+| Total MCP tools | 119 | 118 intelligence tools + `intel_status` |
+| Tool parity | 119 / 119 | `TOOLS` and `_dispatch()` are aligned |
| Static datasets | 18 | Bases, ports, pipelines, nuclear, cables, datacenters, spaceports, minerals, exchanges, trade routes, cloud regions, financial centers |
| RSS feeds | 119 | 24 categories |
-| Tests in repo | 269 | 251 non-smoke tests + 18 live smoke tests; full suite requires `.[dev]` |
+| Tests in repo | 321 | 303 non-smoke tests + 18 live smoke tests; full suite requires `.[dev]` |
| Primary remaining gap | Architecture | `server.py` monolith remains the main refactor target |
-**Bottom line**: 114 tools across 30+ domains, with the roadmap now aligned to the live MCP registry. The main remaining gaps are full-environment test bootstrapping (`.[dev]`) and continued modularization of the monolithic `server.py` tool registry/dispatcher.
+**Bottom line**: 119 tools across 30+ domains, with the roadmap now aligned to the live MCP registry. The main remaining gaps are full-environment test bootstrapping (`.[dev]`) and continued modularization of the monolithic `server.py` tool registry/dispatcher.
diff --git a/src/world_intel_mcp/analysis/aoi.py b/src/world_intel_mcp/analysis/aoi.py
new file mode 100644
index 0000000..e356951
--- /dev/null
+++ b/src/world_intel_mcp/analysis/aoi.py
@@ -0,0 +1,877 @@
+"""User-defined areas of interest (AOIs): geofences (issue #16).
+
+The intel community calls this an AOI; consumer software calls it a
+geofence. This module composes the same domain fetch functions used
+elsewhere in the codebase (seismology, military, conflict, wildfire,
+aviation, news) around a user-named point-plus-radius, the way
+``analysis/daily_digest.py`` composes them around "right now" instead of
+"this place". It lives in ``analysis/`` rather than ``sources/`` because,
+like ``daily_digest.py`` and ``situation.py``, its job is cross-domain
+composition and citation, not talking to a single upstream API.
+
+Follows the same citation discipline as ``situation.py``/``daily_digest.py``:
+every listed item carries a ``[n]`` reference into a numbered ``sources``
+list, and ``cited`` is only true when the brief text actually contains one.
+``data_gaps`` names every domain that could not be geographically scoped
+rather than silently omitting it.
+
+AOI persistence (``AOIStore``) uses a dedicated ``aois`` table in the same
+SQLite database file the process-wide ``Cache`` already opened, using the
+same ``db_path`` and the same WAL / busy_timeout pragmas, via its own connection.
+SQLite's WAL mode is explicitly designed for multiple connections against
+one file, which is already how this repo's ``Cache`` coexists with
+external readers. A dedicated table (not cache-entry abuse) because an AOI
+is a named row a user expects to list and delete, not a TTL'd blob; a
+separate connection (not new methods bolted onto ``Cache``) because
+``Cache`` is a generic TTL key-value store and mixing a structured CRUD
+table into it would blur that class's one job, at the cost of a well-
+tested 188-line module untouched by this change.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import math
+import sqlite3
+import time
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any
+
+from .escalation import score_hotspot
+from .situation import _add_source, _cite, _has_valid_citation
+
+logger = logging.getLogger("world-intel-mcp.analysis.aoi")
+
+MIN_RADIUS_KM = 1.0
+MAX_RADIUS_KM = 2000.0
+
+_EARTH_RADIUS_KM = 6371.0
+_KM_PER_DEGREE_LAT = 111.0
+
+
+def _utc_now_iso() -> str:
+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+# ---------------------------------------------------------------------------
+# Geo helpers
+# ---------------------------------------------------------------------------
+
+
+def haversine_km(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
+ """Great-circle distance between two points, in kilometers."""
+ dlat = math.radians(lat2 - lat1)
+ dlon = math.radians(lon2 - lon1)
+ a = (
+ math.sin(dlat / 2) ** 2
+ + math.cos(math.radians(lat1))
+ * math.cos(math.radians(lat2))
+ * math.sin(dlon / 2) ** 2
+ )
+ return _EARTH_RADIUS_KM * 2 * math.asin(math.sqrt(min(1.0, a)))
+
+
+def bbox_from_radius_km(lat: float, lon: float, radius_km: float) -> str:
+ """Derive a ``lamin,lomin,lamax,lomax`` bounding box (the format
+ ``sources/military.py``'s ``fetch_military_flights(bbox=...)`` takes)
+ that fully contains a circle of ``radius_km`` around (lat, lon).
+
+ Longitude degrees shrink toward the poles; the cosine factor is
+ clamped so a near-polar AOI gets a wide-but-finite box instead of a
+ division blowup. This is a bounding rectangle, not the circle itself;
+ callers that need the exact radius still haversine-filter the
+ candidates it returns (see ``filter_by_radius``), the same way
+ ``analysis/convergence.py``'s grid cells are a coarse pre-filter, not
+ the final answer.
+ """
+ dlat = radius_km / _KM_PER_DEGREE_LAT
+ cos_lat = max(math.cos(math.radians(lat)), 0.01)
+ dlon = radius_km / (_KM_PER_DEGREE_LAT * cos_lat)
+ lamin = max(-90.0, lat - dlat)
+ lamax = min(90.0, lat + dlat)
+ lomin = max(-180.0, lon - dlon)
+ lomax = min(180.0, lon + dlon)
+ return f"{lamin:.4f},{lomin:.4f},{lamax:.4f},{lomax:.4f}"
+
+
+def _distance_or_none(
+ lat: float, lon: float, item_lat: Any, item_lon: Any
+) -> float | None:
+ if item_lat is None or item_lon is None:
+ return None
+ try:
+ return haversine_km(lat, lon, float(item_lat), float(item_lon))
+ except (TypeError, ValueError):
+ return None
+
+
+def filter_by_radius(
+ items: list[dict],
+ lat: float,
+ lon: float,
+ radius_km: float,
+ lat_key: str = "latitude",
+ lon_key: str = "longitude",
+) -> list[dict]:
+ """Keep only items whose coordinates fall within ``radius_km`` of
+ (lat, lon), each annotated with ``distance_km`` and sorted nearest
+ first. Items with missing or unparseable coordinates are dropped, not
+ silently kept: an AOI brief that includes events it can't place on
+ the map isn't a geofence, it's a global feed with extra steps."""
+ out = []
+ for item in items:
+ dist = _distance_or_none(lat, lon, item.get(lat_key), item.get(lon_key))
+ if dist is not None and dist <= radius_km:
+ out.append({**item, "distance_km": round(dist, 1)})
+ out.sort(key=lambda i: i["distance_km"])
+ return out
+
+
+# ---------------------------------------------------------------------------
+# Validation
+# ---------------------------------------------------------------------------
+
+
+def validate_aoi_params(name: Any, lat: Any, lon: Any, radius_km: Any) -> str | None:
+ """Return a human-readable error message, or ``None`` if the AOI
+ parameters are valid. Never raises: every branch it can take from
+ missing/wrong-typed MCP arguments ends in a string, not an exception,
+ so callers can return ``{"error": ...}`` uniformly."""
+ if not isinstance(name, str) or not name.strip():
+ return "name must be a non-empty string."
+ for label, value in (("lat", lat), ("lon", lon), ("radius_km", radius_km)):
+ if not isinstance(value, (int, float)) or isinstance(value, bool):
+ return f"{label} must be a number (got {value!r})."
+ if not (-90.0 <= lat <= 90.0):
+ return f"lat must be between -90 and 90 (got {lat})."
+ if not (-180.0 <= lon <= 180.0):
+ return f"lon must be between -180 and 180 (got {lon})."
+ if not (MIN_RADIUS_KM <= radius_km <= MAX_RADIUS_KM):
+ return (
+ f"radius_km must be between {MIN_RADIUS_KM} and "
+ f"{MAX_RADIUS_KM} (got {radius_km})."
+ )
+ return None
+
+
+# ---------------------------------------------------------------------------
+# Persistence: dedicated table in the shared cache database
+# ---------------------------------------------------------------------------
+
+
+class AOIAlreadyExists(Exception):
+ """Raised by ``AOIStore.define()`` when the (case-insensitive) name is
+ already taken. Carries the existing row so the caller can echo it back
+ politely instead of just saying no."""
+
+ def __init__(self, existing: dict[str, Any]):
+ self.existing = existing
+ super().__init__(f"AOI '{existing['name']}' already exists")
+
+
+class AOIStore:
+ """Named point-radius geofences, persisted in a dedicated ``aois``
+ table inside the same SQLite file the process's ``Cache`` uses (pass
+ its resolved ``db_path`` in, not a fresh default-path computation,
+ so this always lands in the literal file the running cache settled
+ on, fallback path included).
+ """
+
+ def __init__(self, db_path: Path):
+ self.db_path = Path(db_path)
+ self.db_path.parent.mkdir(parents=True, exist_ok=True)
+ self._conn = sqlite3.connect(str(self.db_path), timeout=10)
+ self._conn.execute("PRAGMA journal_mode=WAL")
+ self._conn.execute("PRAGMA busy_timeout=5000")
+ self._conn.execute("PRAGMA synchronous=NORMAL")
+ self._conn.execute(
+ """
+ CREATE TABLE IF NOT EXISTS aois (
+ name_key TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ lat REAL NOT NULL,
+ lon REAL NOT NULL,
+ radius_km REAL NOT NULL,
+ created_at REAL NOT NULL
+ )
+ """
+ )
+ self._conn.commit()
+
+ @staticmethod
+ def _key(name: str) -> str:
+ return name.strip().lower()
+
+ @staticmethod
+ def _row_to_dict(row: tuple) -> dict[str, Any]:
+ _name_key, name, lat, lon, radius_km, created_at = row
+ return {
+ "name": name,
+ "lat": lat,
+ "lon": lon,
+ "radius_km": radius_km,
+ "created_at": created_at,
+ }
+
+ def define(
+ self, name: str, lat: float, lon: float, radius_km: float
+ ) -> dict[str, Any]:
+ """Insert a new AOI. Raises ``AOIAlreadyExists`` (carrying the
+ existing row) if the name is already taken."""
+ existing = self.get(name)
+ if existing is not None:
+ raise AOIAlreadyExists(existing)
+ clean_name = name.strip()
+ now = time.time()
+ self._conn.execute(
+ "INSERT INTO aois (name_key, name, lat, lon, radius_km, created_at) "
+ "VALUES (?, ?, ?, ?, ?, ?)",
+ (self._key(name), clean_name, lat, lon, radius_km, now),
+ )
+ self._conn.commit()
+ return {
+ "name": clean_name,
+ "lat": lat,
+ "lon": lon,
+ "radius_km": radius_km,
+ "created_at": now,
+ }
+
+ def get(self, name: str) -> dict[str, Any] | None:
+ row = self._conn.execute(
+ "SELECT name_key, name, lat, lon, radius_km, created_at "
+ "FROM aois WHERE name_key = ?",
+ (self._key(name),),
+ ).fetchone()
+ return self._row_to_dict(row) if row else None
+
+ def list_all(self) -> list[dict[str, Any]]:
+ rows = self._conn.execute(
+ "SELECT name_key, name, lat, lon, radius_km, created_at "
+ "FROM aois ORDER BY name"
+ ).fetchall()
+ return [self._row_to_dict(r) for r in rows]
+
+ def delete(self, name: str) -> bool:
+ cur = self._conn.execute(
+ "DELETE FROM aois WHERE name_key = ?", (self._key(name),)
+ )
+ self._conn.commit()
+ return cur.rowcount > 0
+
+ def close(self) -> None:
+ self._conn.close()
+
+
+# ---------------------------------------------------------------------------
+# Tool-facing: define / list / delete
+# ---------------------------------------------------------------------------
+
+
+def define_aoi(store: AOIStore, name: Any, lat: Any, lon: Any, radius_km: Any) -> dict:
+ error = validate_aoi_params(name, lat, lon, radius_km)
+ if error:
+ return {"error": error}
+ try:
+ aoi = store.define(name, float(lat), float(lon), float(radius_km))
+ except AOIAlreadyExists as exc:
+ return {
+ "error": f"AOI '{name.strip()}' already exists.",
+ "existing": exc.existing,
+ }
+ return {"aoi": aoi, "source": "aoi-define", "timestamp": _utc_now_iso()}
+
+
+def list_aois(store: AOIStore) -> dict:
+ aois = store.list_all()
+ return {
+ "aois": aois,
+ "count": len(aois),
+ "source": "aoi-list",
+ "timestamp": _utc_now_iso(),
+ }
+
+
+def delete_aoi(store: AOIStore, name: Any) -> dict:
+ if not isinstance(name, str) or not name.strip():
+ return {"error": "name must be a non-empty string."}
+ deleted = store.delete(name)
+ if not deleted:
+ return {"error": f"AOI '{name}' not found."}
+ return {
+ "deleted": name.strip(),
+ "source": "aoi-delete",
+ "timestamp": _utc_now_iso(),
+ }
+
+
+# ---------------------------------------------------------------------------
+# Nearby static infrastructure: pure, no I/O, config datasets only
+# ---------------------------------------------------------------------------
+
+
+def _nearby_points(
+ items: list[dict],
+ lat: float,
+ lon: float,
+ radius_km: float,
+ extra_keys: tuple[str, ...] = (),
+) -> list[dict]:
+ out = []
+ for item in items:
+ dist = _distance_or_none(lat, lon, item.get("lat"), item.get("lon"))
+ if dist is None or dist > radius_km:
+ continue
+ entry = {"name": item.get("name"), "distance_km": round(dist, 1)}
+ for key in extra_keys:
+ entry[key] = item.get(key)
+ out.append(entry)
+ out.sort(key=lambda e: e["distance_km"])
+ return out
+
+
+def nearby_bases(lat: float, lon: float, radius_km: float) -> list[dict]:
+ from ..config.geospatial import MILITARY_BASES
+
+ return _nearby_points(
+ MILITARY_BASES, lat, lon, radius_km, extra_keys=("country", "operator", "type")
+ )
+
+
+def nearby_ports(lat: float, lon: float, radius_km: float) -> list[dict]:
+ from ..config.geospatial import STRATEGIC_PORTS
+
+ return _nearby_points(
+ STRATEGIC_PORTS, lat, lon, radius_km, extra_keys=("country", "type")
+ )
+
+
+def nearby_nuclear(lat: float, lon: float, radius_km: float) -> list[dict]:
+ from ..config.geospatial import NUCLEAR_FACILITIES
+
+ return _nearby_points(
+ NUCLEAR_FACILITIES,
+ lat,
+ lon,
+ radius_km,
+ extra_keys=("country", "type", "status"),
+ )
+
+
+def nearby_datacenters(lat: float, lon: float, radius_km: float) -> list[dict]:
+ from ..config.datacenters import AI_DATACENTERS
+
+ return _nearby_points(AI_DATACENTERS, lat, lon, radius_km, extra_keys=("country",))
+
+
+def nearby_spaceports(lat: float, lon: float, radius_km: float) -> list[dict]:
+ from ..config.spaceports import SPACEPORTS
+
+ return _nearby_points(
+ SPACEPORTS, lat, lon, radius_km, extra_keys=("country", "status")
+ )
+
+
+def nearby_pipelines(lat: float, lon: float, radius_km: float) -> list[dict]:
+ """Pipelines are line features; proximity is approximated from each
+ pipeline's two published endpoints (``lat_start``/``lon_start``,
+ ``lat_end``/``lon_end``); the config dataset carries no intermediate
+ waypoints. A pipeline that passes through the AOI without either
+ endpoint nearby is missed by this approximation; documented here
+ rather than silently wrong."""
+ from ..config.geospatial import PIPELINES
+
+ out = []
+ for p in PIPELINES:
+ d_start = _distance_or_none(lat, lon, p.get("lat_start"), p.get("lon_start"))
+ d_end = _distance_or_none(lat, lon, p.get("lat_end"), p.get("lon_end"))
+ candidates = [d for d in (d_start, d_end) if d is not None]
+ if not candidates:
+ continue
+ dist = min(candidates)
+ if dist <= radius_km:
+ out.append(
+ {
+ "name": p.get("name"),
+ "distance_km": round(dist, 1),
+ "route": p.get("route"),
+ "type": p.get("type"),
+ "status": p.get("status"),
+ }
+ )
+ out.sort(key=lambda e: e["distance_km"])
+ return out
+
+
+def nearby_cables(lat: float, lon: float, radius_km: float) -> list[dict]:
+ """Cables are multi-point routes; proximity is the closest published
+ landing point, not the undersea path between landing points."""
+ from ..config.cables import UNDERSEA_CABLES
+
+ out = []
+ for cable in UNDERSEA_CABLES:
+ best_dist: float | None = None
+ best_landing: str | None = None
+ for lp in cable.get("landing_points", []):
+ dist = _distance_or_none(lat, lon, lp.get("lat"), lp.get("lon"))
+ if dist is not None and (best_dist is None or dist < best_dist):
+ best_dist = dist
+ best_landing = lp.get("name")
+ if best_dist is not None and best_dist <= radius_km:
+ out.append(
+ {
+ "name": cable.get("name"),
+ "distance_km": round(best_dist, 1),
+ "nearest_landing_point": best_landing,
+ "status": cable.get("status"),
+ }
+ )
+ out.sort(key=lambda e: e["distance_km"])
+ return out
+
+
+def nearby_infrastructure(
+ lat: float, lon: float, radius_km: float
+) -> dict[str, list[dict]]:
+ """All seven static infrastructure categories near an AOI, each item
+ carrying ``distance_km``. Pure: no I/O, static config datasets only."""
+ return {
+ "military_bases": nearby_bases(lat, lon, radius_km),
+ "ports": nearby_ports(lat, lon, radius_km),
+ "pipelines": nearby_pipelines(lat, lon, radius_km),
+ "nuclear_facilities": nearby_nuclear(lat, lon, radius_km),
+ "undersea_cables": nearby_cables(lat, lon, radius_km),
+ "datacenters": nearby_datacenters(lat, lon, radius_km),
+ "spaceports": nearby_spaceports(lat, lon, radius_km),
+ }
+
+
+_INFRA_LABELS = {
+ "military_bases": "Military Bases",
+ "ports": "Ports",
+ "pipelines": "Pipelines",
+ "nuclear_facilities": "Nuclear Facilities",
+ "undersea_cables": "Undersea Cables",
+ "datacenters": "Datacenters",
+ "spaceports": "Spaceports",
+}
+
+
+# ---------------------------------------------------------------------------
+# Wildfires: region-mapping (FIRMS has no point+radius query)
+# ---------------------------------------------------------------------------
+
+
+def _overlapping_wildfire_regions(
+ lat: float, lon: float, radius_km: float
+) -> list[str]:
+ """Which of ``sources/wildfire.py``'s ``REGIONS`` continental bboxes
+ the AOI's bounding box overlaps. FIRMS has no point+radius query, and
+ ``fetch_wildfires`` exposes only these 9 continental regions, so an
+ AOI is "region-mappable" whenever its box intersects at least one of
+ them: true for all populated land; an AOI in open ocean far from any
+ region is the honest gap."""
+ from ..sources.wildfire import REGIONS
+
+ dlat = radius_km / _KM_PER_DEGREE_LAT
+ cos_lat = max(math.cos(math.radians(lat)), 0.01)
+ dlon = radius_km / (_KM_PER_DEGREE_LAT * cos_lat)
+ a_west, a_south, a_east, a_north = lon - dlon, lat - dlat, lon + dlon, lat + dlat
+
+ overlapping = []
+ for region_name, bbox in REGIONS.items():
+ west, south, east, north = (float(x) for x in bbox.split(","))
+ if a_west <= east and a_east >= west and a_south <= north and a_north >= south:
+ overlapping.append(region_name)
+ return overlapping
+
+
+async def _safe_fetch(coro, label: str) -> dict:
+ try:
+ result = await coro
+ return result if isinstance(result, dict) else {}
+ except Exception as exc:
+ logger.warning("AOI brief: %s failed: %s", label, exc)
+ return {"error": str(exc)}
+
+
+async def _fetch_wildfires_for_aoi(fetcher, wildfire_regions: list[str]) -> dict:
+ from ..sources import wildfire
+
+ if not wildfire_regions:
+ return {"error": "AOI does not overlap any FIRMS coverage region"}
+
+ results = await asyncio.gather(
+ *[wildfire.fetch_wildfires(fetcher, region=r) for r in wildfire_regions]
+ )
+ clusters: list[dict] = []
+ errors: list[str] = []
+ for res in results:
+ if not isinstance(res, dict):
+ continue
+ if res.get("error"):
+ errors.append(res["error"])
+ continue
+ for region_data in res.get("fires_by_region", {}).values():
+ clusters.extend(region_data.get("top_clusters", []))
+ if not clusters and errors:
+ return {"error": "; ".join(sorted(set(errors)))}
+ return {"clusters": clusters}
+
+
+# ---------------------------------------------------------------------------
+# intel_aoi_brief
+# ---------------------------------------------------------------------------
+
+
+async def fetch_aoi_brief(fetcher, store: AOIStore, name: Any) -> dict:
+ """Compose a cited brief for a user-defined AOI: earthquakes, military
+ flights (bbox-derived), wildfires (region-mapped), ACLED conflict
+ events, sampled aviation traffic, nearby static infrastructure, and
+ news headline mentions of the AOI name. Every listed item carries a
+ ``[n]`` citation; ``data_gaps`` names every domain that could not be
+ scoped to the AOI rather than silently omitting it.
+ """
+ if not isinstance(name, str) or not name.strip():
+ return {"error": "name must be a non-empty string."}
+
+ aoi = store.get(name)
+ if aoi is None:
+ return {
+ "error": f"AOI '{name}' not found. Use intel_aoi_list to see defined areas."
+ }
+
+ from ..sources import aviation, conflict, military, news, seismology
+
+ lat, lon, radius_km = aoi["lat"], aoi["lon"], aoi["radius_km"]
+ aoi_name = aoi["name"]
+ bbox = bbox_from_radius_km(lat, lon, radius_km)
+ wildfire_regions = _overlapping_wildfire_regions(lat, lon, radius_km)
+
+ (
+ eq_result,
+ mil_result,
+ conflict_result,
+ wildfire_result,
+ aviation_result,
+ news_result,
+ ) = await asyncio.gather(
+ _safe_fetch(seismology.fetch_earthquakes(fetcher, hours=72), "earthquakes"),
+ _safe_fetch(
+ military.fetch_military_flights(fetcher, bbox=bbox), "military_flights"
+ ),
+ _safe_fetch(conflict.fetch_acled_events(fetcher, days=7), "acled_events"),
+ _safe_fetch(_fetch_wildfires_for_aoi(fetcher, wildfire_regions), "wildfires"),
+ _safe_fetch(aviation.fetch_domestic_flights(fetcher), "domestic_flights"),
+ _safe_fetch(
+ news.fetch_gdelt_search(fetcher, query=aoi_name, mode="artlist", limit=10),
+ "news",
+ ),
+ )
+
+ sources: list[dict] = []
+ citations: dict[str, list[int]] = {}
+ data_gaps: list[str] = []
+ counts: dict[str, int] = {}
+ sections: dict[str, list[str]] = {}
+
+ def _line(domain: str, text: str) -> None:
+ sections.setdefault(domain, []).append(text)
+
+ # Earthquakes ------------------------------------------------------
+ if isinstance(eq_result, dict) and eq_result.get("error"):
+ data_gaps.append(f"Earthquakes: {eq_result['error']}")
+ counts["earthquakes"] = 0
+ else:
+ eq_events = (
+ eq_result.get("earthquakes", []) if isinstance(eq_result, dict) else []
+ )
+ eq_in_range = filter_by_radius(
+ eq_events, lat, lon, radius_km, "latitude", "longitude"
+ )
+ counts["earthquakes"] = len(eq_in_range)
+ for eq in eq_in_range:
+ n = _add_source(
+ sources,
+ "earthquakes",
+ f"M{eq.get('magnitude')} earthquake, {eq.get('place') or 'unknown location'} "
+ f"({eq['distance_km']} km from {aoi_name})",
+ url=eq.get("url"),
+ timestamp=eq.get("time"),
+ )
+ _cite(citations, "earthquakes", n)
+ _line(
+ "earthquakes",
+ f"- [{n}] M{eq.get('magnitude')} {eq.get('place')} ({eq['distance_km']} km)",
+ )
+
+ # Military flights ---------------------------------------------------
+ if isinstance(mil_result, dict) and mil_result.get("error"):
+ data_gaps.append(f"Military flights: {mil_result['error']}")
+ counts["military_flights"] = 0
+ else:
+ mil_aircraft = (
+ mil_result.get("aircraft", []) if isinstance(mil_result, dict) else []
+ )
+ mil_in_range = filter_by_radius(
+ mil_aircraft, lat, lon, radius_km, "latitude", "longitude"
+ )
+ counts["military_flights"] = len(mil_in_range)
+ if mil_in_range:
+ n = _add_source(
+ sources,
+ "military_flights",
+ f"{len(mil_in_range)} military aircraft within {radius_km} km of {aoi_name}",
+ )
+ _cite(citations, "military_flights", n)
+ for ac in mil_in_range[:10]:
+ _line(
+ "military_flights",
+ f"- [{n}] {ac.get('callsign') or ac.get('icao24')} "
+ f"({ac.get('origin_country') or 'unknown origin'}, {ac['distance_km']} km)",
+ )
+
+ # Conflict (ACLED) ----------------------------------------------------
+ if isinstance(conflict_result, dict) and conflict_result.get("error"):
+ data_gaps.append(f"Conflict events: {conflict_result['error']}")
+ counts["conflict_events"] = 0
+ else:
+ conflict_events = (
+ conflict_result.get("events", [])
+ if isinstance(conflict_result, dict)
+ else []
+ )
+ conflict_in_range = filter_by_radius(
+ conflict_events, lat, lon, radius_km, "latitude", "longitude"
+ )
+ counts["conflict_events"] = len(conflict_in_range)
+ for ev in conflict_in_range[:10]:
+ loc = (
+ ev.get("location")
+ or ev.get("admin1")
+ or ev.get("country")
+ or "unspecified location"
+ )
+ n = _add_source(
+ sources,
+ "conflict_events",
+ f"{ev.get('event_type') or 'conflict event'}, {loc} "
+ f"({ev['distance_km']} km from {aoi_name})",
+ timestamp=ev.get("event_date"),
+ )
+ _cite(citations, "conflict_events", n)
+ _line(
+ "conflict_events",
+ f"- [{n}] {ev.get('event_type')}, {loc} ({ev['distance_km']} km)",
+ )
+
+ # Wildfires ------------------------------------------------------------
+ if isinstance(wildfire_result, dict) and wildfire_result.get("error"):
+ data_gaps.append(f"Wildfires: {wildfire_result['error']}")
+ counts["wildfires"] = 0
+ else:
+ clusters = (
+ wildfire_result.get("clusters", [])
+ if isinstance(wildfire_result, dict)
+ else []
+ )
+ fire_in_range = filter_by_radius(clusters, lat, lon, radius_km, "lat", "lon")
+ counts["wildfires"] = len(fire_in_range)
+ for fc in fire_in_range:
+ n = _add_source(
+ sources,
+ "wildfires",
+ f"{fc.get('fire_count')} fire detections ({fc['distance_km']} km from {aoi_name})",
+ )
+ _cite(citations, "wildfires", n)
+ _line(
+ "wildfires",
+ f"- [{n}] {fc.get('fire_count')} detections, max FRP {fc.get('max_frp')} ({fc['distance_km']} km)",
+ )
+
+ # Aviation (sampled) ---------------------------------------------------
+ if isinstance(aviation_result, dict) and aviation_result.get("error"):
+ data_gaps.append(f"Aviation: {aviation_result['error']}")
+ counts["aviation"] = 0
+ else:
+ sampled = (
+ aviation_result.get("sampled", [])
+ if isinstance(aviation_result, dict)
+ else []
+ )
+ aviation_in_range = filter_by_radius(sampled, lat, lon, radius_km, "lat", "lon")
+ counts["aviation"] = len(aviation_in_range)
+ if aviation_in_range:
+ n = _add_source(
+ sources,
+ "aviation",
+ f"{len(aviation_in_range)} sampled aircraft within {radius_km} km of {aoi_name} "
+ "(1-in-10 global sample, not exhaustive)",
+ )
+ _cite(citations, "aviation", n)
+ _line(
+ "aviation",
+ f"- [{n}] {len(aviation_in_range)} sampled aircraft observed",
+ )
+
+ # News headline mentions -----------------------------------------------
+ articles = news_result.get("articles", []) if isinstance(news_result, dict) else []
+ counts["news"] = len(articles)
+ for art in articles[:10]:
+ title = art.get("title")
+ if not title:
+ continue
+ n = _add_source(
+ sources, "news", title, url=art.get("url"), timestamp=art.get("seendate")
+ )
+ _cite(citations, "news", n)
+ _line("news", f"- [{n}] {title} ({art.get('domain') or 'unknown source'})")
+
+ # Nearby static infrastructure -------------------------------------
+ infra = nearby_infrastructure(lat, lon, radius_km)
+ for category, items in infra.items():
+ counts[category] = len(items)
+ for item in items:
+ n = _add_source(
+ sources,
+ category,
+ f"{item['name']} ({item['distance_km']} km from {aoi_name})",
+ )
+ _cite(citations, category, n)
+ _line(category, f"- [{n}] {item['name']} ({item['distance_km']} km)")
+
+ # --- Markdown ---------------------------------------------------------
+ md_parts = [
+ f"# AOI Brief: {aoi_name}",
+ f"Center: {lat}, {lon} (radius {radius_km} km)",
+ "",
+ ]
+ section_order = [
+ ("earthquakes", "Earthquakes"),
+ ("military_flights", "Military Flights"),
+ ("conflict_events", "Conflict Events (ACLED)"),
+ ("wildfires", "Wildfires"),
+ ("aviation", "Aviation (sampled)"),
+ ("news", "News Headline Mentions"),
+ *[(k, v) for k, v in _INFRA_LABELS.items()],
+ ]
+ for domain, label in section_order:
+ lines = sections.get(domain)
+ md_parts.append(f"## {label}")
+ md_parts.append("\n".join(lines) if lines else "_None observed in range._")
+ md_parts.append("")
+
+ if data_gaps:
+ md_parts.append("## Data Gaps")
+ md_parts.extend(f"- {gap}" for gap in data_gaps)
+
+ markdown = "\n".join(md_parts)
+ cited = _has_valid_citation(markdown, len(sources))
+
+ return {
+ "aoi": {"name": aoi_name, "lat": lat, "lon": lon, "radius_km": radius_km},
+ "markdown": markdown,
+ "counts": counts,
+ "sources": sources,
+ "cited": cited,
+ "data_gaps": data_gaps,
+ "source": "aoi-brief",
+ "timestamp": _utc_now_iso(),
+ }
+
+
+# ---------------------------------------------------------------------------
+# intel_aoi_escalation (optional, reuses analysis/escalation.py unmodified)
+# ---------------------------------------------------------------------------
+
+
+async def fetch_aoi_escalation(fetcher, store: AOIStore, name: Any) -> dict:
+ """Run the existing hotspot escalation scoring (``score_hotspot`` in
+ ``analysis/escalation.py``, unmodified) on a user-defined AOI instead
+ of only the 22 built-in intel hotspots. Gathers military and conflict
+ signals scoped to the AOI's own radius (via haversine), rather than
+ the fixed 2-degree window ``fetch_hotspot_escalation`` uses for the
+ built-ins."""
+ if not isinstance(name, str) or not name.strip():
+ return {"error": "name must be a non-empty string."}
+
+ aoi = store.get(name)
+ if aoi is None:
+ return {
+ "error": f"AOI '{name}' not found. Use intel_aoi_list to see defined areas."
+ }
+
+ from ..sources import conflict as conflict_mod
+ from ..sources import military as mil_mod
+
+ lat, lon, radius_km = aoi["lat"], aoi["lon"], aoi["radius_km"]
+ aoi_name = aoi["name"]
+ bbox = bbox_from_radius_km(lat, lon, radius_km)
+
+ acled_result, mil_result = await asyncio.gather(
+ _safe_fetch(conflict_mod.fetch_acled_events(fetcher, days=7), "acled_events"),
+ _safe_fetch(
+ mil_mod.fetch_military_flights(fetcher, bbox=bbox), "military_flights"
+ ),
+ )
+
+ data_gaps: list[str] = []
+ conflict_count = fatalities = protests = 0
+ if isinstance(acled_result, dict) and acled_result.get("error"):
+ data_gaps.append(f"Conflict events: {acled_result['error']}")
+ else:
+ events = filter_by_radius(
+ acled_result.get("events", []) if isinstance(acled_result, dict) else [],
+ lat,
+ lon,
+ radius_km,
+ "latitude",
+ "longitude",
+ )
+ for ev in events:
+ if "protest" in (ev.get("event_type") or "").lower():
+ protests += 1
+ else:
+ conflict_count += 1
+ fatalities += ev.get("fatalities") or 0
+
+ military_count = 0
+ if isinstance(mil_result, dict) and mil_result.get("error"):
+ data_gaps.append(f"Military flights: {mil_result['error']}")
+ else:
+ aircraft = filter_by_radius(
+ mil_result.get("aircraft", []) if isinstance(mil_result, dict) else [],
+ lat,
+ lon,
+ radius_km,
+ "latitude",
+ "longitude",
+ )
+ military_count = len(aircraft)
+
+ hotspot_config = {
+ "lat": lat,
+ "lon": lon,
+ "baseline_escalation": 0,
+ "associated_countries": [],
+ }
+ scored = score_hotspot(
+ hotspot_config,
+ news_mentions=None,
+ military_count=military_count,
+ conflict_events=conflict_count,
+ convergence_score=None,
+ fatalities=fatalities,
+ protests=protests,
+ )
+
+ return {
+ "aoi": {"name": aoi_name, "lat": lat, "lon": lon, "radius_km": radius_km},
+ "unavailable_components": ["news", "convergence"],
+ "data_gaps": data_gaps,
+ "source": "aoi-escalation",
+ "timestamp": _utc_now_iso(),
+ **scored,
+ }
diff --git a/src/world_intel_mcp/server.py b/src/world_intel_mcp/server.py
index 9a7af7a..77ff366 100644
--- a/src/world_intel_mcp/server.py
+++ b/src/world_intel_mcp/server.py
@@ -38,6 +38,13 @@ Phase 20: Cited situation briefs and intel_daily_digest (+1 = 114 tools). Situat
now carry a numbered sources list and an honest cited flag; the new digest tool
composes a cited markdown morning brief, degrading via data_gaps when the vector
store is unavailable.
+Phase 21: AOI geofences (+5 = 119 tools). intel_aoi_define/list/delete persist named
+ point-radius areas in a dedicated table of the shared cache database.
+ intel_aoi_brief composes a cited, radius-filtered view of earthquakes, military
+ flights, wildfires, ACLED conflict events, sampled aviation, nearby static
+ infrastructure, and news mentions for a user's own area, with data_gaps for
+ domains that can't be scoped. intel_aoi_escalation reuses the existing hotspot
+ scoring unmodified for a user AOI (#16).
"""
import asyncio
@@ -50,6 +57,7 @@ from mcp.server import Server
from mcp.server.stdio import stdio_server
from mcp.types import Tool, TextContent
+from .analysis import aoi
from .cache import Cache
from .circuit_breaker import CircuitBreaker
from .fetcher import Fetcher
@@ -97,6 +105,10 @@ logger = logging.getLogger("world-intel-mcp")
server = Server("world-intel-mcp")
cache = Cache()
breaker = CircuitBreaker(failure_threshold=3, cooldown_seconds=300)
+# Same physical SQLite file the Cache above resolved to (fallback path
+# included); see analysis/aoi.py's module docstring for why AOIs live in
+# a dedicated table there rather than as Cache entries.
+_aoi_store = aoi.AOIStore(cache.db_path)
# Vector store — optional, degrades gracefully if Qdrant unavailable.
_vector_store = None
@@ -1741,6 +1753,71 @@ TOOLS: list[Tool] = [
description="Cited markdown morning brief: top current events by domain (earthquakes, military, conflict, wildfires, cyber, health, air/traffic), recent headlines, and, when the optional vector store is installed, recent activity trends and a 24h timeline. Every listed item carries a [n] citation into a numbered sources list. Degrades honestly via data_gaps when the vector store or a domain fetch is unavailable, instead of showing an empty section as a quiet day.",
inputSchema={"type": "object", "properties": {}},
),
+ # --- AOI Geofences (5 tools) ---
+ Tool(
+ name="intel_aoi_define",
+ description="Define a named area of interest (AOI/geofence): a point plus a radius in kilometers, persisted for intel_aoi_brief, intel_aoi_escalation, intel_aoi_list, and intel_aoi_delete. Required: name, lat (-90..90), lon (-180..180), radius_km (1..2000). Rejects a duplicate name (case-insensitive) politely, echoing the existing definition instead of overwriting it.",
+ inputSchema={
+ "type": "object",
+ "properties": {
+ "name": {
+ "type": "string",
+ "description": "Unique AOI name (case-insensitive)",
+ },
+ "lat": {
+ "type": "number",
+ "description": "Center latitude, -90..90",
+ },
+ "lon": {
+ "type": "number",
+ "description": "Center longitude, -180..180",
+ },
+ "radius_km": {
+ "type": "number",
+ "description": "Radius in kilometers, 1..2000",
+ },
+ },
+ "required": ["name", "lat", "lon", "radius_km"],
+ },
+ ),
+ Tool(
+ name="intel_aoi_list",
+ description="List all user-defined areas of interest (AOIs/geofences).",
+ inputSchema={"type": "object", "properties": {}},
+ ),
+ Tool(
+ name="intel_aoi_delete",
+ description="Delete a user-defined area of interest by name.",
+ inputSchema={
+ "type": "object",
+ "properties": {
+ "name": {"type": "string", "description": "AOI name to delete"},
+ },
+ "required": ["name"],
+ },
+ ),
+ Tool(
+ name="intel_aoi_brief",
+ description="Cited brief for a user-defined AOI: earthquakes, military flights (bbox-derived), wildfires (region-mapped), ACLED conflict events, sampled aviation traffic, nearby static infrastructure (bases, ports, pipelines, nuclear, cables, datacenters, spaceports) with distances in km, and news headline mentions of the AOI name. Every item carries a [n] citation into a numbered sources list; data_gaps names every domain that could not be scoped to the AOI rather than omitting it silently. Required: name (must already be defined via intel_aoi_define).",
+ inputSchema={
+ "type": "object",
+ "properties": {
+ "name": {"type": "string", "description": "AOI name"},
+ },
+ "required": ["name"],
+ },
+ ),
+ Tool(
+ name="intel_aoi_escalation",
+ description="Run the hotspot escalation scoring (baseline, military, conflict, social-unrest components; 0-100) on a user-defined AOI instead of only the 22 built-in intel hotspots. News-mention and geo-convergence components are not wired up and report null, same as intel_hotspot_escalation. Required: name (must already be defined via intel_aoi_define).",
+ inputSchema={
+ "type": "object",
+ "properties": {
+ "name": {"type": "string", "description": "AOI name"},
+ },
+ "required": ["name"],
+ },
+ ),
# --- Reports (1 tool) ---
Tool(
name="intel_generate_report",
@@ -2441,6 +2518,28 @@ async def _dispatch(name: str, arguments: dict[str, Any]) -> Any:
return await fetch_daily_digest(fetcher, vector_store=_vector_store)
+ # AOI Geofences
+ case "intel_aoi_define":
+ return aoi.define_aoi(
+ _aoi_store,
+ name=arguments.get("name"),
+ lat=arguments.get("lat"),
+ lon=arguments.get("lon"),
+ radius_km=arguments.get("radius_km"),
+ )
+ case "intel_aoi_list":
+ return aoi.list_aois(_aoi_store)
+ case "intel_aoi_delete":
+ return aoi.delete_aoi(_aoi_store, name=arguments.get("name"))
+ case "intel_aoi_brief":
+ return await aoi.fetch_aoi_brief(
+ fetcher, _aoi_store, name=arguments.get("name")
+ )
+ case "intel_aoi_escalation":
+ return await aoi.fetch_aoi_escalation(
+ fetcher, _aoi_store, name=arguments.get("name")
+ )
+
# System
# Reports
case "intel_generate_report":
diff --git a/src/world_intel_mcp/tests/test_aoi.py b/src/world_intel_mcp/tests/test_aoi.py
new file mode 100644
index 0000000..c13e314
--- /dev/null
+++ b/src/world_intel_mcp/tests/test_aoi.py
@@ -0,0 +1,611 @@
+"""Tests for analysis/aoi.py and the intel_aoi_* tool family (issue #16).
+
+Persistence tests exercise ``AOIStore`` directly against a ``tmp_path``
+SQLite file (same pattern as ``test_cache.py``'s ``cache`` fixture).
+Composition tests (``fetch_aoi_brief`` / ``fetch_aoi_escalation``) mock at
+the source-function boundary via monkeypatch, matching the pattern
+``test_daily_digest.py`` established for this exact class of function:
+aoi.py composes existing ``sources/*.py`` fetch functions rather than
+making HTTP calls itself, so there is no network edge for respx to sit at.
+"""
+
+from pathlib import Path
+
+import pytest
+
+from world_intel_mcp.analysis import aoi
+from world_intel_mcp.analysis.aoi import AOIAlreadyExists, AOIStore
+from world_intel_mcp.sources import (
+ aviation,
+ conflict,
+ military,
+ news,
+ seismology,
+ wildfire,
+)
+
+_SERVER_PY = Path(__file__).resolve().parents[1] / "server.py"
+
+# Pittsburgh, matching the README worked example (issue #16).
+_PGH_LAT = 40.4406
+_PGH_LON = -79.9959
+_PGH_RADIUS_KM = 50.0
+
+# ~7 km from Pittsburgh, inside a 50 km radius.
+_NEAR_LAT, _NEAR_LON = 40.50, -80.00
+# ~330 km from Pittsburgh (Detroit area), outside a 50 km radius.
+_FAR_LAT, _FAR_LON = 42.33, -83.05
+
+
+def store(tmp_path: Path) -> AOIStore:
+ s = AOIStore(tmp_path / "test_aoi_cache.db")
+ yield s
+ s.close()
+
+
+# ---------------------------------------------------------------------------
+# Geo helpers
+# ---------------------------------------------------------------------------
+
+
+def test_haversine_km_zero_distance() -> None:
+ assert aoi.haversine_km(40.44, -79.99, 40.44, -79.99) == pytest.approx(
+ 0.0, abs=1e-6
+ )
+
+
+def test_haversine_km_known_pair() -> None:
+ # NYC (40.7128, -74.0060) to LA (34.0522, -118.2437) is ~3936 km.
+ dist = aoi.haversine_km(40.7128, -74.0060, 34.0522, -118.2437)
+ assert dist == pytest.approx(3936, rel=0.01)
+
+
+def test_bbox_from_radius_km_widens_at_low_latitude_and_narrows_near_pole() -> None:
+ equator_box = aoi.bbox_from_radius_km(0.0, 0.0, 100.0)
+ polar_box = aoi.bbox_from_radius_km(85.0, 0.0, 100.0)
+ eq_lomin, eq_lomax = (
+ float(equator_box.split(",")[1]),
+ float(equator_box.split(",")[3]),
+ )
+ pl_lomin, pl_lomax = float(polar_box.split(",")[1]), float(polar_box.split(",")[3])
+ # Same radius spans far more longitude near the pole than at the equator.
+ assert (pl_lomax - pl_lomin) > (eq_lomax - eq_lomin)
+
+
+def test_bbox_from_radius_km_clamps_to_valid_ranges() -> None:
+ box = aoi.bbox_from_radius_km(89.5, 179.5, 2000.0)
+ lamin, lomin, lamax, lomax = (float(x) for x in box.split(","))
+ assert -90.0 <= lamin <= lamax <= 90.0
+ assert -180.0 <= lomin <= lomax <= 180.0
+
+
+def test_filter_by_radius_includes_near_excludes_far() -> None:
+ """The load-bearing pair: a fence that does not exclude is not a fence."""
+ items = [
+ {"latitude": _NEAR_LAT, "longitude": _NEAR_LON, "id": "near"},
+ {"latitude": _FAR_LAT, "longitude": _FAR_LON, "id": "far"},
+ ]
+ result = aoi.filter_by_radius(items, _PGH_LAT, _PGH_LON, _PGH_RADIUS_KM)
+ ids = [r["id"] for r in result]
+ assert "near" in ids
+ assert "far" not in ids
+ assert result[0]["distance_km"] < _PGH_RADIUS_KM
+
+
+def test_filter_by_radius_drops_items_missing_coordinates() -> None:
+ items = [{"latitude": None, "longitude": None, "id": "no-coords"}]
+ result = aoi.filter_by_radius(items, _PGH_LAT, _PGH_LON, _PGH_RADIUS_KM)
+ assert result == []
+
+
+# ---------------------------------------------------------------------------
+# Validation
+# ---------------------------------------------------------------------------
+
+
+def test_validate_aoi_params_accepts_valid_input() -> None:
+ assert (
+ aoi.validate_aoi_params("Pittsburgh", _PGH_LAT, _PGH_LON, _PGH_RADIUS_KM)
+ is None
+ )
+
+
+ "name,lat,lon,radius_km",
+ [
+ ("", 40.0, -80.0, 50.0),
+ (" ", 40.0, -80.0, 50.0),
+ ("X", 91.0, -80.0, 50.0),
+ ("X", -91.0, -80.0, 50.0),
+ ("X", 40.0, 181.0, 50.0),
+ ("X", 40.0, -181.0, 50.0),
+ ("X", 40.0, -80.0, 0.5),
+ ("X", 40.0, -80.0, 2001.0),
+ ("X", "not-a-number", -80.0, 50.0),
+ ("X", 40.0, None, 50.0),
+ (123, 40.0, -80.0, 50.0),
+ ],
+)
+def test_validate_aoi_params_rejects_invalid_input(name, lat, lon, radius_km) -> None:
+ assert aoi.validate_aoi_params(name, lat, lon, radius_km) is not None
+
+
+# ---------------------------------------------------------------------------
+# AOIStore persistence
+# ---------------------------------------------------------------------------
+
+
+def test_define_and_get_round_trip(store: AOIStore) -> None:
+ defined = store.define("Pittsburgh", _PGH_LAT, _PGH_LON, _PGH_RADIUS_KM)
+ assert defined["name"] == "Pittsburgh"
+ fetched = store.get("Pittsburgh")
+ assert fetched["lat"] == _PGH_LAT
+ assert fetched["lon"] == _PGH_LON
+ assert fetched["radius_km"] == _PGH_RADIUS_KM
+
+
+def test_get_is_case_insensitive(store: AOIStore) -> None:
+ store.define("Pittsburgh", _PGH_LAT, _PGH_LON, _PGH_RADIUS_KM)
+ assert store.get("pittsburgh") is not None
+ assert store.get("PITTSBURGH") is not None
+
+
+def test_get_missing_returns_none(store: AOIStore) -> None:
+ assert store.get("Nowhere") is None
+
+
+def test_list_all_sorted_by_name(store: AOIStore) -> None:
+ store.define("Zurich", 47.37, 8.54, 25.0)
+ store.define("Austin", 30.27, -97.74, 40.0)
+ names = [a["name"] for a in store.list_all()]
+ assert names == ["Austin", "Zurich"]
+
+
+def test_delete_round_trip(store: AOIStore) -> None:
+ store.define("Pittsburgh", _PGH_LAT, _PGH_LON, _PGH_RADIUS_KM)
+ assert store.delete("Pittsburgh") is True
+ assert store.get("Pittsburgh") is None
+
+
+def test_delete_nonexistent_returns_false(store: AOIStore) -> None:
+ assert store.delete("Nowhere") is False
+
+
+def test_define_duplicate_raises_with_existing_echoed(store: AOIStore) -> None:
+ store.define("Pittsburgh", _PGH_LAT, _PGH_LON, _PGH_RADIUS_KM)
+ with pytest.raises(AOIAlreadyExists) as exc_info:
+ store.define("pittsburgh", 0.0, 0.0, 10.0)
+ assert exc_info.value.existing["name"] == "Pittsburgh"
+ assert exc_info.value.existing["lat"] == _PGH_LAT
+
+
+# ---------------------------------------------------------------------------
+# Tool-facing define / list / delete
+# ---------------------------------------------------------------------------
+
+
+def test_define_aoi_success(store: AOIStore) -> None:
+ result = aoi.define_aoi(store, "Pittsburgh", _PGH_LAT, _PGH_LON, _PGH_RADIUS_KM)
+ assert "error" not in result
+ assert result["aoi"]["name"] == "Pittsburgh"
+
+
+def test_define_aoi_validation_rejection_does_not_touch_store(store: AOIStore) -> None:
+ result = aoi.define_aoi(store, "Bad", 999.0, -80.0, 50.0)
+ assert "error" in result
+ assert store.get("Bad") is None
+
+
+def test_define_aoi_duplicate_echoes_existing_politely(store: AOIStore) -> None:
+ aoi.define_aoi(store, "Pittsburgh", _PGH_LAT, _PGH_LON, _PGH_RADIUS_KM)
+ result = aoi.define_aoi(store, "Pittsburgh", 0.0, 0.0, 10.0)
+ assert "error" in result
+ assert result["existing"]["lat"] == _PGH_LAT
+ assert result["existing"]["radius_km"] == _PGH_RADIUS_KM
+
+
+def test_list_aois_reports_count(store: AOIStore) -> None:
+ aoi.define_aoi(store, "Pittsburgh", _PGH_LAT, _PGH_LON, _PGH_RADIUS_KM)
+ aoi.define_aoi(store, "Austin", 30.27, -97.74, 40.0)
+ result = aoi.list_aois(store)
+ assert result["count"] == 2
+ assert {a["name"] for a in result["aois"]} == {"Pittsburgh", "Austin"}
+
+
+def test_delete_aoi_not_found(store: AOIStore) -> None:
+ result = aoi.delete_aoi(store, "Nowhere")
+ assert "error" in result
+
+
+def test_delete_aoi_success(store: AOIStore) -> None:
+ aoi.define_aoi(store, "Pittsburgh", _PGH_LAT, _PGH_LON, _PGH_RADIUS_KM)
+ result = aoi.delete_aoi(store, "Pittsburgh")
+ assert result["deleted"] == "Pittsburgh"
+
+
+# ---------------------------------------------------------------------------
+# Nearby static infrastructure (pure, real config datasets)
+# ---------------------------------------------------------------------------
+
+
+def test_nearby_bases_finds_norfolk_at_its_own_coordinates() -> None:
+ # Norfolk Naval Station: lat 36.95, lon -76.33 (config/geospatial.py).
+ result = aoi.nearby_bases(36.95, -76.33, 5.0)
+ names = [b["name"] for b in result]
+ assert "Norfolk Naval Station" in names
+
+
+def test_nearby_bases_excludes_far_away_base() -> None:
+ result = aoi.nearby_bases(_PGH_LAT, _PGH_LON, 5.0)
+ assert result == []
+
+
+def test_nearby_pipelines_matches_on_either_endpoint() -> None:
+ # TAPS pipeline ends at Valdez (61.13, -146.35); a tight radius there
+ # should match via the endpoint-proximity approximation.
+ result = aoi.nearby_pipelines(61.13, -146.35, 5.0)
+ names = [p["name"] for p in result]
+ assert "Trans-Alaska (TAPS)" in names
+
+
+def test_nearby_cables_matches_closest_landing_point() -> None:
+ # MAREA lands at Bilbao, Spain and Virginia Beach, USA.
+ result = aoi.nearby_cables(36.95, -76.0, 60.0)
+ assert any(c["name"] == "MAREA" for c in result)
+
+
+def test_nearby_infrastructure_has_all_seven_categories() -> None:
+ result = aoi.nearby_infrastructure(_PGH_LAT, _PGH_LON, _PGH_RADIUS_KM)
+ assert set(result.keys()) == {
+ "military_bases",
+ "ports",
+ "pipelines",
+ "nuclear_facilities",
+ "undersea_cables",
+ "datacenters",
+ "spaceports",
+ }
+
+
+# ---------------------------------------------------------------------------
+# Wildfire region mapping
+# ---------------------------------------------------------------------------
+
+
+def test_overlapping_wildfire_regions_finds_north_america_for_pittsburgh() -> None:
+ regions = aoi._overlapping_wildfire_regions(_PGH_LAT, _PGH_LON, _PGH_RADIUS_KM)
+ assert "north_america" in regions
+
+
+# ---------------------------------------------------------------------------
+# fetch_aoi_brief: composition, citations, data_gaps
+# ---------------------------------------------------------------------------
+
+
+async def _fake_earthquakes(fetcher, **kwargs):
+ return {
+ "earthquakes": [
+ {
+ "id": "near1",
+ "magnitude": 3.2,
+ "place": "near Pittsburgh",
+ "time": "2026-08-16T01:00:00Z",
+ "latitude": _NEAR_LAT,
+ "longitude": _NEAR_LON,
+ "url": "https://earthquake.usgs.gov/near1",
+ },
+ {
+ "id": "far1",
+ "magnitude": 5.0,
+ "place": "near Detroit",
+ "time": "2026-08-16T01:00:00Z",
+ "latitude": _FAR_LAT,
+ "longitude": _FAR_LON,
+ "url": "https://earthquake.usgs.gov/far1",
+ },
+ ],
+ "count": 2,
+ "source": "usgs",
+ }
+
+
+async def _fake_military(fetcher, bbox=None):
+ return {
+ "aircraft": [
+ {
+ "icao24": "aaa111",
+ "callsign": "RCH123",
+ "origin_country": "United States",
+ "latitude": _NEAR_LAT,
+ "longitude": _NEAR_LON,
+ },
+ {
+ "icao24": "bbb222",
+ "callsign": "RCH999",
+ "origin_country": "United States",
+ "latitude": _FAR_LAT,
+ "longitude": _FAR_LON,
+ },
+ ],
+ "count": 2,
+ "source": "adsb.lol",
+ }
+
+
+async def _fake_acled(fetcher, **kwargs):
+ return {
+ "events": [
+ {
+ "event_type": "Protests",
+ "location": "Near Pittsburgh",
+ "admin1": "Pennsylvania",
+ "country": "United States",
+ "event_date": "2026-08-15",
+ "latitude": _NEAR_LAT,
+ "longitude": _NEAR_LON,
+ "fatalities": 0,
+ },
+ {
+ "event_type": "Battles",
+ "location": "Near Detroit",
+ "admin1": "Michigan",
+ "country": "United States",
+ "event_date": "2026-08-15",
+ "latitude": _FAR_LAT,
+ "longitude": _FAR_LON,
+ "fatalities": 2,
+ },
+ ],
+ "count": 2,
+ "source": "acled",
+ }
+
+
+async def _fake_wildfires(fetcher, region=None):
+ return {
+ "fires_by_region": {
+ region or "north_america": {
+ "count": 2,
+ "top_clusters": [
+ {
+ "lat": _NEAR_LAT,
+ "lon": _NEAR_LON,
+ "fire_count": 4,
+ "max_frp": 12.5,
+ },
+ {
+ "lat": _FAR_LAT,
+ "lon": _FAR_LON,
+ "fire_count": 9,
+ "max_frp": 40.0,
+ },
+ ],
+ }
+ },
+ "total_fires": 2,
+ "source": "nasa-firms",
+ }
+
+
+async def _fake_domestic_flights(fetcher):
+ return {
+ "total_aircraft": 2,
+ "sampled": [
+ {"lat": _NEAR_LAT, "lon": _NEAR_LON, "callsign": "UAL1", "origin": "USA"},
+ {"lat": _FAR_LAT, "lon": _FAR_LON, "callsign": "UAL2", "origin": "USA"},
+ ],
+ "source": "opensky-domestic",
+ }
+
+
+async def _fake_gdelt(fetcher, **kwargs):
+ return {
+ "articles": [
+ {
+ "title": "Pittsburgh flooding warning issued",
+ "url": "https://news.example/pgh",
+ "seendate": "20260816T010000Z",
+ "domain": "news.example",
+ }
+ ],
+ "count": 1,
+ "source": "gdelt",
+ }
+
+
+def aoi_store_with_pittsburgh(tmp_path: Path) -> AOIStore:
+ s = AOIStore(tmp_path / "test_aoi_brief_cache.db")
+ s.define("Pittsburgh", _PGH_LAT, _PGH_LON, _PGH_RADIUS_KM)
+ yield s
+ s.close()
+
+
+def _patch_all_domains(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(seismology, "fetch_earthquakes", _fake_earthquakes)
+ monkeypatch.setattr(military, "fetch_military_flights", _fake_military)
+ monkeypatch.setattr(conflict, "fetch_acled_events", _fake_acled)
+ monkeypatch.setattr(wildfire, "fetch_wildfires", _fake_wildfires)
+ monkeypatch.setattr(aviation, "fetch_domestic_flights", _fake_domestic_flights)
+ monkeypatch.setattr(news, "fetch_gdelt_search", _fake_gdelt)
+
+
+async def test_fetch_aoi_brief_not_found(fetcher, store: AOIStore) -> None:
+ result = await aoi.fetch_aoi_brief(fetcher, store, "Nowhere")
+ assert "error" in result
+
+
+async def test_fetch_aoi_brief_includes_in_radius_excludes_out_of_radius(
+ fetcher, aoi_store_with_pittsburgh: AOIStore, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The load-bearing pair, at the tool level: every synthetic domain
+ carries one event inside the 50 km radius and one ~330 km outside it.
+ Only the in-radius ones may appear."""
+ _patch_all_domains(monkeypatch)
+
+ result = await aoi.fetch_aoi_brief(fetcher, aoi_store_with_pittsburgh, "Pittsburgh")
+
+ assert result["counts"]["earthquakes"] == 1
+ assert result["counts"]["military_flights"] == 1
+ assert result["counts"]["conflict_events"] == 1
+ assert result["counts"]["wildfires"] == 1
+ assert result["counts"]["aviation"] == 1
+
+ assert "near Pittsburgh" in result["markdown"]
+ assert "near Detroit" not in result["markdown"]
+ assert "Near Pittsburgh" in result["markdown"]
+ assert "Near Detroit" not in result["markdown"]
+
+
+async def test_fetch_aoi_brief_is_cited(
+ fetcher, aoi_store_with_pittsburgh: AOIStore, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ _patch_all_domains(monkeypatch)
+ result = await aoi.fetch_aoi_brief(fetcher, aoi_store_with_pittsburgh, "Pittsburgh")
+ assert result["cited"] is True
+ assert len(result["sources"]) > 0
+ # Every source has a real, resolvable citation number.
+ max_n = len(result["sources"])
+ assert all(1 <= s["n"] <= max_n for s in result["sources"])
+
+
+async def test_fetch_aoi_brief_reports_data_gap_for_unscopable_domain(
+ fetcher, aoi_store_with_pittsburgh: AOIStore, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ _patch_all_domains(monkeypatch)
+
+ async def _broken_acled(fetcher, **kwargs):
+ return {
+ "error": "ACLED credentials not configured (ACLED_EMAIL + ACLED_PASSWORD)"
+ }
+
+ monkeypatch.setattr(conflict, "fetch_acled_events", _broken_acled)
+
+ result = await aoi.fetch_aoi_brief(fetcher, aoi_store_with_pittsburgh, "Pittsburgh")
+
+ assert any("Conflict events" in gap for gap in result["data_gaps"])
+ assert not any(s["domain"] == "conflict_events" for s in result["sources"])
+
+
+async def test_fetch_aoi_brief_reports_data_gap_when_no_wildfire_region_overlaps(
+ fetcher, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ _patch_all_domains(monkeypatch)
+ s = AOIStore(tmp_path / "test_open_ocean.db")
+ # Deep South Pacific, far from all 9 REGIONS bboxes in wildfire.py.
+ s.define("Open Ocean", -55.0, -140.0, 50.0)
+
+ result = await aoi.fetch_aoi_brief(fetcher, s, "Open Ocean")
+
+ assert any("Wildfires" in gap for gap in result["data_gaps"])
+ s.close()
+
+
+async def test_fetch_aoi_brief_includes_nearby_infrastructure(
+ fetcher, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ _patch_all_domains(monkeypatch)
+ s = AOIStore(tmp_path / "test_norfolk.db")
+ s.define("Norfolk", 36.95, -76.33, 5.0)
+
+ result = await aoi.fetch_aoi_brief(fetcher, s, "Norfolk")
+
+ assert result["counts"]["military_bases"] >= 1
+ assert "Norfolk Naval Station" in result["markdown"]
+ s.close()
+
+
+# ---------------------------------------------------------------------------
+# fetch_aoi_escalation: reuses analysis/escalation.py unmodified
+# ---------------------------------------------------------------------------
+
+
+async def test_fetch_aoi_escalation_not_found(fetcher, store: AOIStore) -> None:
+ result = await aoi.fetch_aoi_escalation(fetcher, store, "Nowhere")
+ assert "error" in result
+
+
+async def test_fetch_aoi_escalation_scores_only_in_radius_signals(
+ fetcher, aoi_store_with_pittsburgh: AOIStore, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(conflict, "fetch_acled_events", _fake_acled)
+ monkeypatch.setattr(military, "fetch_military_flights", _fake_military)
+
+ result = await aoi.fetch_aoi_escalation(
+ fetcher, aoi_store_with_pittsburgh, "Pittsburgh"
+ )
+
+ assert "error" not in result
+ # 1 in-radius military aircraft -> military component = min(20, 1*1.0) = 1.0
+ assert result["components"]["military"] == pytest.approx(1.0)
+ # 1 in-radius protest event, 0 conflict events, 0 fatalities in radius
+ # -> conflict component = min(20, 0*0.5 + 0*0.1) = 0.0
+ assert result["components"]["conflict"] == pytest.approx(0.0)
+ assert result["components"]["news"] is None
+ assert result["components"]["convergence"] is None
+ assert set(result["unavailable_components"]) == {"news", "convergence"}
+
+
+async def test_fetch_aoi_escalation_reports_data_gap_on_fetch_failure(
+ fetcher, aoi_store_with_pittsburgh: AOIStore, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ async def _broken_military(fetcher, bbox=None):
+ return {"error": "adsb.lol and OpenSky both unavailable"}
+
+ monkeypatch.setattr(conflict, "fetch_acled_events", _fake_acled)
+ monkeypatch.setattr(military, "fetch_military_flights", _broken_military)
+
+ result = await aoi.fetch_aoi_escalation(
+ fetcher, aoi_store_with_pittsburgh, "Pittsburgh"
+ )
+
+ assert any("Military flights" in gap for gap in result["data_gaps"])
+
+
+# ---------------------------------------------------------------------------
+# Server registration / dispatch parity (matches test_daily_digest.py's
+# pattern: read server.py as text rather than importing it, since import
+# opens a live Cache()/AOIStore() at the default on-disk path).
+# ---------------------------------------------------------------------------
+
+
+ "tool_name,fn_name",
+ [
+ ("intel_aoi_define", "aoi.define_aoi"),
+ ("intel_aoi_list", "aoi.list_aois"),
+ ("intel_aoi_delete", "aoi.delete_aoi"),
+ ("intel_aoi_brief", "aoi.fetch_aoi_brief"),
+ ("intel_aoi_escalation", "aoi.fetch_aoi_escalation"),
+ ],
+)
+def test_aoi_tools_registered_and_dispatched(tool_name: str, fn_name: str) -> None:
+ """Structural parity check: the TOOLS/`_dispatch` 1:1 invariant this
+ repo maintains (see ROADMAP.md 'MCP tool parity') must hold for every
+ new AOI tool."""
+ text = _SERVER_PY.read_text()
+
+ assert f'name="{tool_name}"' in text
+
+ dispatch_idx = text.index(f'case "{tool_name}":')
+ assert dispatch_idx > 0
+ dispatch_body = text[dispatch_idx : dispatch_idx + 300]
+ assert fn_name in dispatch_body
+
+
+def test_aoi_store_instantiated_from_cache_db_path() -> None:
+ """The AOIStore must share the Cache's resolved db_path, not compute
+ its own default independently (which could diverge under
+ WORLD_INTEL_CACHE_DB or the tempdir fallback)."""
+ text = _SERVER_PY.read_text()
+ assert "_aoi_store = aoi.AOIStore(cache.db_path)" in text