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.

19.9 KB
Raw Blame
"""Conflict and crisis data sources for world-intel-mcp.

Fetches armed conflict events (ACLED), state-based violence data (UCDP),
and humanitarian dataset metadata (HDX) for the world-intel-mcp server.
"""

import asyncio
import logging
import os
import time
from datetime import datetime, timezone, timedelta

import httpx

from ..fetcher import Fetcher
from .freshness import json_answer_freshness

logger = logging.getLogger("world-intel-mcp.sources.conflict")


# ---------------------------------------------------------------------------
# ACLED: Armed Conflict Location & Event Data (OAuth2)
# ---------------------------------------------------------------------------

_ACLED_API_URL = "https://acleddata.com/api/acled/read"
_ACLED_TOKEN_URL = "https://acleddata.com/oauth/token"

# Module-level token cache (refreshed automatically)
_acled_token: str | None = None
_acled_token_expires: float = 0.0
_acled_refresh_token: str | None = None
_acled_token_lock = asyncio.Lock()


async def _acled_get_token() -> str | None:
    """Obtain or refresh an ACLED OAuth2 Bearer token.

    Uses password grant on first call, then refresh_token grant
    before expiry.  Tokens are cached module-wide.
    """
    global _acled_token, _acled_token_expires, _acled_refresh_token

    async with _acled_token_lock:
        # Still valid (with 5-min buffer)
        if _acled_token and time.time() < _acled_token_expires - 300:
            return _acled_token

        email = os.environ.get("ACLED_EMAIL")
        password = os.environ.get("ACLED_PASSWORD")

        # Try refresh_token grant first
        if _acled_refresh_token:
            body = {
                "grant_type": "refresh_token",
                "refresh_token": _acled_refresh_token,
                "client_id": "acled",
            }
        elif email and password:
            body = {
                "grant_type": "password",
                "username": email,
                "password": password,
                "client_id": "acled",
            }
        else:
            return None

        try:
            async with httpx.AsyncClient(timeout=15) as client:
                resp = await client.post(
                    _ACLED_TOKEN_URL,
                    data=body,
                    headers={"Content-Type": "application/x-www-form-urlencoded"},
                )
                resp.raise_for_status()
                data = resp.json()

            _acled_token = data["access_token"]
            _acled_token_expires = time.time() + data.get("expires_in", 86400)
            _acled_refresh_token = data.get("refresh_token", _acled_refresh_token)
            logger.info(
                "ACLED OAuth token acquired (expires in %ds)", data.get("expires_in", 0)
            )
            return _acled_token
        except Exception as exc:
            logger.warning("ACLED OAuth token request failed: %s", exc)
            # If refresh failed, try password grant as fallback
            if _acled_refresh_token and email and password:
                _acled_refresh_token = None
                return await _acled_get_token()
            return None


async def acled_query(
    fetcher: Fetcher, params: dict, cache_key: str, cache_ttl: int = 900
) -> dict | None:
    """Shared ACLED API query with OAuth2 auth.

    Returns parsed JSON or None on failure.  Used by both conflict and
    intelligence modules to avoid duplicating OAuth logic.
    """
    token = await _acled_get_token()
    if not token:
        return None
    return await fetcher.get_json(
        _ACLED_API_URL,
        source="acled",
        cache_key=cache_key,
        cache_ttl=cache_ttl,
        params=params,
        headers={"Authorization": f"Bearer {token}"},
    )


_ACLED_FAILURE_MESSAGES = {
    "acled_unconfigured": "ACLED credentials not configured (ACLED_EMAIL + ACLED_PASSWORD)",
    "acled_auth_failed": (
        "ACLED sign-in failed: ACLED_EMAIL and ACLED_PASSWORD are set, but the "
        "token request was refused or did not complete"
    ),
    "acled_fetch_failed": "ACLED fetch failed (rate limited, API error, or malformed response)",
}


def acled_failure_message(reason: str | None) -> str:
    """The error text for an ``acled_failure_reason()`` value."""
    return _ACLED_FAILURE_MESSAGES.get(reason or "", _ACLED_FAILURE_MESSAGES["acled_fetch_failed"])


def _acled_credentials_set() -> bool:
    return bool(
        (os.environ.get("ACLED_EMAIL") and os.environ.get("ACLED_PASSWORD"))
        or _acled_refresh_token
    )


