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
Cyclone forecasts: allowlist product links, cap cone vertices
Phoenix Agent (mac-studio)1249e696533a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1f1c818..19b3aad 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -25,8 +25,8 @@### Data honesty: forecast tracks- `data_gaps` names every track or cone not delivered, per storm, with a- status: `fetch_failed`, `unparsed`, `not_linked`, `not_published` or- `not_fetched_cap` (at most 10 storms per call; the rest are named,+ status: `fetch_failed`, `unparsed`, `refused_link`, `not_linked`,+ `not_published` or `not_fetched_cap` (at most 10 storms per call; the rest are named,never dropped). A failure marks the response `degraded`; a product theagency does not link is a gap, not degradation. A quiet basin stillanswers zero storms, not degraded, and makes no product fetches; a feed@@ -41,7 +41,13 @@not trip the warning feeds' breakers.- Remote KML is parsed with the standard library: strict UTF-8, anyDOCTYPE refused, size caps (KMZ 2 MB, KML 8 MB), and a cone with more- than one ring refused, never trimmed.+ than one ring refused, never trimmed. A ring of more than 10,000+ vertices is refused before simplifying, and simplifying runs off the+ event loop.+- Product links come from the agencies' feeds and are fetched only when+ they are https on the agency's own host (www.nhc.noaa.gov,+ www.metoc.navy.mil). Any other link is reported as `refused_link` and+ never requested.- Measured 2026-10-17: every product used answered HTTP 200 without akey; nhc.noaa.gov robots.txt disallows nothing and the NWS disclaimerputs the products in the public domain. The JTWC home page anddiff --git a/src/world_intel_mcp/sources/cyclone_forecasts.py b/src/world_intel_mcp/sources/cyclone_forecasts.pyindex d09a645..71f8e71 100644--- a/src/world_intel_mcp/sources/cyclone_forecasts.py+++ b/src/world_intel_mcp/sources/cyclone_forecasts.py@@ -66,6 +66,7 @@ import zipfileimport zlibfrom datetime import datetime, timezonefrom typing import Any+from urllib.parse import urlsplitfrom ..fetcher import Fetcher@@ -85,6 +86,15 @@ CONE_SIMPLIFY_TOLERANCE_DEG = 0.01_FORECAST_CACHE_TTL = 3600_CONE_MAX_BYTES = 2 * 1024 * 1024_KML_MAX_BYTES = 8 * 1024 * 1024+# Douglas-Peucker is quadratic in the worst case, so a ring past this is+# refused before simplifying (Trudy #17's ring has 1,167 vertices).+_CONE_MAX_VERTICES = 10_000++# Product links come from the agencies' feeds; one is fetched only when+# it is https on the agency's own host, so a malformed or tampered feed+# cannot point the server at another host.+_NHC_PRODUCT_HOSTS = frozenset({"www.nhc.noaa.gov"})+_JTWC_PRODUCT_HOSTS = frozenset({"www.metoc.navy.mil"})_MONTHS = {name: number@@ -99,7 +109,14 @@ _MONTHS = {# (or got an older issuance). not_linked / not_published are upstream# coverage facts: named in data_gaps, not degradation._FAILED_STATUSES = frozenset(- {"fetch_failed", "unparsed", "not_fetched_cap", "stale_advisory", "stale_warning"}+ {+ "fetch_failed",+ "unparsed",+ "not_fetched_cap",+ "stale_advisory",+ "stale_warning",+ "refused_link",+ })_CONE_NOTE = (@@ -198,6 +215,18 @@ def _same_number(found: Any, expected: Any) -> bool:return str(found).lstrip("0").upper() == str(expected).lstrip("0").upper()+def _refused_link(url: str, hosts: frozenset[str]) -> str | None:+ """Why a feed-supplied product link is not fetched, or None if it may be."""+ try:+ parts = urlsplit(url)+ port = parts.port+ except ValueError:+ return f"link {url!r} is not a valid URL; not fetched"+ if parts.scheme != "https" or (parts.hostname or "").lower() not in hosts or port not in (None, 443):+ return f"link {url!r} is not https on {', '.join(sorted(hosts))}; not fetched"+ return None++def resolve_day_time(day: int, hour: int, minute: int, anchor: datetime | None) -> datetime | None:@@ -336,8 +365,13 @@ def _ring_from_root(root: ET.Element) -> list[tuple[float, float]]:coords = next((el for el in rings[0].iter() if _local(el.tag) == "coordinates"), None)if coords is None or not (coords.text or "").strip():raise ValueError("cone ring has no coordinates")+ tokens = coords.text.split()+ if len(tokens) > _CONE_MAX_VERTICES + 1: # + 1: the ring repeats its first vertex+ raise ValueError(+ f"cone ring has {len(tokens)} vertices, over the cap of {_CONE_MAX_VERTICES}"+ )ring: list[tuple[float, float]] = []- for token in coords.text.split():+ for token in tokens:parts = token.split(",")if len(parts) < 2:raise ValueError(f"malformed KML coordinate {token!r}")@@ -549,6 +583,11 @@ async def _nhc_track(fetcher: Fetcher, storm_id: str, advisory: dict, now: datetout["track_status"] = "not_linked"out["track_error"] = "CurrentStorms.json links no forecast/advisory for this storm"return out+ refused = _refused_link(url, _NHC_PRODUCT_HOSTS)+ if refused:+ out["track_status"] = "refused_link"+ out["track_error"] = "forecast/advisory " + refused+ return outexpected = advisory.get("advNum")key = f"cyclones:nhc:tcm:{storm_id}:{expected}:{advisory.get('fileUpdateTime')}"@@ -583,6 +622,11 @@ async def _nhc_cone(fetcher: Fetcher, storm_id: str, cone_meta: dict) -> dict:if not url:out["cone_status"] = "not_linked"return out+ refused = _refused_link(url, _NHC_PRODUCT_HOSTS)+ if refused:+ out["cone_status"] = "refused_link"+ out["cone_error"] = "cone KMZ " + refused+ return outkey = f"cyclones:nhc:cone:{storm_id}:{cone_meta.get('advNum')}:{cone_meta.get('fileUpdateTime')}"cached = fetcher.cache.get(key)@@ -598,7 +642,8 @@ async def _nhc_cone(fetcher: Fetcher, storm_id: str, cone_meta: dict) -> dict:)return outtry:- cone = parse_nhc_cone_kmz(result.content)+ # In a worker thread: simplifying is CPU work and must not stall the event loop.+ cone = await asyncio.to_thread(parse_nhc_cone_kmz, result.content)except (zipfile.BadZipFile, zlib.error, ET.ParseError, ValueError, RuntimeError, EOFError) as exc:out["cone_status"] = "unparsed"out["cone_error"] = f"NHC cone KMZ unreadable: {type(exc).__name__}: {exc}"@@ -635,6 +680,11 @@ async def _jtwc_storm_forecast(fetcher: Fetcher, storm: dict, now: datetime) ->out["track_status"] = "not_linked"out["track_error"] = "the JTWC RSS item links no warning text for this storm"return out+ refused = _refused_link(url, _JTWC_PRODUCT_HOSTS)+ if refused:+ out["track_status"] = "refused_link"+ out["track_error"] = "warning text " + refused+ return outexpected = storm.get("warning_number")key = f"jtwc:warning:{storm.get('id')}:{expected}:{storm.get('issued_at')}"@@ -698,7 +748,7 @@ def _summarize(storms: list[dict]) -> tuple[list[str], bool]:gaps.append(f"{label}: forecast track {status}: {forecast.get('track_error')}")degraded = degraded or status in _FAILED_STATUSEScone_status = forecast.get("cone_status")- if cone_status in ("fetch_failed", "unparsed"):+ if cone_status in ("fetch_failed", "unparsed", "refused_link"):gaps.append(f"{label}: no cone, {forecast.get('cone_error')}")degraded = Trueelif cone_status == "not_linked":diff --git a/src/world_intel_mcp/tests/test_sources_cyclone_forecasts.py b/src/world_intel_mcp/tests/test_sources_cyclone_forecasts.pyindex 36c672e..08ca24a 100644--- a/src/world_intel_mcp/tests/test_sources_cyclone_forecasts.py+++ b/src/world_intel_mcp/tests/test_sources_cyclone_forecasts.py@@ -453,6 +453,60 @@ async def test_nhc_storm_without_a_forecast_advisory_link_is_a_gap_not_a_failureassert routes["tcm"].called is False+async def test_nhc_product_links_off_the_nhc_host_are_refused_not_fetched(+ fetcher: Fetcher,+) -> None:+ """Product links come from the feed: one that is not https on+ www.nhc.noaa.gov is never requested. A request would reach respx+ unmocked and read as fetch_failed, not refused_link."""+ current = _current_storms()+ storm = current["activeStorms"][0]+ storm["forecastAdvisory"]["url"] = "https://127.0.0.1:8080/text/MIATCMEP1.shtml"+ storm["trackCone"]["kmzFile"] = _CONE_URL.replace("https://", "http://")+ routes = _mock_nhc(current=current)++ result = await fetch_cyclones(fetcher, include_forecast=True)++ fc = result["storms"][0]["forecast"]+ assert fc["track_status"] == "refused_link"+ assert fc["points"] == []+ assert fc["cone_status"] == "refused_link"+ assert fc["cone"] is None+ assert result["degraded"] is True+ assert result["data_gaps"] == [+ "Trudy (ep212026): forecast track refused_link: forecast/advisory link "+ "'https://127.0.0.1:8080/text/MIATCMEP1.shtml' is not https on "+ "www.nhc.noaa.gov; not fetched",+ "Trudy (ep212026): no cone, cone KMZ link "+ "'http://www.nhc.noaa.gov/storm_graphics/api/EP212026_017adv_CONE.kmz' "+ "is not https on www.nhc.noaa.gov; not fetched",+ ]+ assert routes["tcm"].called is False+ assert routes["cone"].called is False+++ ("url", "allowed"),+ [+ ("https://www.nhc.noaa.gov/text/MIATCMEP1.shtml", True),+ ("https://WWW.NHC.NOAA.GOV/text/MIATCMEP1.shtml", True),+ ("https://www.nhc.noaa.gov:443/text/MIATCMEP1.shtml", True),+ ("http://www.nhc.noaa.gov/text/MIATCMEP1.shtml", False),+ ("https://www.nhc.noaa.gov:8443/text/MIATCMEP1.shtml", False),+ ("https://www.nhc.noaa.gov:99999/text/MIATCMEP1.shtml", False),+ ("https://[email protected]/latest", False),+ ("https://www.nhc.noaa.gov.example.net/text/MIATCMEP1.shtml", False),+ ("https://nhc.noaa.gov/text/MIATCMEP1.shtml", False),+ ("file:///etc/passwd", False),+ ("/text/MIATCMEP1.shtml", False),+ ],+)+def test_product_link_allowlist(url: str, allowed: bool) -> None:+ assert (cf._refused_link(url, cf._NHC_PRODUCT_HOSTS) is None) is allowed++# ---------------------------------------------------------------------------# NHC parsers: direct# ---------------------------------------------------------------------------@@ -487,6 +541,27 @@ def test_cone_kml_with_doctype_is_refused() -> None:cf.parse_nhc_cone_kmz(_kmz(kml))+def _ring_kml(vertices: int) -> str:+ """A closed ring of ``vertices`` distinct points in a minimal cone KML."""+ points = [f"{-100 + i * 1e-4:.4f},{15 + (i % 2) * 1e-4:.4f},0" for i in range(vertices)]+ return (+ '<?xml version="1.0" encoding="UTF-8"?>'+ '<kml xmlns="http://www.opengis.net/kml/2.2"><Placemark><Polygon>'+ "<outerBoundaryIs><LinearRing><coordinates>"+ + " ".join(points + points[:1])+ + "</coordinates></LinearRing></outerBoundaryIs></Polygon></Placemark></kml>"+ )+++def test_cone_ring_over_the_vertex_cap_is_refused_before_simplifying() -> None:+ """Douglas-Peucker is quadratic in the worst case; a ring past the cap+ is refused, one at the cap is simplified."""+ at_cap = cf.parse_nhc_cone_kmz(_kmz(_ring_kml(cf._CONE_MAX_VERTICES)))+ assert at_cap["source_vertex_count"] == cf._CONE_MAX_VERTICES+ with pytest.raises(ValueError, match="over the cap"):+ cf.parse_nhc_cone_kmz(_kmz(_ring_kml(cf._CONE_MAX_VERTICES + 1)))++def test_forecast_advisory_without_synoptic_line_keeps_times_drops_tau() -> None:text = _fixture("nhc_tcm_ep212026_adv017.txt").replace("AT 17/1200Z CENTER WAS LOCATED NEAR 16.3N 103.7W\n", ""@@ -730,6 +805,24 @@ async def test_jtwc_unlinked_text_is_a_gap_and_the_fan_out_cap_a_failure(assert sum("per-call cap" in g for g in gaps) == 1+async def test_jtwc_warning_link_off_the_jtwc_host_is_refused_not_fetched(+ fetcher: Fetcher,+) -> None:+ storm = _unlinked_jtwc_storm(0)+ storm["warning_text_url"] = "https://www.metoc.navy.mil.example.net/jtwc/products/wp0026web.txt"+ gaps, degraded = await cf.attach_jtwc_forecasts(fetcher, [storm])+ assert storm["forecast"]["track_status"] == "refused_link"+ assert storm["forecast"]["points"] == []+ assert degraded is True+ assert gaps[0] == (+ "Storm0 (00W): forecast track refused_link: warning text link "+ "'https://www.metoc.navy.mil.example.net/jtwc/products/wp0026web.txt' "+ "is not https on www.metoc.navy.mil; not fetched"+ )++@respx.mock@pytest.mark.asyncioasync def test_jtwc_text_without_forecast_positions_is_unparsed_and_refetched(