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
Merge feat/cyclone-forecasts round 2: date-proof tests, one stale rule, KMZ caps, no product redirects, streamed body cap
Phoenix Agent (mac-studio)405878200d71
diff --cc src/world_intel_mcp/fetcher.pyindex 2374ae2,8d02345..fa454e3--- a/src/world_intel_mcp/fetcher.py+++ b/src/world_intel_mcp/fetcher.py@@@ -6,12 -6,11 +6,13 @@@ response is returned (marked with _stal"""import asyncio+ import contextlibimport logging+import os+import sqlite3import timefrom dataclasses import dataclass-from typing import Any+from typing import Any, Callableimport httpx@@@ -61,8 -55,9 +62,10 @@@ class BinaryResult``status`` is the final HTTP status (None when no response arrived),``content`` the body on 2xx, ``error`` a short reason otherwise. A404 is reported as ``status=404`` with no error so callers can tell- "not published (yet)" apart from "the fetch failed". ``location`` is- the absolute redirect target when ``follow_redirects=False`` and the+ "not published (yet)" apart from "the fetch failed"; a 404 rejected- by ``accept_404`` carries an error like any failed fetch.++ by ``accept_404`` carries an error like any failed fetch. ``location``++ is the absolute redirect target when ``follow_redirects=False`` and the+ URL answered with a redirect (which was not requested)."""status: int | None@@@ -290,21 -282,31 +294,40 @@@ class Fetchertimeout: float | None = None,max_bytes: int = 256 * 1024 * 1024,*,+ accept_404: Callable[[bytes], bool] | None = None,+ follow_redirects: bool = True,) -> BinaryResult:"""Fetch a binary body with rate limiting, retries and circuit breaking.Not cached here: binary payloads (multi-MB) do not belong in theSQLite TTL cache, so callers own any on-disk caching. A 404 is a- definitive answer (not retried, not a breaker failure). A body- larger than ``max_bytes`` is refused rather than buffered.+ definitive answer (not retried, not a breaker failure). The body+ is read as it arrives and refused as soon as its decoded size+ passes ``max_bytes``, so no more than ``max_bytes`` plus one+ decoded network read is held (one 64 KiB read of gzip can decode+ to about 64 MiB). With ``follow_redirects=False`` a redirect is+ also a definitive answer, and its target is never requested.+ ``accept_404`` (a predicate on the 404 body that must not raise)+ separates the API's own "not found" from a 404 sent by something+ in front of it, such as a proxy error page. A 404 it rejects is+ handled like any other HTTP error: retried, then counted as a+ breaker failure and returned as ``BinaryResult(404, None, error)``.- Without it, every 404 is a definitive answer.++ Without it, every 404 is a definitive answer. A 404 body is read++ for it only up to ``max_bytes``; a longer one counts as rejected.+++ The result (see BinaryResult), by outcome:++ - body: ``status`` 2xx, ``content`` the decoded body.+ - 404: ``status`` 404, ``content`` None, ``error`` None.+ - redirect not followed: ``status`` 3xx, ``content`` None,+ ``error`` "redirect to <location> not followed", ``location``+ the absolute target. ``location`` is None in every other case.+ - over the cap: ``status`` 2xx, ``content`` None, ``error``+ "body exceeds cap <max_bytes>: stopped after <n> decoded bytes".+ - failure (HTTP or transport error after the retries, or an open+ circuit): ``status`` the last status or None, ``content`` None,+ ``error`` a one-line reason."""if not self.breaker.is_available(source):return BinaryResult(None, None, f"circuit open for {source}")@@@ -313,27 -316,42 +336,52 @@@last_error = "unknown error"last_status: int | None = None++ async def read_capped(resp: httpx.Response) -> tuple[bytes | None, int]:++ chunks: list[bytes] = []++ size = 0++ async with contextlib.aclosing(resp.aiter_bytes()) as decoded:++ async for chunk in decoded:++ size += len(chunk)++ if size > max_bytes:++ return None, size++ chunks.append(chunk)++ return b"".join(chunks), size++for attempt in range(self.max_retries + 1):+ await self._source_throttle(source)try:- resp = await client.get(- url, headers=headers, timeout=timeout or self.default_timeout- )- last_status = resp.status_code- if resp.status_code == 404 and (accept_404 is None or accept_404(resp.content)):- self.breaker.record_success(source)- return BinaryResult(404, None, None)- resp.raise_for_status()- body = resp.content- if len(body) > max_bytes:- self.breaker.record_success(source)+ async with client.stream(+ "GET",+ url,+ headers=headers,+ timeout=timeout or self.default_timeout,+ follow_redirects=follow_redirects,+ ) as resp:+ last_status = resp.status_code+ if not follow_redirects and resp.next_request is not None:+ location = str(resp.next_request.url)+ self.breaker.record_success(source)+ return BinaryResult(+ resp.status_code, None, f"redirect to {location} not followed", location+ )+ if resp.status_code == 404:- self.breaker.record_success(source)- return BinaryResult(404, None, None)++ if accept_404 is None:++ self.breaker.record_success(source)++ return BinaryResult(404, None, None)++ not_found, _ = await read_capped(resp)++ if not_found is not None and accept_404(not_found):++ self.breaker.record_success(source)++ return BinaryResult(404, None, None)+ resp.raise_for_status()- chunks: list[bytes] = []- size = 0- async with contextlib.aclosing(resp.aiter_bytes()) as decoded:- async for chunk in decoded:- size += len(chunk)- if size > max_bytes:- break- chunks.append(chunk)++ body, size = await read_capped(resp)+ self.breaker.record_success(source)- if size > max_bytes:++ if body is None:return BinaryResult(- resp.status_code,+ last_status,None,- f"body of {len(body)} bytes exceeds cap {max_bytes}",+ f"body exceeds cap {max_bytes}: stopped after {size} decoded bytes",)- self.breaker.record_success(source)- return BinaryResult(resp.status_code, body, None)- return BinaryResult(last_status, b"".join(chunks), None)++ return BinaryResult(last_status, body, None)except (httpx.HTTPStatusError, httpx.RequestError) as exc:last_error = f"{type(exc).__name__}: {exc}"if attempt < self.max_retries:diff --cc src/world_intel_mcp/tests/test_fetcher_accept_404.pyindex cafff83,0000000..8072376mode 100644,000000..100644--- a/src/world_intel_mcp/tests/test_fetcher_accept_404.py+++ b/src/world_intel_mcp/tests/test_fetcher_accept_404.py@@@ -1,163 -1,0 +1,202 @@@+"""Tests for Fetcher.get_bytes(accept_404=...).++A 404 is normally a definitive answer: not retried, not a source+failure. An API that answers "no data" with a 404 of a known shape can+pass ``accept_404`` (keyword-only), a predicate on the 404 body: a 404+it accepts stays a definitive answer, a 404 it rejects (an error page+from a proxy in front of the API) is retried and counted as a failure+like any other HTTP error status. Callers that pass no predicate are+unaffected.++Gaps / not covered: a predicate that raises (the contract says it must+not); get_text, get_json and get_xml have no such option.+"""++import inspect+from unittest.mock import AsyncMock++import httpx+import pytest+import respx++from world_intel_mcp.cache import Cache+from world_intel_mcp.circuit_breaker import CircuitBreaker+from world_intel_mcp.fetcher import BinaryResult, Fetcher++_URL = "https://a.test/data"+_HTML_404 = b"<html><body><h1>404 Not Found</h1>nginx</body></html>"+_PROBLEM_404 = b'{"title":"Not Found","status":404,"detail":"No Series was returned for the query"}'+++def _json_object(body: bytes) -> bool:+ return body.lstrip().startswith(b"{")+++async def fetcher(tmp_path):+ """Like the conftest fetcher, but closes its client and cache afterwards."""+ f = Fetcher(cache=Cache(db_path=tmp_path / "accept404.db"), breaker=CircuitBreaker(), default_timeout=5.0)+ yield f+ await f.close()+ f.cache.close()+++def sleep(monkeypatch: pytest.MonkeyPatch) -> AsyncMock:+ mock = AsyncMock()+ monkeypatch.setattr("world_intel_mcp.fetcher.asyncio.sleep", mock)+ return mock+++async def test_rejected_404_is_retried_and_counted_as_a_failure(fetcher: Fetcher, sleep: AsyncMock) -> None:+ fetcher.max_retries = 2+ route = respx.get(_URL).mock(+ return_value=httpx.Response(404, content=_HTML_404, headers={"content-type": "text/html"})+ )++ result = await fetcher.get_bytes(_URL, source="t", accept_404=_json_object)++ assert result.status == 404+ assert result.content is None+ assert result.error is not None and result.error.startswith("HTTPStatusError: Client error '404 Not Found'")+ assert route.call_count == 3+ assert sleep.await_count == 2+ state = fetcher.breaker.status()["t"]+ assert state["total_failures"] == 1 and state["total_successes"] == 0+++async def test_rejected_404_failures_open_the_circuit_like_any_error(fetcher: Fetcher, sleep: AsyncMock) -> None:+ fetcher.max_retries = 0+ route = respx.get(_URL).mock(return_value=httpx.Response(404, content=_HTML_404))+ for _ in range(fetcher.breaker.failure_threshold):+ await fetcher.get_bytes(_URL, source="t", accept_404=_json_object)++ assert fetcher.breaker.status()["t"]["status"] == "open"+ blocked = await fetcher.get_bytes(_URL, source="t", accept_404=_json_object)+ assert blocked == BinaryResult(None, None, "circuit open for t")+ assert route.call_count == fetcher.breaker.failure_threshold+++async def test_rejected_404_then_a_body_on_retry_is_a_normal_success(fetcher: Fetcher, sleep: AsyncMock) -> None:+ fetcher.max_retries = 2+ route = respx.get(_URL).mock(+ side_effect=[httpx.Response(404, content=_HTML_404), httpx.Response(200, content=b"body")]+ )++ result = await fetcher.get_bytes(_URL, source="t", accept_404=_json_object)++ assert result == BinaryResult(200, b"body", None)+ assert route.call_count == 2+ assert sleep.await_count == 1+ assert fetcher.breaker.status()["t"]["total_failures"] == 0+++async def test_accepted_404_stays_a_definitive_answer_and_the_predicate_sees_the_body(+ fetcher: Fetcher, sleep: AsyncMock+) -> None:+ fetcher.max_retries = 2+ seen: list[bytes] = []++ def accept(body: bytes) -> bool:+ seen.append(body)+ return True++ route = respx.get(_URL).mock(return_value=httpx.Response(404, content=_PROBLEM_404))++ result = await fetcher.get_bytes(_URL, source="t", accept_404=accept)++ assert result == BinaryResult(404, None, None)+ assert seen == [_PROBLEM_404]+ assert route.call_count == 1+ sleep.assert_not_awaited()+ state = fetcher.breaker.status()["t"]+ assert state["total_failures"] == 0 and state["total_successes"] == 1++[email protected]("body", [+ pytest.param(_HTML_404, id="html"), pytest.param(_PROBLEM_404, id="problem-json"), pytest.param(b"", id="empty"),+])+async def test_without_a_predicate_every_404_is_a_definitive_answer(+ fetcher: Fetcher, sleep: AsyncMock, body: bytes+) -> None:+ fetcher.max_retries = 2+ route = respx.get(_URL).mock(return_value=httpx.Response(404, content=body))++ result = await fetcher.get_bytes(_URL, source="t")++ assert result == BinaryResult(404, None, None)+ assert route.call_count == 1+ sleep.assert_not_awaited()+ state = fetcher.breaker.status()["t"]+ assert state["total_failures"] == 0 and state["total_successes"] == 1++[email protected]("status", [200, 410, 500])+async def test_the_predicate_is_consulted_only_for_404(fetcher: Fetcher, sleep: AsyncMock, status: int) -> None:+ fetcher.max_retries = 0+ calls: list[bytes] = []+ respx.get(_URL).mock(return_value=httpx.Response(status, content=b"x"))++ result = await fetcher.get_bytes(_URL, source="t", accept_404=lambda body: calls.append(body) or True)++ assert calls == []+ assert result.status == status+ assert result.ok is (status == 200)+++async def test_accept_404_is_keyword_only(fetcher: Fetcher, sleep: AsyncMock) -> None:+ """A parameter another change adds after max_bytes can never be bound+ to the predicate by position, nor the predicate to it."""+ route = respx.get(_URL).mock(return_value=httpx.Response(404, content=_HTML_404))+ param = inspect.signature(Fetcher.get_bytes).parameters["accept_404"]+ assert param.kind is inspect.Parameter.KEYWORD_ONLY and param.default is None++ with pytest.raises(TypeError):+ await fetcher.get_bytes(_URL, "t", None, None, 1024, _json_object)+ assert route.call_count == 0++++++async def test_accepted_404_body_is_read_through_the_stream(fetcher: Fetcher, sleep: AsyncMock) -> None:++ """get_bytes streams its response, so the predicate gets the 404 body++ read from the stream, not resp.content (which raises on a stream)."""++ seen: list[bytes] = []++++ def accept(body: bytes) -> bool:++ seen.append(body)++ return True++++ respx.get(_URL).mock(return_value=httpx.Response(404, content=_PROBLEM_404))++++ result = await fetcher.get_bytes(_URL, source="t", accept_404=accept)++++ assert result == BinaryResult(404, None, None)++ assert seen == [_PROBLEM_404]++++++async def test_404_body_over_the_cap_counts_as_rejected(fetcher: Fetcher, sleep: AsyncMock) -> None:++ """A 404 body is read for the predicate only up to max_bytes; a longer++ one is never handed to it and is handled as a rejected 404."""++ fetcher.max_retries = 0++ seen: list[bytes] = []++++ def accept(body: bytes) -> bool:++ seen.append(body)++ return True++++ respx.get(_URL).mock(return_value=httpx.Response(404, content=_PROBLEM_404))++++ result = await fetcher.get_bytes(_URL, source="t", max_bytes=len(_PROBLEM_404) - 1, accept_404=accept)++++ assert seen == []++ assert result.status == 404 and result.content is None++ assert result.error is not None and result.error.startswith("HTTPStatusError: Client error '404 Not Found'")++ assert fetcher.breaker.status()["t"]["total_failures"] == 1