async def acled_failure_reason(data: dict | list | None) -> str | None:
    """Classify why an ``acled_query()``/``fetch_acled_events()`` call returned no data.

    ``acled_query`` returns ``None`` for structurally different reasons that
    callers must not conflate: missing credentials (a config problem, not an
    outage), credentials that are set but whose token request failed (refused
    or unreachable sign-in), and a live fetch that failed after sign-in (a
    transient outage). Callers use this to pick an honest message/marker
    instead of guessing.

    Args:
        data: The value returned by ``acled_query()`` (or ``None``).

    Returns:
        ``None`` if *data* is present (no failure). Otherwise
        ``"acled_unconfigured"`` (no ``ACLED_EMAIL``/``ACLED_PASSWORD``),
        ``"acled_auth_failed"`` (both set, but no token could be obtained) or
        ``"acled_fetch_failed"`` (signed in, the request itself failed).
    """
    if data is not None:
        return None
    if not await _acled_get_token():
        if _acled_credentials_set():
            return "acled_auth_failed"
        return "acled_unconfigured"
    return "acled_fetch_failed"


async def fetch_acled_events(
    fetcher: Fetcher,
    country: str | None = None,
    days: int = 7,
    limit: int = 100,
) -> dict:
    """Fetch recent armed conflict events from the ACLED API.

    Requires ``ACLED_EMAIL`` and ``ACLED_PASSWORD`` in the environment.
    Free access can be obtained at https://acleddata.com.

    Args:
        fetcher: Shared HTTP fetcher with caching and circuit breaking.
        country: Optional country name to filter events.
        days: How far back to search (in days from now).
        limit: Maximum number of results.

    Returns:
        Dict with events list, count, query params, source, timestamp and
        ``fetched_at`` (when ACLED answered; earlier than ``timestamp`` for
        a cached answer). An expired cached copy served because ACLED did
        not answer carries ``_stale`` and ``_stale_age_seconds``.
    """
    now = datetime.now(timezone.utc)

    start_date = (now - timedelta(days=days)).strftime("%Y-%m-%d")
    end_date = now.strftime("%Y-%m-%d")

    params: dict = {
        "limit": limit,
        "event_date": f"{start_date}|{end_date}",
        "event_date_where": "BETWEEN",
    }
    if country:
        params["country"] = country

    cache_country = country or "global"
    # The limit is part of the key: a 15-event answer cached for one
    # caller must not be served to another that asked for 100.
    cache_key = f"conflict:acled:{cache_country}:{days}:{limit}"
    data = await acled_query(
        fetcher,
        params,
        cache_key=cache_key,
        cache_ttl=900,
    )
    if data is None:
        reason = await acled_failure_reason(data)
        if reason == "acled_unconfigured":
            return {
                "error": acled_failure_message(reason),
                "note": "Free access at acleddata.com",
                "reason": reason,
            }

        # Credentials are fine — the live fetch itself failed (rate limit,
        # 500, malformed payload, retries exhausted). Returning a bare
        # {"events": [], "count": 0} here would be byte-identical to a
        # genuine zero-match result, so callers can't tell an outage from
        # peace. Surface it explicitly instead; keep events/count in their
        # normal shape so existing callers that don't check "error" or
        # "reason" still iterate an empty list rather than crashing.
        logger.warning("ACLED API returned no data (%s)", reason)
        return {
            "error": acled_failure_message(reason),
            "degraded": True,
            "reason": reason,
            "events": [],
            "count": 0,
            "query": {"country": country, "days": days},
            "source": "acled",
            "timestamp": now.strftime("%Y-%m-%dT%H:%M:%SZ"),
        }

    events = []
    for event in data.get("data", []):
        fatalities_raw = event.get("fatalities")
        fatalities = int(fatalities_raw) if fatalities_raw is not None else 0
        events.append(
            {
                "event_id_cnty": event.get("event_id_cnty"),
                "event_date": event.get("event_date"),
                "event_type": event.get("event_type"),
                "sub_event_type": event.get("sub_event_type"),
                "actor1": event.get("actor1"),
                "actor2": event.get("actor2"),
                "country": event.get("country"),
                "admin1": event.get("admin1"),
                "admin2": event.get("admin2"),
                "location": event.get("location"),
                "latitude": event.get("latitude"),
                "longitude": event.get("longitude"),
                "fatalities": fatalities,
                "notes": event.get("notes"),
                "source": event.get("source"),
            }
        )

    # Sort by fatalities descending, then event_date descending
    # Negate fatalities for desc; negate date lexicographically is not possible,
    # so use a two-pass stable sort: secondary key first, primary key second.
    events.sort(key=lambda e: e.get("event_date") or "", reverse=True)
    events.sort(key=lambda e: e.get("fatalities") or 0, reverse=True)

    return {
        "events": events,
        "count": len(events),
        "query": {"country": country, "days": days},
        "source": "acled",
        "timestamp": now.strftime("%Y-%m-%dT%H:%M:%SZ"),
        **json_answer_freshness(fetcher, cache_key, data),
    }


