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
Border crossings: never follow redirects, cap each download as it streams
Phoenix Agent (mac-studio)2303662d85b3
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 35013b7..5448290 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1065,9 +1065,11 @@ source here, and no proxy is substituted for any of these measures.paths it disallows are never requested; a newer-looking CBP file at sucha path is named in `data_gaps` instead, as is any encounters link thetool cannot read (including names with "_" or a space after- "nationwide"). Redirects are followed, and the- download size caps apply after the body is read, both in the shared- fetcher (see the module's gaps).+ "nationwide"). No redirect is followed: a 3xx from any of the four+ requests reads as a failed refresh naming its Location (degraded, or the+ last good copy marked stale), never as data. Downloads stop as soon as+ the decoded body passes its cap (CBP page 2 MiB, CBP CSV 32 MiB, GOV.UK+ Content API 2 MiB, Home Office ODS 8 MiB), and the refusal names the cap.- Frontex is not built: its only data file is an XLSX under `/assets/`,which its robots.txt disallows (measured 2026-10-17, see ROADMAP Phase 28).- Tools 139 -> 141.diff --git a/ROADMAP.md b/ROADMAP.mdindex a387445..b281d42 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -566,10 +566,9 @@ identifying User-Agent:Not exposed yet: CBP sector and field-office (area of responsibility) andby-state detail, and CBP years before FY2023 (robots-disallowed path).-Open (shared fetcher): redirects are followed, and the download size caps-apply only after the body is read; the fix is for both tools to request-with `Fetcher.get_bytes(..., follow_redirects=False)` once the fetcher-offers it.+Both tools request with `Fetcher.get_bytes(..., follow_redirects=False)`+and a per-request cap checked as the body streams in; a redirect or a body+past its cap reads as a failed refresh that names the Location or the cap.---diff --git a/src/world_intel_mcp/sources/border_crossings.py b/src/world_intel_mcp/sources/border_crossings.pyindex 0924e23..8c36188 100644--- a/src/world_intel_mcp/sources/border_crossings.py+++ b/src/world_intel_mcp/sources/border_crossings.py@@ -54,17 +54,21 @@ Gaps / not covered:2026-10-17 their figures matched the ODS).* robots.txt is not re-read at run time; the CBP path rule is pinned as read on2026-10-17.-* Redirects: the shared fetcher follows them, and only the first URL is- checked against the host, scheme and robots.txt rules, so a redirect could- reach a path those rules refuse and the response would name the first URL.- Download caps are checked after the whole decoded body is in memory. Both- are fetcher behaviour and are left to the fetcher.+* Redirects are never followed: a redirect's target was not checked against+ the host, scheme and robots.txt rules, so a 3xx from any of the four+ requests reads as a failed refresh naming its Location (degraded, or the+ last good copy marked stale), never as data. A publisher that moves a file+ behind a redirect therefore reads as an outage until the module follows it.+* Download caps, checked as the body streams in (decoded size): CBP dataset+ page 2 MiB (123 kB on 2026-10-17), CBP CSV 32 MiB (6.7 MB), GOV.UK Content+ API item 2 MiB (133 kB), Home Office ODS 8 MiB (77 kB). A body past its cap+ reads as a failed refresh naming the cap.* Memory, measured 2026-10-17 (peak RSS growth): the ODS limits bound what thereader keeps and what expat holds, but zipfile reads the whole centraldirectory when it opens an archive (400,000 empty entries, a 35 MB file:- about 230 MB), bounded only by the 32 MiB download cap. The CBP CSV is parsed+ about 230 MB), bounded only by the 8 MiB download cap. The CBP CSV is parsedwhole: a crafted 64 MiB file with every row a new citizenship took about- 470 MB (the live 6.7 MB file about 21 MB).+ 470 MB (the live 6.7 MB file about 21 MB); the cap is now 32 MiB.* Neither file has a person identifier, so neither series counts uniquepeople; the responses say so as a tool note, not in the publishers' words."""@@ -134,6 +138,22 @@ def _why(result: BinaryResult) -> str:return f"HTTP {result.status}" if result.status is not None else "no response"+_STOPPED_AFTER = re.compile(r"stopped after (\d+) decoded bytes")+++def _no_body(what: str, result: BinaryResult, cap: int) -> str:+ """Why a download gave no body, said for data_gaps. A redirect names its target, which was+ never requested; a body past the cap names the cap. Neither is ever read as data."""+ if result.location is not None:+ return (f"{what} redirects to {_shown(result.location)} (HTTP {result.status}); redirects are not "+ "followed, since their target is not checked against the host and robots.txt rules")+ stopped = _STOPPED_AFTER.search(result.error or "")+ if result.content is None and result.status is not None and 200 <= result.status < 300 and stopped:+ return (f"{what} is larger than this tool's {cap >> 20} MiB cap (stopped after {int(stopped[1]):,} "+ "bytes); refused")+ return f"{what} unavailable: {_why(result)}"++def _pct(current: int | None, prior: int | None) -> float | None:if current is None or not prior:return None@@ -231,8 +251,9 @@ CBP_STATS_PAGE = "https://www.cbp.gov/newsroom/stats/nationwide-encounters"CBP_CACHE_KEY = "border_crossings:cbp_encounters"_CBP_SCHEMA = 2 # 2: unreadable-byte rows and skipped links are recorded_CBP_TTL = 43200 # 12 h; CBP posts one file a month-_CBP_PAGE_MAX_BYTES = 8 * 1024 * 1024-_CBP_CSV_MAX_BYTES = 64 * 1024 * 1024 # the August 2026 file is 6.7 MB+# Download caps (decoded bytes, whole MiB): each at least 4x the 17 October 2026 payload.+_CBP_PAGE_MAX_BYTES = 2 * 1024 * 1024 # the dataset page was 123 kB+_CBP_CSV_MAX_BYTES = 32 * 1024 * 1024 # the August 2026 file is 6.7 MB, one year more is about 8.4 MB_CBP_HOST = "www.cbp.gov"# https://www.cbp.gov/robots.txt, read 2026-10-17: "#Disallow the files/assets/documents directory"._CBP_DISALLOWED_PREFIXES = ("/sites/default/files/assets/documents/",)@@ -688,10 +709,10 @@ def cbp_page_last_modified(html: str) -> str | None:async def _fetch_cbp_dataset(fetcher: Fetcher) -> dict[str, Any]:page_result = await fetcher.get_bytes(- CBP_DATASET_PAGE, CBP_SOURCE, headers=_HEADERS, max_bytes=_CBP_PAGE_MAX_BYTES+ CBP_DATASET_PAGE, CBP_SOURCE, headers=_HEADERS, max_bytes=_CBP_PAGE_MAX_BYTES, follow_redirects=False)if page_result.content is None:- raise _SourceError("cbp_fetch_failed", f"CBP dataset page unavailable: {_why(page_result)}")+ raise _SourceError("cbp_fetch_failed", _no_body("CBP dataset page", page_result, _CBP_PAGE_MAX_BYTES))try:page = _parse_page(page_result.content.decode("utf-8", errors="replace"))latest, skipped, text = _latest_file(page), _skipped_links(page), _page_text(page)@@ -706,9 +727,11 @@ async def _fetch_cbp_dataset(fetcher: Fetcher) -> dict[str, Any]:"robots.txt allows" + (f"; links it has that this tool cannot read: {', '.join(skipped[:5])}"if skipped else ""),)- csv_result = await fetcher.get_bytes(latest["url"], CBP_SOURCE, headers=_HEADERS, max_bytes=_CBP_CSV_MAX_BYTES)+ csv_result = await fetcher.get_bytes(+ latest["url"], CBP_SOURCE, headers=_HEADERS, max_bytes=_CBP_CSV_MAX_BYTES, follow_redirects=False+ )if csv_result.content is None:- raise _SourceError("cbp_fetch_failed", f"CBP encounters file unavailable: {_why(csv_result)}")+ raise _SourceError("cbp_fetch_failed", _no_body("CBP encounters file", csv_result, _CBP_CSV_MAX_BYTES))try:# A byte that is not UTF-8 becomes U+FFFD, which parse_cbp_csv counts per row instead of# failing the file over it.@@ -953,8 +976,8 @@ UK_CONTENT_API = "https://www.gov.uk/api/content" + UK_PUBLICATION_PATHUK_CACHE_KEY = "border_crossings:uk_small_boats"_UK_SCHEMA = 2 # 2: rows dated outside the series window are left out (an older copy may hold them)_UK_TTL = 10800 # 3 h; its change history shows 72 updates from 1 August to 16 October 2026-_UK_API_MAX_BYTES = 8 * 1024 * 1024-_UK_ODS_MAX_BYTES = 32 * 1024 * 1024 # the 16 October 2026 file is 76,787 bytes+_UK_API_MAX_BYTES = 2 * 1024 * 1024 # the Content API item was 133 kB+_UK_ODS_MAX_BYTES = 8 * 1024 * 1024 # the 16 October 2026 file is 76,787 bytes_UK_FILE_HOSTS = {"assets.publishing.service.gov.uk", "www.gov.uk"}_UK_GOV_UK_FILES = "/government/uploads/" # the only www.gov.uk path read: robots.txt disallows others_UK_FIRST_DAY = date(2018, 1, 1) # SB_01 starts on 1 January 2018@@ -1571,10 +1594,11 @@ def _uk_attachment(item: Any) -> dict[str, Any]:async def _fetch_uk_dataset(fetcher: Fetcher) -> dict[str, Any]:api = await fetcher.get_bytes(- UK_CONTENT_API, UK_SOURCE, headers={**_HEADERS, "Accept": "application/json"}, max_bytes=_UK_API_MAX_BYTES+ UK_CONTENT_API, UK_SOURCE, headers={**_HEADERS, "Accept": "application/json"}, max_bytes=_UK_API_MAX_BYTES,+ follow_redirects=False,)if api.content is None:- raise _SourceError("uk_fetch_failed", f"GOV.UK Content API unavailable: {_why(api)}")+ raise _SourceError("uk_fetch_failed", _no_body("GOV.UK Content API", api, _UK_API_MAX_BYTES))try:item = json.loads(api.content)except MemoryError:@@ -1586,9 +1610,11 @@ async def _fetch_uk_dataset(fetcher: Fetcher) -> dict[str, Any]:if history is not None and not isinstance(history, list):raise _SourceError("uk_unexpected_format", "GOV.UK Content API response not readable: its change_history "f"is not a list ({type(history).__name__})")- ods = await fetcher.get_bytes(attachment["url"], UK_SOURCE, headers=_HEADERS, max_bytes=_UK_ODS_MAX_BYTES)+ ods = await fetcher.get_bytes(+ attachment["url"], UK_SOURCE, headers=_HEADERS, max_bytes=_UK_ODS_MAX_BYTES, follow_redirects=False+ )if ods.content is None:- raise _SourceError("uk_fetch_failed", f"Home Office time series unavailable: {_why(ods)}")+ raise _SourceError("uk_fetch_failed", _no_body("Home Office time series", ods, _UK_ODS_MAX_BYTES))try:tables = read_ods_tables(ods.content, _UK_SHEETS)if not {"SB_01", "SB_02"} <= tables.keys():diff --git a/src/world_intel_mcp/tests/test_sources_border_crossings_redirects.py b/src/world_intel_mcp/tests/test_sources_border_crossings_redirects.pynew file mode 100644index 0000000..e95f6e9--- /dev/null+++ b/src/world_intel_mcp/tests/test_sources_border_crossings_redirects.py@@ -0,0 +1,216 @@+"""Border crossings: redirects are never followed and every download has its own cap.++All offline: respx serves the fixtures of ``test_sources_border_crossings``. Each of the+four requests (CBP dataset page, CBP CSV, GOV.UK Content API, Home Office ODS) is tested on+its own: a 302 whose target would return good data, a body one byte past the cap, and a+body exactly at the cap.++Gaps / not covered:++* The fetcher's streaming cap itself (decoded size, one network read past the cap) is the+ fetcher's to test; here respx delivers each body in one piece.+* No live publisher was asked whether it redirects today; a redirect reads as an outage.+"""++from __future__ import annotations++import io+import json+import re+import zipfile+from dataclasses import dataclass++import httpx+import pytest+import respx++from world_intel_mcp.fetcher import Fetcher+from world_intel_mcp.sources import border_crossings as bc++from .test_sources_border_crossings import (+ _CBP_CSV_URL,+ _CBP_HEADER,+ _CBP_NORTHERN_USBP_AUG,+ _CBP_PAGE,+ _UK_ITEM,+ _UK_ODS_URL,+ _main_ods,+ _no_sleep,+)++_MIB = 1024 * 1024+++@dataclass(frozen=True)+class _Site:+ name: str # the request under test+ what: str # how the module names it+ url: str+ cap_mib: int+ us: bool+++_SITES = [+ _Site("cbp_page", "CBP dataset page", bc.CBP_DATASET_PAGE, 2, True),+ _Site("cbp_csv", "CBP encounters file", _CBP_CSV_URL, 32, True),+ _Site("uk_api", "GOV.UK Content API", bc.UK_CONTENT_API, 2, False),+ _Site("uk_ods", "Home Office time series", _UK_ODS_URL, 8, False),+]+_IDS = [site.name for site in _SITES]+++def _good() -> dict[str, httpx.Response]:+ return {+ bc.CBP_DATASET_PAGE: httpx.Response(200, text=_CBP_PAGE, headers={"content-type": "text/html; charset=utf-8"}),+ _CBP_CSV_URL: httpx.Response(200, text=_CBP_HEADER + "\n" + _CBP_NORTHERN_USBP_AUG,+ headers={"content-type": "text/csv"}),+ bc.UK_CONTENT_API: httpx.Response(200, json=_UK_ITEM),+ _UK_ODS_URL: httpx.Response(200, content=_main_ods(), headers={"content-type": bc._ODS_TYPE}),+ }+++def _good_body(site: _Site) -> bytes:+ return _good()[site.url].content+++async def _call(fetcher: Fetcher, site: _Site) -> dict:+ if site.us:+ return await bc.fetch_us_border_encounters(fetcher, region="northern", component="usbp")+ return await bc.fetch_uk_small_boat_arrivals(fetcher)+++async def _with(fetcher: Fetcher, site: _Site, response: httpx.Response, extra: dict | None = None) -> tuple:+ """The tool's result with `site` answering `response` and the other requests answering well."""+ routes = {**_good(), site.url: response}+ with respx.mock(assert_all_called=False) as mock:+ handles = {url: mock.get(url).mock(return_value=answer) for url, answer in {**routes, **(extra or {})}.items()}+ result = await _call(fetcher, site)+ return result, handles+++def _figures(site: _Site) -> str:+ return "latest" if site.us else "latest_day"+++# ---------------------------------------------------------------------------+# Redirects+# ---------------------------------------------------------------------------+[email protected]("site", _SITES, ids=_IDS)+async def test_a_redirect_is_never_followed_and_is_named(fetcher: Fetcher, site: _Site) -> None:+ # Invented target, robots-disallowed for CBP; it would answer with good data if requested.+ target = ("https://www.cbp.gov/sites/default/files/assets/documents/2026-10/elsewhere.csv" if site.us+ else "https://assets.publishing.service.gov.uk/media/elsewhere/time_series.ods")+ result, handles = await _with(fetcher, site, httpx.Response(302, headers={"Location": target}),+ extra={target: httpx.Response(200, content=_good_body(site))})+ assert not handles[target].called # never requested+ assert result["degraded"] is True and result["reason"] == ("cbp_fetch_failed" if site.us else "uk_fetch_failed")+ assert result["error"] == (f"{site.what} redirects to {target} (HTTP 302); redirects are not followed, since "+ "their target is not checked against the host and robots.txt rules")+ assert result["data_gaps"] == [f"No figures: {result['error']}."]+ assert _figures(site) not in result++[email protected]("status", [301, 303, 307, 308])+async def test_every_redirect_status_reads_as_a_failed_refresh(fetcher: Fetcher, status: int) -> None:+ site = _SITES[0]+ target = "https://www.cbp.gov/document/stats/moved" # invented+ result, handles = await _with(fetcher, site, httpx.Response(status, headers={"Location": target}),+ extra={target: httpx.Response(200, text=_CBP_PAGE)})+ assert not handles[target].called+ assert result["degraded"] is True and f"redirects to {target} (HTTP {status})" in result["error"]+++async def test_a_redirect_location_has_its_credentials_masked(fetcher: Fetcher) -> None:+ site = _SITES[2]+ target = "https://[email protected]/api/content/x" # invented+ result, handles = await _with(fetcher, site, httpx.Response(302, headers={"Location": target}),+ extra={target: httpx.Response(200, json=_UK_ITEM)})+ assert not handles[target].called+ assert "redirects to https://***@gov.uk.example/api/content/x (HTTP 302)" in result["error"]+ assert "someone" not in json.dumps(result)++[email protected]("site", _SITES, ids=_IDS)+async def test_a_redirect_on_refresh_serves_the_last_good_copy_marked_stale(+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch, site: _Site) -> None:+ _no_sleep(monkeypatch)+ first, _handles = await _with(fetcher, site, _good()[site.url])+ key = bc.CBP_CACHE_KEY if site.us else bc.UK_CACHE_KEY+ value, _created = fetcher.cache.get_stale_meta(key)+ fetcher.cache.set(key, value, ttl_seconds=-1)+ target = "https://evil.example/x" # invented+ stale, handles = await _with(fetcher, site, httpx.Response(302, headers={"Location": target}),+ extra={target: httpx.Response(200, content=b"")})+ assert not handles[target].called+ assert stale["stale"] is True and stale[_figures(site)] == first[_figures(site)]+ assert any(gap.startswith(f"Refresh failed ({site.what} redirects to {target} (HTTP 302)")+ for gap in stale["data_gaps"])+++# ---------------------------------------------------------------------------+# Download caps+# ---------------------------------------------------------------------------+[email protected]("site", _SITES, ids=_IDS)+async def test_a_body_one_byte_past_its_cap_is_refused_and_the_cap_named(fetcher: Fetcher, site: _Site) -> None:+ body = _good_body(site)+ body += b" " * (site.cap_mib * _MIB + 1 - len(body)) # good data, one byte too long+ result, _handles = await _with(fetcher, site, httpx.Response(200, content=body))+ assert result["degraded"] is True and _figures(site) not in result+ assert re.fullmatch(rf"{re.escape(site.what)} is larger than this tool's {site.cap_mib} MiB cap "+ r"\(stopped after [0-9,]+ bytes\); refused", result["error"]), result["error"]+ assert result["data_gaps"] == [f"No figures: {result['error']}."]+++def _padded_ods(size: int) -> bytes:+ """The fixture ODS with a stored padding member, exactly `size` bytes long."""+ def build(pad: int) -> bytes:+ buf = io.BytesIO()+ with zipfile.ZipFile(io.BytesIO(_main_ods())) as source, zipfile.ZipFile(buf, "w") as out:+ for info in source.infolist():+ out.writestr(info, source.read(info.filename))+ out.writestr("Thumbnails/padding.bin", b"\0" * pad, compress_type=zipfile.ZIP_STORED)+ return buf.getvalue()++ data = build(size - len(build(0)))+ assert len(data) == size+ return data+++def _at_cap(site: _Site) -> bytes:+ cap = site.cap_mib * _MIB+ if site.name == "uk_ods":+ return _padded_ods(cap)+ body = _good_body(site)+ if site.name == "cbp_csv": # a trailing line of padding: one unreadable row, named+ return body + b"\n" + b"x" * (cap - len(body) - 1)+ return body + b" " * (cap - len(body))++[email protected]("site", _SITES, ids=_IDS)+async def test_a_body_exactly_at_its_cap_is_read(fetcher: Fetcher, site: _Site) -> None:+ body = _at_cap(site)+ assert len(body) == site.cap_mib * _MIB+ result, _handles = await _with(fetcher, site, httpx.Response(200, content=body))+ assert "degraded" not in result, result.get("error")+ if site.us:+ assert result["latest"]["encounters"] == 563+ else:+ assert result["latest_day"]["date"] == "2026-10-15"+++def test_caps_fit_each_payload() -> None:+ # At least 4x the 17 October 2026 payload, so a cap is not hit by normal growth.+ sizes = {"cbp_page": 123_000, "cbp_csv": 6_677_601, "uk_api": 133_000, "uk_ods": 76_787}+ caps = {"cbp_page": bc._CBP_PAGE_MAX_BYTES, "cbp_csv": bc._CBP_CSV_MAX_BYTES,+ "uk_api": bc._UK_API_MAX_BYTES, "uk_ods": bc._UK_ODS_MAX_BYTES}+ assert {name: cap // _MIB for name, cap in caps.items()} == {site.name: site.cap_mib for site in _SITES}+ assert all(caps[name] >= 4 * size for name, size in sizes.items())+++async def test_another_failure_still_reads_unavailable(fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch) -> None:+ _no_sleep(monkeypatch)+ site = _SITES[3]+ result, _handles = await _with(fetcher, site, httpx.Response(503))+ assert result["degraded"] is True and result["error"].startswith("Home Office time series unavailable: ")