Add fetch MCP server with proxy routing, challenge solving and failure reports
ci / static (push) Failing after 27s
ci / test-3.12 (push) Skipped
ci / test-3.13 (push) Skipped
ci / image (push) Skipped
ci / smoke (push) Skipped
ci / publish (push) Skipped

Live reads go through an operator proxy pool (round-robin over the newest 100
entries, cooling on connect failures, no direct fallback); stored clearances are
replayed only on the exit that earned them. Identity, clearance, solver and
Turnstile rungs escalate automatically. fetch_pages reads up to 12 URLs four at
a time with per-item isolation. report/reports/reports_update keep a durable
queue of unreadable pages for the operator.

Ships a pinned multi-stage image (non-root 10001, data in /data), an ordered CI
with static gates, tests on 3.12 and 3.13 at 85% coverage, an offline image
smoke, and sha/latest publishing gated on main.
This commit is contained in:
omar committed 2026-11-28 19:29:46 +03:00
commit 5d36fddd30
35 files changed
+7616

No files matched your search

BIN
View File
Binary file not shown.
+12
View File
@@ -0,0 +1,12 @@
*
!pyproject.toml
!uv.lock
!server.py
!transport.py
!proxy.py
!identity.py
!solve.py
!clearance.py
!reports.py
!html_reader.py
!json_reader.py
+31
View File
@@ -0,0 +1,31 @@
# Live traffic route. proxy sends every agent request through the operator pool
# and never falls back to direct. direct ignores the pool entirely.
MCP_LIVE_ROUTE=proxy
# Pick exactly one pool source. Leave the other empty.
# Literal JSON array of full proxy URLs (http, https, socks5, socks5h, credentials allowed).
MCP_PROXY_URLS=[]
# List service: one proxy URL per line, UTF-8, read directly and never proxied.
MCP_PROXY_LIST_URL=
MCP_PROXY_LIST_TOKEN=
MCP_PROXY_LIST_REFRESH_MINUTES=15
# One initial attempt plus this many retries for the whole request.
MCP_HTTP_MAX_RETRIES=3
# Trust store for https:// proxies: extra PEM appended to the bundled roots.
MCP_PROXY_CA=
# Optional request-based solver (cfsolve). Empty uses the default WSL command;
# "off" disables solving. A JSON array overrides the command prefix.
MCP_SOLVER=
MCP_SOLVER_PROFILE=profiles/safari-26-ios.json
MCP_SOLVER_TIMEOUT=120
MCP_TLS_PROFILE=
MCP_SOLVE_TURNSTILE=1
MCP_CLEARANCE_TTL=1800
# JSONL file for page-failure reports; the report tools append and rewrite it.
MCP_REPORT_FILE=
# Keep only the newest N pool entries; the catalog grows, rotation must not.
MCP_PROXY_LIMIT=100
+160
View File
@@ -0,0 +1,160 @@
# Public repository, self-hosted runner: trusted pushes only, so a fork cannot
# execute on the runner. Stages are sequential; nothing publishes unless every
# earlier stage is green.
name: ci
on:
push:
branches: [main]
workflow_dispatch:
permissions:
contents: read
defaults:
run:
shell: bash
env:
PYTHONUNBUFFERED: "1"
UV_LINK_MODE: copy
UV_PYTHON_DOWNLOADS: never
IMAGE: git.eeee.host/omar/fetch-mcp
jobs:
static:
name: static
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install tooling from the lock file
run: uv sync --locked --all-groups
- name: ASCII only
run: uv run --locked python scripts/check_ascii.py
- name: Lint and format
run: |
uv run --locked ruff check .
uv run --locked ruff format --check .
- name: Byte-compile everything
run: uv run --locked python -m compileall -q $(git ls-files '*.py')
test:
name: test-${{ matrix.python }}
needs: static
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
python: ["3.12", "3.13"]
steps:
- uses: actions/checkout@v4
- name: Select interpreter
run: |
uv python install ${{ matrix.python }}
uv venv --python ${{ matrix.python }}
- name: Install from the lock file
run: uv sync --locked --all-groups
- name: Tests with coverage gate
run: uv run --locked pytest -q --junitxml=junit.xml
- name: Keep the report
if: always()
uses: actions/upload-artifact@v3.2.2
with:
name: coverage-${{ matrix.python }}
path: |
coverage.xml
junit.xml
.coverage
if-no-files-found: warn
image:
name: image
needs: test
runs-on: ubuntu-latest
outputs:
digest: ${{ steps.build.outputs.digest }}
tag: ${{ steps.meta.outputs.tag }}
steps:
- uses: actions/checkout@v4
- name: Derive the content tag
id: meta
run: echo "tag=sha-$(git rev-parse --short=12 HEAD)" >> "$GITHUB_OUTPUT"
- name: Build
id: build
run: |
set -euo pipefail
docker build --pull --label "org.opencontainers.image.revision=$(git rev-parse HEAD)" \
-t "$IMAGE:${{ steps.meta.outputs.tag }}" .
docker image inspect "$IMAGE:${{ steps.meta.outputs.tag }}" --format '{{.Id}}'
docker save "$IMAGE:${{ steps.meta.outputs.tag }}" > /dev/null
- name: Record digest
run: echo "digest=$(docker image inspect "$IMAGE:${{ steps.meta.outputs.tag }}" --format '{{.Id}}')" >> "$GITHUB_OUTPUT"
id: digest
smoke:
name: smoke
needs: image
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Run the built image offline over stdio
run: |
set -euo pipefail
image="$IMAGE:${{ needs.image.outputs.tag }}"
name="smoke-$$"
docker create --name "$name" --network none -e MCP_LIVE_ROUTE=direct -i "$image" > /dev/null
trap 'docker rm -f "$name" > /dev/null 2>&1 || true' EXIT
python3 scripts/mcp_smoke.py | docker start -a -i "$name" > smoke.out
code=$(docker inspect --format '{{.State.ExitCode}}' "$name")
cat smoke.out
test "$code" = "0"
python3 - "$name" <<'PY'
import json, sys
lines = [line for line in open("smoke.out", encoding="utf-8") if line.strip()]
assert lines, "no stdout"
ids = []
for line in lines:
frame = json.loads(line)
assert frame.get("jsonrpc") == "2.0", frame
assert "error" not in frame, frame
if "id" in frame:
ids.append(frame["id"])
assert ids == [1, 2, 3], ids
init = next(json.loads(line) for line in lines if '"id": 1' in line or '"id":1' in line)
tools = init["result"]["capabilities"]["tools"]
assert tools is not None
print("smoke ok:", ids)
PY
- name: Keep the transcript
if: always()
uses: actions/upload-artifact@v3.2.2
with:
name: smoke
path: smoke.out
publish:
name: publish
needs: [image, smoke]
if: github.ref == 'refs/heads/main' && github.event_name == 'push'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Log in with the package token
run: echo "${{ secrets.REGISTRY_TOKEN }}" | docker login git.eeee.moe -u omar --password-stdin
- name: Push the immutable tag
run: |
set -euo pipefail
docker build -t "$IMAGE:${{ needs.image.outputs.tag }}" .
docker push "$IMAGE:${{ needs.image.outputs.tag }}"
- name: Move latest only if HEAD has not moved
run: |
set -euo pipefail
built=$(docker image inspect "$IMAGE:${{ needs.image.outputs.tag }}" --format '{{index .Config.Labels "org.opencontainers.image.revision"}}')
head=$(git rev-parse HEAD)
docker tag "$IMAGE:${{ needs.image.outputs.tag }}" "$IMAGE:latest"
if [ "$built" = "$head" ]; then
docker push "$IMAGE:latest"
else
echo "HEAD moved to $head, leaving latest alone"
fi
+4
View File
@@ -0,0 +1,4 @@
.venv/
__pycache__/
.clearance.json
.reports.jsonl
+27
View File
@@ -0,0 +1,27 @@
# syntax=docker/dockerfile:1
ARG PYTHON_IMAGE=python:3.13-slim@sha256:168d3a5d10f2152f8e8d77b6843ac82c22a846cfefeef7afdf9aa630404e82a7
FROM ${PYTHON_IMAGE} AS deps
ENV UV_COMPILE_BYTECODE=1 UV_LINK_MODE=copy UV_PYTHON_DOWNLOADS=never
RUN pip install --no-cache-dir uv==0.11.16
WORKDIR /app
COPY pyproject.toml uv.lock ./
RUN uv sync --locked --no-dev --no-install-project
FROM ${PYTHON_IMAGE} AS runtime
ENV PYTHONUNBUFFERED=1 \
PYTHONDONTWRITEBYTECODE=1 \
HOME=/app \
PATH=/app/.venv/bin:/usr/local/bin:/usr/bin:/bin \
MCP_LIVE_ROUTE=proxy \
MCP_SOLVER=off \
MCP_CLEARANCE_FILE=/data/.clearance.json \
MCP_REPORT_FILE=/data/.reports.jsonl
RUN mkdir -p /data && chown 10001:10001 /data
WORKDIR /app
COPY --from=deps --chown=10001:10001 /app/.venv /app/.venv
COPY --chown=10001:10001 server.py transport.py proxy.py identity.py solve.py clearance.py reports.py \
html_reader.py json_reader.py ./
USER 10001:10001
VOLUME ["/data"]
ENTRYPOINT ["/app/.venv/bin/python", "server.py"]
+72
View File
@@ -0,0 +1,72 @@
# Fetch MCP
A local stdio MCP server that reads public HTML, JSON and plain text as bounded source excerpts. No browser: requests use a real browser's TLS and header identity, an operator proxy pool, and an optional request-based Cloudflare solver.
## Run
Requires Python 3.11+ and `uv`. Copy `.env.example` to `.env` and set the route and pool.
```json
{
"command": "uv",
"args": ["run", "--locked", "--env-file", ".env", "--directory", "C:/Users/Admin/Desktop/projects/fetch_mcp", "server.py"]
}
```
The process speaks MCP on stdio and never listens on a port. `MCP_LIVE_ROUTE` defaults to `proxy`: every agent request must go through the pool, and a dead pool reports `proxy_unavailable` instead of quietly going direct. `direct` ignores the pool. `HTTP_PROXY`, `HTTPS_PROXY` and `NO_PROXY` do not decide either.
## Proxy pool
Exactly one source, set by the operator:
- `MCP_PROXY_URLS`: JSON array of full URLs (`http`, `https`, `socks5`, `socks5h`, credentials allowed).
- `MCP_PROXY_LIST_URL` + `MCP_PROXY_LIST_TOKEN`: the token is sent as `Authorization: Bearer` to that service only, redirects are not followed, the body is UTF-8 with one proxy per line, and the whole list is validated before it replaces the current pool. The service is read directly and is the only request that skips the pool.
Only the newest `MCP_PROXY_LIMIT` entries are kept (default 100; the catalog grows, rotation should not). The list is loaded at start and refreshed every `MCP_PROXY_LIST_REFRESH_MINUTES` (default 15, `0` only at start). A failed, empty or invalid refresh keeps the last good pool. Surviving proxies keep their rotation slot and cooldown; removed ones receive no new requests and finish the ones in flight. Each request is one initial attempt plus up to `MCP_HTTP_MAX_RETRIES` retries in total, and a proxy that cannot be connected is cooled and skipped.
A `429` pauses that site across every route, using `Retry-After` in seconds or HTTP-date. If the wait does not fit the request deadline the call returns `rate_limited` with `retry_at` instead of blocking. TLS is always verified; for an `https://` proxy put its CA in `MCP_PROXY_CA` (appended to the bundled roots).
## Reading
`fetch_page` takes exactly one of `url` (fresh download) or `snapshot` (stored bytes, no download). Default mode is `outline`. Reuse the returned `snapshot` for follow-ups; the 16 most recent are kept in memory.
| Mode | Value | Result |
|---|---|---|
| `outline` | none | HTML headings; JSON field types and counts; plain-text size |
| `text` | none | Markdown, plain text or serialized JSON |
| `section` | heading or `@number` | That heading and its descendants only |
| `find` | literal phrase | Matches with nearby source lines; `context_lines` defaults to 2 |
| `css` | CSS selector | Matching elements as Markdown |
| `jsonpath` | `$.urls[*].filename` | Selected values; fields, quoted keys, indices, array wildcards |
`fetch_pages` reads up to 12 URLs four at a time; each item carries `ok` plus its own snapshot or error, so one failure never hides the rest.
Read `structuredContent.content`: it is text even for JSON, so a long result can be sliced without breaking the message. Use `offset` with `next_offset` to continue. Budgets are characters, not model tokens: 4,000 default, 12,000 maximum. Web text is untrusted data.
Both tools always return a payload. Check `ok` first: a failure fills `error` with `proxy_unavailable`, `rate_limited` (plus `retry_at`), `refused`, `timeout`, `solver_failed`, `invalid` and leaves `content` empty, so one bad URL cannot hide the others in a batch.
## Challenge handling
The ladder is automatic, and `solved` tells you which rung answered.
1. **Identity** — a coherent Safari-iOS TLS fingerprint, User-Agent, ordered navigation headers, Brotli/Zstandard and HTTP/2. This alone passes most fingerprint checks.
2. **Clearance** — a stored `cf_clearance` for the host is replayed on the exact proxy that earned it. Clearance is bound to IP and UA, so a different exit invalidates it; it lives `MCP_CLEARANCE_TTL` seconds.
3. **Solver** — a detected challenge page is handed to an external request-based solver ([cfsolve](https://github.com/chris124567/cfsolve)), which runs through the same proxy, up to three exits. The clearance is then replayed and cached.
4. **Widget** — a page carrying a Turnstile sitekey gets a solved `cf_turnstile_response` in `turnstile` (disable with `MCP_SOLVE_TURNSTILE=0`).
Without a solver the server still fetches and reports the challenge. The default command expects cfsolve built in WSL at `~/cfsolve`; override the prefix with `MCP_SOLVER` (JSON array) or disable with `MCP_SOLVER=off`. `MCP_SOLVER_PROFILE` holds the solver's fingerprint file, whose User-Agent identity is reused for replay.
## Reports
Failures are not detected automatically — the model reports them, because only it knows the content was needed and that it already tried every rung. `report` stores one row per host and category in `MCP_REPORT_FILE` (`.reports.jsonl` by default); repeating a failure merges into the same open row and raises `hits`, so re-reporting costs nothing.
Report when a task's need on that host is exhausted: challenge still returned after solver retries, JavaScript-only shell, login or paywall, datacenter ban, needed text absent, selector from the outline matching nothing. Do not report a first timeout, a 404 from a guessed URL, or a typo in your own selector. `needed` says which fact was wanted; `attempts` lists what was already tried; `note` says what the page showed instead.
Close the queue one at a time: `reports` lists open rows by `hits`, then `reports_update(id, "closed" | "ignored", note)` records the fix or the decision. `open` reopens a row that still reproduces.
## Verification
- `uv run --locked smoke_proxy.py` — loopback stand: all four proxy schemes, credentials, round-robin, pin reuse, dead-proxy failover, wrong credentials, whole-pool outage, no direct fallback, 429 with and without room in the deadline, and pool replacement during an in-flight request. No external network.
- `uv run --locked smoke_live.py` — real MCP client against the live server on the direct route: HTML, documentation, JSON, snapshot views, batch isolation, error reporting.
Both are checks, not benchmarks. Upstream pages change.
+14
View File
@@ -0,0 +1,14 @@
# Runner-side image for Gitea Actions: job container with uv, git and a docker CLI.
# Kept out of the shipped image; built by the operator, not by CI.
FROM python:3.13-slim@sha256:168d3a5d10f2152f8e8d77b6843ac82c22a846cfefeef7afdf9aa630404e82a7
RUN apt-get update \
&& apt-get install -y --no-install-recommends git curl ca-certificates \
&& rm -rf /var/lib/apt/lists/*
RUN pip install --no-cache-dir uv==0.11.16
COPY --from=docker:27-cli /usr/local/bin/docker /usr/local/bin/docker
COPY --from=docker:27-cli /usr/local/libexec/docker/cli-plugins/docker-buildx /usr/local/libexec/docker/cli-plugins/docker-buildx
RUN mkdir -p /home/runner/work && chown -R 1001:1001 /home/runner /usr/local/bin
ENV HOME=/home/runner
USER 1001:1001
WORKDIR /home/runner
+100
View File
@@ -0,0 +1,100 @@
"""Short-lived clearance cookies, bound to host and the exit that earned them.
cf_clearance is only valid from the IP and User-Agent that earned it, so the
entry keeps the proxy URL that produced it and replay is pinned there. Values
live in a JSON file so a restart does not force a new solve.
"""
import json
import os
import threading
from dataclasses import dataclass
from pathlib import Path
from time import time
_TTL = min(max(float(os.environ.get("MCP_CLEARANCE_TTL", "1800")), 60.0), 14400.0)
_FILE = Path(os.environ.get("MCP_CLEARANCE_FILE", Path(__file__).with_name(".clearance.json")))
@dataclass(frozen=True, slots=True)
class Entry:
cookies: dict[str, str]
proxy: str | None
expires: float
def header(self) -> str:
return "; ".join(f"{name}={value}" for name, value in self.cookies.items())
class Store:
def __init__(self, path: Path = _FILE) -> None:
self._path = path
self._lock = threading.Lock()
self._data: dict[str, Entry] = self._load()
def _load(self) -> dict[str, Entry]:
try:
raw = json.loads(self._path.read_text("utf-8"))
except (OSError, ValueError):
return {}
now = time()
def read(host: str, value: object) -> tuple[str, Entry] | None:
if not isinstance(value, dict) or not isinstance(value.get("cookies"), dict):
return None
try:
expires = float(value.get("expires", 0))
cookies = {str(k): str(v) for k, v in value["cookies"].items()}
except (TypeError, ValueError, AttributeError):
return None
entry = Entry(cookies, value.get("proxy"), expires)
return (host, entry) if entry.expires > now else None
data: dict[str, Entry] = {}
for host, value in raw.items() if isinstance(raw, dict) else ():
kept = read(host, value)
if kept:
data[kept[0]] = kept[1]
return data
def _save(self) -> None:
now = time()
self._data = {host: entry for host, entry in self._data.items() if entry.expires > now}
temporary = self._path.with_suffix(".tmp")
try:
temporary.write_text(
json.dumps(
{
host: {"cookies": entry.cookies, "proxy": entry.proxy, "expires": entry.expires}
for host, entry in self._data.items()
}
),
"utf-8",
)
os.replace(temporary, self._path)
except OSError:
pass
def lookup(self, host: str) -> tuple[str | None, str | None]:
"""Proxy to pin and the Cookie header for ``host``, or Nones."""
with self._lock:
entry = self._data.get(host)
if entry is None or entry.expires <= time():
return None, None
return entry.proxy, entry.header()
def put(self, host: str, proxy: str | None, cookies: dict[str, str]) -> None:
if not cookies:
return
with self._lock:
self._data[host] = Entry(dict(cookies), proxy, time() + _TTL)
self._save()
def drop(self, host: str) -> None:
with self._lock:
if self._data.pop(host, None) is not None:
self._save()
def __len__(self) -> int:
with self._lock:
return len(self._data)
+1386
View File
File diff suppressed because it is too large. Load diff
+478
View File
@@ -0,0 +1,478 @@
"""Extract readable, unpaginated Markdown from an already fetched HTML page."""
import re
from collections.abc import Callable, Iterator
from dataclasses import dataclass
from urllib.parse import quote, urldefrag, urljoin, urlsplit
from uuid import uuid4
import soupsieve
from bs4 import BeautifulSoup, Comment, NavigableString, Tag
from markdownify import MarkdownConverter
_HEADING_LEVELS = {f"h{level}": level for level in range(1, 7)}
_ALWAYS_HIDDEN = frozenset(
{
"head",
"title",
"script",
"style",
"template",
"noscript",
"svg",
"canvas",
"iframe",
"object",
"embed",
"link",
"meta",
}
)
_CHROME = frozenset({"nav", "aside", "footer", "form"})
_CHROME_ROLES = frozenset({"navigation", "banner", "contentinfo", "complementary", "search"})
_PRE_FENCE = re.compile(r"`+")
_CODE_LANGUAGE = re.compile(r"(?:language|lang)-([a-zA-Z0-9_+#.-]{1,32})\Z")
_LABEL_SPECIAL = re.compile(r"([\\`*_<>\[\]&])")
_OUTLINE_ID = re.compile(r"@[0-9]+\Z")
_MAX_DEPTH = 96
_MAX_MARKDOWN = 8 * 1024 * 1024
_MAX_RENDER_WORK = 32 * 1024 * 1024
_URL_SAFE = ":/?#[]@!$&'*+,;=%~.-_"
@dataclass(frozen=True, slots=True)
class _Heading:
tag: Tag
number: int
level: int
label: str
@property
def reference(self) -> str:
return f"@{self.number}"
def _attr(tag: Tag, name: str) -> str:
value = tag.get(name)
return value if isinstance(value, str) else ""
def _ignored(tag: Tag, drop_chrome: bool) -> bool:
name = tag.name
if name in _ALWAYS_HIDDEN or tag.has_attr("hidden") or _attr(tag, "aria-hidden").lower() == "true":
return True
if name == "a" and _attr(tag, "href").startswith("#"):
classes = tag.get("class", ())
if "headerlink" in classes or "heading-anchor" in classes:
return True
if not drop_chrome:
return False
return (
name in _CHROME
or _attr(tag, "role") in _CHROME_ROLES
or (name == "header" and tag.parent is not None and tag.parent.name in {"body", "html", "[document]"})
)
def _walk(root: Tag, drop_chrome: bool, stop_at: set[int] | None = None) -> Iterator[Tag | NavigableString]:
stack: list[Iterator[Tag | NavigableString]] = [iter((root,))]
while stack:
node = next(stack[-1], None)
if node is None:
stack.pop()
continue
if isinstance(node, Tag):
if _ignored(node, drop_chrome):
continue
if len(stack) > _MAX_DEPTH:
raise ValueError("HTML is nested too deeply to render safely.")
yield node
if stop_at is None or id(node) not in stop_at:
stack.append(iter(node.children))
elif type(node) is NavigableString:
yield node
def _reader_root(document: BeautifulSoup) -> Tag:
body = document.body
if body is None:
body = document
article = None
for node in _walk(body, True):
if not isinstance(node, Tag):
continue
if node.name == "main" or _attr(node, "role") == "main":
return node
if article is None and node.name == "article":
article = node
return article if article is not None else body
def _label(tag: Tag) -> str:
parts: list[str] = []
for node in _walk(tag, True):
if isinstance(node, NavigableString):
parts.append(str(node))
elif node.name == "br":
parts.append(" ")
elif node.name == "img":
parts.append(_attr(node, "alt"))
return " ".join("".join(parts).split())
def _headings(root: Tag) -> Iterator[_Heading]:
number = 0
label_size = 0
for node in _walk(root, True):
if isinstance(node, Tag) and (level := _HEADING_LEVELS.get(node.name)):
label = _label(node)
if not label:
continue
label_size += len(label)
if label_size > _MAX_MARKDOWN:
raise ValueError("HTML heading text exceeds the rendering limit.")
number += 1
yield _Heading(node, number, level, label)
def _section_heading(headings: list[_Heading], value: str) -> _Heading:
if _OUTLINE_ID.fullmatch(value):
for heading in headings:
if heading.reference == value:
return heading
else:
matches = [heading for heading in headings if heading.label == value]
if len(matches) == 1:
return matches[0]
if matches:
references = ", ".join(heading.reference for heading in matches[:8])
if len(matches) > 8:
references += ", ..."
raise ValueError(f"Heading text is ambiguous; use an outline ID ({references}).")
raise ValueError(f"No heading matches {value!r}; use outline to see available headings.")
def _anchor(tag: Tag) -> str:
if anchor := _attr(tag, "id"):
return anchor
for child in tag.find_all("a"):
if anchor := _attr(child, "id") or _attr(child, "name"):
return anchor
previous = tag.previous_sibling
while isinstance(previous, Comment) or (isinstance(previous, NavigableString) and not previous.strip()):
previous = previous.previous_sibling
if isinstance(previous, Tag) and previous.name == "a":
return _attr(previous, "id") or _attr(previous, "name")
if previous is None and tag.parent is not None and tag.parent.name in {"section", "article", "div"}:
return _attr(tag.parent, "id")
return ""
def _outline(headings: list[_Heading], url: str) -> str:
if not headings:
return "No headings found."
page = quote(urldefrag(url).url, safe=_URL_SAFE)
lines: list[str] = []
size = 0
for heading in headings:
label = _LABEL_SPECIAL.sub(r"\\\1", heading.label)
if anchor := _anchor(heading.tag):
destination = f"{page}#{quote(anchor, safe='')}"
label = f"[{label}]({destination})"
line = f"- `{heading.reference}` H{heading.level} {label}"
size += len(line) + 1
if size > _MAX_MARKDOWN:
raise ValueError("HTML outline exceeds the Markdown rendering limit.")
lines.append(line)
return "\n".join(lines)
def _absolute_link(base: str, target: str, *, web_only: bool = False) -> str:
target = target.strip()
if not target:
return ""
try:
resolved = urljoin(base, target)
parsed = urlsplit(resolved)
except ValueError:
return ""
if parsed.scheme in {"http", "https"} and parsed.hostname:
return quote(resolved, safe=_URL_SAFE)
if not web_only and parsed.scheme in {"mailto", "tel"}:
return quote(resolved, safe=_URL_SAFE)
return ""
def _bounded_start(tag: Tag) -> int:
value = _attr(tag, "start")
digits = value.removeprefix("-")
return int(value) if len(digits) <= 9 and digits.isascii() and digits.isdecimal() else 1
def _colspan(tag: Tag) -> int:
value = _attr(tag, "colspan")
if len(value) <= 4 and value.isascii() and value.isdecimal():
return max(1, min(1000, int(value)))
return 1
class _Converter(MarkdownConverter):
def __init__(
self,
base: str,
*,
drop_chrome: bool,
start: Tag | None = None,
stop: Tag | None = None,
markers: dict[int, str] | None = None,
) -> None:
# Collapse insignificant source newlines without wrapping rendered lines.
super().__init__(heading_style="ATX", wrap=True, wrap_width=None, escape_misc=True)
self.base = base
self.drop_chrome = drop_chrome
self.start = start
self.stop = stop
self.leading_ancestors = {id(parent) for parent in start.parents} if start is not None else set()
self.active = start is None
self.markers = markers or {}
self.depth = 0
self.work = 0
self.ordered_counts: dict[int, int] = {}
self.tables: set[int] = set()
def _charge(self, text: str) -> str:
self.work += len(text)
if len(text) > _MAX_MARKDOWN or self.work > _MAX_RENDER_WORK:
raise ValueError("HTML exceeds the Markdown rendering limit.")
return text
def process_tag(self, node: Tag, parent_tags: set[str] | None = None) -> str:
if self.depth >= _MAX_DEPTH:
raise ValueError("HTML is nested too deeply to render safely.")
if _ignored(node, self.drop_chrome):
return ""
if node is self.stop:
self.active = False
return ""
if node is self.start:
self.active = True
if not self.active and id(node) not in self.leading_ancestors:
return ""
self.depth += 1
try:
return self._charge(super().process_tag(node, parent_tags))
finally:
self.depth -= 1
def process_text(self, el: NavigableString, parent_tags: set[str] | None = None) -> str:
return self._charge(super().process_text(el, parent_tags)) if self.active else ""
def get_conv_fn(self, tag_name: str) -> Callable[[Tag, str, set[str]], str] | None:
# Unknown tags named h123... are not HTML headings.
if tag_name.startswith("h") and tag_name[1:2].isdigit() and tag_name not in _HEADING_LEVELS:
return None
return super().get_conv_fn(tag_name)
def convert_hN(self, n: int, el: Tag, text: str, parent_tags: set[str]) -> str:
return super().convert_hN(n, el, self.markers.get(id(el), "") + text, parent_tags)
def convert_a(self, el: Tag, text: str, parent_tags: set[str]) -> str:
el["href"] = _absolute_link(self.base, _attr(el, "href"))
return super().convert_a(el, text, parent_tags)
def convert_video(self, el: Tag, text: str, parent_tags: set[str]) -> str:
source = el.find("source", src=True)
target = _attr(el, "src") or (_attr(source, "src") if isinstance(source, Tag) else "")
destination = _absolute_link(self.base, target, web_only=True)
if not destination:
return text
el["src"] = destination
el["poster"] = _absolute_link(self.base, _attr(el, "poster"), web_only=True)
return super().convert_video(el, text, parent_tags)
def convert_img(self, el: Tag, text: str, parent_tags: set[str]) -> str:
destination = _absolute_link(self.base, _attr(el, "src"), web_only=True)
el["alt"] = _LABEL_SPECIAL.sub(r"\\\1", _attr(el, "alt"))
if not destination:
return _attr(el, "alt")
el["src"] = destination
return super().convert_img(el, text, parent_tags)
def convert_pre(self, el: Tag, text: str, parent_tags: set[str]) -> str:
if not text:
return ""
text = text.removeprefix("\n").removesuffix("\n")
fence = "`" * max(3, 1 + max((len(run[0]) for run in _PRE_FENCE.finditer(text)), default=0))
code = el.find("code", recursive=False)
language = ""
for token in (code if code is not None else el).get("class", ()):
if match := _CODE_LANGUAGE.fullmatch(token):
language = match[1]
break
return f"\n\n{fence}{language}\n{text}\n{fence}\n\n"
def convert_li(self, el: Tag, text: str, parent_tags: set[str]) -> str:
parent = el.parent
if parent is None or parent.name != "ol":
return super().convert_li(el, text, parent_tags)
text = text.strip()
if not text:
return ""
key = id(parent)
index = self.ordered_counts.get(key)
if index is None:
index = _bounded_start(parent)
self.ordered_counts[key] = index + 1
bullet = f"{index}. "
indent = " " * len(bullet)
first, *rest = text.split("\n")
return f"{bullet}{first}\n" + "".join(f"{indent}{line}\n" if line else "\n" for line in rest)
def convert_td(self, el: Tag, text: str, parent_tags: set[str]) -> str:
return " " + text.strip().replace("\n", " ") + " |" * _colspan(el)
convert_th = convert_td
def convert_tr(self, el: Tag, text: str, parent_tags: set[str]) -> str:
if not text.strip():
return ""
table = el.find_parent("table")
key = id(table) if table is not None else id(el)
row = f"| {text.strip()}\n"
if key not in self.tables:
self.tables.add(key)
columns = sum(_colspan(cell) for cell in el.find_all(["th", "td"], recursive=False))
if columns:
row += "|" + " --- |" * columns + "\n"
return row
def convert_main(self, el: Tag, text: str, parent_tags: set[str]) -> str:
return self.convert_div(el, text, parent_tags)
def _find(markdown: str, marker: str, headings: list[_Heading], query: str, context: int) -> str:
needle = query.casefold()
pattern = re.compile(re.escape(marker) + r"([1-9][0-9]*):")
lines = markdown.split("\n")
locations: list[tuple[int, int]] = [(0, 0)]
for index, line in enumerate(lines):
if marker not in line:
continue
matches = list(pattern.finditer(line))
if not matches:
continue
location = (index, int(matches[-1][1]))
if locations[-1][0] == index:
locations[-1] = location
else:
locations.append(location)
lines[index] = pattern.sub("", line)
locations.append((len(lines), 0))
output: list[str] = []
for (start, number), (stop, _) in zip(locations, locations[1:], strict=False):
visible = [index for index in range(start, stop) if lines[index].strip()]
windows: list[tuple[int, int]] = []
for position, index in enumerate(visible):
line = lines[index].casefold()
if needle not in line and needle not in re.sub(r"\\([!-/:-@\[-`{-~])", r"\1", line):
continue
left = max(0, position - context)
right = min(len(visible), position + context + 1)
if windows and left <= windows[-1][1]:
windows[-1] = (windows[-1][0], right)
else:
windows.append((left, right))
if not windows:
continue
if number:
heading = headings[number - 1]
label = _LABEL_SPECIAL.sub(r"\\\1", heading.label)
output.append(f"**{heading.reference} {label}**")
else:
output.append("**Before first heading**")
output.append(
"\n\n...\n\n".join("\n".join(lines[visible[left] : visible[right - 1] + 1]) for left, right in windows)
)
if sum(len(part) + 2 for part in output) > _MAX_MARKDOWN:
raise ValueError("Find results exceed the Markdown rendering limit.")
return "\n\n".join(output) if output else f"No matches found for {query!r}."
def _select(document: BeautifulSoup, value: str) -> list[Tag]:
if len(value) > 1024:
raise ValueError("CSS selector exceeds 1024 characters.")
try:
matches = {id(tag) for tag in document.select(value)}
except soupsieve.SelectorSyntaxError as exc:
raise ValueError(f"Invalid CSS selector: {exc}") from exc
except RecursionError as exc:
raise ValueError("CSS selector is too complex for this document.") from exc
selected = [
node for node in _walk(document, False, stop_at=matches) if isinstance(node, Tag) and id(node) in matches
]
if not selected:
raise ValueError(f"CSS selector matched no visible elements: {value!r}.")
return selected
def render_html(
body: bytes,
url: str,
charset: str | None,
mode: str,
value: str | None,
context_lines: int,
) -> tuple[str, str]:
"""Return the page title and full view. Find searches literal rendered Markdown lines."""
if mode not in {"outline", "text", "section", "find", "css"}:
raise ValueError(f"Unsupported HTML view: {mode!r}.")
query = value.strip() if value is not None else ""
if mode in {"section", "find", "css"} and not query:
raise ValueError(f"The {mode} view requires a non-empty value.")
if mode == "find" and context_lines < 0:
raise ValueError("Find context_lines must be non-negative.")
document = BeautifulSoup(body, "html.parser", from_encoding=charset)
root = _reader_root(document)
title_tag = document.title
title = " ".join(title_tag.get_text().split()) if title_tag is not None else ""
headings = list(_headings(root)) if mode in {"outline", "section", "find"} else None
if not title:
first_heading = headings[0] if headings else next(_headings(root), None)
title = first_heading.label if first_heading is not None else url
if mode == "outline" and headings is not None:
return title, _outline(headings, url)
base_tag = document.find("base", href=True)
base = _absolute_link(url, _attr(base_tag, "href"), web_only=True) if isinstance(base_tag, Tag) else ""
base = base or url
if mode == "css":
selected = _select(document, query)
converter = _Converter(base, drop_chrome=False)
blocks: list[str] = []
size = 0
for tag in selected:
block = converter.convert_soup(tag).strip("\n")
if not block:
continue
size += len(block) + 2
if size > _MAX_MARKDOWN:
raise ValueError("CSS selection exceeds the Markdown rendering limit.")
blocks.append(block)
return title, "\n\n".join(blocks)
if mode == "section" and headings is not None:
start = _section_heading(headings, query)
stop = next((heading.tag for heading in headings[start.number :] if heading.level <= start.level), None)
converter = _Converter(base, drop_chrome=True, start=start.tag, stop=stop)
elif mode == "find" and headings is not None:
marker = f"fetchmcp{uuid4().hex}:"
markers = {id(heading.tag): f"{marker}{heading.number}:" for heading in headings}
converter = _Converter(base, drop_chrome=True, markers=markers)
markdown = converter.convert_soup(root).strip("\n")
return title, _find(markdown, marker, headings, query, context_lines)
else:
converter = _Converter(base, drop_chrome=True)
return title, converter.convert_soup(root).strip("\n")
+105
View File
@@ -0,0 +1,105 @@
"""Browser identity that requests and clearance replay must share.
The identity comes from the solver's own profile so the TLS handshake, the
User-Agent and the stored cookies are one coherent browser. Cloudflare binds
clearance to the exact UA and IP, so a mixed identity silently fails.
"""
import json
import os
import subprocess
from dataclasses import dataclass
from pathlib import Path
from curl_cffi.requests.impersonate import DEFAULT_CHROME, DEFAULT_SAFARI, DEFAULT_SAFARI_IOS
_DEFAULT_PROFILE = "profiles/safari-26-ios.json"
_NO_WINDOW = 0x08000000 if os.name == "nt" else 0
# curl only accepts concrete targets, never the bare family name.
_TARGETS = {"safari": DEFAULT_SAFARI, "safari_ios": DEFAULT_SAFARI_IOS, "chrome": DEFAULT_CHROME}
_FALLBACK = (
"Mozilla/5.0 (iPhone; CPU iPhone OS 18_7 like Mac OS X) AppleWebKit/605.1.15 "
"(KHTML, like Gecko) Version/26.6.3 Mobile/15E148 Safari/604.1"
)
_NAVIGATION = (
"sec-fetch-dest: document",
"user-agent",
"accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"sec-fetch-site: none",
"sec-fetch-mode: navigate",
"accept-language: en-US,en;q=0.9",
"accept-encoding: gzip, deflate, br, zstd",
)
@dataclass(frozen=True, slots=True)
class Identity:
user_agent: str
tls: str
headers: tuple[str, ...]
def as_headers(self) -> dict[str, str]:
"""Ordered headers with the UA filled in and duplicates dropped."""
result: dict[str, str] = {}
for line in self.headers:
if line == "user-agent":
result["user-agent"] = self.user_agent
continue
name, _, value = line.partition(": ")
result[name.lower()] = value
return result
def _tls_for(profile: str) -> str:
override = os.environ.get("MCP_TLS_PROFILE", "").strip()
if override:
return override
lowered = profile.lower()
engine = lowered.partition("-")[0].partition("_")[0]
if "ios" in lowered or "iphone" in lowered:
return DEFAULT_SAFARI_IOS
return _TARGETS.get(engine, DEFAULT_SAFARI_IOS)
def _from_profile(raw: str) -> Identity:
data = json.loads(raw)
transport = data["transport"]
user_agent = transport["headers"]["User-Agent"]
navigation = transport["requests"]["headers"]["navigation"]
tls = _tls_for(str(transport.get("profile", "safari_ios")))
return Identity(user_agent=user_agent, tls=tls, headers=tuple(navigation))
def _read_profile(runner: list[str], path: str) -> str:
"""Read the profile file; a WSL runner needs a plain `cat`, not the solver."""
if runner and runner[0].lower().endswith("wsl"):
done = subprocess.run(
[runner[0], "-e", "bash", "-lc", 'cat "$@"', "cat", path],
capture_output=True,
text=True,
encoding="utf-8",
timeout=20,
check=True,
env={**os.environ, "WSL_UTF8": "1"},
stdin=subprocess.DEVNULL,
creationflags=_NO_WINDOW,
)
return done.stdout
return Path(path).read_text("utf-8")
def load(runner: list[str] | None) -> Identity:
"""Read the solver profile once; fall back to a built-in Safari iOS identity."""
path = os.environ.get("MCP_SOLVER_PROFILE", _DEFAULT_PROFILE)
try:
return _from_profile(_read_profile(runner or [], path))
except (OSError, subprocess.SubprocessError, ValueError, KeyError, TypeError):
return Identity(user_agent=_FALLBACK, tls=_tls_for(path), headers=_NAVIGATION)
DEFAULT = Identity(user_agent=_FALLBACK, tls=_tls_for("safari_ios"), headers=_NAVIGATION)
def fallback() -> Identity:
"""Identity used when no solver profile can be read."""
return DEFAULT
+61
View File
@@ -0,0 +1,61 @@
"""Compact JSON discovery and explicit, lossless field selection."""
import json
import re
_TOKEN = re.compile(r"\.([A-Za-z_][A-Za-z0-9_-]*)|\[(\*|0|[1-9][0-9]{0,8})\]|\[(\"(?:[^\"\\]|\\.)*\")\]")
def select(data: object, path: str) -> object:
if not path.startswith("$"):
raise ValueError('Use a path starting with $, e.g. $.info.name or $[*]["foo.bar"]')
nodes = [data]
many = False
pos = 1
while pos < len(path):
match = _TOKEN.match(path, pos)
if match is None:
raise ValueError(f"Unsupported JSON path at character {pos}")
field, index, quoted = match.groups()
pos = match.end()
if field is not None or quoted is not None:
key = field if field is not None else json.loads(quoted)
nodes = [n[key] for n in nodes if isinstance(n, dict) and key in n]
elif index == "*":
many = True
nodes = [v for n in nodes if isinstance(n, list) for v in n]
else:
i = int(index)
nodes = [n[i] for n in nodes if isinstance(n, list) and i < len(n)]
if many:
return nodes
if not nodes:
raise ValueError("No such JSON field or index")
return nodes[0]
def shape(value: object, depth: int = 0) -> object:
if isinstance(value, dict):
info = {"type": "object", "count": len(value)}
if depth < 2:
from itertools import islice
info["fields"] = {k: shape(v, depth + 1) for k, v in islice(value.items(), 16)}
return info
if isinstance(value, list):
info = {"type": "array", "count": len(value)}
if value and depth < 2:
info["first_item_shape"] = shape(value[0], depth + 1)
return info
return {str: "string", int: "integer", float: "number", bool: "boolean", type(None): "null"}[type(value)]
def render_json(body: bytes, mode: str, value: str | None) -> str:
data = json.loads(body)
if mode == "outline":
data = shape(data)
elif mode == "jsonpath" and value is not None:
data = select(data, value)
elif mode != "text":
raise ValueError("JSON supports outline, jsonpath or text")
return json.dumps(data, ensure_ascii=False, separators=(",", ":"))
+339
View File
@@ -0,0 +1,339 @@
"""Operator-managed proxy pool: exclusive sources, atomic refresh, round-robin.
Configuration is read once from the environment; the agent never chooses a
route. Two exclusive sources exist: a literal JSON array (``MCP_PROXY_URLS``)
or an HTTP list service (``MCP_PROXY_LIST_URL`` + ``MCP_PROXY_LIST_TOKEN``).
The list service is always read directly, never through the pool, and its
token goes nowhere else.
"""
import json
import os
import re
from collections.abc import Iterator
from dataclasses import dataclass, field
from datetime import UTC, datetime
from email.utils import parsedate_to_datetime
from ipaddress import IPv4Address, IPv6Address, ip_address
from threading import Event, Lock, Thread
from time import monotonic
from urllib.parse import quote, unquote, urlsplit
_SCHEMES = frozenset({"http", "https", "socks5", "socks5h"})
_DEFAULT_PORTS = {"http": 80, "https": 443, "socks5": 1080, "socks5h": 1080}
_BAD = re.compile(r"[\x00-\x20\x7f\\]")
_AUTHORITY = re.compile(r"(?:([^:@/\[\]]+):([^@/]*)@)?(\[[0-9a-fA-F:.]+\]|[^:@/\[\]]+)(?::([0-9]{1,5}))?\Z")
_MAX_LIST_BODY = 1024 * 1024
_MAX_PROXIES = 512
class PoolError(ValueError):
"""The pool configuration or the list service is unusable."""
@dataclass(frozen=True, slots=True, eq=False)
class Proxy:
"""One pool entry. Identity is the URL, so a refresh keeps surviving objects."""
url: str
scheme: str
host: str
port: int
user: str = ""
password: str = ""
@property
def label(self) -> str:
"""URL with the password masked, safe for messages and logs."""
userinfo = f"{quote(self.user, safe='')}:***@" if self.user else ""
host = f"[{self.host}]" if ":" in self.host else self.host
return f"{self.scheme}://{userinfo}{host}:{self.port}"
def _parse(raw: str) -> Proxy:
url = raw.strip()
if not url or len(url) > 2048 or _BAD.search(url) or "#" in url or "?" in url:
raise PoolError(f"invalid proxy URL: {raw.strip()!r}")
try:
parts = urlsplit(url)
except ValueError:
raise PoolError(f"invalid proxy URL: {raw.strip()!r}") from None
scheme = parts.scheme.lower()
if scheme not in _SCHEMES:
raise PoolError(f"unsupported proxy scheme {parts.scheme!r}")
if parts.path not in {"", "/"}:
raise PoolError(f"proxy URL must have no path: {raw.strip()!r}")
match = _AUTHORITY.fullmatch(parts.netloc)
if match is None:
raise PoolError(f"invalid proxy authority: {raw.strip()!r}")
user, password, host, port_text = match.groups()
if (user is None) != (password is None):
raise PoolError("proxy credentials need both user and password")
port = int(port_text) if port_text else _DEFAULT_PORTS[scheme]
if not 1 <= port <= 65535:
raise PoolError("proxy port must be in 1..65535")
user, password = unquote(user or ""), unquote(password or "")
if host.startswith("["):
host = host[1:-1]
try:
ip_address(host)
except ValueError:
if host.startswith("[") or ":" in host:
raise PoolError(f"invalid proxy IP literal: {host!r}") from None
host = host.lower()
canonical_host = f"[{host}]" if ":" in host else host
userinfo = f"{quote(user, safe='')}:{quote(password, safe='')}@" if user else ""
canonical = f"{scheme}://{userinfo}{canonical_host}:{port}"
return Proxy(canonical, scheme, host, port, user or "", password or "")
def parse_one(raw: str) -> Proxy:
"""Public single-URL parser for a pinned proxy."""
return _parse(raw)
def parse_list(text: str) -> tuple[Proxy, ...]:
"""Parse a whole one-URL-per-line list, rejecting it as a unit."""
seen: dict[str, Proxy] = {}
for _number, line in enumerate(text.splitlines(), 1):
if not line.strip():
continue
if len(seen) >= _MAX_PROXIES:
raise PoolError(f"more than {_MAX_PROXIES} proxies")
proxy = _parse(line)
seen.setdefault(proxy.url, proxy)
if not seen:
raise PoolError("proxy list is empty")
return tuple(seen.values())
def retry_after_seconds(value: str | None, now: datetime | None = None) -> float | None:
"""Delay from a Retry-After header (delta-seconds or HTTP-date), or None."""
if not value:
return None
value = value.strip()
if value.isdigit():
return float(value)
try:
moment = parsedate_to_datetime(value)
except (TypeError, ValueError):
return None
if moment.tzinfo is None:
moment = moment.replace(tzinfo=UTC)
return max(0.0, (moment - (now or datetime.now(UTC))).total_seconds())
@dataclass
class _Entry:
proxy: Proxy
cooling_until: float = 0.0
last_error: str = ""
in_flight: int = 0
@dataclass
class Pool:
"""Available proxies in fixed order, plus per-proxy cooldown state."""
refresh_minutes: int = 15
limit: int = 100
entries: list[_Entry] = field(default_factory=list)
_cursor: int = 0
_lock: Lock = field(default_factory=Lock)
_route: str = "proxy"
_list_url: str = ""
_token: str = ""
_version: int = 0
_stop: Event = field(default_factory=Event)
_thread: Thread | None = None
_last_refresh: float = 0.0
_last_error: str = ""
@property
def route(self) -> str:
return self._route
@property
def version(self) -> int:
return self._version
def __len__(self) -> int:
with self._lock:
return len(self.entries)
def snapshot(self) -> list[dict[str, object]]:
with self._lock:
now = monotonic()
return [
{
"proxy": entry.proxy.label,
"available": entry.cooling_until <= now,
"in_flight": entry.in_flight,
"last_error": entry.last_error,
}
for entry in self.entries
]
def acquire(self, pinned: str | None = None) -> _Entry | None:
"""Next proxy in rotation that is not cooling; None when none is usable.
A ``pinned`` URL is preferred, which keeps a clearance on its own exit IP.
"""
with self._lock:
now = monotonic()
if pinned:
for entry in self.entries:
if pinned in {entry.proxy.url, entry.proxy.label} and entry.cooling_until <= now:
entry.in_flight += 1
return entry
count = len(self.entries)
for offset in range(count):
index = (self._cursor + offset) % count
entry = self.entries[index]
if entry.cooling_until <= now:
entry.in_flight += 1
self._cursor = (index + 1) % count
return entry
return None
def release(self, entry: _Entry) -> None:
with self._lock:
entry.in_flight = max(0, entry.in_flight - 1)
def cool(self, entry: _Entry, seconds: float, reason: str) -> None:
with self._lock:
entry.cooling_until = monotonic() + seconds
entry.last_error = reason
def _apply(self, proxies: tuple[Proxy, ...]) -> None:
with self._lock:
current = {entry.proxy.url: entry for entry in self.entries}
self.entries = [current.get(proxy.url) or _Entry(proxy) for proxy in proxies]
self._version += 1
for entry in self.entries:
entry.last_error = ""
def load_literal(self, raw: str) -> None:
try:
values = json.loads(raw)
except json.JSONDecodeError as error:
raise PoolError(f"MCP_PROXY_URLS is not valid JSON: {error}") from None
if not isinstance(values, list) or not all(isinstance(value, str) for value in values):
raise PoolError("MCP_PROXY_URLS must be a JSON array of strings")
if len(values) > _MAX_PROXIES:
raise PoolError(f"more than {_MAX_PROXIES} proxies")
seen: dict[str, Proxy] = {}
for value in values:
if value.strip():
proxy = _parse(value)
seen.setdefault(proxy.url, proxy)
if not seen:
raise PoolError("MCP_PROXY_URLS contains no proxy")
self._apply(tuple(seen.values())[-self.limit :])
def refresh(self, fetch) -> bool:
"""Replace the pool from the list service; keep the last good list on error."""
try:
text = fetch(self._list_url, self._token)
proxies = parse_list(text)
except ValueError as error: # PoolError and transport.FetchError alike.
with self._lock:
self._last_error = str(error)
return False
self._apply(proxies[-self.limit :])
with self._lock:
self._last_error = ""
self._last_refresh = monotonic()
return True
def start(self, fetch) -> bool:
"""First load happens synchronously; later refreshes run in the background."""
if self._route != "proxy" or not self._list_url:
return False
loaded = self.refresh(fetch)
if self.refresh_minutes <= 0:
return loaded
def loop() -> None:
while not self._stop.wait(self.refresh_minutes * 60):
self.refresh(fetch)
self._thread = Thread(target=loop, name="proxy-refresh", daemon=True)
self._thread.start()
return loaded
def stop(self) -> None:
self._stop.set()
def iter_entries(self) -> Iterator[_Entry]:
with self._lock:
yield from list(self.entries)
def from_env(environ: dict[str, str] | None = None) -> Pool:
"""Build a pool from operator settings, validating mutually exclusive sources."""
env = os.environ if environ is None else environ
route = (env.get("MCP_LIVE_ROUTE") or "proxy").strip().lower()
if route not in {"proxy", "direct"}:
raise PoolError("MCP_LIVE_ROUTE must be proxy or direct")
pool = Pool(_route=route)
if route == "direct":
return pool
urls = (env.get("MCP_PROXY_URLS") or "").strip()
list_url = (env.get("MCP_PROXY_LIST_URL") or "").strip()
token = (env.get("MCP_PROXY_LIST_TOKEN") or "").strip()
if urls and list_url:
raise PoolError("set either MCP_PROXY_URLS or MCP_PROXY_LIST_URL, not both")
if not urls and not list_url:
raise PoolError("MCP_LIVE_ROUTE=proxy needs MCP_PROXY_URLS or MCP_PROXY_LIST_URL")
if list_url and not token:
raise PoolError("MCP_PROXY_LIST_URL needs MCP_PROXY_LIST_TOKEN")
if urls:
pool.load_literal(urls)
return pool
pool._list_url = list_url
pool._token = token
pool.limit = _limit(env)
refresh = (env.get("MCP_PROXY_LIST_REFRESH_MINUTES") or "15").strip()
try:
pool.refresh_minutes = int(refresh)
except ValueError:
raise PoolError("MCP_PROXY_LIST_REFRESH_MINUTES must be an integer") from None
if pool.refresh_minutes < 0:
raise PoolError("MCP_PROXY_LIST_REFRESH_MINUTES must be >= 0")
return pool
def _limit(env: dict[str, str]) -> int:
raw = (env.get("MCP_PROXY_LIMIT") or "100").strip()
try:
value = int(raw)
except ValueError:
raise PoolError("MCP_PROXY_LIMIT must be an integer") from None
if not 1 <= value <= _MAX_PROXIES:
raise PoolError(f"MCP_PROXY_LIMIT must be in 1..{_MAX_PROXIES}")
return value
def max_retries(environ: dict[str, str] | None = None) -> int:
env = os.environ if environ is None else environ
raw = (env.get("MCP_HTTP_MAX_RETRIES") or "3").strip()
try:
value = int(raw)
except ValueError:
raise PoolError("MCP_HTTP_MAX_RETRIES must be an integer") from None
if not 0 <= value <= 9:
raise PoolError("MCP_HTTP_MAX_RETRIES must be in 0..9")
return value
def is_private_host(host: str) -> bool:
try:
address = ip_address(host)
except ValueError:
return False
if isinstance(address, (IPv4Address, IPv6Address)):
return not address.is_global
return False
+53
View File
@@ -0,0 +1,53 @@
[project]
name = "fetch-mcp"
version = "0.1.0"
requires-python = ">=3.11"
dependencies = [
"beautifulsoup4>=4.13,<5",
"certifi>=2024.2",
"curl-cffi>=0.14,<1",
"markdownify>=1.2,<2",
"mcp>=1.12,<2",
]
[dependency-groups]
dev = [
"pytest>=8.3",
"pytest-cov>=6.0",
"ruff>=0.9",
]
[tool.pytest.ini_options]
addopts = "-q --cov --cov-report=term-missing --cov-report=xml:coverage.xml"
testpaths = ["tests"]
[tool.ruff]
line-length = 120
target-version = "py311"
[tool.ruff.lint]
select = ["E", "F", "W", "I", "UP", "B", "SIM"]
ignore = ["E501"]
[tool.coverage.run]
branch = true
source = [
"server",
"transport",
"proxy",
"identity",
"solve",
"clearance",
"reports",
"json_reader",
]
[tool.coverage.report]
fail_under = 85
show_missing = true
skip_covered = true
exclude_lines = [
"pragma: no cover",
"if __name__ == .__main__.:",
"raise AssertionError",
]
+143
View File
@@ -0,0 +1,143 @@
"""Durable, host-deduplicated reports about pages that could not be read.
The model writes a report when a rung is exhausted and the content was needed;
the operator reads them newest-first and closes them one by one. Entries live in
an append-only-then-rewritten JSONL file with one row per open host+category, so
repeating a failure increments ``hits`` rather than piling up duplicates.
"""
import json
import os
from dataclasses import asdict, dataclass, field
from datetime import UTC, datetime
from pathlib import Path
from secrets import token_hex
from threading import Lock
from time import time
_PATH = Path(os.environ.get("MCP_REPORT_FILE", Path(__file__).with_name(".reports.jsonl")))
_MAX_ROWS = 2000
_lock = Lock()
CATEGORIES = {
"cloudflare_challenge": "Interstitial, `cf-mitigated`, or a solver that kept failing.",
"turnstile": "A Turnstile widget gated the content or the token was rejected.",
"js_required": "The served HTML is a shell; the text appears only after script runs.",
"login_paywall": "Login, cookie wall, or subscription gate.",
"robots_denied": "The site blocks datacenter exits or the page regardless of identity.",
"http_error": "A 4xx/5xx the ladder could not clear.",
"rate_limited": "429 that outlived the deadline.",
"content_missing": "The page loaded but the needed text is absent from it.",
"selector_no_match": "A selector or heading from the outline returned nothing useful.",
"other": "Anything else; say which in the note.",
}
STATUSES = ("open", "closed", "ignored")
@dataclass
class Report:
host: str
category: str
needed: str
url: str = ""
attempts: list[str] = field(default_factory=list)
note: str = ""
snapshot: str = ""
route: str = ""
proxy: str = ""
user_agent: str = ""
error: str = ""
status: str = "open"
hits: int = 1
id: str = ""
first_seen: str = ""
last_seen: str = ""
def key(self) -> str:
return f"{self.host}|{self.category}"
def _now() -> str:
return datetime.now(UTC).isoformat(timespec="seconds")
def _load() -> list[Report]:
try:
lines = _PATH.read_text("utf-8").splitlines()
except OSError:
return []
rows: list[Report] = []
for line in lines:
if not line.strip():
continue
try:
raw = json.loads(line)
rows.append(Report(**{name: raw[name] for name in Report.__dataclass_fields__ if name in raw}))
except (ValueError, TypeError):
continue
return rows
def _save(rows: list[Report]) -> None:
temporary = _PATH.with_suffix(".tmp")
text = "\n".join(json.dumps(asdict(row), ensure_ascii=False) for row in rows[-_MAX_ROWS:])
temporary.write_text(text + ("\n" if text else ""), "utf-8")
os.replace(temporary, _PATH)
def add(entry: Report) -> Report:
"""Insert, or bump the open row for the same host and category."""
entry.host = entry.host.lower().removeprefix("www.")
entry.category = entry.category if entry.category in CATEGORIES else "other"
with _lock:
rows = _load()
stamp = _now()
for row in rows:
if row.status == "open" and row.key() == entry.key():
row.hits += 1
row.last_seen = stamp
row.attempts = sorted({*row.attempts, *entry.attempts})
row.error = entry.error or row.error
row.snapshot = entry.snapshot or row.snapshot
if entry.note:
row.note = f"{row.note}\n{entry.note}".strip()
_save(rows)
return row
entry.id = f"{int(time())}-{token_hex(3)}"
entry.first_seen = entry.last_seen = stamp
rows.append(entry)
_save(rows)
return entry
def listing(status: str = "open", limit: int = 40) -> list[Report]:
with _lock:
rows = [row for row in _load() if status == "all" or row.status == status]
rows.sort(key=lambda row: (-row.hits, row.last_seen))
return rows[:limit]
def update(entry_id: str, status: str, note: str = "") -> Report:
if status not in STATUSES:
raise ValueError(f"status must be one of {', '.join(STATUSES)}")
with _lock:
rows = _load()
for row in rows:
if row.id == entry_id:
row.status = status
if note:
row.note = f"{row.note}\n{note}".strip()
row.last_seen = _now()
_save(rows)
return row
raise ValueError(f"No report with id {entry_id!r}")
def counts() -> dict[str, int]:
with _lock:
rows = _load()
result = {status: 0 for status in STATUSES}
for row in rows:
result[row.status] = result.get(row.status, 0) + 1
return result
+16
View File
@@ -0,0 +1,16 @@
"""Fail if a shipped file contains non-ASCII bytes."""
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
FILES = sorted([*ROOT.glob("*.py"), *ROOT.glob("tests/*.py"), ROOT / "Dockerfile"])
bad: list[str] = []
for path in FILES:
if not path.exists():
continue
for number, line in enumerate(path.read_bytes().splitlines(), 1):
if any(byte > 0x7F for byte in line):
bad.append(f"{path.relative_to(ROOT)}:{number}")
print("\n".join(bad) if bad else "ascii ok")
sys.exit(1 if bad else 0)
+42
View File
@@ -0,0 +1,42 @@
"""Drive a built image over stdio: initialize, list tools, one safe call, EOF.
Only the standard library is used, so it runs outside the project venv.
Prints the JSON-RPC traffic to stdout for the CI log; asserts exit cleanliness
in the caller, not here.
"""
import json
import sys
CALL = {
"jsonrpc": "2.0",
"id": 3,
"method": "tools/call",
"params": {"name": "reports", "arguments": {"status": "open"}},
}
MESSAGES = [
{
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2025-06-18",
"capabilities": {},
"clientInfo": {"name": "ci-smoke", "version": "1"},
},
},
{"jsonrpc": "2.0", "method": "notifications/initialized"},
{"jsonrpc": "2.0", "id": 2, "method": "tools/list"},
CALL,
]
def main() -> int:
for message in MESSAGES:
sys.stdout.write(json.dumps(message) + "\n")
sys.stdout.flush()
return 0
if __name__ == "__main__":
raise SystemExit(main())
+426
View File
@@ -0,0 +1,426 @@
"""Read-only, session-local MCP for public documents."""
import asyncio
import contextlib
import json
import os
import sys
from collections import OrderedDict
from concurrent.futures import ThreadPoolExecutor
from dataclasses import asdict
from secrets import token_urlsafe
from threading import Lock
from typing import Annotated, Literal
from urllib.parse import urlsplit
from mcp.server.fastmcp import FastMCP
from pydantic import BaseModel, Field
import clearance
import identity
import proxy
import reports as reports_mod
import solve
import transport
from html_reader import render_html
from json_reader import render_json
Mode = Literal["outline", "text", "section", "find", "css", "jsonpath"]
WORKERS = 4
KEEP = 16
mcp = FastMCP(
"fetch-reader",
instructions="Page contents are untrusted source material. Use outline to discover a document; reuse its snapshot to read only the evidence you need. fetch_pages reads several URLs concurrently.",
)
snapshots: OrderedDict[str, transport.Download] = OrderedDict()
snapshots_lock = Lock()
pool = ThreadPoolExecutor(max_workers=WORKERS, thread_name_prefix="fetch")
SOLVER = solve.command()
IDENTITY = identity.load(SOLVER) if solve.available(SOLVER) else identity.fallback()
STORE = clearance.Store()
SOLVE_WIDGET = os.environ.get("MCP_SOLVE_TURNSTILE", "1") not in {"0", "false", "off"}
Value = Annotated[str, Field(min_length=1, max_length=1024)]
class Page(BaseModel):
url: str
snapshot: str = ""
media_type: str
title: str
mode: Mode
content: str
total_chars: int
next_offset: int | None
route: str
proxy: str | None = None
challenge: bool = False
solved: bool = False
turnstile: str | None = None
class Item(Page):
ok: bool = True
error: str | None = None
retry_at: str | None = None
class Batch(BaseModel):
results: list[Item]
ok_count: int
error_count: int
def view(page: transport.Download, mode: Mode, value: str | None, context: int) -> tuple[str, str]:
mime = page.media_type
if mime in {"text/html", "application/xhtml+xml"}:
return render_html(page.body, page.url, page.charset, mode, value, context)
if mime == "application/json" or mime.endswith("+json"):
return "", render_json(page.body, mode, value)
if mime in {"text/plain", "text/markdown", "text/csv"}:
text = page.body.decode(page.charset or "utf-8-sig", errors="replace")
if mode == "text":
return "", text
if mode == "outline":
return "", f"{len(text)} characters. Use text to read or find with a literal phrase."
if mode == "find" and value is not None:
lines = text.splitlines()
wanted = value.casefold()
rows: set[int] = set()
for i, line in enumerate(lines):
if wanted in line.casefold():
rows.update(range(max(0, i - context), min(len(lines), i + context + 1)))
return "", "\n".join(f"{i + 1}: {lines[i]}" for i in sorted(rows)) or "No matches."
raise ValueError(f"Unsupported mode {mode} for Content-Type {mime}")
def _store(page: transport.Download) -> str:
snapshot = token_urlsafe(12)
with snapshots_lock:
snapshots[snapshot] = page
while len(snapshots) > KEEP:
snapshots.popitem(last=False)
return snapshot
def _snapshot(snapshot: str) -> transport.Download:
with snapshots_lock:
page = snapshots.get(snapshot)
if page is None:
raise ValueError("Unknown or expired snapshot; fetch the URL again")
snapshots.move_to_end(snapshot)
return page
def _guard(mode: Mode, value: str | None) -> None:
if (mode in {"section", "find", "css", "jsonpath"}) != (value is not None):
raise ValueError("Provide value only for section, find, css or jsonpath")
def _host(url: str) -> str:
return urlsplit(url).hostname or ""
def _fetch(url: str) -> transport.Download:
"""Read once, then solve and retry when a challenge or refusal gets through."""
host = _host(url)
pinned, cookies = (None, None) if transport.POOL.route != "proxy" else STORE.lookup(host)
try:
page = transport.download(url, identity=IDENTITY, cookies=cookies, pin=pinned)
except transport.FetchError as error:
if error.code != "refused" or not SOLVER:
raise
if pinned:
STORE.drop(host)
return _solve_and_retry(url, error, None)
if page.challenge and SOLVER:
return _solve_and_retry(url, None, page)
return page
def clearance_header(cleared: solve.Clearance) -> str:
return "; ".join(f"{name}={value}" for name, value in cleared.cookies.items())
def _solve_and_retry(
url: str, error: transport.FetchError | None, page: transport.Download | None
) -> transport.Download:
"""Solve on a fresh exit and replay there. Falls back to ``page`` when given."""
failure: solve.SolverError | None = None
for _ in range(3):
proxy_url = None
entry = None
if transport.POOL.route == "proxy":
entry = transport.POOL.acquire()
if entry is None:
break
proxy_url = entry.proxy.url
transport.POOL.release(entry)
try:
cleared = solve.clearance(SOLVER, url, IDENTITY.user_agent, proxy_url)
except solve.SolverError as refusal:
failure = refusal
# warm: the page answered; retry plainly. Exit-independent failures
# keep the pool intact.
if entry is not None and refusal.code == "solver_failed":
transport.POOL.cool(entry, 60.0, refusal.code)
if refusal.code == "solver_warm":
try:
warm = transport.download(url, identity=IDENTITY, pin=proxy_url)
except transport.FetchError:
continue
warm.solved = not warm.challenge
return warm
continue
try:
retried = transport.download(url, identity=IDENTITY, cookies=clearance_header(cleared), pin=proxy_url)
except transport.FetchError:
continue
STORE.put(_host(retried.url), retried.proxy_url, cleared.cookies)
retried.solved = not retried.challenge
return retried
if error is not None:
suffix = f"; {failure}" if failure else "; clearance replay failed"
raise transport.FetchError(error.code, f"{error}{suffix}") from None
assert page is not None
return page
def _render(page: transport.Download, mode: Mode, value: str | None, context: int, offset: int, max_chars: int) -> Page:
title, content = view(page, mode, value, context)
if offset > len(content):
raise ValueError("Offset is beyond the selected view")
end = min(offset + max_chars, len(content))
return Page(
url=page.url,
media_type=page.media_type,
title=title[:256],
mode=mode,
content=content[offset:end],
total_chars=len(content),
next_offset=end if end < len(content) else None,
route=page.route,
proxy=page.proxy,
challenge=page.challenge,
solved=page.solved,
turnstile=page.turnstile,
)
def _token(page: transport.Download) -> None:
"""Solve one embedded Turnstile widget once per download."""
if not (SOLVE_WIDGET and SOLVER and page.turnstile is None):
return
if page.media_type != "text/html":
return
key = solve.sitekey(page.body)
if not key:
return
with contextlib.suppress(solve.SolverError):
page.turnstile = solve.turnstile(SOLVER, page.url, key)
def _read(
url: str | None, snapshot: str | None, mode: Mode, value: str | None, context: int, offset: int, max_chars: int
) -> Page:
if (url is None) == (snapshot is None):
raise ValueError("Provide exactly one of url or snapshot")
if offset and snapshot is None:
raise ValueError("Continue with a snapshot, not a new URL fetch")
_guard(mode, value)
page = _fetch(url) if snapshot is None else _snapshot(snapshot)
result = _render(page, mode, value, context, offset, max_chars)
if snapshot is None:
snapshot = _store(page)
result.snapshot = snapshot
_token(page)
result.turnstile = page.turnstile
return result
def _failed(url: str, mode: Mode, code: str, message: str, retry_at: str | None = None) -> Item:
return Item(
ok=False,
url=url,
media_type="",
title=message,
mode=mode,
content="",
total_chars=0,
next_offset=None,
route=transport.POOL.route,
error=code,
retry_at=retry_at,
)
async def _one(url: str, mode: Mode, value: str | None, context: int, max_chars: int) -> Item:
loop = asyncio.get_running_loop()
try:
page = await loop.run_in_executor(pool, _read, url, None, mode, value, context, 0, max_chars)
except transport.FetchError as error:
return _failed(url, mode, error.code, str(error), error.retry_at.isoformat() if error.retry_at else None)
except ValueError as error:
return _failed(url, mode, "invalid", str(error))
except Exception as error: # noqa: BLE001 - one item must never break the batch
return _failed(url, mode, "internal", f"{type(error).__name__}: {error}")
return Item(**page.model_dump())
@mcp.tool()
async def fetch_page(
url: str | None = None,
snapshot: str | None = None,
mode: Mode = "outline",
value: Value | None = None,
context_lines: Annotated[int, Field(ge=0, le=5)] = 2,
offset: Annotated[int, Field(ge=0)] = 0,
max_chars: Annotated[int, Field(ge=1, le=12000)] = 4000,
) -> Item:
"""Read one public URL or one existing snapshot (supply exactly one). HTML: outline, text (Markdown), section (value=heading or @number), find (literal), css (selector). JSON: outline (shape), text, jsonpath ($.field, [index], [*], or [\"quoted.key\"]). Plain text: outline, text, find. All views return bounded source excerpts, not summaries. To continue, reuse snapshot, mode, value and context_lines with next_offset. Only the 16 most recently used snapshots are retained; use url for a fresh copy. Failures still return a payload: check ok, then error (proxy_unavailable, rate_limited with retry_at, refused, ...)."""
loop = asyncio.get_running_loop()
try:
page = await loop.run_in_executor(pool, _read, url, snapshot, mode, value, context_lines, offset, max_chars)
except transport.FetchError as error:
return _failed(url or "", mode, error.code, str(error), error.retry_at.isoformat() if error.retry_at else None)
except ValueError as error:
return _failed(url or "", mode, "invalid", str(error))
return Item(**page.model_dump())
@mcp.tool()
async def fetch_pages(
urls: Annotated[list[str], Field(min_length=1, max_length=12)],
mode: Mode = "outline",
value: Value | None = None,
context_lines: Annotated[int, Field(ge=0, le=5)] = 2,
max_chars: Annotated[int, Field(ge=1, le=12000)] = 3000,
) -> Batch:
"""Read up to 12 URLs concurrently (4 at a time), each independently. Same modes as fetch_page; value applies to every URL. Every item carries ok and its own snapshot or error code, so one failure does not hide the others. proxy_unavailable means the whole pool is down; rate_limited carries retry_at."""
try:
_guard(mode, value)
except ValueError as error:
failures = [_failed(u, mode, "invalid", str(error)) for u in urls]
return Batch(results=failures, ok_count=0, error_count=len(failures))
items = await asyncio.gather(*(_one(u, mode, value, context_lines, max_chars) for u in urls))
failed = sum(not item.ok for item in items)
return Batch(results=items, ok_count=len(items) - failed, error_count=failed)
@mcp.tool()
async def report(
url: str,
category: Literal[
"cloudflare_challenge",
"turnstile",
"js_required",
"login_paywall",
"robots_denied",
"http_error",
"rate_limited",
"content_missing",
"selector_no_match",
"other",
],
needed: Annotated[str, Field(min_length=3, max_length=400)],
attempts: Annotated[list[str], Field(max_length=8)] | None = None,
note: Annotated[str, Field(max_length=1200)] = "",
error: Annotated[str, Field(max_length=200)] = "",
) -> Item:
"""Record a page that could not be read, so the operator can fix or accept it one by one.
Report once a whole task's need on that host is exhausted, not per attempt: the content was required, every rung failed (direct, stored clearance, solver, widget), and the cause looks structural. Good triggers: a challenge still returned after the solver retried on other exits; a shell that needs JavaScript; login or paywall; a datacenter ban; the page loaded but the needed text is absent; a selector or heading from the outline matched nothing. Do not report a first timeout, a 404 from a guessed URL, or your own typo in a selector - fix and retry those first. Repeated calls for the same host and category merge into one row and raise `hits`, so re-reporting is cheap.
Say in `needed` which fact was wanted (the operator judges importance by it), and in `attempts` the short codes or modes already tried, e.g. ["direct", "solver x3", "find: parse_float"]. Use `note` for what the page showed instead, and `error` for the last code (refused, timeout, ...). Report what you saw, not what you infer."""
host = urlsplit(url).hostname or urlsplit(f"https://{url}").hostname or url
entry = reports_mod.add(
reports_mod.Report(
host=host,
category=category,
needed=needed,
url=url,
attempts=list(attempts or []),
note=note,
error=error,
route=transport.POOL.route,
user_agent=IDENTITY.user_agent,
)
)
return Item(
ok=True,
url=entry.url,
media_type="application/report",
title=f"{entry.host} | {entry.category}",
mode="text",
content=f"#{entry.id} {entry.host} [{entry.category}] hits={entry.hits}",
total_chars=0,
next_offset=None,
route=transport.POOL.route,
)
@mcp.tool()
async def reports(
status: Literal["open", "closed", "ignored", "all"] = "open", limit: Annotated[int, Field(ge=1, le=200)] = 40
) -> Batch:
"""List stored page-failure reports, highest `hits` first, with per-status counts.
Close them one at a time: read a row, then call `reports_update` with its id and status `closed` (fixed or acceptable) or `ignored` (cannot or need not be fixed), plus a short note saying why. Leave rows open that still reproduce."""
rows = reports_mod.listing(status, limit)
items = [
Item(
ok=True,
url=row.url,
media_type="application/report",
title=f"#{row.id} {row.host} | {row.category} | hits {row.hits} | {row.status}",
mode="text",
content=json.dumps(asdict(row), ensure_ascii=False, indent=1),
total_chars=row.hits,
next_offset=None,
route=row.route or transport.POOL.route,
error=None,
)
for row in rows
]
return Batch(results=items, ok_count=len(items), error_count=reports_mod.counts().get("open", 0))
@mcp.tool()
async def reports_update(
report_id: str, status: Literal["open", "closed", "ignored"], note: Annotated[str, Field(max_length=1200)] = ""
) -> Item:
"""Change one report's status. Use it to close reports one by one once the cause is handled, or to reopen one that still reproduces. `note` records the fix, the decision, or why it stays."""
try:
row = reports_mod.update(report_id, status, note)
except ValueError as failure:
return _failed(report_id, "text", "invalid", str(failure))
return Item(
ok=True,
url=row.url,
media_type="application/report",
title=f"#{row.id} {row.host} | {row.category} | {row.status}",
mode="text",
content=f"#{row.id} -> {row.status}",
total_chars=0,
next_offset=None,
route=row.route or transport.POOL.route,
)
def main() -> None:
try:
transport.configure()
except (proxy.PoolError, transport.FetchError) as error:
# stdout belongs to the protocol, so a bad route is reported per request.
print(f"fetch-mcp: proxy configuration rejected: {error}", file=sys.stderr, flush=True)
transport.POOL = proxy.Pool(_route="proxy")
try:
mcp.run(transport="stdio")
finally:
transport.POOL.stop()
pool.shutdown(wait=False, cancel_futures=True)
if __name__ == "__main__":
main()
+73
View File
@@ -0,0 +1,73 @@
"""On-demand end-to-end smoke: exercise the wire protocol against public pages."""
import asyncio
import json
import sys
from pathlib import Path
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
async def main() -> None:
child = StdioServerParameters(
command=sys.executable,
args=[str(Path(__file__).with_name("server.py"))],
env={**__import__("os").environ, "MCP_LIVE_ROUTE": "direct", "MCP_SOLVE_TURNSTILE": "0"},
)
async with stdio_client(child) as streams, ClientSession(*streams) as client:
await client.initialize()
listed = await client.list_tools()
assert [t.name for t in listed.tools] == ["fetch_page", "fetch_pages"]
async def call(label: str, **args):
result = await client.call_tool("fetch_page", args)
if result.isError or result.structuredContent is None:
raise RuntimeError(f"{label}: {result.content}")
page = result.structuredContent
assert len(page["content"]) <= args.get("max_chars", 4000)
print(label, json.dumps(page, ensure_ascii=True), flush=True)
return page
example = await call("simple", url="https://example.com/", mode="text", max_chars=500)
assert example["title"] == "Example Domain"
assert "documentation examples" in example["content"] and "<html" not in example["content"].lower()
toc = await call("outline", url="https://docs.python.org/3.13/library/tomllib.html", max_chars=1200)
snapshot = toc["snapshot"]
assert "conversion table" in toc["content"].lower()
section = await call("section", snapshot=snapshot, mode="section", value="Conversion Table", max_chars=400)
assert "integer" in section["content"].lower()
more = (
await call(
"continue",
snapshot=snapshot,
mode="section",
value="Conversion Table",
offset=section["next_offset"],
max_chars=90,
)
if section["next_offset"] is not None
else None
)
assert not more or more["total_chars"] == section["total_chars"]
hit = await call("find", snapshot=snapshot, mode="find", value="parse_float", context_lines=1, max_chars=900)
assert "**@" in hit["content"] and "parse_float" in hit["content"].replace("\\_", "_")
table = await call("css", snapshot=snapshot, mode="css", value="table", max_chars=480)
assert "integer" in table["content"].lower() and "|" in table["content"]
api = await call("json-outline", url="https://pypi.org/pypi/sampleproject/4.0.0/json", max_chars=450)
fields = await call("json-field", snapshot=api["snapshot"], mode="jsonpath", value="$.urls[*].filename")
assert "sampleproject-4.0.0.tar.gz" in json.loads(fields["content"])
invalid = await client.call_tool("fetch_page", {"snapshot": "expired-example"})
assert invalid.structuredContent is not None and invalid.structuredContent["ok"] is False
assert invalid.structuredContent["error"] == "invalid"
batch = await client.call_tool(
"fetch_pages", {"urls": ["https://example.com/", "https://example.com/nope-404"]}
)
assert batch.structuredContent is not None
items = batch.structuredContent["results"]
assert batch.structuredContent["ok_count"] == 1 and items[1]["ok"] is False
print("PASS: public HTML, documentation, JSON, snapshots, batch isolation and MCP error reporting.")
if __name__ == "__main__":
asyncio.run(main())
+402
View File
@@ -0,0 +1,402 @@
"""Local stand: proxy pool behaviour without external networks.
Starts throwaway target, HTTP, HTTPS, SOCKS5 and dead servers on loopback, then
drives transport directly. Run: uv run smoke_proxy.py
"""
import base64
import contextlib
import datetime
import ipaddress
import socket
import ssl
import struct
import tempfile
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import urlsplit
import proxy
import transport
REQUESTS: dict[str, int] = {"ok": 0, "429": 0, "slow": 0}
class Target(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def do_GET(self) -> None:
path = urlsplit(self.path).path
REQUESTS[path.strip("/")] = REQUESTS.get(path.strip("/"), 0) + 1
if path == "/429" and REQUESTS["429"] == 1:
body = b"wait"
self.send_response(429)
self.send_header("Retry-After", "1")
elif path == "/429toomuch":
body = b"wait"
self.send_response(429)
self.send_header("Retry-After", "120")
elif path == "/slow":
time.sleep(1.0)
body = b"slow"
self.send_response(200)
else:
body = b"OK"
self.send_response(200)
self.send_header("Content-Type", "text/plain; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args: object) -> None:
pass
class Server:
"""A listener that counts accepted connections."""
def __init__(self, handler) -> None:
self.sock = socket.socket()
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.bind(("127.0.0.1", 0))
self.sock.listen(16)
self.port = self.sock.getsockname()[1]
self.hits = 0
self.handler = handler
self.alive = True
threading.Thread(target=self.loop, daemon=True).start()
def loop(self) -> None:
while self.alive:
try:
client, _ = self.sock.accept()
except OSError:
return
self.hits += 1
threading.Thread(target=self.wrap, args=(client,), daemon=True).start()
def wrap(self, client: socket.socket) -> None:
try:
self.handler(client)
finally:
client.close()
def close(self) -> None:
self.alive = False
self.sock.close()
def tunnel(client: socket.socket, host: str, port: int) -> None:
upstream = socket.create_connection((host, port), timeout=5)
try:
client.settimeout(None)
threading.Thread(target=_pipe, args=(upstream, client), daemon=True).start()
_pipe(client, upstream)
finally:
upstream.close()
def _pipe(src: socket.socket, dst: socket.socket) -> None:
try:
while data := src.recv(65536):
dst.sendall(data)
except OSError:
pass
finally:
with contextlib.suppress(OSError):
dst.shutdown(socket.SHUT_WR)
def read_headers(client: socket.socket) -> str:
buffer = b""
while b"\r\n\r\n" not in buffer and len(buffer) < 65536:
chunk = client.recv(4096)
if not chunk:
break
buffer += chunk
return buffer.decode("latin-1")
def http_proxy(credentials: tuple[str, str] | None = None):
def handle(client: socket.socket) -> None:
head = read_headers(client)
lines = head.split("\r\n")
if credentials and len(lines) > 1:
expected = "Basic " + base64.b64encode(("{}:{}".format(*credentials)).encode()).decode()
sent = [line.split(": ", 1)[1].strip() for line in lines[1:] if ":" in line]
if expected not in sent:
client.sendall(b"HTTP/1.1 407 Proxy Authentication Required\r\n\r\n")
return
method, target, _ = lines[0].split(" ")
if method == "CONNECT":
host, port = target.rsplit(":", 1)
client.sendall(b"HTTP/1.1 200 Connection Established\r\n\r\n")
tunnel(client, host, int(port))
return
parts = urlsplit(target)
upstream = socket.create_connection((parts.hostname, parts.port or 80), timeout=5)
rest = head.split("\r\n", 1)[1]
path = parts.path + (f"?{parts.query}" if parts.query else "")
upstream.sendall(f"{method} {path} HTTP/1.1\r\n{rest}".encode("latin-1"))
_pipe(upstream, client)
upstream.close()
return handle
def https_proxy(context: ssl.SSLContext):
inner = http_proxy()
def handle(client: socket.socket) -> None:
try:
wrapped = context.wrap_socket(client, server_side=True)
except ssl.SSLError:
return
try:
inner(wrapped)
finally:
wrapped.close()
return handle
def socks5(credentials: tuple[str, str] | None = None):
def handle(client: socket.socket) -> None:
version, count = client.recv(2)
methods = client.recv(count)
want = 2 if credentials else 0
if want not in methods:
client.sendall(b"\x05\xff")
return
client.sendall(bytes([5, want]))
if credentials:
_, length = client.recv(2)
user = client.recv(length).decode()
_, length = client.recv(2)
password = client.recv(length).decode()
client.sendall(b"\x01\x00" if (user, password) == credentials else b"\x01\x01")
if (user, password) != credentials:
return
_, command, _, address_type = client.recv(4)
if address_type == 1:
host = socket.inet_ntoa(client.recv(4))
elif address_type == 3:
host = client.recv(client.recv(1)[0]).decode()
else:
host = socket.inet_ntop(socket.AF_INET6, client.recv(16))
port = struct.unpack("!H", client.recv(2))[0]
if command != 1:
client.sendall(b"\x05\x07\x00\x01" + b"\x00" * 6)
return
client.sendall(b"\x05\x00\x00\x01" + b"\x00" * 6)
tunnel(client, host, port)
return handle
def selfsigned() -> tuple[Path, ssl.SSLContext]:
"""Create a throwaway CA plus a 127.0.0.1 leaf it signs; return CA path and server TLS."""
from cryptography import x509
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.x509.oid import NameOID
now = datetime.datetime.now(datetime.UTC)
ca_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
ca_name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "fetch-mcp test CA")])
ca = (
x509.CertificateBuilder()
.subject_name(ca_name)
.issuer_name(ca_name)
.public_key(ca_key.public_key())
.serial_number(x509.random_serial_number())
.not_valid_before(now - datetime.timedelta(minutes=5))
.not_valid_after(now + datetime.timedelta(days=1))
.add_extension(x509.BasicConstraints(ca=True, path_length=0), True)
.add_extension(
x509.KeyUsage(
digital_signature=True,
key_cert_sign=True,
crl_sign=True,
content_commitment=False,
key_encipherment=False,
data_encipherment=False,
key_agreement=False,
encipher_only=False,
decipher_only=False,
),
True,
)
.sign(ca_key, hashes.SHA256())
)
key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
cert = (
x509.CertificateBuilder()
.subject_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "127.0.0.1")]))
.issuer_name(ca_name)
.public_key(key.public_key())
.serial_number(x509.random_serial_number())
.not_valid_before(now - datetime.timedelta(minutes=5))
.not_valid_after(now + datetime.timedelta(days=1))
.add_extension(x509.BasicConstraints(ca=False, path_length=None), True)
.add_extension(
x509.SubjectAlternativeName(
[
x509.DNSName("127.0.0.1"),
x509.IPAddress(ipaddress.ip_address("127.0.0.1")),
]
),
False,
)
.sign(ca_key, hashes.SHA256())
)
folder = Path(tempfile.mkdtemp())
ca_path = folder / "ca.pem"
ca_path.write_bytes(ca.public_bytes(serialization.Encoding.PEM))
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain(_pair(folder, cert, key))
return ca_path, context
def _pair(folder: Path, cert, key) -> str:
from cryptography.hazmat.primitives import serialization
path = folder / "pair.pem"
path.write_bytes(
cert.public_bytes(serialization.Encoding.PEM)
+ key.private_bytes(
serialization.Encoding.PEM, serialization.PrivateFormat.TraditionalOpenSSL, serialization.NoEncryption()
)
)
return str(path)
def pool_of(*urls: str) -> proxy.Pool:
result = proxy.Pool(_route="proxy")
result.load_literal("[" + ",".join(f'"{u}"' for u in urls) + "]")
return result
def check(label: str, condition: bool, detail: str = "") -> None:
print(("PASS " if condition else "FAIL ") + label + (f" - {detail}" if detail and not condition else ""))
if not condition:
raise SystemExit(1)
def main() -> None:
target = Server(Target.__init__ and None) # placeholder, replaced below
target.close()
target = ThreadingHTTPServer(("127.0.0.1", 0), Target)
target_port = target.server_address[1]
threading.Thread(target=target.serve_forever, daemon=True).start()
base = f"http://127.0.0.1:{target_port}"
pem, tls = selfsigned()
import os
os.environ["MCP_PROXY_CA"] = str(pem)
os.environ["MCP_HTTP_MAX_RETRIES"] = "2"
http_a, http_b = Server(http_proxy()), Server(http_proxy(("user", "pa ss")))
https_a = Server(https_proxy(tls))
socks5_a = Server(socks5())
socks5h_a = Server(socks5())
dead = Server(http_proxy())
dead.close()
transport.POOL = pool_of(
f"http://127.0.0.1:{http_a.port}",
f"https://127.0.0.1:{https_a.port}",
f"socks5://127.0.0.1:{socks5_a.port}",
f"socks5h://127.0.0.1:{socks5h_a.port}",
f"http://user:pa%20ss@127.0.0.1:{http_b.port}",
)
# Every scheme reaches the target.
for label in ("http", "https", "socks5", "socks5h", "http+credentials"):
result = transport.download(base + "/ok", allow_private=True)
check(f"scheme {label}", result.body == b"OK" and result.route == "proxy", result.body.decode(errors="replace"))
# Round-robin distributes over distinct proxies.
before = {s.port: s.hits for s in (http_a, https_a, socks5_a, socks5h_a, http_b)}
for _ in range(5):
transport.download(base + "/ok", allow_private=True)
moved = {s.port: s.hits - before[s.port] for s in (http_a, https_a, socks5_a, socks5h_a, http_b)}
check("round-robin spreads load", all(count >= 1 for count in moved.values()), str(moved))
# One dead proxy cools and the next one serves.
transport.POOL = pool_of(f"http://127.0.0.1:{dead.port}", f"http://127.0.0.1:{http_a.port}")
check("dead proxy fails over", transport.download(base + "/ok", allow_private=True).body == b"OK")
check("dead proxy cools down", transport.POOL.snapshot()[0]["available"] is False)
# Whole pool dead: no silent direct fallback.
transport.POOL = pool_of(f"http://127.0.0.1:{dead.port}")
try:
transport.download(base + "/ok", allow_private=True)
check("pool down reports", False)
except transport.FetchError as error:
check("pool down reports proxy_unavailable", error.code == "proxy_unavailable", error.code)
# 429 honours Retry-After and then succeeds on the same site.
transport.POOL = pool_of(f"http://127.0.0.1:{http_a.port}")
REQUESTS["429"] = 0
started = time.monotonic()
result = transport.download(base + "/429", allow_private=True)
waited = time.monotonic() - started
check("429 waits then succeeds", result.body == b"OK" and waited >= 0.9, f"{waited:.2f}s")
# 429 beyond the deadline surfaces retry_at instead of blocking.
try:
transport.download(base + "/429toomuch", allow_private=True, deadline=3)
check("long 429 reports", False)
except transport.FetchError as error:
check("long 429 reports retry_at", error.code == "rate_limited" and error.retry_at is not None, error.code)
# Replacement during an in-flight request lets the old one finish.
transport._pauses._until.clear()
transport.POOL = pool_of(f"http://127.0.0.1:{http_a.port}")
outcome: list[str] = []
def slow_call() -> None:
try:
outcome.append(transport.download(base + "/slow", allow_private=True).body.decode())
except transport.FetchError as error: # pragma: no cover
outcome.append(error.code)
worker = threading.Thread(target=slow_call)
worker.start()
time.sleep(0.2)
transport.POOL._apply(proxy.parse_list(f"http://user:pa%20ss@127.0.0.1:{http_b.port}\n"))
worker.join(10)
check("in-flight survives replacement", outcome == ["slow"], str(outcome))
after = transport.download(base + "/ok", allow_private=True)
check("replacement proxy is used", after.proxy is not None and str(http_b.port) in after.proxy, str(after.proxy))
# A pin keeps the same exit even though rotation would move on.
transport.POOL = pool_of(f"http://127.0.0.1:{http_a.port}", f"http://127.0.0.1:{socks5_a.port}")
pinned_url = transport.POOL.snapshot()[0]["proxy"]
start_hits = socks5_a.hits
for _ in range(3):
kept = transport.download(base + "/ok", allow_private=True, pin=pinned_url)
check("pin reuses the exit", str(http_a.port) in (kept.proxy or ""), str(kept.proxy))
check("pin does not touch the other exit", socks5_a.hits == start_hits)
# Wrong proxy credentials are a proxy fault: cool it and use the next exit.
bad = Server(http_proxy(("user", "wrong")))
transport._pauses._until.clear()
transport.POOL = pool_of(f"http://user:pa%20ss@127.0.0.1:{bad.port}", f"http://127.0.0.1:{http_a.port}")
check("bad credentials rotate", transport.download(base + "/ok", allow_private=True).body == b"OK")
check("bad credentials cool the exit", transport.POOL.snapshot()[0]["available"] is False)
# Direct route keeps working and ignores the pool.
transport.POOL = proxy.Pool(_route="direct")
direct = transport.download(base + "/ok", allow_private=True)
check("direct route is separate", direct.route == "direct" and direct.body == b"OK")
print("PASS: four schemes, credentials, round-robin, failover, pool outage, 429, live replacement, direct")
if __name__ == "__main__":
main()
+179
View File
@@ -0,0 +1,179 @@
"""Solver adapter: request-based Cloudflare clearance and Turnstile tokens.
The solver is an external binary (cfsolve). It is optional: without one the
client still works and simply reports the challenge.
"""
import json
import os
import shlex
import shutil
import subprocess
import tempfile
import time
from dataclasses import dataclass
_NO_WINDOW = 0x08000000 if os.name == "nt" else 0
_DEFAULT_COMMAND = [
"wsl",
"-e",
"bash",
"-lc",
'cd ~/cfsolve && exec ./target/release/challenge "$@"',
"challenge",
]
_TIMEOUT = float(os.environ.get("MCP_SOLVER_TIMEOUT", "120"))
class SolverError(RuntimeError):
def __init__(self, code: str, message: str) -> None:
super().__init__(message)
self.code = code
@dataclass(frozen=True, slots=True)
class Clearance:
cookies: dict[str, str]
user_agent: str
def command() -> list[str]:
raw = os.environ.get("MCP_SOLVER", "").strip()
if not raw:
return list(_DEFAULT_COMMAND)
if raw in {"off", "0", "false"}:
return []
try:
value = json.loads(raw)
except json.JSONDecodeError:
value = None
if isinstance(value, list) and all(isinstance(part, str) for part in value):
return list(value)
return shlex.split(raw)
def available(runner: list[str]) -> bool:
if not runner:
return False
return shutil.which(runner[0]) is not None
def _wsl(runner: list[str]) -> bool:
return bool(runner) and runner[0].lower().endswith("wsl")
def _work_dir(runner: list[str]) -> str:
"""Output directory the solver can actually write: a WSL path when it runs there."""
work = tempfile.mkdtemp(prefix="solve-")
if not _wsl(runner):
return work
try:
done = subprocess.run(
["wslpath", "-u", work],
capture_output=True,
text=True,
timeout=15,
check=True,
stdin=subprocess.DEVNULL,
creationflags=_NO_WINDOW,
env={**os.environ, "WSL_UTF8": "1"},
)
except (OSError, subprocess.SubprocessError):
return work
return done.stdout.strip() or work
def _cleanup(runner: list[str], work: str) -> None:
if _wsl(runner):
try:
subprocess.run(
[runner[0], "-e", "rm", "-rf", work],
timeout=15,
stdin=subprocess.DEVNULL,
creationflags=_NO_WINDOW,
env={**os.environ, "WSL_UTF8": "1"},
check=False,
)
return
except OSError:
pass
shutil.rmtree(work, ignore_errors=True)
def _run(runner: list[str], page: str, extra: list[str]) -> str:
work = _work_dir(runner)
profile = os.environ.get("MCP_SOLVER_PROFILE", "profiles/safari-26-ios.json")
args = [*runner, "--page", page, work, "--solve", "--fingerprint", profile, *extra]
try:
done = subprocess.run(
args,
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
timeout=_TIMEOUT,
creationflags=_NO_WINDOW,
stdin=subprocess.DEVNULL,
env={**os.environ, "WSL_UTF8": "1"},
)
except subprocess.TimeoutExpired:
raise SolverError("solver_timeout", f"Solver exceeded {_TIMEOUT:.0f}s.") from None
except OSError as error:
raise SolverError("solver_unavailable", f"Solver could not start: {error.strerror}.") from None
finally:
_cleanup(runner, work)
lines = [line.strip() for line in done.stdout.splitlines() if line.strip()]
if done.returncode != 0 or not lines:
detail = _last_error(done.stderr)
# A page that already answers 200 has no challenge to clear; the exit is
# still usable, so mark it apart instead of as a hard failure.
if "no .cf-turnstile container" in detail:
raise SolverError("solver_warm", "The page answered without a challenge.")
raise SolverError("solver_failed", detail)
return lines[-1]
def _cookies(text: str) -> dict[str, str]:
cookies: dict[str, str] = {}
for part in text.split(";"):
name, _, value = part.strip().partition("=")
if name:
cookies[name] = value
if "cf_clearance" not in cookies:
# A widget page yields a token instead of a clearance; the exit is fine.
raise SolverError("solver_warm", f"No clearance in solver output: {text[:120]}")
return cookies
def _last_error(stderr: str) -> str:
lines = [line.strip() for line in stderr.splitlines() if line.strip()]
return lines[-1][:300] if lines else "no diagnostic"
def clearance(runner: list[str], url: str, user_agent: str, proxy: str | None = None) -> Clearance:
"""Solve a challenge page and return its cookies."""
extra = ["--proxy", proxy] if proxy else []
output = _run(runner, url, extra)
return Clearance(_cookies(output), user_agent)
def turnstile(runner: list[str], url: str, sitekey: str) -> str:
token = _run(runner, url, ["--sitekey", sitekey])
if not token or token.startswith("Error"):
raise SolverError("solver_failed", token[:200])
return token
def sitekey(html: bytes) -> str | None:
"""First Turnstile sitekey in the markup, if a widget is embedded."""
import re
match = re.search(rb'data-sitekey="(0x[0-9A-Za-z_-]{10,})"', html)
if match:
return match.group(1).decode()
match = re.search(rb'sitekey["\']?\s*[:=]\s*["\'](0x[0-9A-Za-z_-]{10,})', html)
return match.group(1).decode() if match else None
def sleep_hint(seconds: float) -> None:
time.sleep(seconds)
+89
View File
@@ -0,0 +1,89 @@
import sys
from pathlib import Path
import pytest
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
sys.path.insert(0, str(Path(__file__).resolve().parent))
from servers import Server, Site, ca_and_tls, http_proxy, https_proxy, socks5 # noqa: E402
import proxy # noqa: E402
import transport # noqa: E402
@pytest.fixture
def site():
server = Site()
yield server
server.close()
@pytest.fixture
def ca(tmp_path, monkeypatch):
path, context = ca_and_tls()
monkeypatch.setenv("MCP_PROXY_CA", path)
monkeypatch.setenv("MCP_HTTP_MAX_RETRIES", "2")
monkeypatch.setattr(transport, "_bundle", None)
return context
@pytest.fixture
def proxies(ca):
made = {
"http": Server(http_proxy()),
"https": Server(https_proxy(ca)),
"socks5": Server(socks5()),
"creds": Server(http_proxy(("user", "pa ss"))),
}
yield made
for server in made.values():
server.close()
@pytest.fixture
def dead():
server = Server(http_proxy())
server.close()
return server
@pytest.fixture
def pool(monkeypatch):
def configure(*urls: str, route: str = "proxy") -> proxy.Pool:
made = proxy.Pool(_route=route)
if urls:
made.load_literal("[" + ",".join(f'"{url}"' for url in urls) + "]")
monkeypatch.setattr(transport, "POOL", made)
transport._pauses._until.clear()
return made
return configure
@pytest.fixture
def reports_file(tmp_path, monkeypatch):
path = tmp_path / "reports.jsonl"
monkeypatch.setenv("MCP_REPORT_FILE", str(path))
import reports
monkeypatch.setattr(reports, "_PATH", path)
return path
@pytest.fixture
def clearance_file(tmp_path, monkeypatch):
path = tmp_path / "clearance.json"
import clearance
monkeypatch.setattr(clearance, "_FILE", path)
return path
@pytest.fixture(autouse=True)
def _quiet(monkeypatch):
monkeypatch.setenv("WSL_UTF8", "1")
monkeypatch.delenv("MCP_SOLVER", raising=False)
yield
+306
View File
@@ -0,0 +1,306 @@
"""Loopback fixtures: a target site plus HTTP, HTTPS and SOCKS5 proxies."""
import base64
import contextlib
import datetime
import ipaddress
import socket
import ssl
import struct
import tempfile
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import urlsplit
class Target(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def do_GET(self) -> None:
path = urlsplit(self.path).path
hits = self.server.hits
hits[path] = hits.get(path, 0) + 1
status = 200
body = b"OK"
extra: dict[str, str] = {}
if path == "/429" and hits["/429"] == 1:
status = 429
extra["Retry-After"] = "1"
body = b"wait"
elif path == "/429forever":
status = 429
extra["Retry-After"] = "120"
body = b"wait"
elif path == "/429once":
status = 429
extra["Retry-After"] = "0"
body = b"wait"
elif path == "/challenge":
status = 403
extra["cf-mitigated"] = "challenge"
body = b'<html><title>Just a moment...</title><div id="challenge-stage"></div></html>'
elif path == "/html":
body = b"<html><body><h1>Hello</h1><p>text</p></body></html>"
elif path == "/json":
body = b'{"a": 1, "b": [1, 2]}'
elif path == "/big":
body = b"x" * (2 * 1024 * 1024 + 10)
self.send_response(status)
self.send_header("Content-Type", "application/json" if path == "/json" else "text/html; charset=utf-8")
for name, value in extra.items():
self.send_header(name, value)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args: object) -> None:
pass
class _Daemon(ThreadingHTTPServer):
daemon_threads = True
block_on_close = False
class Site:
def __init__(self) -> None:
self.server = _Daemon(("127.0.0.1", 0), Target)
self.server.hits = {}
self.port = self.server.server_address[1]
threading.Thread(target=self.server.serve_forever, daemon=True).start()
@property
def hits(self) -> dict[str, int]:
return self.server.hits
def url(self, path: str = "/ok") -> str:
return f"http://127.0.0.1:{self.port}{path}"
def close(self) -> None:
self.server.shutdown()
self.server.server_close()
class Server:
"""A proxy listener that counts accepted connections and can be killed."""
def __init__(self, handler) -> None:
self.sock = socket.socket()
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.bind(("127.0.0.1", 0))
self.sock.listen(16)
self.port = self.sock.getsockname()[1]
self.hits = 0
self.handler = handler
self.alive = True
threading.Thread(target=self._loop, daemon=True).start()
def _loop(self) -> None:
while self.alive:
try:
client, _ = self.sock.accept()
except OSError:
return
self.hits += 1
threading.Thread(target=self._wrap, args=(client,), daemon=True).start()
def _wrap(self, client: socket.socket) -> None:
try:
self.handler(client)
finally:
client.close()
def url(self, scheme: str = "http") -> str:
return f"{scheme}://127.0.0.1:{self.port}"
def close(self) -> None:
self.alive = False
self.sock.close()
def _pipe(src: socket.socket, dst: socket.socket) -> None:
try:
while data := src.recv(65536):
dst.sendall(data)
except OSError:
pass
finally:
with contextlib.suppress(OSError):
dst.shutdown(socket.SHUT_WR)
def _tunnel(client: socket.socket, host: str, port: int) -> None:
upstream = socket.create_connection((host, port), timeout=5)
try:
client.settimeout(None)
threading.Thread(target=_pipe, args=(upstream, client), daemon=True).start()
_pipe(client, upstream)
finally:
upstream.close()
def _read_heads(client: socket.socket) -> str:
buffer = b""
while b"\r\n\r\n" not in buffer and len(buffer) < 65536:
chunk = client.recv(4096)
if not chunk:
break
buffer += chunk
return buffer.decode("latin-1")
def http_proxy(credentials: tuple[str, str] | None = None):
def handle(client: socket.socket) -> None:
head = _read_heads(client)
lines = head.split("\r\n")
if credentials and len(lines) > 1:
expected = "Basic " + base64.b64encode(("{}:{}".format(*credentials)).encode()).decode()
sent = [line.split(": ", 1)[1].strip() for line in lines[1:] if ":" in line]
if expected not in sent:
client.sendall(b"HTTP/1.1 407 Proxy Authentication Required\r\n\r\n")
return
method, target, _ = lines[0].split(" ")
if method == "CONNECT":
host, port = target.rsplit(":", 1)
client.sendall(b"HTTP/1.1 200 Connection Established\r\n\r\n")
_tunnel(client, host, int(port))
return
parts = urlsplit(target)
upstream = socket.create_connection((parts.hostname, parts.port or 80), timeout=5)
path = parts.path + (f"?{parts.query}" if parts.query else "")
# Keep the client's own header block, including its terminator, and
# only rewrite the request line to origin form.
upstream.sendall((f"{method} {path} HTTP/1.1" + head[len(lines[0]) :]).encode("latin-1"))
_pipe(upstream, client)
upstream.close()
return handle
def socks5(credentials: tuple[str, str] | None = None):
def handle(client: socket.socket) -> None:
_, count = client.recv(2)
methods = client.recv(count)
want = 2 if credentials else 0
if want not in methods:
client.sendall(b"\x05\xff")
return
client.sendall(bytes([5, want]))
if credentials:
_, length = client.recv(2)
user = client.recv(length).decode()
_, length = client.recv(2)
password = client.recv(length).decode()
ok = (user, password) == credentials
client.sendall(b"\x01\x00" if ok else b"\x01\x01")
if not ok:
return
_, command, _, address_type = client.recv(4)
if address_type == 1:
host = socket.inet_ntoa(client.recv(4))
elif address_type == 3:
host = client.recv(client.recv(1)[0]).decode()
else:
host = socket.inet_ntop(socket.AF_INET6, client.recv(16))
port = struct.unpack("!H", client.recv(2))[0]
if command != 1:
client.sendall(b"\x05\x07\x00\x01" + b"\x00" * 6)
return
client.sendall(b"\x05\x00\x00\x01" + b"\x00" * 6)
_tunnel(client, host, port)
return handle
def _pair(folder: Path, cert, key) -> str:
from cryptography.hazmat.primitives import serialization
path = folder / "pair.pem"
path.write_bytes(
cert.public_bytes(serialization.Encoding.PEM)
+ key.private_bytes(
serialization.Encoding.PEM, serialization.PrivateFormat.TraditionalOpenSSL, serialization.NoEncryption()
)
)
return str(path)
def ca_and_tls() -> tuple[str, ssl.SSLContext]:
"""Throwaway CA and a 127.0.0.1 leaf it signs."""
from cryptography import x509
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.x509.oid import NameOID
now = datetime.datetime.now(datetime.UTC)
ca_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
ca_name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "fetch-mcp test CA")])
ca = (
x509.CertificateBuilder()
.subject_name(ca_name)
.issuer_name(ca_name)
.public_key(ca_key.public_key())
.serial_number(x509.random_serial_number())
.not_valid_before(now - datetime.timedelta(minutes=5))
.not_valid_after(now + datetime.timedelta(days=1))
.add_extension(x509.BasicConstraints(ca=True, path_length=0), True)
.add_extension(
x509.KeyUsage(
digital_signature=True,
key_cert_sign=True,
crl_sign=True,
content_commitment=False,
key_encipherment=False,
data_encipherment=False,
key_agreement=False,
encipher_only=False,
decipher_only=False,
),
True,
)
.sign(ca_key, hashes.SHA256())
)
key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
cert = (
x509.CertificateBuilder()
.subject_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "127.0.0.1")]))
.issuer_name(ca_name)
.public_key(key.public_key())
.serial_number(x509.random_serial_number())
.not_valid_before(now - datetime.timedelta(minutes=5))
.not_valid_after(now + datetime.timedelta(days=1))
.add_extension(x509.BasicConstraints(ca=False, path_length=None), True)
.add_extension(
x509.SubjectAlternativeName(
[
x509.DNSName("127.0.0.1"),
x509.IPAddress(ipaddress.ip_address("127.0.0.1")),
]
),
False,
)
.sign(ca_key, hashes.SHA256())
)
folder = Path(tempfile.mkdtemp())
ca_path = folder / "ca.pem"
ca_path.write_bytes(ca.public_bytes(serialization.Encoding.PEM))
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain(_pair(folder, cert, key))
return str(ca_path), context
def https_proxy(context: ssl.SSLContext):
inner = http_proxy()
def handle(client: socket.socket) -> None:
try:
wrapped = context.wrap_socket(client, server_side=True)
except ssl.SSLError:
return
try:
inner(wrapped)
finally:
wrapped.close()
return handle
+69
View File
@@ -0,0 +1,69 @@
import time
import clearance
def test_put_and_lookup(clearance_file):
store = clearance.Store(clearance_file)
store.put("example.com", "http://p:1", {"cf_clearance": "v"})
pin, cookie = store.lookup("example.com")
assert pin == "http://p:1"
assert cookie == "cf_clearance=v"
assert clearance_file.exists()
def test_lookup_missing(clearance_file):
store = clearance.Store(clearance_file)
assert store.lookup("absent") == (None, None)
def test_empty_cookies_are_not_stored(clearance_file):
store = clearance.Store(clearance_file)
store.put("example.com", None, {})
assert len(store) == 0
def test_expired_entry_is_ignored(clearance_file, monkeypatch):
monkeypatch.setattr(clearance, "_TTL", -1.0)
store = clearance.Store(clearance_file)
store.put("example.com", None, {"cf_clearance": "v"})
assert store.lookup("example.com") == (None, None)
def test_drop_and_reload(clearance_file):
store = clearance.Store(clearance_file)
store.put("example.com", None, {"cf_clearance": "v"})
store.drop("example.com")
assert len(store) == 0
store.put("a.com", None, {"cf_clearance": "x"})
assert clearance.Store(clearance_file).lookup("a.com")[1] == "cf_clearance=x"
def test_broken_file_is_tolerated(clearance_file):
clearance_file.write_text('{"a": {"cookies": {"k": "v"}, "expires": "bad"}, "b": 7}', "utf-8")
store = clearance.Store(clearance_file)
assert len(store) == 0
def test_unwritable_path_is_tolerated(tmp_path, monkeypatch):
store = clearance.Store(tmp_path / "missing-dir" / "c.json")
store.put("a.com", None, {"k": "v"})
assert store.lookup("a.com")[1] == "k=v"
def test_ttl_bounds(monkeypatch):
import importlib
monkeypatch.setenv("MCP_CLEARANCE_TTL", "5")
reloaded = importlib.reload(clearance)
assert reloaded._TTL == 60.0
monkeypatch.setenv("MCP_CLEARANCE_TTL", "999999")
reloaded = importlib.reload(clearance)
assert reloaded._TTL == 14400.0
def test_now_based_expiry(clearance_file):
store = clearance.Store(clearance_file)
store.put("a.com", None, {"k": "v"})
entry = store._data["a.com"]
assert entry.expires > time.time()
+91
View File
@@ -0,0 +1,91 @@
import json
import pytest
import identity
class Runner:
def __init__(self, stdout: str = "", code: int = 0, error: Exception | None = None) -> None:
self.stdout = stdout
self.code = code
self.error = error
self.args = None
def __call__(self, args, **kwargs):
self.args = args
if self.error:
raise self.error
class Done:
returncode = self.code
stdout = self.stdout
return Done()
PROFILE = json.dumps(
{
"transport": {
"profile": "safari_ios_26.2",
"headers": {"User-Agent": "UA-from-profile"},
"requests": {"headers": {"navigation": ["sec-fetch-dest: document", "user-agent", "accept: text/html"]}},
}
}
)
def test_from_profile_identity(monkeypatch):
monkeypatch.setattr(identity.subprocess, "run", Runner(PROFILE))
ident = identity.load(["wsl", "-e", "bash"])
assert ident.user_agent == "UA-from-profile"
assert ident.tls.endswith("_ios")
assert ident.as_headers()["user-agent"] == "UA-from-profile"
assert "accept" in ident.as_headers()
def test_wsl_runner_uses_cat(monkeypatch):
runner = Runner(PROFILE)
monkeypatch.setattr(identity.subprocess, "run", runner)
identity.load(["wsl"])
assert runner.args[:5] == ["wsl", "-e", "bash", "-lc", 'cat "$@"']
def test_local_path_reader(tmp_path, monkeypatch):
path = tmp_path / "profile.json"
path.write_text(PROFILE, "utf-8")
monkeypatch.setenv("MCP_SOLVER_PROFILE", str(path))
assert identity.load([]).user_agent == "UA-from-profile"
ident = identity.load([])
assert ident.user_agent == "UA-from-profile"
def test_missing_profile_falls_back(monkeypatch):
monkeypatch.setattr(identity.subprocess, "run", Runner("", error=OSError("no wsl")))
ident = identity.load(["wsl"])
assert ident.user_agent == identity._FALLBACK
assert ident.tls.endswith("_ios")
def test_broken_profile_falls_back(monkeypatch):
monkeypatch.setattr(identity.subprocess, "run", Runner("{}"))
assert identity.load(["wsl"]).user_agent == identity._FALLBACK
def test_tls_override_and_chrome_detection(monkeypatch):
monkeypatch.setenv("MCP_TLS_PROFILE", "chrome152")
assert identity._tls_for("safari_ios_26.2") == "chrome152"
monkeypatch.delenv("MCP_TLS_PROFILE")
assert identity._tls_for("chrome-131").startswith("chrome")
assert identity._tls_for("safari-26-ios").endswith("_ios")
def test_fallback_identity_is_coherent():
ident = identity.fallback()
assert ident.tls.endswith("_ios")
assert "iPhone" in ident.user_agent
@pytest.mark.parametrize("header", ["sec-fetch-dest: document", "accept-language: en-US,en;q=0.9"])
def test_navigation_headers_present(header):
assert header in identity.DEFAULT.headers
+161
View File
@@ -0,0 +1,161 @@
import pytest
import proxy
def test_parse_default_ports_and_host_lower():
parsed = proxy.parse_one("HTTP://Example.COM")
assert parsed.scheme == "http"
assert parsed.host == "example.com"
assert parsed.port == 80
assert parsed.user == ""
def test_parse_credentials_are_decoded():
parsed = proxy.parse_one("socks5://user:p%40ss@10.0.0.1:1080")
assert (parsed.user, parsed.password) == ("user", "p@ss")
assert parsed.password not in parsed.label
assert "user:" in parsed.label
@pytest.mark.parametrize(
"raw",
["", "ftp://h:1", "http://h:1/path", "http://h:1?x=1", "http://u@h:1", "http://h:99999", "http://:1"],
)
def test_parse_rejects(raw):
with pytest.raises(proxy.PoolError):
proxy.parse_one(raw)
def test_parse_list_skips_blanks_and_duplicates():
parsed = proxy.parse_list("\nhttp://a:1\n\nhttp://a:1\nhttp://b:2\n")
assert [entry.host for entry in parsed] == ["a", "b"]
def test_parse_list_rejects_invalid_whole_list():
with pytest.raises(proxy.PoolError):
proxy.parse_list("http://a:1\nftp://b:2\n")
def test_retry_after_seconds_and_date():
assert proxy.retry_after_seconds("7") == 7.0
assert proxy.retry_after_seconds(None) is None
assert proxy.retry_after_seconds("garbage") is None
assert proxy.retry_after_seconds("Wed, 21 Oct 2015 07:28:00 GMT") == 0.0
def test_pool_round_robin_and_cooldown(pool):
made = pool("http://a:1", "http://b:2")
first = made.acquire()
second = made.acquire()
made.release(first)
made.release(second)
assert first.proxy.host != second.proxy.host
made.cool(first, 30, "proxy")
assert [entry.proxy.host for entry in [made.acquire()] if entry] == [second.proxy.host]
made.release(made.acquire())
def test_pool_pin_by_url_and_label(pool):
made = pool("http://a:1", "http://b:2")
target = made.entries[1]
for pinned in (target.proxy.url, target.proxy.label):
got = made.acquire(pinned)
assert got is target
made.release(got)
def test_pool_returns_none_when_all_cooling(pool):
made = pool("http://a:1")
entry = made.acquire()
made.release(entry)
made.cool(entry, 30, "proxy")
assert made.acquire() is None
def test_refresh_keeps_last_good_and_reuses_entries(pool):
made = pool("http://a:1")
def failing(url, token):
raise proxy.PoolError("boom")
assert made.refresh(failing) is False
assert len(made) == 1
kept = made.entries[0]
def good(url, token):
return "http://a:1\nhttp://b:2\n"
assert made.refresh(good) is True
assert len(made) == 2
assert made.entries[0] is kept
def test_refresh_accepts_transport_style_errors(pool):
made = pool("http://a:1")
class Boom(ValueError):
pass
def failing(url, token):
raise Boom("network down")
assert made.refresh(failing) is False
assert len(made) == 1
def test_snapshot_reports_state(pool):
made = pool("http://a:1")
assert made.snapshot()[0]["available"] is True
assert "***" not in made.snapshot()[0]["proxy"]
def test_from_env_requires_one_source():
with pytest.raises(proxy.PoolError):
proxy.from_env({"MCP_LIVE_ROUTE": "proxy"})
with pytest.raises(proxy.PoolError):
proxy.from_env({"MCP_PROXY_URLS": "[]", "MCP_PROXY_LIST_URL": "http://x"})
def test_from_env_direct_skips_sources():
made = proxy.from_env({"MCP_LIVE_ROUTE": "direct"})
assert made.route == "direct"
assert len(made) == 0
def test_from_env_literal_and_list_validation():
made = proxy.from_env({"MCP_PROXY_URLS": '["http://a:1"]'})
assert len(made) == 1
with pytest.raises(proxy.PoolError):
proxy.from_env({"MCP_PROXY_LIST_URL": "http://x"})
with pytest.raises(proxy.PoolError):
proxy.from_env(
{"MCP_PROXY_LIST_URL": "http://x", "MCP_PROXY_LIST_TOKEN": "t", "MCP_PROXY_LIST_REFRESH_MINUTES": "abc"}
)
with pytest.raises(proxy.PoolError):
proxy.from_env({"MCP_PROXY_URLS": "{}"})
def test_max_retries_bounds():
assert proxy.max_retries({"MCP_HTTP_MAX_RETRIES": "0"}) == 0
with pytest.raises(proxy.PoolError):
proxy.max_retries({"MCP_HTTP_MAX_RETRIES": "99"})
def test_start_without_list_url_is_false():
assert proxy.Pool(_route="proxy").start(lambda url, token: "") is False
def test_limit_keeps_newest_entries(pool):
made = proxy.Pool(_route="proxy", limit=2)
made.refresh(lambda url, token: "http://a:1\nhttp://b:2\nhttp://c:3\n")
assert [entry.proxy.host for entry in made.entries] == ["b", "c"]
def test_limit_validation():
assert (
proxy.from_env({"MCP_PROXY_LIST_URL": "http://x", "MCP_PROXY_LIST_TOKEN": "t", "MCP_PROXY_LIMIT": "5"}).limit
== 5
)
with pytest.raises(proxy.PoolError):
proxy.from_env({"MCP_PROXY_LIST_URL": "http://x", "MCP_PROXY_LIST_TOKEN": "t", "MCP_PROXY_LIMIT": "0"})
+113
View File
@@ -0,0 +1,113 @@
import pytest
import json_reader
from html_reader import render_html
DOC = b"""<html><head><title>Doc</title></head><body>
<nav><a href="/top">top</a></nav>
<article>
<h1>Guide</h1>
<p>Intro text.</p>
<h2 id="auth">Authentication</h2>
<p>Use the token <code>parse_float</code> parameter.</p>
<h3>Details</h3>
<p>Deeper.</p>
<h2>Limits</h2>
<table><tr><th>k</th><th>v</th></tr><tr><td>a</td><td>1</td></tr></table>
<p><a href="/rel">relative link</a></p>
</article></body></html>"""
def test_outline_numbers_headings_and_keeps_real_anchor():
title, outline = render_html(DOC, "https://example.com/x", None, "outline", None, 2)
assert title == "Doc"
assert "@1" in outline and "Guide" in outline
assert "#auth" in outline
assert "nav" not in outline
def test_outline_without_headings():
_, outline = render_html(b"<html><body><p>x</p></body></html>", "https://e.com/", None, "outline", None, 2)
assert "no headings" in outline.lower()
def test_section_by_label_and_by_id():
_, by_label = render_html(DOC, "https://example.com/", None, "section", "Authentication", 2)
assert "parse_float" in by_label
_, by_id = render_html(DOC, "https://example.com/", None, "section", "@2", 2)
assert "parse_float" in by_id
def test_section_unknown_heading():
with pytest.raises(ValueError):
render_html(DOC, "https://example.com/", None, "section", "nope", 2)
def test_find_is_literal_and_case_insensitive():
_, found = render_html(DOC, "https://example.com/", None, "find", "PARSE_FLOAT", 1)
assert "**@2" in found
assert "parse" in found.replace("\\_", "_")
def test_find_without_match_returns_message():
_, found = render_html(DOC, "https://example.com/", None, "find", "absent", 1)
assert "No matches" in found
def test_css_selects_and_absolutizes_links():
_, table = render_html(DOC, "https://example.com/a/b", None, "css", "table", 2)
assert "| a | 1 |" in table
_, link = render_html(DOC, "https://example.com/a/b", None, "css", "article p a", 2)
assert "https://example.com/rel" in link
def test_css_invalid_selector():
with pytest.raises(ValueError):
render_html(DOC, "https://example.com/", None, "css", "[[", 2)
def test_text_mode_renders_markdown():
_, text = render_html(DOC, "https://example.com/", None, "text", None, 2)
assert "## Authentication" in text
assert "| k | v |" in text
def test_unknown_mode():
with pytest.raises(ValueError):
render_html(DOC, "https://example.com/", None, "jsonpath", None, 2)
DATA = {
"info": {"name": "pkg", "tags": ["a", "b"]},
"urls": [{"filename": "x.whl"}, {"filename": "y.tar.gz"}],
"none": None,
}
def test_shape_reports_types_without_values():
shape = json_reader.shape(DATA)
assert shape["type"] == "object"
assert shape["fields"]["info"]["fields"]["name"] == "string"
assert shape["fields"]["urls"]["type"] == "array"
def test_select_field_index_and_wildcard():
assert json_reader.select(DATA, "$.info.name") == "pkg"
assert json_reader.select(DATA, "$.urls[1].filename") == "y.tar.gz"
assert json_reader.select(DATA, "$.urls[*].filename") == ["x.whl", "y.tar.gz"]
assert json_reader.select(DATA, '$["info"]["name"]') == "pkg"
@pytest.mark.parametrize("path", ["info", "$.missing", "$.info.name.deeper", "$[9]"])
def test_select_errors(path):
with pytest.raises(ValueError):
json_reader.select(DATA, path)
def test_render_json_modes():
body = b'{"a": 1}'
assert json_reader.render_json(body, "outline", None).startswith('{"type"')
assert json_reader.render_json(body, "jsonpath", "$.a") == "1"
assert json_reader.render_json(body, "text", None) == '{"a":1}'
with pytest.raises(ValueError):
json_reader.render_json(body, "css", None)
+121
View File
@@ -0,0 +1,121 @@
import json
import pytest
import reports
def build(**overrides) -> reports.Report:
data = {"host": "example.com", "category": "js_required", "needed": "price", "url": "https://example.com/x"}
data.update(overrides)
return reports.Report(**data)
def test_add_creates_open_row(reports_file):
row = reports.add(build())
assert row.id and row.status == "open" and row.hits == 1
assert reports_file.exists()
assert json.loads(reports_file.read_text("utf-8").splitlines()[0])["host"] == "example.com"
def test_repeat_merges_and_raises_hits(reports_file):
first = reports.add(build())
second = reports.add(build(attempts=["solver"], note="shell", url="https://example.com/y"))
assert first.id == second.id
assert second.hits == 2
assert "solver" in second.attempts
assert "shell" in second.note
assert second.url == first.url
def test_host_is_normalised(reports_file):
row = reports.add(build(host="WWW.Example.COM."))
assert row.host == "example.com."
def test_unknown_category_becomes_other(reports_file):
assert reports.add(build(category="weird")).category == "other"
def test_listing_sorts_by_hits_and_filters_status(reports_file):
low = reports.add(build(host="a.com"))
reports.add(build(host="b.com"))
for _ in range(3):
reports.add(build(host="b.com"))
listed = reports.listing()
assert [row.host for row in listed] == ["b.com", "a.com"]
reports.update(low.id, "closed")
assert [row.host for row in reports.listing()] == ["b.com"]
assert len(reports.listing("all")) == 2
def test_update_status_and_note(reports_file):
row = reports.add(build())
closed = reports.update(row.id, "closed", "accepted")
assert closed.status == "closed" and "accepted" in closed.note
reopened = reports.update(row.id, "open")
assert reopened.status == "open"
def test_update_rejects_bad_status_and_id(reports_file):
with pytest.raises(ValueError):
reports.update("nope", "closed")
row = reports.add(build())
with pytest.raises(ValueError):
reports.update(row.id, "weird")
def test_counts(reports_file):
reports.add(build(host="a.com"))
other = reports.add(build(host="c.com"))
reports.update(other.id, "ignored")
assert reports.counts() == {"open": 1, "closed": 0, "ignored": 1}
def test_broken_lines_are_skipped(reports_file):
reports_file.write_text(
'not json\n{"host": 5}\n'
+ json.dumps(
{
"host": "ok.com",
"category": "other",
"needed": "x",
"id": "1",
"status": "open",
"hits": 1,
"first_seen": "now",
"last_seen": "now",
"url": "",
"attempts": [],
"note": "",
"snapshot": "",
"route": "",
"proxy": "",
"user_agent": "",
"error": "",
}
)
+ "\n",
"utf-8",
)
assert [row.host for row in reports.listing()] == ["ok.com"]
def test_row_cap_trims_oldest(reports_file, monkeypatch):
monkeypatch.setattr(reports, "_MAX_ROWS", 3)
for index in range(5):
reports.add(build(host=f"h{index}.com"))
rows = [json.loads(line) for line in reports_file.read_text("utf-8").splitlines()]
assert len(rows) == 3
assert rows[-1]["host"] == "h4.com"
def test_rows_persist_and_unknown_keys_are_tolerated(reports_file):
row = reports.add(build())
stored = json.loads(reports_file.read_text("utf-8"))
stored["expires"] = 1
stored["surprise"] = True
reports_file.write_text(json.dumps(stored) + "\n", "utf-8")
reports.add(build(host="other.com"))
hosts = [json.loads(line)["host"] for line in reports_file.read_text("utf-8").splitlines()]
assert row.host in hosts and "other.com" in hosts
+228
View File
@@ -0,0 +1,228 @@
import asyncio
import json
import pytest
import clearance
import proxy
import server
import solve
import transport
def doc(body: bytes = b"<h1>Title</h1><p>hello</p>", media: str = "text/html") -> transport.Download:
return transport.Download("https://example.com/a", 200, {}, media, None, body, False, "direct", None)
@pytest.fixture(autouse=True)
def _isolated(tmp_path, monkeypatch):
monkeypatch.setattr(server, "STORE", clearance.Store(tmp_path / "c.json"))
monkeypatch.setattr(server, "SOLVER", ["solver"])
monkeypatch.setattr(transport, "POOL", proxy.Pool(_route="direct"))
server.snapshots.clear()
yield
server.snapshots.clear()
@pytest.fixture
def fetch(monkeypatch):
calls: list[str] = []
def fake(url, **kwargs):
calls.append(url)
return doc()
monkeypatch.setattr(transport, "download", fake)
return calls
def answer(steps):
def fake(url, **kwargs):
value = next(steps)
if isinstance(value, Exception):
raise value
return value
return fake
def run(coro):
return asyncio.run(coro)
def test_read_text_and_snapshot_reuse(fetch):
page = server._read("https://example.com/a", None, "text", None, 2, 0, 100)
assert "hello" in page.content
assert page.snapshot
again = server._read(None, page.snapshot, "outline", None, 2, 0, 100)
assert "@1" in again.content
assert len(fetch) == 1
def test_read_requires_exactly_one_source(fetch):
with pytest.raises(ValueError):
server._read(None, None, "text", None, 2, 0, 10)
with pytest.raises(ValueError):
server._read("https://e.com/", "snap", "text", None, 2, 0, 10)
def test_read_rejects_offset_for_new_url(fetch):
with pytest.raises(ValueError):
server._read("https://e.com/", None, "text", None, 2, 5, 10)
def test_read_unknown_snapshot(fetch):
with pytest.raises(ValueError):
server._read(None, "nope", "text", None, 2, 0, 10)
def test_read_offset_beyond_view(fetch):
with pytest.raises(ValueError):
server._read("https://e.com/", None, "text", None, 2, 500, 10)
def test_guard_matrix(fetch):
with pytest.raises(ValueError):
server._read("https://e.com/", None, "text", "value", 2, 0, 10)
with pytest.raises(ValueError):
server._read("https://e.com/", None, "find", None, 2, 0, 10)
def test_snapshot_retention_evicts_oldest(fetch, monkeypatch):
monkeypatch.setattr(server, "KEEP", 2)
first = server._read("https://e.com/", None, "text", None, 2, 0, 10).snapshot
second = server._read("https://e.com/", None, "text", None, 2, 0, 10).snapshot
third = server._read("https://e.com/", None, "text", None, 2, 0, 10).snapshot
assert third and second and first not in server.snapshots
def test_json_and_plain_text_paths(monkeypatch):
monkeypatch.setattr(transport, "download", lambda url, **kw: doc(b'{"a":1}', "application/json"))
assert server._read("https://e.com/", None, "jsonpath", "$.a", 2, 0, 10).content == "1"
monkeypatch.setattr(transport, "download", lambda url, **kw: doc(b"line one\nline two", "text/plain"))
assert "line two" in server._read("https://e.com/", None, "find", "two", 2, 0, 50).content
def test_plain_text_outline_and_bad_mode(monkeypatch):
monkeypatch.setattr(transport, "download", lambda url, **kw: doc(b"abc", "text/plain"))
assert "characters" in server._read("https://e.com/", None, "outline", None, 2, 0, 99).content
with pytest.raises(ValueError):
server._read("https://e.com/", None, "css", "p", 2, 0, 10)
def test_fetch_solves_a_served_challenge(monkeypatch, tmp_path):
challenged = doc()
challenged.challenge = True
fresh = doc()
monkeypatch.setattr(transport, "download", answer(iter([challenged, fresh])))
monkeypatch.setattr(
solve, "clearance", lambda runner, url, ua, proxy=None: solve.Clearance({"cf_clearance": "v"}, ua)
)
page = server._fetch("https://example.com/a")
assert page.solved is True
assert server.STORE.lookup("example.com")[1] == "cf_clearance=v"
def test_fetch_refusal_without_solver_raises(monkeypatch):
monkeypatch.setattr(server, "SOLVER", [])
monkeypatch.setattr(
transport,
"download",
lambda url, **kw: (_ for _ in ()).throw(transport.FetchError("refused", "Challenge page")),
)
with pytest.raises(transport.FetchError):
server._fetch("https://example.com/a")
def test_fetch_retries_and_reports_refused(monkeypatch):
monkeypatch.setattr(
transport,
"download",
lambda url, **kw: (_ for _ in ()).throw(transport.FetchError("refused", "Challenge page")),
)
def failing(runner, url, ua, proxy=None):
raise solve.SolverError("solver_failed", "no luck")
monkeypatch.setattr(solve, "clearance", failing)
with pytest.raises(transport.FetchError) as caught:
server._fetch("https://example.com/a")
assert caught.value.code == "refused"
assert "no luck" in str(caught.value)
def test_warm_solver_result_retries_plainly(monkeypatch):
monkeypatch.setattr(transport, "download", answer(iter([transport.FetchError("refused", "c"), doc()])))
monkeypatch.setattr(
solve, "clearance", lambda *a, **k: (_ for _ in ()).throw(solve.SolverError("solver_warm", "no challenge"))
)
assert server._fetch("https://example.com/a").body
def test_stale_clearance_is_dropped(monkeypatch):
monkeypatch.setattr(transport, "POOL", proxy.Pool(_route="proxy"))
transport.POOL.load_literal('["http://127.0.0.1:1"]')
monkeypatch.setattr(server.STORE, "lookup", lambda host: ("http://127.0.0.1:1", "cf_clearance=old"))
dropped: list[str] = []
monkeypatch.setattr(server.STORE, "drop", dropped.append)
monkeypatch.setattr(transport, "download", answer(iter([transport.FetchError("refused", "c"), doc()])))
monkeypatch.setattr(
solve, "clearance", lambda runner, url, ua, proxy_url=None: solve.Clearance({"cf_clearance": "new"}, ua)
)
server._fetch("https://example.com/a")
assert dropped == ["example.com"]
def test_widget_token_is_solved_once(monkeypatch):
body = b'<div class="cf-turnstile" data-sitekey="0x4AAAAAAAAGzw6rXeQWJ_y2P"></div>'
monkeypatch.setattr(transport, "download", lambda url, **kw: doc(body))
calls: list[str] = []
monkeypatch.setattr(solve, "turnstile", lambda runner, url, key: calls.append(key) or "tok")
first = server._read("https://e.com/", None, "text", None, 2, 0, 200)
second = server._read(None, first.snapshot, "text", None, 2, 0, 200)
assert first.turnstile == second.turnstile == "tok"
assert len(calls) == 1
def test_widget_failure_is_ignored(monkeypatch):
body = b'<div class="cf-turnstile" data-sitekey="0x4AAAAAAAAGzw6rXeQWJ_y2P"></div>'
monkeypatch.setattr(transport, "download", lambda url, **kw: doc(body))
monkeypatch.setattr(solve, "turnstile", lambda *a: (_ for _ in ()).throw(solve.SolverError("x", "y")))
assert server._read("https://e.com/", None, "text", None, 2, 0, 100).turnstile is None
def test_fetch_page_error_payload(fetch):
item = run(server.fetch_page(snapshot="missing"))
assert item.ok is False and item.error == "invalid"
item = run(server.fetch_page(url="https://example.com/a", mode="text"))
assert item.ok and "hello" in item.content
def test_fetch_pages_isolates_failures(monkeypatch):
def fake(url, **kw):
if "bad" in url:
raise transport.FetchError("proxy_unavailable", "no exits")
return doc()
monkeypatch.setattr(transport, "download", fake)
batch = run(server.fetch_pages(urls=["https://a.com/", "https://bad.com/"], mode="text"))
assert batch.ok_count == 1
assert batch.results[1].error == "proxy_unavailable"
def test_fetch_pages_invalid_mode_returns_items(fetch):
batch = run(server.fetch_pages(urls=["https://a.com/", "https://b.com/"], mode="text", value="x"))
assert batch.ok_count == 0 and len(batch.results) == 2
assert batch.results[0].error == "invalid"
def test_report_and_update_tools(reports_file):
made = run(server.report("https://www.Example.com/x", "js_required", "price", ["direct"], "shell"))
assert made.ok and made.title.startswith("example.com")
listed = run(server.reports())
assert listed.ok_count == 1 and listed.error_count == 1
row = json.loads(listed.results[0].content)
updated = run(server.reports_update(row["id"], "closed", "accepted"))
assert updated.ok and "closed" in updated.title
bad = run(server.reports_update("nope", "closed"))
assert bad.ok is False and bad.error == "invalid"
+144
View File
@@ -0,0 +1,144 @@
import json
import pytest
import solve
REAL_WORK_DIR, REAL_CLEANUP = solve._work_dir, solve._cleanup
class Done:
def __init__(self, stdout: str = "", stderr: str = "", code: int = 0) -> None:
self.stdout = stdout
self.stderr = stderr
self.returncode = code
@pytest.fixture(autouse=True)
def _fast(monkeypatch, tmp_path):
monkeypatch.setattr(solve, "_work_dir", lambda runner: str(tmp_path))
monkeypatch.setattr(solve, "_cleanup", lambda runner, work: None)
def test_command_defaults_when_unset(monkeypatch):
monkeypatch.delenv("MCP_SOLVER", raising=False)
assert solve.command()[:2] == ["wsl", "-e"]
@pytest.mark.parametrize("value", ["off", "0", "false"])
def test_command_can_be_disabled(monkeypatch, value):
monkeypatch.setenv("MCP_SOLVER", value)
assert solve.command() == []
def test_command_json_array_and_plain_string(monkeypatch):
monkeypatch.setenv("MCP_SOLVER", json.dumps(["/opt/challenge"]))
assert solve.command() == ["/opt/challenge"]
monkeypatch.setenv("MCP_SOLVER", "/opt/challenge --fast")
assert solve.command() == ["/opt/challenge", "--fast"]
def test_available_checks_the_binary(monkeypatch):
assert solve.available([]) is False
monkeypatch.setattr(solve.shutil, "which", lambda name: "/usr/bin/" + name)
assert solve.available(["wsl"]) is True
def test_cookies_parses_and_requires_clearance():
assert solve._cookies("cf_clearance=v; __cf_bm=b")["cf_clearance"] == "v"
with pytest.raises(solve.SolverError) as caught:
solve._cookies("0.TOKEN")
assert caught.value.code == "solver_warm"
def test_clearance_success_passes_proxy(monkeypatch):
seen: dict[str, object] = {}
def fake_run(runner, page, extra):
seen.update(runner=runner, page=page, extra=extra)
return "cf_clearance=v"
monkeypatch.setattr(solve, "_run", fake_run)
cleared = solve.clearance(["s"], "https://e.com/", "UA", "http://p:1")
assert cleared.cookies == {"cf_clearance": "v"}
assert cleared.user_agent == "UA"
assert seen["extra"] == ["--proxy", "http://p:1"]
solve.clearance(["s"], "https://e.com/", "UA")
assert seen["extra"] == []
def test_turnstile_returns_token(monkeypatch):
monkeypatch.setattr(solve, "_run", lambda *a: "1.TOKEN")
assert solve.turnstile(["s"], "https://e.com/", "0xKEY") == "1.TOKEN"
def test_turnstile_rejects_error_text(monkeypatch):
monkeypatch.setattr(solve, "_run", lambda *a: "Error: nope")
with pytest.raises(solve.SolverError):
solve.turnstile(["s"], "https://e.com/", "0xKEY")
def test_run_parses_stdout(monkeypatch):
monkeypatch.setattr(solve.subprocess, "run", lambda *a, **k: Done(stdout="\n TOKEN \n"))
assert solve._run(["s"], "https://e.com/", []) == "TOKEN"
def test_run_maps_failure_and_warm(monkeypatch):
monkeypatch.setattr(solve.subprocess, "run", lambda *a, **k: Done(stderr="boom\nlast line", code=1))
with pytest.raises(solve.SolverError) as caught:
solve._run(["s"], "https://e.com/", [])
assert caught.value.code == "solver_failed"
assert "last line" in str(caught.value)
monkeypatch.setattr(
solve.subprocess, "run", lambda *a, **k: Done(stderr="Error: page has no .cf-turnstile container", code=1)
)
with pytest.raises(solve.SolverError) as warm:
solve._run(["s"], "https://e.com/", [])
assert warm.value.code == "solver_warm"
def test_run_maps_timeout_and_missing_binary(monkeypatch):
def boom(*a, **k):
raise solve.subprocess.TimeoutExpired("s", 1)
monkeypatch.setattr(solve.subprocess, "run", boom)
with pytest.raises(solve.SolverError) as caught:
solve._run(["s"], "https://e.com/", [])
assert caught.value.code == "solver_timeout"
def missing(*a, **k):
raise OSError("nope")
monkeypatch.setattr(solve.subprocess, "run", missing)
with pytest.raises(solve.SolverError) as gone:
solve._run(["s"], "https://e.com/", [])
assert gone.value.code == "solver_unavailable"
def test_sitekey_extraction():
assert solve.sitekey(b'<div class="cf-turnstile" data-sitekey="0x4AAAAAAAAGzw6rXeQWJ_y2P"></div>')
assert solve.sitekey(b"turnstile.render(el, {sitekey: '0x4AAAAAAAAGzw6rXeQWJ_y2P'})")
assert solve.sitekey(b"<p>none</p>") is None
def test_work_dir_without_wsl(monkeypatch, tmp_path):
monkeypatch.setattr(solve, "_work_dir", REAL_WORK_DIR)
monkeypatch.setattr(solve, "_cleanup", REAL_CLEANUP)
monkeypatch.setattr(solve.tempfile, "mkdtemp", lambda prefix="": str(tmp_path / "w"))
(tmp_path / "w").mkdir()
assert solve._work_dir(["challenge"]) == str(tmp_path / "w")
solve._cleanup(["challenge"], str(tmp_path / "w"))
assert not (tmp_path / "w").exists()
def test_wsl_helpers(monkeypatch):
monkeypatch.setattr(solve, "_work_dir", REAL_WORK_DIR)
monkeypatch.setattr(solve, "_cleanup", REAL_CLEANUP)
assert solve._wsl(["wsl"]) and not solve._wsl(["challenge"])
calls: list[list[str]] = []
monkeypatch.setattr(solve.tempfile, "mkdtemp", lambda prefix="": "C:/tmp/x")
monkeypatch.setattr(solve.subprocess, "run", lambda args, **k: calls.append(args) or Done(stdout="/mnt/c/tmp/x\n"))
assert solve._work_dir(["wsl"]) == "/mnt/c/tmp/x"
solve._cleanup(["wsl"], "/mnt/c/tmp/x")
assert calls[-1][:3] == ["wsl", "-e", "rm"]
+210
View File
@@ -0,0 +1,210 @@
import socket
import threading
import time
import pytest
import proxy
import transport
def test_schemes_reach_target(site, proxies, pool):
pool(
*[server.url(scheme) for scheme, server in proxies.items() if scheme == "http"]
+ [
proxies["https"].url("https"),
proxies["socks5"].url("socks5"),
f"http://user:pa%20ss@127.0.0.1:{proxies['creds'].port}",
]
)
for _ in range(5):
result = transport.download(site.url(), allow_private=True)
assert result.body == b"OK"
assert result.route == "proxy"
assert result.proxy and "***" in (result.proxy if "@" in result.proxy else "***")
def test_no_direct_fallback_when_pool_is_empty(pool, site):
pool("http://127.0.0.1:1")
with pytest.raises(transport.FetchError) as caught:
transport.download(site.url(), allow_private=True)
assert caught.value.code == "proxy_unavailable"
def test_dead_proxy_cools_and_next_serves(site, proxies, pool, dead):
made = pool(dead.url(), proxies["http"].url())
assert transport.download(site.url(), allow_private=True).body == b"OK"
assert made.snapshot()[0]["available"] is False
def test_wrong_credentials_are_a_proxy_fault(site, proxies, pool):
pool(f"http://user:wrong@127.0.0.1:{proxies['creds'].port}", proxies["http"].url())
assert transport.download(site.url(), allow_private=True).body == b"OK"
def test_pinned_exit_is_reused(site, proxies, pool):
made = pool(proxies["http"].url(), proxies["socks5"].url())
pinned = made.snapshot()[0]["proxy"]
before = proxies["socks5"].hits
for _ in range(2):
result = transport.download(site.url(), allow_private=True, pin=pinned)
assert str(proxies["http"].port) in (result.proxy or "")
assert proxies["socks5"].hits == before
def test_challenge_is_classified(site, proxies, pool):
pool(proxies["http"].url())
with pytest.raises(transport.FetchError) as caught:
transport.download(site.url("/challenge"), allow_private=True)
assert caught.value.code == "refused"
assert "Challenge" in str(caught.value)
def test_429_waits_then_succeeds(site, proxies, pool):
pool(proxies["http"].url())
started = time.monotonic()
assert transport.download(site.url("/429"), allow_private=True).body == b"OK"
assert time.monotonic() - started >= 0.9
def test_429_beyond_deadline_reports_retry_at(site, proxies, pool):
pool(proxies["http"].url())
with pytest.raises(transport.FetchError) as caught:
transport.download(site.url("/429forever"), allow_private=True, deadline=2)
assert caught.value.code == "rate_limited"
assert caught.value.retry_at is not None
def test_site_pause_blocks_the_host(site, proxies, pool):
pool(proxies["http"].url())
with pytest.raises(transport.FetchError):
transport.download(site.url("/429forever"), allow_private=True, deadline=1)
with pytest.raises(transport.FetchError) as caught:
transport.download(site.url("/ok"), allow_private=True, deadline=1)
assert caught.value.code == "rate_limited"
def test_body_cap(site, proxies, pool):
pool(proxies["http"].url())
with pytest.raises(transport.FetchError) as caught:
transport.download(site.url("/big"), allow_private=True)
assert caught.value.code == "too_large"
def test_json_media_type(site, proxies, pool):
pool(proxies["http"].url())
result = transport.download(site.url("/json"), allow_private=True)
assert result.media_type == "application/json"
assert result.body.startswith(b"{")
def test_redirect_loop_detected(pool):
answers = {"http://127.0.0.1:1/a": "http://127.0.0.1:1/b", "http://127.0.0.1:1/b": "http://127.0.0.1:1/a"}
seen: list[str] = []
def fake(target, proxy_entry, deadline, headers, cookies, allow_private, identity):
seen.append(target.url)
reply = transport._Reply()
reply.status = 302
reply.location = answers[target.url].encode()
reply.headers_complete = True
reply.content_type = b"text/html"
return reply
pool("http://127.0.0.1:1")
transport._request, original = fake, transport._request
try:
with pytest.raises(transport.FetchError) as caught:
transport.download("http://127.0.0.1:1/a", allow_private=True)
assert caught.value.code == "redirect"
assert len(seen) == 2
finally:
transport._request = original
def test_invalid_url_and_private_target():
with pytest.raises(transport.FetchError):
transport.download("ftp://example.com/")
with pytest.raises(transport.FetchError):
transport.download("http://127.0.0.1/")
def test_fetch_text_honours_retry_after(site, proxies):
import transport as module
calls = {"n": 0}
def fake(target, proxy_entry, deadline, headers, cookies, allow_private, identity=None):
calls["n"] += 1
reply = module._Reply()
reply.status = 429 if calls["n"] == 1 else 200
reply.headers_complete = True
reply.headers_lower["retry-after"] = "0"
reply.content_type = b"text/plain"
if reply.status == 200:
reply.body.extend(b"OK")
return reply
original = module._request
module._request = fake
try:
assert transport.fetch_text(site.url("/ok")) == "OK"
assert calls["n"] == 2
finally:
module._request = original
def test_fetch_text_rejects_non_utf8(monkeypatch, site):
original = transport._request
def fake(*args, **kwargs):
reply = transport._Reply()
reply.status = 200
reply.headers_complete = True
reply.content_type = b"text/plain"
reply.body.extend(b"\xff\xfe")
return reply
transport._request = fake
try:
with pytest.raises(transport.FetchError) as caught:
transport.fetch_text(site.url("/ok"))
assert caught.value.code == "encoding"
finally:
transport._request = original
def test_header_lines_are_built_from_mapping():
assert transport._headers({"a": "1", "b": "x"}) == ["a: 1", "b: x"]
assert transport._headers(None) == []
def test_dns_slots_release_on_timeout(monkeypatch):
transport._DNS_SLOTS = threading.BoundedSemaphore(1)
def slow(*args, **kwargs):
time.sleep(0.6)
return ()
monkeypatch.setattr(transport, "_lookup", slow)
with pytest.raises(transport.FetchError):
transport._resolve(transport._target("https://example.com/"), time.monotonic() + 0.05, allow_private=False)
assert transport._DNS_SLOTS.acquire(blocking=False)
transport._DNS_SLOTS.release()
def test_proxy_bundle_missing_file(monkeypatch):
monkeypatch.setenv("MCP_PROXY_CA", "C:/definitely/missing.pem")
monkeypatch.setattr(transport, "_bundle", None)
with pytest.raises(transport.FetchError) as caught:
transport._proxy_bundle()
assert caught.value.code == "config"
def test_socket_helpers_do_not_leak(proxies, pool, site):
pool(proxies["socks5"].url("socks5"))
for _ in range(2):
transport.download(site.url(), allow_private=True)
assert proxies["socks5"].alive
assert socket is not None
assert proxy is not None
+229
View File
@@ -0,0 +1,229 @@
import socket
from datetime import UTC, datetime
import pytest
import proxy
import transport
def reply(status=200, *, body=b"", ctype=b"text/plain", headers=None) -> transport._Reply:
made = transport._Reply()
made.status = status
made.headers_complete = True
made.content_type = ctype
made.discard_body = not 200 <= status < 300
for name, value in (headers or {}).items():
made.headers_lower[name] = value
if name == "cf-mitigated":
made.cf_mitigated = True
if name == "location":
made.location = value.encode()
made.body.extend(body)
return made
def patch(monkeypatch, replies):
seq = iter(replies)
def fake(target, proxy_entry, deadline, headers, cookies, allow_private, identity=None):
value = next(seq)
if isinstance(value, Exception):
raise value
return value
monkeypatch.setattr(transport, "_request", fake)
@pytest.mark.parametrize(
"url",
[
"http://user:pass@example.com/",
"ftp://example.com/",
"http://exa mple.com/",
"http://example.com/%zz",
"http://[::1]:99999/",
"http://example.com/" + "a" * 9000,
"http://localhost/",
"http://example.com\\",
],
)
def test_url_validation_rejects(pool, url):
pool("http://127.0.0.1:1")
with pytest.raises(transport.FetchError):
transport.download(url)
def test_private_literal_and_private_resolution(monkeypatch):
with pytest.raises(transport.FetchError) as caught:
transport._resolve(transport._target("http://10.0.0.1/"), 10**9, allow_private=False)
assert caught.value.code == "private"
assert transport._target("http://10.0.0.1/", allow_private=True).host == "10.0.0.1"
monkeypatch.setattr(
transport, "_lookup", lambda host, port, allow_private: (_ for _ in ()).throw(transport.FetchError("dns", "no"))
)
with pytest.raises(transport.FetchError):
transport._resolve(transport._target("https://example.com/"), 10**9, allow_private=False)
assert caught is not None
def test_public_address_matrix():
assert transport._public(transport.ip_address("1.1.1.1"))
assert not transport._public(transport.ip_address("192.0.0.9"))
assert not transport._public(transport.ip_address("2001:db8::1"))
assert transport._public(transport.ip_address("2606:4700::1111"))
def test_status_500_and_protocol_invalid(monkeypatch, pool):
pool("http://127.0.0.1:1")
patch(monkeypatch, [reply(500)])
with pytest.raises(transport.FetchError) as caught:
transport.download("https://example.com/")
assert caught.value.code == "status"
empty = transport._Reply()
patch(monkeypatch, [empty])
with pytest.raises(transport.FetchError) as caught:
transport.download("https://example.com/")
assert caught.value.code == "protocol"
def test_407_is_proxy_fault(monkeypatch, pool):
pool("http://127.0.0.1:1", "http://127.0.0.1:2")
patch(monkeypatch, [reply(407), reply(200, body=b"ok")])
assert transport.download("https://example.com/").body == b"ok"
def test_challenge_header_sets_flag(monkeypatch, pool):
pool("http://127.0.0.1:1")
patch(monkeypatch, [reply(403, headers={"cf-mitigated": "challenge"})])
with pytest.raises(transport.FetchError) as caught:
transport.download("https://example.com/")
assert "Challenge" in str(caught.value)
def test_redirect_rules(monkeypatch, pool):
pool("http://127.0.0.1:1")
patch(monkeypatch, [reply(302), reply(200, body=b"ok")])
with pytest.raises(transport.FetchError) as caught:
transport.download("https://example.com/")
assert caught.value.code == "redirect"
steps = [reply(302, headers={"location": f"/h{i}"}) for i in range(8)]
patch(monkeypatch, steps)
with pytest.raises(transport.FetchError) as caught:
transport.download("https://example.com/")
assert caught.value.code == "redirect"
patch(monkeypatch, [reply(302, headers={"location": "/a"}), reply(302, headers={"location": "/"})])
with pytest.raises(transport.FetchError) as caught:
transport.download("https://example.com/")
assert "loop" in str(caught.value)
def test_duplicate_location_rejected(monkeypatch, pool):
pool("http://127.0.0.1:1")
made = reply(302)
made.duplicate_location = True
patch(monkeypatch, [made])
with pytest.raises(transport.FetchError) as caught:
transport.download("https://example.com/")
assert "exactly one" in str(caught.value)
def test_header_and_body_caps(monkeypatch):
made = transport._Reply()
for _ in range(200):
made.receive_header(b"X-Pad: " + b"y" * 900 + b"\r\n")
assert made.too_large == "headers"
body = transport._Reply()
body.status = 200
assert body.receive_body(b"z" * (transport._MAX_BODY + 1)) == transport.CURL_WRITEFUNC_ERROR
assert body.too_large == "body"
def test_receive_header_ignores_undecodable(monkeypatch):
made = transport._Reply()
made.receive_header(b"HTTP/1.1 200 OK\r\n")
made.receive_header(b"X-Bin: \xff\xfe\r\n")
assert made.headers_lower["x-bin"] == "\xff\xfe"
def test_curl_error_mapping():
class Err:
def __init__(self, code):
self.code = code
assert transport._curl_error(Err(transport.CurlECode.OPERATION_TIMEDOUT), True).code == "proxy"
assert transport._curl_error(Err(transport.CurlECode.OPERATION_TIMEDOUT), False).code == "timeout"
assert transport._curl_error(Err(transport.CurlECode.PEER_FAILED_VERIFICATION), True).code == "tls"
assert transport._curl_error(Err(transport.CurlECode.BAD_CONTENT_ENCODING), False).code == "encoding"
assert transport._curl_error(Err(transport.CurlECode.COULDNT_CONNECT), True).code == "proxy"
assert transport._curl_error(Err(transport.CurlECode.COULDNT_CONNECT), False).code == "network"
assert transport._curl_error(Err(999), False).code == "network"
def test_content_metadata_fallbacks():
assert transport._content_metadata(b"garbage")[0] == "application/octet-stream"
media, charset = transport._content_metadata(b"text/html; charset=latin-1")
assert media == "text/html" and charset == "latin-1"
def test_fetch_text_errors(monkeypatch, pool):
pool("http://127.0.0.1:1")
patch(monkeypatch, [reply(503)])
with pytest.raises(transport.FetchError) as caught:
transport.fetch_text("https://example.com/")
assert caught.value.code == "status"
patch(monkeypatch, [reply(429, headers={"retry-after": "0"}) for _ in range(4)])
with pytest.raises(transport.FetchError):
transport.fetch_text("https://example.com/")
def test_retry_after_overflow_is_clamped(monkeypatch, pool):
pool("http://127.0.0.1:1")
patch(monkeypatch, [reply(429, headers={"retry-after": "999999999999"})])
with pytest.raises(transport.FetchError) as caught:
transport.download("https://example.com/", deadline=5)
assert caught.value.code == "rate_limited"
assert caught.value.retry_at.year > 2000
def test_pause_wait_inside_deadline(monkeypatch, pool):
pool("http://127.0.0.1:1")
transport._pauses.set("example.com", 0.05)
patch(monkeypatch, [reply(200, body=b"ok")])
assert transport.download("https://example.com/", deadline=5).body == b"ok"
def test_proxy_bundle_reads_and_caches(monkeypatch, tmp_path):
ca = tmp_path / "ca.pem"
ca.write_text("PEM", "utf-8")
monkeypatch.setenv("MCP_PROXY_CA", str(ca))
monkeypatch.setattr(transport, "_bundle", None)
path = transport._proxy_bundle()
assert path and "fetch-mcp-trust" in path
assert transport._proxy_bundle() == path
def test_headers_skip_multiline_values():
assert transport._headers({"a": "1\n2"}) == []
def test_pool_start_loads_list(monkeypatch):
made = proxy.Pool(_route="proxy", _list_url="https://list.example/", _token="t", refresh_minutes=0)
assert made.start(lambda url, token: "http://a:1\n") is True
assert len(made) == 1
assert made.start(lambda url, token: "") is False
def test_pool_stop_sets_event():
made = proxy.Pool()
made.stop()
assert made._stop.is_set()
def test_now_helper_timezone():
assert datetime.now(UTC).tzinfo is UTC
assert socket is not None
+603
View File
@@ -0,0 +1,603 @@
"""Anonymous, bounded HTTP(S) GETs with an operator-controlled route.
Direct requests validate and pin a public destination for every hop. Proxied
requests rotate the operator pool and never fall back to direct. ``download``
is the live path; ``fetch_text`` is the direct-only path for background work
such as refreshing the pool from its list service.
"""
import contextlib
import os
import re
import socket
import sys
import tempfile
from collections.abc import Mapping
from contextlib import suppress
from dataclasses import dataclass, field
from datetime import UTC, datetime, timedelta
from email.message import Message
from ipaddress import IPv4Address, IPv4Network, IPv6Address, IPv6Network, ip_address
from pathlib import Path
from queue import Empty, Full, Queue
from threading import BoundedSemaphore, Thread
from time import monotonic, sleep
from urllib.parse import quote, urljoin, urlsplit, urlunsplit
import certifi
from curl_cffi import Curl, CurlECode, CurlError, CurlOpt
from curl_cffi.curl import CURL_WRITEFUNC_ERROR
from identity import Identity
from proxy import Pool, Proxy, from_env, max_retries, retry_after_seconds
__all__ = ["Download", "FetchError", "download", "fetch_text", "POOL"]
_MAX_URL_LENGTH = 8192
_MAX_REDIRECTS = 5
_MAX_HEADERS = 128 * 1024
_MAX_BODY = 2 * 1024 * 1024
_TIMEOUT = 25.0 # Whole request, including DNS, every hop, waits and retries.
_CONNECT_TIMEOUT_MS = 5000
_DNS_TIMEOUT = 5.0
_DNS_SLOTS = BoundedSemaphore(8)
_PROXY_COOL_SECONDS = 30.0
_REDIRECT_CODES = {301, 302, 303, 307, 308}
_REFUSALS = {401, 403, 407, 451}
_CHALLENGE_MARKERS = (
'id="challenge-stage"',
"window._cf_chl_opt",
"cf-browser-verification",
"cf-turnstile",
"/cdn-cgi/challenge-platform/scripts/jsd/main.js",
)
_BAD_URL = re.compile(r"[\x00-\x20\x7f\\]")
_BAD_ESCAPE = re.compile(r"%(?![0-9a-fA-F]{2})")
_AUTHORITY = re.compile(r"(\[[0-9a-fA-F:.]+\]|[^:@\[\]]+)(?::([0-9]{1,5}))?\Z")
_DNS_LABEL = re.compile(r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\Z")
_NUMERIC_LABEL = re.compile(r"(?:[0-9]+|0x[0-9a-f]*)\Z")
_LOCAL_SUFFIXES = {"alt", "internal", "local", "localhost", "onion", "test"}
_IPV4_SPECIAL = (IPv4Network("192.0.0.0/24"), IPv4Network("192.88.99.0/24"))
_IPV6_GLOBAL_UNICAST = IPv6Network("2000::/3")
_IPV6_SPECIAL = (
IPv6Network("2001::/23"),
IPv6Network("2002::/16"),
IPv6Network("3fff::/20"),
)
_URI_SAFE = "/!$&'()*+,;=:@%"
_HTTP_STATUS = re.compile(rb"HTTP/\d+(?:\.\d+)? ([1-5][0-9]{2})(?:[ \r\n]|$)")
_MEDIA_TYPE = re.compile(r"[a-z0-9!#$%&'*+.^_`|~-]+/[a-z0-9!#$%&'*+.^_`|~-]+\Z")
_Address = IPv4Address | IPv6Address
class FetchError(ValueError):
"""A request failed. ``code`` is a stable classification for the caller."""
def __init__(self, code: str, message: str, retry_at: datetime | None = None) -> None:
super().__init__(message)
self.code = code
self.retry_at = retry_at
@dataclass(slots=True)
class Download:
url: str
status: int
headers: dict[str, str]
media_type: str
charset: str | None
body: bytes
challenge: bool
route: str
proxy: str | None
proxy_url: str | None = None
solved: bool = False
turnstile: str | None = None
@dataclass(frozen=True, slots=True)
class _Target:
url: str
host: str
port: int
literal: _Address | None
def _check_url_text(url: str) -> None:
if not url or len(url) > _MAX_URL_LENGTH or _BAD_URL.search(url):
raise FetchError("invalid_url", "URL is empty, too long, or contains whitespace, controls or a backslash.")
def _authority(netloc: str) -> tuple[str, int | None, _Address | None]:
match = _AUTHORITY.fullmatch(netloc)
if match is None:
raise FetchError("invalid_url", "Invalid URL authority or port; credentials are not allowed.")
host, port_text = match.groups()
port = int(port_text) if port_text else None
if port is not None and not 1 <= port <= 65535:
raise FetchError("invalid_url", "URL port must be in 1..65535.")
bracketed = host.startswith("[")
if bracketed:
host = host[1:-1]
try:
literal = ip_address(host)
except ValueError:
if bracketed:
raise FetchError("invalid_url", "Invalid IPv6 literal in URL.") from None
return host, port, None
if bracketed != isinstance(literal, IPv6Address):
raise FetchError("invalid_url", "Invalid IP literal in URL.")
return str(literal), port, literal
def _target(url: str, *, allow_private: bool = False) -> _Target:
_check_url_text(url)
try:
parts = urlsplit(url)
except ValueError:
raise FetchError("invalid_url", "Invalid URL.") from None
if parts.scheme not in {"http", "https"}:
raise FetchError("invalid_url", "Only absolute HTTP and HTTPS URLs are allowed.")
host, explicit_port, literal = _authority(parts.netloc)
if literal is None:
try:
host = host.encode("idna").decode("ascii").lower().removesuffix(".")
except UnicodeError:
raise FetchError("invalid_url", "Invalid internationalized hostname.") from None
labels = host.split(".")
if len(host) > 253 or not labels or any(not _DNS_LABEL.fullmatch(label) for label in labels):
raise FetchError("invalid_url", "Invalid hostname.")
if not allow_private and (
len(labels) < 2
or _NUMERIC_LABEL.fullmatch(labels[-1])
or labels[-1] in _LOCAL_SUFFIXES
or host == "home.arpa"
or host.endswith(".home.arpa")
):
raise FetchError("invalid_url", "Use a fully qualified hostname or a canonical IP literal.")
default_port = 443 if parts.scheme == "https" else 80
port = explicit_port if explicit_port is not None else default_port
authority = f"[{host}]" if isinstance(literal, IPv6Address) else host
if port != default_port:
authority = f"{authority}:{port}"
if _BAD_ESCAPE.search(parts.path) or _BAD_ESCAPE.search(parts.query):
raise FetchError("invalid_url", "URL contains an invalid percent escape.")
try:
path = quote(parts.path or "/", safe=_URI_SAFE)
query = quote(parts.query, safe=_URI_SAFE + "?")
except UnicodeError:
raise FetchError("invalid_url", "URL contains invalid Unicode.") from None
canonical = urlunsplit((parts.scheme, authority, path, query, ""))
_check_url_text(canonical)
return _Target(canonical, host, port, literal)
def _public(address: _Address) -> bool:
if not address.is_global or address.is_multicast or address.is_reserved:
return False
if isinstance(address, IPv4Address):
return not any(address in network for network in _IPV4_SPECIAL)
return address in _IPV6_GLOBAL_UNICAST and not any(address in network for network in _IPV6_SPECIAL)
def _lookup(host: str, port: int, *, allow_private: bool) -> tuple[_Address, ...]:
try:
records = socket.getaddrinfo(host + ".", port, type=socket.SOCK_STREAM, proto=socket.IPPROTO_TCP)
except OSError:
raise FetchError("dns", "Could not resolve the destination hostname.") from None
addresses: dict[_Address, None] = {}
for family, _, _, _, sockaddr in records:
if family not in {socket.AF_INET, socket.AF_INET6}:
raise FetchError("dns", "DNS returned an unsupported address family.")
if len(sockaddr) == 4 and sockaddr[3]:
raise FetchError("dns", "Scoped IPv6 addresses are not allowed.")
try:
address = ip_address(sockaddr[0])
except ValueError:
raise FetchError("dns", "DNS returned an invalid address.") from None
if not allow_private and not _public(address):
raise FetchError("private", "The destination resolved to a non-public address.")
addresses[address] = None
if not addresses:
raise FetchError("dns", "DNS returned no addresses for the destination.")
return tuple(addresses)
def _remaining(deadline: float) -> float:
remaining = deadline - monotonic()
if remaining <= 0:
raise FetchError("timeout", "Request timed out.")
return remaining
def _resolve(target: _Target, deadline: float, *, allow_private: bool) -> tuple[_Address, ...]:
if target.literal is not None:
if not allow_private and not _public(target.literal):
raise FetchError("private", "The destination address is not public.")
return (target.literal,)
if not _DNS_SLOTS.acquire(blocking=False):
raise FetchError("dns", "DNS resolver is busy.")
result: Queue[tuple[_Address, ...] | FetchError] = Queue(maxsize=1)
def resolve() -> None:
try:
outcome = _lookup(target.host, target.port, allow_private=allow_private)
except FetchError as error:
outcome = error
with suppress(Full):
result.put_nowait(outcome) # The caller may already have given up.
# The caller owns the slot, so a getaddrinfo that outlives its deadline
# cannot starve later lookups.
try:
Thread(target=resolve, daemon=True).start()
except RuntimeError:
_DNS_SLOTS.release()
raise FetchError("dns", "Could not start the DNS resolver.") from None
try:
addresses = result.get(timeout=min(_remaining(deadline), _DNS_TIMEOUT))
except Empty:
raise FetchError("dns", "DNS resolution timed out.") from None
finally:
_DNS_SLOTS.release()
if isinstance(addresses, FetchError):
raise addresses
return addresses
@dataclass(slots=True)
class _Reply:
body: bytearray = field(default_factory=bytearray)
status: int = 0
content_type: bytes = b""
location: bytes = b""
duplicate_location: bool = False
headers_lower: dict[str, str] = field(default_factory=dict)
cf_mitigated: bool = False
challenge_stage: bool = False
headers_complete: bool = False
header_bytes: int = 0
too_large: str = ""
discard_body: bool = False
head: bytearray = field(default_factory=bytearray)
def receive_header(self, line: bytes) -> int:
self.header_bytes += len(line)
if self.header_bytes > _MAX_HEADERS:
self.too_large = "headers"
return CURL_WRITEFUNC_ERROR
if status := _HTTP_STATUS.match(line):
self.status = int(status.group(1))
self.content_type = self.location = b""
self.cf_mitigated = self.challenge_stage = self.headers_complete = False
self.discard_body = not 200 <= self.status < 300
self.headers_lower.clear()
elif line in {b"\r\n", b"\n"}:
self.headers_complete = True
elif not self.headers_complete:
name, _, value = line.partition(b":")
name = name.strip().lower()
value = value.strip()
if name == b"content-type":
self.content_type = value
elif name == b"location":
self.duplicate_location = bool(self.location)
self.location = value
elif name == b"cf-mitigated" and value.lower() == b"challenge":
self.cf_mitigated = True
with contextlib.suppress(UnicodeDecodeError):
self.headers_lower[name.decode("latin-1")] = value.decode("latin-1")
return len(line)
def receive_body(self, chunk: bytes) -> int:
"""Write callback: sniff early bytes and keep the body when it is useful."""
if len(self.head) < 64 * 1024:
self.head.extend(chunk[: 64 * 1024 - len(self.head)])
if not (self.cf_mitigated or 200 <= self.status < 300):
return len(chunk)
if len(self.body) + len(chunk) > _MAX_BODY:
self.too_large = "body"
return CURL_WRITEFUNC_ERROR
self.body.extend(chunk)
return len(chunk)
def _curl_error(error: CurlError, proxied: bool) -> FetchError:
if error.code == CurlECode.OPERATION_TIMEDOUT:
if proxied:
# A dead or overloaded exit is the usual cause; another one may answer.
return FetchError("proxy", "Timed out through the proxy.")
return FetchError("timeout", "Request timed out.")
if error.code in {CurlECode.PEER_FAILED_VERIFICATION, CurlECode.SSL_CONNECT_ERROR}:
return FetchError("tls", "TLS handshake or certificate verification failed.")
if error.code == CurlECode.BAD_CONTENT_ENCODING:
return FetchError("encoding", "The server's content encoding could not be decoded.")
if error.code in {
CurlECode.PROXY,
CurlECode.COULDNT_RESOLVE_PROXY,
CurlECode.COULDNT_CONNECT,
CurlECode.RECV_ERROR,
CurlECode.SSL_CONNECT_ERROR,
}:
if proxied:
return FetchError("proxy", "Could not complete the exchange through the proxy.")
return FetchError("network", "Could not connect to the public destination.")
return FetchError("network", f"HTTP transfer failed (libcurl error {int(error.code)}).")
_bundle: str | None = None
def _proxy_bundle() -> str | None:
"""Trust store for an HTTPS proxy: the bundled roots plus MCP_PROXY_CA."""
global _bundle
extra = os.environ.get("MCP_PROXY_CA", "").strip()
if not extra:
return None
if _bundle is not None:
return _bundle
try:
root = Path(certifi.where()).read_bytes()
addition = Path(extra).read_bytes()
except OSError as error:
raise FetchError("config", f"MCP_PROXY_CA could not be read: {error.strerror}.") from None
path = Path(tempfile.gettempdir(), "fetch-mcp-trust.pem")
path.write_bytes(root + b"\n" + addition)
_bundle = str(path)
return _bundle
def _headers(values: Mapping[str, str] | None) -> list[str]:
if not values:
return []
return [f"{name}: {value}" for name, value in values.items() if "\n" not in value and "\r" not in value]
def _request(
target: _Target,
proxy: Proxy | None,
deadline: float,
headers: list[str],
cookies: str | None,
allow_private: bool,
identity: "Identity | None" = None,
) -> _Reply:
pinned = _resolve(target, deadline, allow_private=allow_private) if proxy is None else ()
timeout_ms = max(1, int(_remaining(deadline) * 1000))
reply = _Reply()
curl = Curl()
try:
curl.setopt(CurlOpt.URL, target.url)
curl.setopt(CurlOpt.PROTOCOLS_STR, "http,https")
curl.setopt(CurlOpt.HTTPGET, 1)
curl.setopt(CurlOpt.FOLLOWLOCATION, 0)
if proxy is None:
curl.setopt(CurlOpt.PROXY, "")
curl.setopt(CurlOpt.NOPROXY, "*")
else:
curl.setopt(CurlOpt.PROXY, f"{proxy.scheme}://{proxy.host}:{proxy.port}")
curl.setopt(CurlOpt.NOPROXY, "")
if proxy.user:
curl.setopt(CurlOpt.PROXYUSERPWD, f"{proxy.user}:{proxy.password}")
if proxy.scheme == "https" and (bundle := _proxy_bundle()):
# CAINFO also marks the handle as configured, so perform()
# does not overwrite the proxy trust store with the bundled one.
curl.setopt(CurlOpt.CAINFO, bundle)
curl.setopt(CurlOpt.PROXY_CAINFO, bundle)
if pinned:
# Keep the origin authority but hand libcurl only vetted addresses.
value = ",".join(f"[{ip}]" if isinstance(ip, IPv6Address) else str(ip) for ip in pinned)
curl.setopt(CurlOpt.RESOLVE, [f"{target.host}:{target.port}:{value}"])
curl.setopt(CurlOpt.SSL_VERIFYPEER, 1)
curl.setopt(CurlOpt.SSL_VERIFYHOST, 2)
curl.setopt(CurlOpt.NETRC, 0)
curl.setopt(CurlOpt.NOSIGNAL, 1)
curl.setopt(CurlOpt.TIMEOUT_MS, timeout_ms)
curl.setopt(CurlOpt.CONNECTTIMEOUT_MS, min(timeout_ms, _CONNECT_TIMEOUT_MS))
curl.setopt(CurlOpt.ACCEPT_ENCODING, "")
if identity is not None:
curl.setopt(CurlOpt.IMPERSONATE, identity.tls)
if headers:
curl.setopt(CurlOpt.HTTPHEADER, [line.encode("latin-1") for line in headers])
if cookies:
curl.setopt(CurlOpt.COOKIE, cookies)
curl.setopt(CurlOpt.HEADERFUNCTION, reply.receive_header)
curl.setopt(CurlOpt.WRITEFUNCTION, reply.receive_body)
curl.perform()
except CurlError as error:
if reply.too_large == "body":
raise FetchError("too_large", "Decoded response body exceeds 2 MiB.") from None
if reply.too_large == "headers":
raise FetchError("too_large", "Response headers exceed 128 KiB.") from None
if not (reply.discard_body and error.code == CurlECode.WRITE_ERROR):
raise _curl_error(error, proxy is not None) from None
finally:
curl.close()
return reply
def _content_metadata(raw: bytes) -> tuple[str, str | None]:
value = raw.decode("latin-1")
media_type = value.partition(";")[0].strip().lower()
if not _MEDIA_TYPE.fullmatch(media_type):
return "application/octet-stream", None
message = Message()
message["Content-Type"] = value
return media_type, message.get_content_charset()
def _redirect(current: _Target, reply: _Reply, *, allow_private: bool) -> _Target:
if reply.duplicate_location or not reply.location or reply.status in {303} and not reply.location:
raise FetchError("redirect", "Redirect must have exactly one nonempty Location header.")
try:
location = reply.location.decode("utf-8")
_check_url_text(location)
return _target(urljoin(current.url, location), allow_private=allow_private)
except FetchError as error:
raise FetchError("redirect", f"Unsafe redirect: {error}") from None
except ValueError:
raise FetchError("redirect", "Redirect Location is not a valid URL reference.") from None
def _headers_map(reply: _Reply) -> dict[str, str]:
return {}
def _classify(reply: _Reply) -> bool:
if reply.cf_mitigated:
return True
head = bytes(reply.head).lower()
return any(marker.encode() in head for marker in _CHALLENGE_MARKERS)
class _Pauses:
"""Per-site 429 pause, shared by every proxy."""
def __init__(self) -> None:
self._until: dict[str, float] = {}
def wait_for(self, host: str) -> float:
return max(0.0, self._until.get(host, 0.0) - monotonic())
def set(self, host: str, seconds: float) -> None:
self._until[host] = max(self._until.get(host, 0.0), monotonic() + seconds)
_pauses = _Pauses()
POOL: Pool = Pool(_route="proxy")
def _classify_proxy_failure(error: FetchError) -> bool:
return error.code == "proxy"
def download(
url: str,
*,
headers: Mapping[str, str] | None = None,
cookies: str | None = None,
deadline: float = _TIMEOUT,
allow_private: bool = False,
identity: Identity | None = None,
pin: str | None = None,
) -> Download:
"""Fetch a live URL over the configured route, or raise :class:`FetchError`."""
target = _target(url, allow_private=allow_private)
until = monotonic() + deadline
merged = dict(identity.as_headers()) if identity else {}
merged.update(headers or {})
wanted = _headers(merged)
attempts_left = 1 + max_retries()
last: FetchError | None = None
visited = {target.url}
while attempts_left:
attempts_left -= 1
entry = POOL.acquire(pin) if POOL.route == "proxy" else None
if POOL.route == "proxy" and entry is None:
raise FetchError("proxy_unavailable", "No proxy in the pool is currently usable.", None) from last
proxy = entry.proxy if entry is not None else None
try:
wait = _pauses.wait_for(target.host)
if wait:
if wait > _remaining(until):
raise FetchError(
"rate_limited",
f"{target.host} is rate-limited for {wait:.0f}s.",
datetime.now(UTC) + timedelta(seconds=wait),
)
sleep(wait)
for hop in range(_MAX_REDIRECTS + 1):
reply = _request(target, proxy, until, wanted, cookies, allow_private, identity)
if not reply.headers_complete or not reply.status:
raise FetchError("protocol", "The server did not return a valid HTTP response.")
if reply.status in _REDIRECT_CODES and hop < _MAX_REDIRECTS:
target = _redirect(target, reply, allow_private=allow_private)
if target.url in visited:
raise FetchError("redirect", "HTTP redirect loop.")
visited.add(target.url)
continue
if reply.status in _REDIRECT_CODES:
raise FetchError("redirect", "Too many HTTP redirects.")
break
if reply.status == 429:
delay = retry_after_seconds(reply.headers_lower.get("retry-after"))
pause = min(2.0 if delay is None else delay, 10**8)
_pauses.set(target.host, pause)
retry_at = datetime.now(UTC) + timedelta(seconds=pause)
if pause > _remaining(until) or not attempts_left:
raise FetchError("rate_limited", f"{target.host} asked to wait {pause:.0f}s.", retry_at)
continue
if reply.status in {200, 201, 203, 204, 206} or reply.status == 304:
media_type, charset = _content_metadata(reply.content_type)
return Download(
target.url,
reply.status,
dict(reply.headers_lower),
media_type,
charset,
bytes(reply.body),
_classify(reply),
POOL.route,
proxy.label if proxy else None,
proxy.url if proxy else None,
)
if reply.status == 407 and proxy is not None:
raise FetchError("proxy", "The proxy rejected its credentials (HTTP 407).")
if reply.status in _REFUSALS:
detail = "Challenge page" if _classify(reply) else f"HTTP {reply.status}"
raise FetchError("refused", f"The server refused the request ({detail}).")
raise FetchError("status", f"HTTP request failed with status {reply.status}.")
except FetchError as error:
last = error
if error.code == "rate_limited":
# A site pause is not a proxy fault: retry only if the budget allows.
if attempts_left and (error.retry_at is None or _pauses.wait_for(target.host) <= _remaining(until)):
continue
raise
if not attempts_left or not _classify_proxy_failure(error):
raise
if entry is not None:
POOL.cool(entry, _PROXY_COOL_SECONDS, error.code)
finally:
if entry is not None:
POOL.release(entry)
raise last or FetchError("network", "Request failed.")
def fetch_text(url: str, *, token: str = "", deadline: float = 20.0) -> str:
"""Direct GET of a UTF-8 text body (the pool list service). Never proxied."""
target = _target(url, allow_private=True)
until = monotonic() + deadline
for attempt in range(4):
reply = _request(target, None, until, [f"Authorization: Bearer {token}"] if token else [], None, True)
if reply.status == 429 and attempt < 3:
pause = retry_after_seconds(reply.headers_lower.get("retry-after")) or 2.0
if pause < _remaining(until):
sleep(pause)
continue
if reply.status != 200:
raise FetchError("status", f"List service answered HTTP {reply.status}.")
try:
return bytes(reply.body).decode("utf-8")
except UnicodeDecodeError:
raise FetchError("encoding", "List service body is not UTF-8.") from None
raise FetchError("status", "List service kept answering HTTP 429.")
def _refresh(url: str, token: str) -> str:
return fetch_text(url, token=token)
def configure() -> Pool:
"""Read operator settings, publish the pool and start refreshing it."""
global POOL
POOL = from_env()
if POOL.route == "proxy" and not POOL.start(_refresh):
print("fetch-mcp: initial proxy list unavailable; pool empty until refresh", file=sys.stderr, flush=True)
return POOL
Generated
+1129
View File
File diff suppressed because it is too large. Load diff