# ---------------------------------------------------------------------------
# UCDP: Uppsala Conflict Data Program (GED API)
# ---------------------------------------------------------------------------

_UCDP_GED_URL = "https://ucdpapi.pcr.uu.se/api/gedevents/25.1"

_VIOLENCE_TYPES = {
    1: "state-based",
    2: "non-state",
    3: "one-sided",
}


async def fetch_ucdp_events(
    fetcher: Fetcher,
    days: int = 30,
    limit: int = 100,
) -> dict:
    """Fetch recent conflict events from the UCDP GED API.

    Sends ``UCDP_ACCESS_TOKEN`` when set; the API refuses requests
    without one (HTTP 401 since 2026). Fetches multiple pages in parallel
    when the dataset spans more than one page.

    Args:
        fetcher: Shared HTTP fetcher with caching and circuit breaking.
        days: Only include events whose ``date_start`` is within this
              many days from now.
        limit: Page size (max 1000 per page). Every page is requested,
               so this does not cap the number of events returned; a page
               that cannot be fetched is named in the result (below).

    Returns:
        Dict with events list, count, total fatalities, query params,
        source, and timestamp. When the first page cannot be fetched
        (no token, a refused token, an outage) it carries ``error``,
        ``degraded`` and ``reason`` (``ucdp_unconfigured`` or
        ``ucdp_fetch_failed``) next to the empty events list, the same
        shape as ACLED's fetch failure, so a failure never reads as zero
        events. When a later page cannot be fetched (an outage, or the
        circuit breaker skipping it), the events from the other pages are
        kept and the result carries ``degraded``, ``reason``
        ``ucdp_partial``, ``pages_failed``, ``pages_total`` and a
        ``data_gaps`` entry: count and fatalities are then lower bounds.
    """
    now = datetime.now(timezone.utc)
    cutoff = now - timedelta(days=days)

    ucdp_headers: dict[str, str] = {}
    ucdp_token = os.environ.get("UCDP_ACCESS_TOKEN")
    if ucdp_token:
        ucdp_headers["x-ucdp-access-token"] = ucdp_token

    # Every page, the first included, has its own cache key, and the key
    # carries the page size: pages of different sizes hold different
    # events.
    page_size = min(limit, 1000)

    # Fetch the first page to discover total pages (UCDP is slow — 30s timeout)
    page1_data = await fetcher.get_json(
        _UCDP_GED_URL,
        source="ucdp",
        cache_key=f"conflict:ucdp:{days}:{page_size}:page0",
        cache_ttl=21600,
        params={"pagesize": page_size, "page": 0},
        headers=ucdp_headers or None,
        timeout=30.0,
    )

    if page1_data is None:
        if ucdp_token:
            reason = "ucdp_fetch_failed"
            error = (
                "UCDP fetch failed (token refused, rate limited, API error, "
                "or malformed response)"
            )
        else:
            reason = "ucdp_unconfigured"
            error = (
                "UCDP_ACCESS_TOKEN is not set and the request failed; the UCDP "
                "API refuses requests without a token"
            )
        logger.warning("UCDP GED API returned no data (%s)", reason)
        return {
            "error": error,
            "degraded": True,
            "reason": reason,
            "events": [],
            "count": 0,
            "total_fatalities_best": 0,
            "query": {"days": days},
            "source": "ucdp",
            "timestamp": now.strftime("%Y-%m-%dT%H:%M:%SZ"),
        }

    total_pages = page1_data.get("TotalPages", 1)
    all_results = list(page1_data.get("Result", []))

    # Fetch remaining pages in parallel
    pages_failed: list[int] = []
    if total_pages > 1:
        page_tasks = [
            fetcher.get_json(
                _UCDP_GED_URL,
                source="ucdp",
                cache_key=f"conflict:ucdp:{days}:{page_size}:page{p}",
                cache_ttl=21600,
                params={"pagesize": page_size, "page": p},
                headers=ucdp_headers or None,
                timeout=30.0,
            )
            for p in range(1, total_pages)
        ]
        page_results = await asyncio.gather(*page_tasks)
        for page_number, page_data in enumerate(page_results, start=1):
            if isinstance(page_data, dict):
                all_results.extend(page_data.get("Result", []))
            else:
                pages_failed.append(page_number)

    # Filter to recent events and extract fields
    events = []
    total_fatalities_best = 0

    for record in all_results:
        date_start = record.get("date_start")
        if date_start is None:
            continue

        # Parse date_start and filter by cutoff
        try:
            event_date = datetime.strptime(date_start[:10], "%Y-%m-%d").replace(
                tzinfo=timezone.utc,
            )
        except (ValueError, TypeError):
            continue

        if event_date < cutoff:
            continue

        violence_type_raw = record.get("type_of_violence")
        violence_type_int = None
        if violence_type_raw is not None:
            try:
                violence_type_int = int(violence_type_raw)
            except (ValueError, TypeError):
                pass

        best = 0
        if record.get("best") is not None:
            try:
                best = int(record["best"])
            except (ValueError, TypeError):
                pass

        high = 0
        if record.get("high") is not None:
            try:
                high = int(record["high"])
            except (ValueError, TypeError):
                pass

        low = 0
        if record.get("low") is not None:
            try:
                low = int(record["low"])
            except (ValueError, TypeError):
                pass

        total_fatalities_best += best

        events.append(
            {
                "id": record.get("id"),
                "relid": record.get("relid"),
                "year": record.get("year"),
                "date_start": date_start,
                "date_end": record.get("date_end"),
                "country": record.get("country"),
                "region": record.get("region"),
                "type_of_violence": violence_type_int,
                "type_of_violence_label": _VIOLENCE_TYPES.get(
                    violence_type_int, "unknown"
                )
                if violence_type_int is not None
                else "unknown",
                "side_a": record.get("side_a"),
                "side_b": record.get("side_b"),
                "best": best,
                "high": high,
                "low": low,
                "latitude": record.get("latitude"),
                "longitude": record.get("longitude"),
                "source_article": record.get("source_article"),
                "source_headline": record.get("source_headline"),
            }
        )

    result = {
        "events": events,
        "count": len(events),
        "total_fatalities_best": total_fatalities_best,
        "query": {"days": days},
        "source": "ucdp",
        "timestamp": now.strftime("%Y-%m-%dT%H:%M:%SZ"),
    }
    if pages_failed:
        # A dropped page would otherwise shrink the count with no trace.
        logger.warning(
            "UCDP: %d of %d pages could not be fetched", len(pages_failed), total_pages
        )
        result["degraded"] = True
        result["reason"] = "ucdp_partial"
        result["pages_failed"] = pages_failed
        result["pages_total"] = total_pages
        result["data_gaps"] = [
            f"UCDP: {len(pages_failed)} of {total_pages} pages could not be "
            "fetched, so count and total_fatalities_best are lower bounds"
        ]
    return result


