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
Four hazard/space domains: NWS weather alerts, launch schedules, GVP volcanoes, NHC cyclones (source layer)
Phoenix Agent (Marcs-Mac-Studio)7605984decf6
diff --git a/src/world_intel_mcp/sources/cyclones.py b/src/world_intel_mcp/sources/cyclones.pynew file mode 100644index 0000000..edae887--- /dev/null+++ b/src/world_intel_mcp/sources/cyclones.py@@ -0,0 +1,132 @@+"""NHC tropical cyclone source for world-intel-mcp.++Provides active tropical cyclones from the National Hurricane Center's+CurrentStorms.json feed. No API key required. Covers the NHC/CPHC+basins (Atlantic, Eastern Pacific, Central Pacific) — not JTWC's+Western Pacific / Indian Ocean areas of responsibility.++Shape facts, verified live 2026-09-01 against four active storms:+intensity and pressure arrive as strings (knots and millibars per+NHC's CurrentStorms.json documentation; the 945 mb / "120" pairing on+a major hurricane is consistent with knots), positions as+latitudeNumeric/longitudeNumeric floats, movement as movementDir+(degrees) and movementSpeed integers.++An empty activeStorms array is a VALID quiet-season result and is+returned without degradation markers; only an actual fetch failure is+marked degraded. The quiet-season shape itself (activeStorms: []) is+assumed from the populated shape, not observed — four storms were+active on the day this was written.+"""++import logging+from datetime import datetime, timezone++from ..fetcher import Fetcher++logger = logging.getLogger("world-intel-mcp.sources.cyclones")++_NHC_CURRENT_STORMS_URL = "https://www.nhc.noaa.gov/CurrentStorms.json"++_CLASSIFICATION_NAMES: dict[str, str] = {+ "TD": "Tropical Depression",+ "TS": "Tropical Storm",+ "HU": "Hurricane",+ "MH": "Major Hurricane",+ "SD": "Subtropical Depression",+ "SS": "Subtropical Storm",+ "PTC": "Potential Tropical Cyclone",+ "PC": "Post-tropical Cyclone",+ "STD": "Subtropical Depression",+ "STS": "Subtropical Storm",+}++_BASIN_NAMES: dict[str, str] = {+ "al": "atlantic",+ "ep": "eastern_pacific",+ "cp": "central_pacific",+}+++async def fetch_cyclones(fetcher: Fetcher) -> dict:+ """Fetch active tropical cyclones from the NHC.++ Args:+ fetcher: Shared HTTP fetcher with caching and circuit breaking.++ Returns:+ Dict with storms list (name, classification, intensity,+ position, movement), count, by_basin counts, source, and+ timestamp. Zero storms with no degraded marker means a quiet+ tropics, not a failure.+ """+ now = datetime.now(timezone.utc)++ data = await fetcher.get_json(+ url=_NHC_CURRENT_STORMS_URL,+ source="nhc",+ cache_key="cyclones:nhc:current",+ cache_ttl=600,+ )++ if data is None:+ logger.warning("NHC CurrentStorms feed returned no data")+ return {+ "error": "NHC CurrentStorms feed unavailable (no live or cached data)",+ "degraded": True,+ "reason": "nhc_fetch_failed",+ "storms": [],+ "count": 0,+ "by_basin": {},+ "source": "nhc",+ "timestamp": now.strftime("%Y-%m-%dT%H:%M:%SZ"),+ }++ storms = []+ by_basin: dict[str, int] = {}+ for storm in data.get("activeStorms", []):+ storm_id = storm.get("id") or ""+ basin = _BASIN_NAMES.get(storm_id[:2].lower(), storm_id[:2].lower() or None)+ if basin:+ by_basin[basin] = by_basin.get(basin, 0) + 1++ classification = storm.get("classification")+ advisory = storm.get("publicAdvisory") or {}++ storms.append(+ {+ "id": storm_id or None,+ "name": storm.get("name"),+ "basin": basin,+ "classification": classification,+ "classification_name": _CLASSIFICATION_NAMES.get(+ classification, classification+ ),+ "intensity_kt": _safe_int(storm.get("intensity")),+ "pressure_mb": _safe_int(storm.get("pressure")),+ "latitude": storm.get("latitudeNumeric"),+ "longitude": storm.get("longitudeNumeric"),+ "movement_dir_deg": storm.get("movementDir"),+ "movement_speed_kt": storm.get("movementSpeed"),+ "last_update": storm.get("lastUpdate"),+ "advisory_url": advisory.get("url"),+ }+ )++ return {+ "storms": storms,+ "count": len(storms),+ "by_basin": by_basin,+ "source": "nhc",+ "timestamp": now.strftime("%Y-%m-%dT%H:%M:%SZ"),+ }+++def _safe_int(value: str | int | None) -> int | None:+ """Convert a value to int, returning None when absent or unparseable."""+ if value is None:+ return None+ try:+ return int(value)+ except (ValueError, TypeError):+ return Nonediff --git a/src/world_intel_mcp/sources/launches.py b/src/world_intel_mcp/sources/launches.pynew file mode 100644index 0000000..3787f0c--- /dev/null+++ b/src/world_intel_mcp/sources/launches.py@@ -0,0 +1,116 @@+"""Launch Library 2 upcoming-launch schedule source for world-intel-mcp.++Provides upcoming orbital/suborbital launch schedules from The Space+Devs' Launch Library 2 API. No API key required, but the free tier is+rate-limited to roughly 15 requests/hour — hence the long cache TTL.+The upstream "upcoming" endpoint also includes very recently launched+missions (verified live 2026-09-01: first result had already flown,+status "Launch Successful"); the status field passes that through+rather than filtering it out.+"""++import logging+from datetime import datetime, timezone++from ..fetcher import Fetcher++logger = logging.getLogger("world-intel-mcp.sources.launches")++_LL2_UPCOMING_URL = "https://ll.thespacedevs.com/2.2.0/launch/upcoming/"++# Free tier is ~15 req/hr; a fresh fetch at most once per hour.+_CACHE_TTL = 3600+++async def fetch_launch_schedule(+ fetcher: Fetcher,+ limit: int = 20,+) -> dict:+ """Fetch upcoming launches from Launch Library 2.++ Args:+ fetcher: Shared HTTP fetcher with caching and circuit breaking.+ limit: Maximum launches to return (passed to the API).++ Returns:+ Dict with launches list (name, provider, vehicle, pad with+ lat/lon, net launch time, status, mission), count, source,+ and timestamp.+ """+ now = datetime.now(timezone.utc)++ data = await fetcher.get_json(+ url=_LL2_UPCOMING_URL,+ source="launch-library",+ cache_key=f"launches:ll2:upcoming:{limit}",+ cache_ttl=_CACHE_TTL,+ params={"limit": limit},+ )++ if data is None:+ logger.warning("Launch Library 2 API returned no data")+ return {+ "error": "Launch Library 2 API unavailable (no live or cached data)",+ "degraded": True,+ "reason": "launch_library_fetch_failed",+ "launches": [],+ "count": 0,+ "source": "launch-library",+ "timestamp": now.strftime("%Y-%m-%dT%H:%M:%SZ"),+ }++ launches = []+ for result in data.get("results", [])[:limit]:+ status = result.get("status") or {}+ provider = result.get("launch_service_provider") or {}+ config = (result.get("rocket") or {}).get("configuration") or {}+ pad = result.get("pad") or {}+ pad_location = pad.get("location") or {}+ mission = result.get("mission") or {}+ orbit = mission.get("orbit") or {}++ description = mission.get("description")+ if description and len(description) > 500:+ description = description[:500]++ launches.append(+ {+ "id": result.get("id"),+ "name": result.get("name"),+ "provider": provider.get("name"),+ "provider_type": provider.get("type"),+ "vehicle": config.get("full_name") or config.get("name"),+ "pad": pad.get("name"),+ "pad_location": pad_location.get("name"),+ "country_code": pad_location.get("country_code"),+ # LL2 serializes pad coordinates as strings+ "latitude": _safe_float(pad.get("latitude")),+ "longitude": _safe_float(pad.get("longitude")),+ "net": result.get("net"),+ "window_start": result.get("window_start"),+ "window_end": result.get("window_end"),+ "status": status.get("name"),+ "status_abbrev": status.get("abbrev"),+ "mission": mission.get("name"),+ "mission_type": mission.get("type"),+ "orbit": orbit.get("abbrev"),+ "mission_description": description,+ }+ )++ return {+ "launches": launches,+ "count": len(launches),+ "source": "launch-library",+ "timestamp": now.strftime("%Y-%m-%dT%H:%M:%SZ"),+ }+++def _safe_float(value: str | float | None) -> float | None:+ """Convert a value to float, returning None when absent or unparseable."""+ if value is None:+ return None+ try:+ return float(value)+ except (ValueError, TypeError):+ return Nonediff --git a/src/world_intel_mcp/sources/volcano.py b/src/world_intel_mcp/sources/volcano.pynew file mode 100644index 0000000..1c9308e--- /dev/null+++ b/src/world_intel_mcp/sources/volcano.py@@ -0,0 +1,162 @@+"""Smithsonian GVP weekly volcanic activity source for world-intel-mcp.++Parses the Smithsonian Global Volcanism Program / USGS Weekly Volcanic+Activity Report RSS feed (updated Thursdays). No API key required.++Feed facts, verified live 2026-09-01: RSS 2.0 with one item per+volcano; titles follow "Name (Country) - Report for <week> - <status>"+where status is "New Eruptive Activity" or "Continuing Eruptive+Activity"; each item carries a georss:point that feedparser exposes as+``entry.where`` with GeoJSON-ordered (lon, lat) coordinates; item+descriptions are HTML paragraphs.++Encoding honesty: the XML declares ISO-8859-1 but the server's+Content-Type header claims UTF-8, so httpx's decode can leave U+FFFD+replacement characters inside accented volcano names (e.g. Popocatépetl).+The feed structure survives; only some non-ASCII name/summary characters+may be mangled. Not fixable from here without bypassing the shared+fetcher, which this repo forbids.+"""++import logging+import re+from datetime import datetime, timezone+from html import unescape++from ..fetcher import Fetcher++try:+ import feedparser+except ImportError:+ feedparser = None # type: ignore[assignment]++logger = logging.getLogger("world-intel-mcp.sources.volcano")++_GVP_WEEKLY_RSS = "https://volcano.si.edu/news/WeeklyVolcanoRSS.xml"++# Report is published weekly (Thursdays); refetching hourly is plenty.+_CACHE_TTL = 3600++_TITLE_RE = re.compile(r"^(?P<name>.*?)\s+\((?P<country>[^)]*)\)$")+_TAG_RE = re.compile(r"<[^>]+>")+++async def fetch_volcano_activity(fetcher: Fetcher) -> dict:+ """Fetch the GVP/USGS weekly volcanic activity report.++ Args:+ fetcher: Shared HTTP fetcher with caching and circuit breaking.++ Returns:+ Dict with volcanoes list (name, country, lat/lon, activity+ status, summary, report week), count, new/continuing activity+ counts, report_published, source, and timestamp.+ """+ now = datetime.now(timezone.utc)++ if feedparser is None:+ return {+ "error": "feedparser not installed — run: pip install feedparser",+ "degraded": True,+ "reason": "feedparser_missing",+ "volcanoes": [],+ "count": 0,+ "source": "gvp",+ "timestamp": now.strftime("%Y-%m-%dT%H:%M:%SZ"),+ }++ xml_text = await fetcher.get_xml(+ _GVP_WEEKLY_RSS,+ source="gvp",+ cache_key="volcano:gvp:weekly",+ cache_ttl=_CACHE_TTL,+ )++ if xml_text is None:+ logger.warning("GVP weekly volcano feed returned no data")+ return {+ "error": "GVP weekly volcano feed unavailable (no live or cached data)",+ "degraded": True,+ "reason": "gvp_fetch_failed",+ "volcanoes": [],+ "count": 0,+ "source": "gvp",+ "timestamp": now.strftime("%Y-%m-%dT%H:%M:%SZ"),+ }++ parsed = feedparser.parse(xml_text)++ volcanoes = []+ new_count = 0+ continuing_count = 0+ for entry in parsed.get("entries", []):+ name, country, week, activity_status = _parse_title(entry.get("title", ""))++ if activity_status and "new" in activity_status.lower():+ new_count += 1+ elif activity_status and "continuing" in activity_status.lower():+ continuing_count += 1++ lat: float | None = None+ lon: float | None = None+ where = entry.get("where")+ if where and where.get("type") == "Point":+ coords = where.get("coordinates") or ()+ if len(coords) >= 2:+ # feedparser normalizes georss:point to (lon, lat)+ lon, lat = coords[0], coords[1]++ summary = _strip_html(entry.get("summary") or "")+ if len(summary) > 500:+ summary = summary[:500]++ volcanoes.append(+ {+ "name": name,+ "country": country,+ "latitude": lat,+ "longitude": lon,+ "activity_status": activity_status,+ "summary": summary,+ "report_week": week,+ "published": entry.get("published"),+ "link": entry.get("id") or entry.get("link"),+ }+ )++ return {+ "volcanoes": volcanoes,+ "count": len(volcanoes),+ "new_activity_count": new_count,+ "continuing_activity_count": continuing_count,+ "report_published": parsed.get("feed", {}).get("published"),+ "source": "gvp",+ "timestamp": now.strftime("%Y-%m-%dT%H:%M:%SZ"),+ }+++def _parse_title(+ title: str,+) -> tuple[str, str | None, str | None, str | None]:+ """Split a GVP item title into (name, country, week, activity_status).++ Expected form: "Name (Country) - Report for <week>[ - <status>]".+ A title that doesn't match falls back to (title, None, None, None)+ rather than guessing.+ """+ parts = title.split(" - ")+ if len(parts) < 2 or not parts[1].startswith("Report for "):+ return (title, None, None, None)++ week = parts[1][len("Report for ") :]+ activity_status = parts[2] if len(parts) > 2 else None++ match = _TITLE_RE.match(parts[0])+ if match:+ return (match.group("name"), match.group("country"), week, activity_status)+ return (parts[0], None, week, activity_status)+++def _strip_html(text: str) -> str:+ """Reduce an HTML fragment to whitespace-normalized plain text."""+ return " ".join(unescape(_TAG_RE.sub(" ", text)).split())diff --git a/src/world_intel_mcp/sources/weather.py b/src/world_intel_mcp/sources/weather.pynew file mode 100644index 0000000..ddee0f7--- /dev/null+++ b/src/world_intel_mcp/sources/weather.py@@ -0,0 +1,162 @@+"""NWS severe weather alerts source for world-intel-mcp.++Provides active CAP alerts from the US National Weather Service API+(api.weather.gov). No API key required, but NWS policy requires a+descriptive User-Agent, which this module sends explicitly.++Coverage is US-only (states, territories, and marine zones) — there is+no global feed behind this endpoint, and the output says so via a+``coverage: "US"`` key.++Geometry honesty: many active alerts are zone-based and carry a null+GeoJSON geometry (measured 2026-09-01: 17 of 28 nationwide Severe+alerts had polygons). When a polygon is present, latitude/longitude are+the mean of its outer-ring vertices — a representative point, not an+official centroid. When geometry is null they are None; no coordinates+are invented from zone URLs.+"""++import logging+from datetime import datetime, timezone++from ..fetcher import Fetcher++logger = logging.getLogger("world-intel-mcp.sources.weather")++_NWS_ALERTS_URL = "https://api.weather.gov/alerts/active"++# NWS policy: identify your application. The Fetcher default UA is+# generic, so this module always sends its own descriptive one.+_NWS_HEADERS = {+ "User-Agent": "world-intel-mcp (https://github.com/marc-shade/world-intel-mcp)",+ "Accept": "application/geo+json",+}+++async def fetch_weather_alerts(+ fetcher: Fetcher,+ area: str | None = None,+ severity: str | None = None,+ limit: int = 50,+) -> dict:+ """Fetch active NWS severe weather alerts (US only).++ Args:+ fetcher: Shared HTTP fetcher with caching and circuit breaking.+ area: Optional two-letter state/territory code (e.g. "TX").+ severity: Optional severity filter — one of Extreme, Severe,+ Moderate, Minor, Unknown (case-insensitive input).+ limit: Maximum alerts to return. Applied client-side: the+ /alerts/active endpoint rejects a limit query parameter+ with HTTP 400 (verified live 2026-09-01).++ Returns:+ Dict with alerts list, count, by_severity counts, coverage,+ query, source, and timestamp.+ """+ now = datetime.now(timezone.utc)++ params: dict[str, str] = {}+ if area:+ params["area"] = area.strip().upper()+ if severity:+ params["severity"] = severity.strip().capitalize()++ query = {"area": params.get("area"), "severity": params.get("severity")}++ data = await fetcher.get_json(+ url=_NWS_ALERTS_URL,+ source="nws",+ cache_key=f"weather:alerts:{params.get('area')}:{params.get('severity')}",+ cache_ttl=300,+ headers=_NWS_HEADERS,+ params=params or None,+ )++ if data is None:+ logger.warning("NWS alerts API returned no data")+ return {+ "error": "NWS alerts API unavailable (no live or cached data)",+ "degraded": True,+ "reason": "nws_fetch_failed",+ "alerts": [],+ "count": 0,+ "by_severity": {},+ "coverage": "US",+ "query": query,+ "source": "nws",+ "timestamp": now.strftime("%Y-%m-%dT%H:%M:%SZ"),+ }++ alerts = []+ by_severity: dict[str, int] = {}+ for feature in data.get("features", [])[:limit]:+ props = feature.get("properties", {})+ lat, lon = _representative_point(feature.get("geometry"))++ alert_severity = props.get("severity") or "Unknown"+ by_severity[alert_severity] = by_severity.get(alert_severity, 0) + 1++ alerts.append(+ {+ "id": feature.get("id"),+ "event": props.get("event"),+ "severity": alert_severity,+ "urgency": props.get("urgency"),+ "certainty": props.get("certainty"),+ "headline": props.get("headline"),+ "area": props.get("areaDesc"),+ "effective": props.get("effective"),+ "expires": props.get("expires"),+ "onset": props.get("onset"),+ "ends": props.get("ends"),+ "sender": props.get("senderName"),+ "latitude": lat,+ "longitude": lon,+ }+ )++ return {+ "alerts": alerts,+ "count": len(alerts),+ "by_severity": by_severity,+ "coverage": "US",+ "query": query,+ "source": "nws",+ "timestamp": now.strftime("%Y-%m-%dT%H:%M:%SZ"),+ }+++def _representative_point(+ geometry: dict | None,+) -> tuple[float | None, float | None]:+ """Derive a representative (lat, lon) from an alert's GeoJSON geometry.++ Polygon: mean of the outer-ring vertices (closing duplicate vertex+ dropped). MultiPolygon: same, on the first polygon's outer ring.+ Null or unrecognized geometry: (None, None) — zone-based alerts+ carry no coordinates and none are fabricated.+ """+ if not geometry:+ return (None, None)++ gtype = geometry.get("type")+ coords = geometry.get("coordinates")+ if gtype == "Polygon" and coords:+ ring = coords[0]+ elif gtype == "MultiPolygon" and coords and coords[0]:+ ring = coords[0][0]+ else:+ return (None, None)++ if not ring:+ return (None, None)+ if len(ring) > 1 and ring[0] == ring[-1]:+ ring = ring[:-1]++ try:+ lon = sum(pt[0] for pt in ring) / len(ring)+ lat = sum(pt[1] for pt in ring) / len(ring)+ except (TypeError, IndexError, ZeroDivisionError):+ return (None, None)+ return (round(lat, 4), round(lon, 4))diff --git a/src/world_intel_mcp/tests/test_sources_cyclones.py b/src/world_intel_mcp/tests/test_sources_cyclones.pynew file mode 100644index 0000000..3fb517f--- /dev/null+++ b/src/world_intel_mcp/tests/test_sources_cyclones.py@@ -0,0 +1,156 @@+"""Tests for sources/cyclones.py — respx-mocked NHC CurrentStorms.json.++Gaps / not covered: the real quiet-season payload shape (assumed+``{"activeStorms": []}`` from the populated shape — four storms were+active when this was written, so the quiet shape is mocked, not+observed); Central Pacific (cp) storm ids, mocked only.+"""++import asyncio as asyncio_mod++import httpx+import pytest+import respx++from world_intel_mcp.fetcher import Fetcher+from world_intel_mcp.sources.cyclones import _safe_int, fetch_cyclones++# Field shapes mirror the live feed observed 2026-09-01: intensity and+# pressure are strings, positions are the *Numeric floats.+_NHC = {+ "activeStorms": [+ {+ "id": "al052026",+ "binNumber": "AT5",+ "name": "Edouard",+ "classification": "TS",+ "intensity": "45",+ "pressure": "1000",+ "latitudeNumeric": 29.6,+ "longitudeNumeric": -93.5,+ "movementDir": 305,+ "movementSpeed": 8,+ "lastUpdate": "2026-09-01T17:00:00.000Z",+ "publicAdvisory": {+ "advNum": "005",+ "url": "https://www.nhc.noaa.gov/text/MIATCPAT5.shtml",+ },+ },+ {+ "id": "ep112026",+ "name": "Karina",+ "classification": "HU",+ "intensity": "120",+ "pressure": "945",+ "latitudeNumeric": 18.1,+ "longitudeNumeric": -129.0,+ "movementDir": 270,+ "movementSpeed": 12,+ "lastUpdate": "2026-09-01T15:00:00.000Z",+ },+ {+ "id": "cp032026",+ "name": "Unnamed",+ "classification": "ZZ", # unknown code passes through raw+ "intensity": "not-a-number",+ "latitudeNumeric": 15.0,+ "longitudeNumeric": 179.9,+ },+ ]+}+++async def test_fetch_cyclones_extracts_storms(fetcher: Fetcher) -> None:+ respx.get(url__regex=r".*nhc\.noaa\.gov.*").mock(+ return_value=httpx.Response(200, json=_NHC)+ )++ result = await fetch_cyclones(fetcher)++ assert result["source"] == "nhc"+ assert result["count"] == 3+ assert "degraded" not in result+ assert result["by_basin"] == {+ "atlantic": 1,+ "eastern_pacific": 1,+ "central_pacific": 1,+ }++ edouard = result["storms"][0]+ assert edouard["id"] == "al052026"+ assert edouard["name"] == "Edouard"+ assert edouard["basin"] == "atlantic"+ assert edouard["classification"] == "TS"+ assert edouard["classification_name"] == "Tropical Storm"+ assert edouard["intensity_kt"] == 45 # string "45" coerced+ assert edouard["pressure_mb"] == 1000+ assert edouard["latitude"] == pytest.approx(29.6)+ assert edouard["longitude"] == pytest.approx(-93.5)+ assert edouard["movement_dir_deg"] == 305+ assert edouard["movement_speed_kt"] == 8+ assert edouard["last_update"] == "2026-09-01T17:00:00.000Z"+ assert edouard["advisory_url"] == "https://www.nhc.noaa.gov/text/MIATCPAT5.shtml"++ karina = result["storms"][1]+ assert karina["basin"] == "eastern_pacific"+ assert karina["classification_name"] == "Hurricane"+ assert karina["intensity_kt"] == 120+ assert karina["advisory_url"] is None # no publicAdvisory block++ unnamed = result["storms"][2]+ assert unnamed["basin"] == "central_pacific"+ assert unnamed["classification"] == "ZZ"+ assert unnamed["classification_name"] == "ZZ" # unknown code kept raw+ assert unnamed["intensity_kt"] is None # unparseable+ assert unnamed["pressure_mb"] is None # absent+++async def test_fetch_cyclones_quiet_season_is_valid_not_degraded(+ fetcher: Fetcher,+) -> None:+ """Zero active storms is a real state of the world, not an outage."""+ respx.get(url__regex=r".*nhc\.noaa\.gov.*").mock(+ return_value=httpx.Response(200, json={"activeStorms": []})+ )++ result = await fetch_cyclones(fetcher)++ assert result["count"] == 0+ assert result["storms"] == []+ assert result["by_basin"] == {}+ assert "degraded" not in result+ assert "error" not in result+++async def test_fetch_cyclones_feed_down_is_marked_degraded(+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch+) -> None:+ """A fetch failure must never be shape-identical to a quiet tropics."""++ async def _no_sleep(*args, **kwargs) -> None:+ return None++ monkeypatch.setattr(asyncio_mod, "sleep", _no_sleep)++ respx.get(url__regex=r".*nhc\.noaa\.gov.*").mock(return_value=httpx.Response(500))++ result = await fetch_cyclones(fetcher)++ assert result["degraded"] is True+ assert result["reason"] == "nhc_fetch_failed"+ assert "unavailable" in result["error"].lower()+ assert result["storms"] == []+ assert result["count"] == 0+++def test_safe_int() -> None:+ assert _safe_int(None) is None+ assert _safe_int("45") == 45+ assert _safe_int(45) == 45+ assert _safe_int("nope") is Nonediff --git a/src/world_intel_mcp/tests/test_sources_launches.py b/src/world_intel_mcp/tests/test_sources_launches.pynew file mode 100644index 0000000..a853793--- /dev/null+++ b/src/world_intel_mcp/tests/test_sources_launches.py@@ -0,0 +1,158 @@+"""Tests for sources/launches.py — respx-mocked Launch Library 2.++Gaps / not covered: LL2 pagination (next/previous are ignored by+design); the free-tier 429 throttle response path (exercised only as a+generic failure via the 500 test).+"""++import asyncio as asyncio_mod++import httpx+import pytest+import respx++from world_intel_mcp.fetcher import Fetcher+from world_intel_mcp.sources.launches import _safe_float, fetch_launch_schedule++_LL2 = {+ "count": 2,+ "next": None,+ "previous": None,+ "results": [+ {+ "id": "ll2-launch-demo-1",+ "name": "Pallas-1 | Demo Flight",+ "net": "2026-09-01T02:00:00Z",+ "window_start": "2026-09-01T01:52:00Z",+ "window_end": "2026-09-01T04:09:00Z",+ "status": {"id": 3, "name": "Launch Successful", "abbrev": "Success"},+ "launch_service_provider": {+ "name": "Galactic Energy",+ "type": "Commercial",+ },+ "rocket": {+ "configuration": {"name": "Pallas-1", "full_name": "Pallas-1 Block A"}+ },+ "pad": {+ "name": "Pallas-1 Launch Pad",+ # LL2 serializes pad coordinates as strings.+ "latitude": "40.7759",+ "longitude": "99.8102",+ "location": {+ "name": "Jiuquan Satellite Launch Center",+ "country_code": "CHN",+ },+ },+ "mission": {+ "name": "Demo Flight",+ "type": "Test Flight",+ "orbit": {"name": "Sun-Synchronous Orbit", "abbrev": "SSO"},+ "description": "First test launch with a dummy payload. " + "x" * 600,+ },+ },+ {+ "id": "ll2-launch-mystery-2",+ "name": "Mystery Rocket | Classified",+ "net": "2026-09-03T00:00:00Z",+ "status": {"name": "To Be Confirmed", "abbrev": "TBC"},+ "launch_service_provider": None,+ "rocket": {"configuration": {"name": "Mystery", "full_name": ""}},+ "pad": {"name": "Unknown Pad", "latitude": None, "longitude": "bogus"},+ "mission": None,+ },+ ],+}+++async def test_fetch_launch_schedule_extracts_fields(fetcher: Fetcher) -> None:+ route = respx.get(url__regex=r".*ll\.thespacedevs\.com.*").mock(+ return_value=httpx.Response(200, json=_LL2)+ )++ result = await fetch_launch_schedule(fetcher, limit=10)++ assert result["source"] == "launch-library"+ assert result["count"] == 2+ assert "degraded" not in result+ assert route.calls.last.request.url.params["limit"] == "10"++ first = result["launches"][0]+ assert first["name"] == "Pallas-1 | Demo Flight"+ assert first["provider"] == "Galactic Energy"+ assert first["provider_type"] == "Commercial"+ assert first["vehicle"] == "Pallas-1 Block A"+ assert first["pad"] == "Pallas-1 Launch Pad"+ assert first["pad_location"] == "Jiuquan Satellite Launch Center"+ assert first["country_code"] == "CHN"+ # String coordinates converted to floats.+ assert first["latitude"] == pytest.approx(40.7759)+ assert first["longitude"] == pytest.approx(99.8102)+ assert first["net"] == "2026-09-01T02:00:00Z"+ assert first["window_start"] == "2026-09-01T01:52:00Z"+ assert first["status"] == "Launch Successful"+ assert first["status_abbrev"] == "Success"+ assert first["mission"] == "Demo Flight"+ assert first["mission_type"] == "Test Flight"+ assert first["orbit"] == "SSO"+ # Long descriptions are truncated to 500 chars.+ assert len(first["mission_description"]) == 500+ assert first["mission_description"].startswith(+ "First test launch with a dummy payload."+ )++ second = result["launches"][1]+ assert second["provider"] is None # null launch_service_provider+ assert second["vehicle"] == "Mystery" # empty full_name falls back to name+ assert second["latitude"] is None+ assert second["longitude"] is None # unparseable string+ assert second["mission"] is None+ assert second["orbit"] is None+ assert second["status"] == "To Be Confirmed"+++async def test_fetch_launch_schedule_limit_truncates_client_side(+ fetcher: Fetcher,+) -> None:+ """Even if the API returns more rows than asked, limit caps output."""+ respx.get(url__regex=r".*ll\.thespacedevs\.com.*").mock(+ return_value=httpx.Response(200, json=_LL2)+ )++ result = await fetch_launch_schedule(fetcher, limit=1)++ assert result["count"] == 1+ assert result["launches"][0]["name"] == "Pallas-1 | Demo Flight"+++async def test_fetch_launch_schedule_api_down_is_marked_degraded(+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch+) -> None:+ async def _no_sleep(*args, **kwargs) -> None:+ return None++ monkeypatch.setattr(asyncio_mod, "sleep", _no_sleep)++ respx.get(url__regex=r".*ll\.thespacedevs\.com.*").mock(+ return_value=httpx.Response(500)+ )++ result = await fetch_launch_schedule(fetcher)++ assert result["degraded"] is True+ assert result["reason"] == "launch_library_fetch_failed"+ assert "unavailable" in result["error"].lower()+ assert result["launches"] == []+ assert result["count"] == 0+++def test_safe_float() -> None:+ assert _safe_float(None) is None+ assert _safe_float("40.5") == 40.5+ assert _safe_float(40.5) == 40.5+ assert _safe_float("bogus") is Nonediff --git a/src/world_intel_mcp/tests/test_sources_volcano.py b/src/world_intel_mcp/tests/test_sources_volcano.pynew file mode 100644index 0000000..fbaa2d4--- /dev/null+++ b/src/world_intel_mcp/tests/test_sources_volcano.py@@ -0,0 +1,164 @@+"""Tests for sources/volcano.py — respx-mocked Smithsonian GVP weekly RSS.++Gaps / not covered: the live feed's ISO-8859-1 / UTF-8 charset+mismatch (mocks are clean UTF-8, so the replacement-character behavior+described in the module docstring is untested); very long summaries+beyond the 500-char truncation.+"""++import asyncio as asyncio_mod++import httpx+import pytest+import respx++import world_intel_mcp.sources.volcano as volcano_mod+from world_intel_mcp.fetcher import Fetcher+from world_intel_mcp.sources.volcano import _parse_title, fetch_volcano_activity++# Repeated sentence pushes the Telica summary past the 500-char cap.+_LONG_SUMMARY = "Daily gas-and-ash emissions continued. " * 20++_GVP_RSS = """<?xml version="1.0" encoding="UTF-8"?>+<rss version="2.0" xmlns:georss="http://www.georss.org/georss">+ <channel>+ <title>Smithsonian / USGS Weekly Volcanic Activity Report</title>+ <link>https://volcano.si.edu/reports_weekly.cfm</link>+ <pubDate>Thu, 27 Aug 2026 03:30:31 -0500</pubDate>+ <item>+ <title>Ambae (Vanuatu) - Report for 20 August-26 August 2026 - New Eruptive Activity</title>+ <description><p>Explosive activity produced tall ash plumes on 25 August.</p></description>+ <link>https://volcano.si.edu/reports_weekly.cfm</link>+ <guid isPermaLink="true">https://volcano.si.edu/reports_weekly.cfm#vn_257030</guid>+ <pubDate>Thu, 27 Aug 2026 03:30:31 -0400</pubDate>+ <georss:point>-15.389 167.835</georss:point>+ </item>+ <item>+ <title>Telica (Nicaragua) - Report for 20 August-26 August 2026 - Continuing Eruptive Activity</title>+ <description><p>LONG_SUMMARY_HERE</p></description>+ <link>https://volcano.si.edu/reports_weekly.cfm</link>+ <guid isPermaLink="true">https://volcano.si.edu/reports_weekly.cfm#vn_344090</guid>+ <pubDate>Thu, 27 Aug 2026 03:30:31 -0400</pubDate>+ <georss:point>12.602 -86.845</georss:point>+ </item>+ <item>+ <title>Some unstructured bulletin title</title>+ <description>No structured title, no coordinates.</description>+ <link>https://volcano.si.edu/reports_weekly.cfm</link>+ </item>+ </channel>+</rss>+""".replace("LONG_SUMMARY_HERE", _LONG_SUMMARY)+++async def test_fetch_volcano_activity_parses_feed(fetcher: Fetcher) -> None:+ respx.get(url__regex=r".*volcano\.si\.edu.*").mock(+ return_value=httpx.Response(200, text=_GVP_RSS)+ )++ result = await fetch_volcano_activity(fetcher)++ assert result["source"] == "gvp"+ assert result["count"] == 3+ assert "degraded" not in result+ assert result["new_activity_count"] == 1+ assert result["continuing_activity_count"] == 1+ assert result["report_published"] == "Thu, 27 Aug 2026 03:30:31 -0500"++ ambae = result["volcanoes"][0]+ assert ambae["name"] == "Ambae"+ assert ambae["country"] == "Vanuatu"+ assert ambae["report_week"] == "20 August-26 August 2026"+ assert ambae["activity_status"] == "New Eruptive Activity"+ # georss:point is "lat lon"; feedparser hands back (lon, lat) —+ # the module must un-swap it.+ assert ambae["latitude"] == pytest.approx(-15.389)+ assert ambae["longitude"] == pytest.approx(167.835)+ # HTML stripped from the summary.+ assert (+ ambae["summary"] == "Explosive activity produced tall ash plumes on 25 August."+ )+ assert ambae["link"] == "https://volcano.si.edu/reports_weekly.cfm#vn_257030"+ assert ambae["published"] == "Thu, 27 Aug 2026 03:30:31 -0400"++ telica = result["volcanoes"][1]+ assert telica["country"] == "Nicaragua"+ assert telica["activity_status"] == "Continuing Eruptive Activity"+ assert telica["latitude"] == pytest.approx(12.602)+ assert telica["longitude"] == pytest.approx(-86.845)+ # Long summaries are truncated to 500 chars.+ assert len(telica["summary"]) == 500+ assert telica["summary"].startswith("Daily gas-and-ash emissions continued.")++ odd = result["volcanoes"][2]+ assert odd["name"] == "Some unstructured bulletin title"+ assert odd["country"] is None+ assert odd["latitude"] is None+ assert odd["longitude"] is None+ assert odd["activity_status"] is None+++async def test_fetch_volcano_activity_feed_down_is_marked_degraded(+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch+) -> None:+ async def _no_sleep(*args, **kwargs) -> None:+ return None++ monkeypatch.setattr(asyncio_mod, "sleep", _no_sleep)++ respx.get(url__regex=r".*volcano\.si\.edu.*").mock(return_value=httpx.Response(500))++ result = await fetch_volcano_activity(fetcher)++ assert result["degraded"] is True+ assert result["reason"] == "gvp_fetch_failed"+ assert "unavailable" in result["error"].lower()+ assert result["volcanoes"] == []+ assert result["count"] == 0+++async def test_fetch_volcano_activity_without_feedparser(+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setattr(volcano_mod, "feedparser", None)++ result = await fetch_volcano_activity(fetcher)++ assert result["degraded"] is True+ assert result["reason"] == "feedparser_missing"+ assert "feedparser" in result["error"]+ assert result["volcanoes"] == []+++def test_parse_title_variants() -> None:+ assert _parse_title(+ "Kilauea (United States) - Report for 1 January-7 January 2026 - Continuing Eruptive Activity"+ ) == (+ "Kilauea",+ "United States",+ "1 January-7 January 2026",+ "Continuing Eruptive Activity",+ )+ # No trailing status segment.+ assert _parse_title("Etna (Italy) - Report for 1 January-7 January 2026") == (+ "Etna",+ "Italy",+ "1 January-7 January 2026",+ None,+ )+ # No "(Country)" in the head segment.+ assert _parse_title(+ "Oddball - Report for 1 January-7 January 2026 - New Eruptive Activity"+ ) == (+ "Oddball",+ None,+ "1 January-7 January 2026",+ "New Eruptive Activity",+ )+ # Fully unstructured title falls back whole.+ assert _parse_title("Just a title") == ("Just a title", None, None, None)diff --git a/src/world_intel_mcp/tests/test_sources_weather.py b/src/world_intel_mcp/tests/test_sources_weather.pynew file mode 100644index 0000000..3dbf210--- /dev/null+++ b/src/world_intel_mcp/tests/test_sources_weather.py@@ -0,0 +1,208 @@+"""Tests for sources/weather.py — respx-mocked NWS active alerts.++Gaps / not covered: real NWS zone-URL resolution (the module never+resolves affectedZones, by design); marine area codes; the severity+parameter's full value set against the live API.+"""++import asyncio as asyncio_mod++import httpx+import pytest+import respx++from world_intel_mcp.fetcher import Fetcher+from world_intel_mcp.sources.weather import _representative_point, fetch_weather_alerts++# Square ring around (-100.5, 30.5); closing vertex repeats the first.+_POLYGON = {+ "type": "Polygon",+ "coordinates": [+ [+ [-100.0, 30.0],+ [-101.0, 30.0],+ [-101.0, 31.0],+ [-100.0, 31.0],+ [-100.0, 30.0],+ ]+ ],+}++_NWS = {+ "features": [+ {+ "id": "urn:oid:2.49.0.1.840.0.aaa",+ "geometry": _POLYGON,+ "properties": {+ "event": "Tornado Warning",+ "severity": "Extreme",+ "urgency": "Immediate",+ "certainty": "Observed",+ "headline": "Tornado Warning issued for Kerr County",+ "areaDesc": "Kerr, TX",+ "effective": "2026-09-01T11:46:00-05:00",+ "expires": "2026-09-01T12:30:00-05:00",+ "onset": "2026-09-01T11:46:00-05:00",+ "ends": "2026-09-01T12:30:00-05:00",+ "senderName": "NWS San Antonio TX",+ },+ },+ {+ "id": "urn:oid:2.49.0.1.840.0.bbb",+ # Zone-based alert: null geometry, must yield None coords.+ "geometry": None,+ "properties": {+ "event": "Extreme Heat Warning",+ "severity": "Severe",+ "urgency": "Expected",+ "certainty": "Likely",+ "headline": "Extreme Heat Warning until September 5",+ "areaDesc": "Jefferson; Wayne; Edwards",+ "effective": "2026-09-01T11:46:00-05:00",+ "expires": "2026-09-02T06:00:00-05:00",+ "senderName": "NWS Paducah KY",+ },+ },+ {+ "id": "urn:oid:2.49.0.1.840.0.ccc",+ "geometry": None,+ "properties": {+ "event": "Red Flag Warning",+ "severity": "Severe",+ "urgency": "Expected",+ "certainty": "Likely",+ "areaDesc": "Eastern Beaverhead National Forest",+ "senderName": "NWS Missoula MT",+ },+ },+ ]+}+++async def test_fetch_weather_alerts_extracts_fields_and_centroid(+ fetcher: Fetcher,+) -> None:+ route = respx.get(url__regex=r".*api\.weather\.gov.*").mock(+ return_value=httpx.Response(200, json=_NWS)+ )++ result = await fetch_weather_alerts(fetcher, area="tx", severity="severe")++ assert result["source"] == "nws"+ assert result["coverage"] == "US"+ assert result["count"] == 3+ assert "degraded" not in result+ assert result["by_severity"] == {"Extreme": 1, "Severe": 2}++ tornado = result["alerts"][0]+ assert tornado["event"] == "Tornado Warning"+ assert tornado["severity"] == "Extreme"+ assert tornado["urgency"] == "Immediate"+ assert tornado["headline"] == "Tornado Warning issued for Kerr County"+ assert tornado["area"] == "Kerr, TX"+ assert tornado["effective"] == "2026-09-01T11:46:00-05:00"+ assert tornado["expires"] == "2026-09-01T12:30:00-05:00"+ assert tornado["sender"] == "NWS San Antonio TX"+ # Mean of the square's 4 distinct vertices.+ assert tornado["latitude"] == 30.5+ assert tornado["longitude"] == -100.5++ heat = result["alerts"][1]+ assert heat["latitude"] is None+ assert heat["longitude"] is None++ # Input normalization: area upper-cased, severity capitalized.+ request = route.calls.last.request+ assert request.url.params["area"] == "TX"+ assert request.url.params["severity"] == "Severe"+ assert result["query"] == {"area": "TX", "severity": "Severe"}+ # NWS policy: a descriptive User-Agent must be sent.+ assert "world-intel-mcp" in request.headers["User-Agent"]+++async def test_fetch_weather_alerts_limit_is_client_side(+ fetcher: Fetcher,+) -> None:+ """The live endpoint rejects a limit query param with HTTP 400+ (verified 2026-09-01), so limit must never reach the request."""+ route = respx.get(url__regex=r".*api\.weather\.gov.*").mock(+ return_value=httpx.Response(200, json=_NWS)+ )++ result = await fetch_weather_alerts(fetcher, limit=2)++ assert result["count"] == 2+ assert len(result["alerts"]) == 2+ assert "limit" not in route.calls.last.request.url.params+++async def test_fetch_weather_alerts_empty_is_valid_not_degraded(+ fetcher: Fetcher,+) -> None:+ respx.get(url__regex=r".*api\.weather\.gov.*").mock(+ return_value=httpx.Response(200, json={"features": []})+ )++ result = await fetch_weather_alerts(fetcher, area="RI")++ assert result["count"] == 0+ assert result["alerts"] == []+ assert result["by_severity"] == {}+ assert "degraded" not in result+ assert "error" not in result+++async def test_fetch_weather_alerts_api_down_is_marked_degraded(+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch+) -> None:+ async def _no_sleep(*args, **kwargs) -> None:+ return None++ monkeypatch.setattr(asyncio_mod, "sleep", _no_sleep)++ respx.get(url__regex=r".*api\.weather\.gov.*").mock(+ return_value=httpx.Response(500)+ )++ result = await fetch_weather_alerts(fetcher)++ assert result["degraded"] is True+ assert result["reason"] == "nws_fetch_failed"+ assert "unavailable" in result["error"].lower()+ assert result["alerts"] == []+ assert result["count"] == 0+ assert result["coverage"] == "US"+++def test_representative_point_variants() -> None:+ assert _representative_point(None) == (None, None)+ assert _representative_point({}) == (None, None)+ assert _representative_point({"type": "Point", "coordinates": [1, 2]}) == (+ None,+ None,+ )+ assert _representative_point({"type": "Polygon", "coordinates": []}) == (+ None,+ None,+ )+ assert _representative_point({"type": "Polygon", "coordinates": [[]]}) == (+ None,+ None,+ )++ lat, lon = _representative_point(_POLYGON)+ assert (lat, lon) == (30.5, -100.5)++ multi = {"type": "MultiPolygon", "coordinates": [_POLYGON["coordinates"]]}+ assert _representative_point(multi) == (30.5, -100.5)++ malformed = {"type": "Polygon", "coordinates": [[["x", "y"], ["x", "y"]]]}+ assert _representative_point(malformed) == (None, None)