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.

Fetcher: optional accept_404 predicate on get_bytes

Phoenix Agent (mac-studio)5ba2891ac61f
diff --git a/src/world_intel_mcp/fetcher.py b/src/world_intel_mcp/fetcher.py
index 8bdd7e3..e71a534 100644
--- a/src/world_intel_mcp/fetcher.py
+++ b/src/world_intel_mcp/fetcher.py
@@ -9,7 +9,7 @@ import asyncio
import logging
import time
from dataclasses import dataclass
-from typing import Any
+from typing import Any, Callable
import httpx
@@ -55,7 +55,8 @@ class BinaryResult:
``status`` is the final HTTP status (None when no response arrived),
``content`` the body on 2xx, ``error`` a short reason otherwise. A
404 is reported as ``status=404`` with no error so callers can tell
- "not published (yet)" apart from "the fetch failed".
+ "not published (yet)" apart from "the fetch failed"; a 404 rejected
+ by ``accept_404`` carries an error like any failed fetch.
"""
status: int | None
@@ -278,6 +279,7 @@ class Fetcher:
headers: dict[str, str] | None = None,
timeout: float | None = None,
max_bytes: int = 256 * 1024 * 1024,
+ accept_404: Callable[[bytes], bool] | None = None,
) -> BinaryResult:
"""Fetch a binary body with rate limiting, retries and circuit breaking.
@@ -285,6 +287,13 @@ class Fetcher:
SQLite 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.
+
+ ``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.
"""
if not self.breaker.is_available(source):
return BinaryResult(None, None, f"circuit open for {source}")
@@ -300,7 +309,7 @@ class Fetcher:
url, headers=headers, timeout=timeout or self.default_timeout
)
last_status = resp.status_code
- if resp.status_code == 404:
+ 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()
diff --git a/src/world_intel_mcp/tests/test_fetcher_accept_404.py b/src/world_intel_mcp/tests/test_fetcher_accept_404.py
new file mode 100644
index 0000000..7fd81dc
--- /dev/null
+++ b/src/world_intel_mcp/tests/test_fetcher_accept_404.py
@@ -0,0 +1,148 @@
+"""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``, 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.
+"""
+
+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
+
+
+ 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)