# ---------------------------------------------------------------------------
# HDX: Humanitarian Data Exchange (CKAN API)
# ---------------------------------------------------------------------------

_HDX_SEARCH_URL = "https://data.humdata.org/api/3/action/package_search"


async def fetch_humanitarian_summary(
    fetcher: Fetcher,
    country: str | None = None,
) -> dict:
    """Fetch recent humanitarian crisis datasets from HDX (Humanitarian Data Exchange).

    No API key required.  Uses the CKAN package_search API.

    Args:
        fetcher: Shared HTTP fetcher with caching and circuit breaking.
        country: Optional ISO 3166-1 alpha-3 country code (lowercase) to
                 filter datasets by geographic group.

    Returns:
        Dict with datasets list, count, source, and timestamp.
    """
    now = datetime.now(timezone.utc)

    params: dict = {
        "q": "crisis",
        "rows": 20,
        "sort": "metadata_modified desc",
    }
    if country:
        params["fq"] = f"groups:{country.lower()}"

    cache_country = country or "global"
    data = await fetcher.get_json(
        _HDX_SEARCH_URL,
        source="hdx",
        cache_key=f"conflict:humanitarian:{cache_country}",
        cache_ttl=21600,
        params=params,
    )

    if data is None:
        logger.warning("HDX API returned no data")
        return {
            "datasets": [],
            "count": 0,
            "source": "hdx",
            "timestamp": now.strftime("%Y-%m-%dT%H:%M:%SZ"),
        }

    datasets = []
    results = data.get("result", {}).get("results", [])

    for dataset in results:
        notes = dataset.get("notes") or ""
        if len(notes) > 200:
            notes = notes[:200] + "..."

        org = dataset.get("organization") or {}
        org_title = org.get("title") if isinstance(org, dict) else None

        datasets.append(
            {
                "name": dataset.get("name"),
                "title": dataset.get("title"),
                "organization": org_title,
                "metadata_modified": dataset.get("metadata_modified"),
                "num_resources": dataset.get("num_resources"),
                "notes": notes,
            }
        )

    return {
        "datasets": datasets,
        "count": len(datasets),
        "source": "hdx",
        "timestamp": now.strftime("%Y-%m-%dT%H:%M:%SZ"),
    }