From 83784b00186339eaf2e591cae4408dbbb4e1757a Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sun, 22 Nov 2026 19:28:16 +0000 Subject: [PATCH 01/15] Add a bounded outbound MCP read client Configure one remote read engine for resources and explicitly approved tools. Keep protocol evidence separate from source authorization and publication, and qualify transport limits, revocation and cancellation with synthetic SDK servers. Signed-off-by: zlareb1 --- docs/architecture/mcp-source-client.md | 121 ++++ llms.txt | 1 + pyproject.toml | 4 + server/clients/mcp_source.py | 852 +++++++++++++++++++++++++ tests/unit/test_mcp_source_client.py | 721 +++++++++++++++++++++ tests/unit/test_mcp_source_network.py | 174 +++++ tests/unit/test_mcp_source_protocol.py | 637 ++++++++++++++++++ uv.lock | 242 +++++++ 8 files changed, 2752 insertions(+) create mode 100644 docs/architecture/mcp-source-client.md create mode 100644 server/clients/mcp_source.py create mode 100644 tests/unit/test_mcp_source_client.py create mode 100644 tests/unit/test_mcp_source_network.py create mode 100644 tests/unit/test_mcp_source_protocol.py diff --git a/docs/architecture/mcp-source-client.md b/docs/architecture/mcp-source-client.md new file mode 100644 index 0000000000..f549e989bf --- /dev/null +++ b/docs/architecture/mcp-source-client.md @@ -0,0 +1,121 @@ +# Outbound MCP source client + +The outbound MCP source client reads resources through a configured remote HTTP endpoint. +It provides protocol discovery and normalized evidence without storing documents, authorizing +Loom readers or running an agent. Source lifecycle and publication remain responsibilities +of the [document source layer](document-sources.md). + +## Source entry points + +`server/clients/mcp_source.py` contains the client configuration, approved tool mappings, +capability discovery and evidence types. The official protocol SDK handles MCP messages; +the client constrains the HTTP transport and validates configured operations and results. + +This client is an internal prerequisite. It adds no source registration operation, dashboard +control, worker dispatch or operator cutover. Connecting existing document sources continues +to use their current implementation. The client does not qualify an external service. + +## Connection and endpoint boundary + +A configuration identifies one exact HTTPS endpoint. Its caller supplies a separately +acquired upstream credential bound to that endpoint. The client does not accept a Loom +request, forward incoming headers, discover alternate endpoints or follow redirects. +A mandatory access validator runs around operations and HTTP response work. The source +layer is responsible for storing credentials sealed, binding the connection +to the authenticated owner and organization, checking current grants and revocation, +and approving the endpoint through operator policy before constructing a client. + +The transport uses `server/core/webhooks.py` (`pinned_target`) to validate public DNS +addresses and preserve the configured Host header and TLS server name while connecting +to a validated address. Proxy environment variables do not select another route. +Requests outside the configured endpoint are refused. A server response cannot select +a different server, credential or connection. + +The supported profile is Streamable HTTP with an explicitly supplied upstream bearer +credential, or an explicitly anonymous endpoint. Interactive authorization, credential +refresh, legacy HTTP with SSE and local +stdio commands are outside this profile. The client launches no external command. An +expired or refused credential ends the operation; no native connector or broader +credential substitutes for it. Transport and token binding follow the +[MCP HTTP transport](https://modelcontextprotocol.io/specification/2025-11-25/basic/transports) +and [authorization contract](https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization). + +## Read operations and capabilities + +Standard resource listing and reading use `resources/list` and `resources/read` when the +server advertises resources. Tool-based reads require an explicit mapping approved by +the caller's control plane. A mapping names the exact tool, its argument and result +schemas, fixed scope arguments and result selectors. Search text, a selected resource +identity or a pagination cursor fills only its configured argument. It cannot replace +a fixed scope argument or choose another tool. + +Discovery verifies the configured schemas before execution. Tool descriptions and +`readOnlyHint` are untrusted descriptive fields, never approval to call a tool. Unknown +capabilities remain unsupported; an action-only server supplies no usable document source. +Schema drift refuses the configured operation rather than guessing another result shape. +Returned resource links are evidence, never instructions to fetch an arbitrary URL. +Listing and search do not expand the explicitly approved resource identities. An empty +selection grants no read authority. + +The qualified content profile is text resources and mapped structured tool output. Binary +resource blobs and tools that return only unstructured text are unsupported. Approved +tool schemas use a bounded subset with closed objects, bounded arrays and strings, +and no references, regular expressions or combinatorial validators. + +Each read produces normalized evidence: resource identity, citation URI, title, media +type, content and any supplied revision. A read receipt binds the requested identity, +configured operation and returned body; listing metadata and search snippets have no +successful resource-read receipt. Identity is scoped by the source connection; +the same upstream identifier on another connection denotes separate evidence. A caller +that persists a document must retain the connection and resource identity with its +provenance. A citation address alone does not establish tenant or reader authority. + +## Bounds and cancellation + +Discovery, pagination, results, content and HTTP responses have finite limits. A session +has an overall deadline as well as request bounds. Cancellation ends owned protocol work; +it does not publish partial evidence as a successful read. Errors expose bounded error +codes rather than upstream content, endpoints or credentials. + +A successful final page closes that listing operation. It does not establish a deletion +history, complete reader permissions, revision support or a subscription contract. +Partial pages, errors, refused access and notifications are never deletion evidence. +The client has no retirement or erasure authority. + +## Storage and publication + +The client keeps evidence in memory for its caller and writes no knowledge document, +original, chunk, memory, account, cache or source checkpoint. There is no persistent +connection cache shared between users. The caller decides whether the evidence serves +live retrieval, an explicitly selected snapshot or a supported refresh contract. + +Live retrieval belongs in the existing protected live-search path. That path checks +current owner authority around reads and again before delivery, and applies private +result, accounting and publication rules. Calling this client does not grant permission +to bypass those checks or expose private content through diagnostics, exports or derived +memories. A team destination does not establish permission to private source evidence. +Without admitted upstream ACL evidence, a personal import remains owner-only. An +intentional collection-wide publication needs separate explicit authority. + +The absence of a client-side durable cache is not a no-retention guarantee. The remote +server, downstream host, application logging and trace configuration have their own +retention. The integrating source layer must disclose those boundaries and protect +content-bearing outputs under the existing publication contract. + +## Invariants + +- Endpoint, credential audience, approved tool, fixed scope and identity cannot be + widened by query arguments, resource content or server metadata. +- A protocol capability is not a permission grant or a synchronization guarantee. +- A read receipt proves the operation that produced evidence; it does not prove that + a different user may read the result. +- A connection or live lookup imports nothing and deletes nothing. +- Unsupported authentication, transport, schema and access contracts fail closed. + +## Upgrade boundary + +This internal client changes no stored row, wire field or source kind. Builds continue +using the same schema, account history, source checkpoints, documents and originals. +There is no account migration, credential reuse, source retirement or runtime switch. +Integrating the client into source registration requires its own explicit storage, +rolling-upgrade, access and operator reconfiguration contract. diff --git a/llms.txt b/llms.txt index 4b32f3b00c..3acffda1d2 100644 --- a/llms.txt +++ b/llms.txt @@ -165,6 +165,7 @@ Start with [the docs map](docs/index.md). To install Loom, a coding agent reads - [Knowledge gaps](docs/architecture/knowledge-gaps.md): Loom records the searches that found nothing a caller could use and groups them, once a day, into knowledge gaps: the questions several people asked that the namespace's memory and documents do not answer. - [Live connected-source search](docs/architecture/live-source-search.md): `search.query(live=true)` adds an ephemeral section from the asker's own connected Drive and Notion registrations. - [LLM and embedding architecture](docs/architecture/llm-architecture.md): Loom has two pluggable providers: an embedder (`server/embedding/`) that turns text into vectors, and an LLM client (`server/llm/`) that completes prompts. +- [Outbound MCP source client](docs/architecture/mcp-source-client.md): The outbound MCP source client reads resources through a configured remote HTTP endpoint. - [Memory architecture](docs/architecture/memory-architecture.md): The memory plane stores facts in `loom.memory`, makes them searchable through `loom.memory_embeddings`, and derives evidence, chunks, graph rows and statistics from them. - [Memory consent and derived text](docs/architecture/memory-consent.md): A deletion contracts memory and records content refusal before its tombstone commits. - [n8n adapter](docs/architecture/n8n-adapter.md): The n8n community package stores conversation history and durable facts in a Loom deployment through the TypeScript SDK. diff --git a/pyproject.toml b/pyproject.toml index 5b377ade10..cdf2dc91b0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -27,6 +27,9 @@ dependencies = [ "aiohttp>=3.10", # clickhouse-connect's async client requires it "anyio>=4", # a wait no cancellation cuts short: server.core.shielded "httpx[http2]>=0.27", + # Outbound MCP sources use the official protocol client; schemas constrain approved tool mappings. + "mcp>=1.30.0,<2", + "jsonschema>=4.20", "idna>=3.7", # UTS 46 host names: server.settings.catalog.ascii_host "dnspython>=2.6", # a cancellable lookup for names a tenant chooses: server.core.hosts "tenacity>=9.0", @@ -103,6 +106,7 @@ dev = [ "mdx-truly-sane-lists==1.3", "pymdown-extensions==12.3", "markdown-it-py==4.0.0", + "types-jsonschema>=4.20", ] # Operator CLI extra — needed only by `dev/loom_ingest.py` to fetch an S3 # source. Not a server dep; the CLI lazy-imports it with an actionable error diff --git a/server/clients/mcp_source.py b/server/clients/mcp_source.py new file mode 100644 index 0000000000..e0922d0067 --- /dev/null +++ b/server/clients/mcp_source.py @@ -0,0 +1,852 @@ +"""Bounded reads from an explicitly configured remote MCP source. + +The caller owns connection authorization and secret storage. No remote hint grants +permission to call a tool, import a document, or share its contents. +""" + +from __future__ import annotations + +import asyncio +import copy +import hashlib +import json +import math +from collections.abc import AsyncIterator, Awaitable, Callable +from contextlib import AsyncExitStack +from dataclasses import asdict, dataclass, field, replace +from datetime import timedelta +from typing import Any, Literal, TypeVar +from urllib.parse import urlsplit + +import httpx +from jsonschema import Draft202012Validator, SchemaError +from mcp import ClientSession, types +from mcp.client.streamable_http import streamable_http_client +from mcp.shared.exceptions import McpError +from pydantic import AnyUrl + +from server.core.ch import set_query_tag +from server.core.diagnostics import private_work +from server.core.webhooks import pinned_target + +ErrorCode = Literal[ + "config", "unsupported", "denied", "protocol", "schema", "limit", "timeout", "closed" +] + + +class MCPSourceError(Exception): + """Only a fixed code may cross the client boundary.""" + + def __init__(self, code: ErrorCode) -> None: + if code not in { + "config", + "unsupported", + "denied", + "protocol", + "schema", + "limit", + "timeout", + "closed", + }: + code = "protocol" + self.code = code + super().__init__("MCP source " + code) + + +def _error_code(error: BaseException) -> ErrorCode: + if isinstance(error, MCPSourceError): + return error.code + if isinstance(error, (TimeoutError, httpx.TimeoutException)): + return "timeout" + if isinstance(error, McpError) and error.error.code == httpx.codes.REQUEST_TIMEOUT: + return "timeout" + if isinstance(error, BaseExceptionGroup): + codes = {_error_code(child) for child in error.exceptions} + priorities: tuple[ErrorCode, ...] = ( + "denied", + "limit", + "timeout", + "schema", + "unsupported", + "closed", + ) + for code in priorities: + if code in codes: + return code + return "protocol" + + +@dataclass(frozen=True) +class MCPLimits: + timeout_seconds: float = 30 + request_seconds: float = 10 + max_pages: int = 8 + max_results: int = 100 + max_content_bytes: int = 1_000_000 + max_wire_bytes: int = 4_000_000 + max_requests: int = 64 + + def __post_init__(self) -> None: + for value, ceiling in ((self.timeout_seconds, 120), (self.request_seconds, 30)): + if ( + type(value) not in (int, float) + or not math.isfinite(value) + or not 0 < value <= ceiling + ): + raise MCPSourceError("config") + for value, ceiling in ( + (self.max_pages, 32), + (self.max_results, 1000), + (self.max_content_bytes, 4_000_000), + (self.max_wire_bytes, 16_000_000), + (self.max_requests, 256), + ): + if type(value) is not int or not 0 < value <= ceiling: + raise MCPSourceError("config") + + +@dataclass(frozen=True, repr=False) +class MCPBearer: + token: str + audience: str + + +@dataclass(frozen=True, repr=False) +class MCPToolMapping: + name: str + input_schema: dict[str, Any] + output_schema: dict[str, Any] + argument_name: str + fixed_arguments: dict[str, Any] = field(default_factory=dict) + items_path: tuple[str, ...] = () + id_path: tuple[str, ...] = ("id",) + title_path: tuple[str, ...] | None = ("title",) + text_path: tuple[str, ...] | None = ("text",) + uri_path: tuple[str, ...] | None = ("uri",) + revision_path: tuple[str, ...] | None = None + cursor_argument: str | None = None + next_cursor_path: tuple[str, ...] | None = None + + +@dataclass(frozen=True, repr=False) +class MCPSourceConfig: + endpoint: str + bearer_audience: str | None = None + approved_tools: tuple[str, ...] = () + search: MCPToolMapping | None = None + read: MCPToolMapping | None = None + limits: MCPLimits = field(default_factory=MCPLimits) + approved_resource_ids: tuple[str, ...] = () + + +@dataclass(frozen=True, repr=False) +class MCPEvidence: + resource_id: str + uri: str + title: str + text: str = "" + mime_type: str = "text/plain" + revision: str | None = None + receipt: MCPReadReceipt | None = None + + +@dataclass(frozen=True, repr=False) +class MCPReadReceipt: + operation: Literal["resources/read", "tools/call"] + requested_id: str + content_sha256: str + config_sha256: str + + +@dataclass(frozen=True, repr=False) +class MCPPage: + items: tuple[MCPEvidence, ...] + next_cursor: str | None + complete: bool + + +@dataclass(frozen=True) +class MCPDiscovery: + resources: bool + tools: tuple[str, ...] + + +def _json(value: Any, maximum: int) -> bytes: + try: + encoded = json.dumps( + value, ensure_ascii=True, allow_nan=False, separators=(",", ":"), sort_keys=True + ).encode() + except (ValueError, TypeError, RecursionError): + raise MCPSourceError("schema") from None + if len(encoded) > maximum: + raise MCPSourceError("limit") + return encoded + + +def _string(value: Any, maximum: int = 2048, *, empty: bool = False) -> str: + if not isinstance(value, str) or (not value and not empty): + raise MCPSourceError("schema") + if len(value.encode()) > maximum or any(ord(c) < 32 or ord(c) == 127 for c in value): + raise MCPSourceError("limit") + return value + + +def _origin(url: str) -> tuple[str, str, int]: + _string(url, 2048) + try: + parts = urlsplit(url) + if ( + parts.scheme != "https" + or not parts.hostname + or parts.username is not None + or parts.password is not None + or parts.query + or parts.fragment + or "\\" in url + or "%" in url + or any(c.isspace() for c in url) + or parts.port == 0 + or any(p in (".", "..") for p in parts.path.split("/")) + ): + raise MCPSourceError("config") + return parts.scheme, parts.hostname.encode("idna").decode().lower(), parts.port or 443 + except (ValueError, UnicodeError): + raise MCPSourceError("config") from None + + +# This subset has no references, regular expressions or combinatorial validators. +_SCHEMA_KEYS = frozenset( + { + "type", + "properties", + "required", + "additionalProperties", + "items", + "maxItems", + "minItems", + "maxLength", + "minLength", + "minimum", + "maximum", + "enum", + "const", + "title", + "description", + } +) + + +def _schema(schema: dict[str, Any]) -> None: + _json(schema, 16_384) + remaining = 256 + + def visit(node: Any, depth: int) -> None: + nonlocal remaining + remaining -= 1 + if remaining < 0 or depth > 8 or not isinstance(node, dict) or set(node) - _SCHEMA_KEYS: + raise MCPSourceError("schema") + if not isinstance(node.get("type"), str) or node["type"] not in { + "object", + "array", + "string", + "integer", + "number", + "boolean", + "null", + }: + raise MCPSourceError("schema") + if node["type"] == "object": + if node.get("additionalProperties") is not False: + raise MCPSourceError("schema") + properties = node.get("properties", {}) + if not isinstance(properties, dict) or len(properties) > 32: + raise MCPSourceError("schema") + for name, child in properties.items(): + _string(name, 128) + visit(child, depth + 1) + if node["type"] == "array": + if type(node.get("maxItems")) is not int or not 0 <= node["maxItems"] <= 1000: + raise MCPSourceError("schema") + visit(node.get("items"), depth + 1) + if node["type"] == "string": + if type(node.get("maxLength")) is not int or not 0 <= node["maxLength"] <= 4_000_000: + raise MCPSourceError("schema") + if "enum" in node and (not isinstance(node["enum"], list) or len(node["enum"]) > 32): + raise MCPSourceError("schema") + + visit(schema, 0) + try: + Draft202012Validator.check_schema(schema) + except (SchemaError, ValueError, TypeError, RecursionError): + raise MCPSourceError("schema") from None + + +def _validate(schema: dict[str, Any], value: Any, maximum: int) -> None: + _json(value, maximum) + if not Draft202012Validator(schema).is_valid(value): + raise MCPSourceError("schema") + + +def _path(value: Any, path: tuple[str, ...] | None, default: Any = "") -> Any: + if path is None: + return default + for key in path: + if not isinstance(value, dict) or key not in value: + raise MCPSourceError("schema") + value = value[key] + return value + + +class _LimitedStream(httpx.AsyncByteStream): + def __init__(self, stream: httpx.AsyncByteStream, owner: _PinnedTransport) -> None: + self.stream, self.owner = stream, owner + + async def __aiter__(self) -> AsyncIterator[bytes]: + try: + async with asyncio.timeout_at(self.owner.deadline): + async for chunk in self.stream: + self.owner.received += len(chunk) + if self.owner.received > self.owner.limits.max_wire_bytes: + raise MCPSourceError("limit") + await self.owner.validate_access() + yield chunk + except Exception as error: # noqa: BLE001 — only fixed diagnostics cross the transport boundary + self.owner.failure = _error_code(error) + raise MCPSourceError(self.owner.failure) from None + + async def aclose(self) -> None: + await self.stream.aclose() + + +class _PinnedTransport(httpx.AsyncBaseTransport): + def __init__( + self, + config: MCPSourceConfig, + credential: MCPBearer | None, + deadline: float, + validate_access: Callable[[], Awaitable[None]], + *, + transport: httpx.AsyncBaseTransport | None = None, + ) -> None: + self.endpoint = httpx.URL(config.endpoint) + self.credential, self.deadline, self.limits = credential, deadline, config.limits + self.validate_access = validate_access + self.inner = ( + transport + if transport is not None + else httpx.AsyncHTTPTransport(retries=0, trust_env=False) + ) + self.received, self.requests = 0, 0 + self.target: tuple[str, str, str] | None = None + self.pin_lock = asyncio.Lock() + self.failure: ErrorCode | None = None + + async def handle_async_request(self, request: httpx.Request) -> httpx.Response: + try: + return await self._handle(request) + except Exception as error: # noqa: BLE001 — HTTP exceptions may contain upstream credentials + self.failure = _error_code(error) + raise MCPSourceError(self.failure) from None + + async def _handle(self, request: httpx.Request) -> httpx.Response: + async with asyncio.timeout_at(self.deadline): + if self.failure is not None: + raise MCPSourceError(self.failure) + if request.url != self.endpoint or request.method not in {"POST", "GET", "DELETE"}: + raise MCPSourceError("denied") + self.requests += 1 + if self.requests > self.limits.max_requests: + raise MCPSourceError("limit") + await self.validate_access() + if self.target is None: + async with self.pin_lock: + if self.target is None: + refusal, pinned, host, sni = await pinned_target( + str(self.endpoint), schemes=("https",) + ) + if refusal or not host or not sni: + raise MCPSourceError("denied") + self.target = pinned, host, sni + pinned, host, sni = self.target + # Construct an allowlist of protocol headers, never propagate inbound headers. + headers = { + key: value + for key, value in request.headers.items() + if key + in { + "accept", + "content-type", + "mcp-session-id", + "mcp-protocol-version", + "last-event-id", + "mcp-method", + "mcp-name", + } + } + if any(len(v) > 2048 for v in headers.values()): + raise MCPSourceError("limit") + headers.update({"host": host, "accept-encoding": "identity"}) + if self.credential is not None: + headers["authorization"] = "Bearer " + self.credential.token + body = await request.aread() + if len(body) > 32_768: + raise MCPSourceError("limit") + outgoing = httpx.Request( + request.method, + pinned, + headers=headers, + content=body, + extensions={"timeout": request.extensions.get("timeout", {}), "sni_hostname": sni}, + ) + await self.validate_access() + response = await self.inner.handle_async_request(outgoing) + try: + await self.validate_access() + except Exception as error: # noqa: BLE001 — a revoked response must close before returning its fixed refusal + await response.aclose() + raise MCPSourceError(_error_code(error)) from None + if response.is_redirect: + await response.aclose() + raise MCPSourceError("denied") + if response.status_code in {401, 403}: + await response.aclose() + raise MCPSourceError("denied") + # Reject compression so the wire budget also bounds decoded protocol bytes. + if response.headers.get("content-encoding", "identity") != "identity": + await response.aclose() + raise MCPSourceError("protocol") + if not isinstance(response.stream, httpx.AsyncByteStream): + await response.aclose() + raise MCPSourceError("protocol") + response.stream = _LimitedStream(response.stream, self) + return response + + async def aclose(self) -> None: + await self.inner.aclose() + + +_T = TypeVar("_T") + + +class MCPSourceClient: + """One owner-authorized, bounded session; resources and tools yield evidence.""" + + def __init__( + self, + config: MCPSourceConfig, + credential: MCPBearer | None, + *, + validate_access: Callable[[], Awaitable[None]], + _transport: httpx.AsyncBaseTransport | None = None, + ) -> None: + self._config = copy.deepcopy(config) + self._test_transport = _transport + self.credential = credential + self.validate_access = validate_access + origin = _origin(config.endpoint) + if credential is None: + if config.bearer_audience is not None: + raise MCPSourceError("config") + elif ( + config.bearer_audience is None + or origin != _origin(config.bearer_audience) + or credential.audience != config.bearer_audience + or not isinstance(credential.token, str) + or not 0 < len(credential.token) <= 8192 + or any(not 33 <= ord(c) <= 126 for c in credential.token) + ): + raise MCPSourceError("config") + if len(config.approved_tools) > 2 or len(set(config.approved_tools)) != len( + config.approved_tools + ): + raise MCPSourceError("config") + mappings = [m for m in (self._config.search, self._config.read) if m is not None] + if set(config.approved_tools) != {m.name for m in mappings}: + raise MCPSourceError("config") + for mapping in mappings: + _string(mapping.name, 128) + _string(mapping.argument_name, 128) + _schema(mapping.input_schema) + _schema(mapping.output_schema) + if ( + mapping.input_schema["type"] != "object" + or mapping.output_schema["type"] != "object" + ): + raise MCPSourceError("config") + if not isinstance(mapping.fixed_arguments, dict): + raise MCPSourceError("config") + if mapping.cursor_argument is not None: + _string(mapping.cursor_argument, 128) + _json(mapping.fixed_arguments, 16_384) + if mapping.argument_name in mapping.fixed_arguments or ( + mapping.cursor_argument is not None + and ( + mapping.cursor_argument == mapping.argument_name + or mapping.cursor_argument in mapping.fixed_arguments + ) + ): + raise MCPSourceError("config") + for path in ( + mapping.items_path, + mapping.id_path, + mapping.title_path, + mapping.text_path, + mapping.uri_path, + mapping.revision_path, + mapping.next_cursor_path, + ): + if path is not None: + if not isinstance(path, tuple) or len(path) > 8: + raise MCPSourceError("config") + for part in path: + _string(part, 128) + self._stack: AsyncExitStack | None = None + self._session: ClientSession | None = None + self._transport: _PinnedTransport | None = None + self._operation_failure: ErrorCode | None = None + self._deadline = 0.0 + self._discovery: MCPDiscovery | None = None + self._schema_changed = False + self._pages, self._results = 0, 0 + self._issued_cursors: dict[str, tuple[str, str]] = {} + self._used_cursors: set[str] = set() + if len(config.approved_resource_ids) > config.limits.max_results: + raise MCPSourceError("config") + self._selected_ids = frozenset( + _string(identity) for identity in config.approved_resource_ids + ) + self._resource_titles: dict[str, str] = {} + + def __repr__(self) -> str: + return "MCPSourceClient()" + + @property + def config(self) -> MCPSourceConfig: + return copy.deepcopy(self._config) + + @property + def config_sha256(self) -> str: + return hashlib.sha256(_json(asdict(self._config), 131_072)).hexdigest() + + def _with_receipt( + self, evidence: MCPEvidence, operation: Literal["resources/read", "tools/call"] + ) -> MCPEvidence: + receipt = MCPReadReceipt( + operation, + evidence.resource_id, + hashlib.sha256(evidence.text.encode()).hexdigest(), + self.config_sha256, + ) + return replace(evidence, receipt=receipt) + + async def __aenter__(self) -> MCPSourceClient: + if self._stack is not None or self._deadline: + raise MCPSourceError("closed") + self._stack = AsyncExitStack() + self._stack.enter_context(private_work()) + self._deadline = asyncio.get_running_loop().time() + self._config.limits.timeout_seconds + try: + async with asyncio.timeout_at(self._deadline): + await self.validate_access() + transport = _PinnedTransport( + self._config, + self.credential, + self._deadline, + self.validate_access, + transport=self._test_transport, + ) + self._transport = transport + client = await self._stack.enter_async_context( + httpx.AsyncClient( + transport=transport, + trust_env=False, + follow_redirects=False, + timeout=httpx.Timeout(self._config.limits.request_seconds), + ) + ) + read, write, _ = await self._stack.enter_async_context( + streamable_http_client(self._config.endpoint, http_client=client) + ) + self._session = await self._stack.enter_async_context( + ClientSession( + read, + write, + read_timeout_seconds=timedelta(seconds=self._config.limits.request_seconds), + message_handler=self._message_handler, + ) + ) + result = await self._session.initialize() + self._discovery = MCPDiscovery(result.capabilities.resources is not None, ()) + await self.validate_access() + return self + except asyncio.CancelledError as error: + code = self._transport.failure if self._transport else None + try: + await self._close(error) + except (Exception, asyncio.CancelledError): # noqa: BLE001 — SDK teardown repeats its transport refusal + if code is None: + raise asyncio.CancelledError from None + if code is not None: + raise MCPSourceError(code) from None + raise + except Exception as error: # noqa: BLE001 — initialization errors contain untrusted server metadata + code = ( + self._transport.failure + if self._transport and self._transport.failure + else _error_code(error) + ) + try: + await self._close(error) + except (Exception, asyncio.CancelledError): # noqa: BLE001 — cleanup must preserve the first fixed failure + pass + raise MCPSourceError(code) from None + + async def _close(self, error: BaseException | None = None) -> None: + stack, self._stack = self._stack, None + self._session = None + if stack is not None: + await stack.__aexit__( + type(error) if error else None, error, error.__traceback__ if error else None + ) + + async def __aexit__(self, exc_type: Any, error: BaseException | None, traceback: Any) -> None: + try: + await self._close(error) + except (Exception, asyncio.CancelledError) as cleanup: # Preserve the first fixed refusal. + code = ( + self._transport.failure + if self._transport and self._transport.failure + else _error_code(cleanup) + ) + if self._operation_failure != code: + if isinstance(cleanup, asyncio.CancelledError): + raise + raise MCPSourceError(code) from None + + async def _message_handler(self, message: Any) -> None: + if isinstance(message, types.ServerNotification) and isinstance( + message.root, types.ToolListChangedNotification + ): + self._schema_changed = True + + async def _run(self, action: Callable[[ClientSession], Awaitable[_T]]) -> _T: + set_query_tag("mcp-source") + if self._session is None: + raise MCPSourceError("closed") + if self._operation_failure is not None: + raise MCPSourceError(self._operation_failure) + try: + async with asyncio.timeout_at(self._deadline): + await self.validate_access() + result = await action(self._session) + await self.validate_access() + return result + except asyncio.CancelledError: + if self._transport and self._transport.failure: + self._operation_failure = self._transport.failure + raise MCPSourceError(self._operation_failure) from None + raise + except MCPSourceError as error: + self._operation_failure = error.code + raise + except Exception as error: # noqa: BLE001 — upstream errors may contain credentials or document content + code = ( + self._transport.failure + if self._transport and self._transport.failure + else _error_code(error) + ) + self._operation_failure = code + raise MCPSourceError(code) from None + + async def discover(self) -> MCPDiscovery: + async def action(session: ClientSession) -> MCPDiscovery: + approved = set(self._config.approved_tools) + found: set[str] = set() + cursor: str | None = None + seen: set[str] = set() + if approved: + for _ in range(self._config.limits.max_pages): + result = await session.list_tools( + params=types.PaginatedRequestParams(cursor=cursor) + ) + if len(result.tools) > self._config.limits.max_results: + raise MCPSourceError("limit") + for tool in result.tools: + if tool.name in seen: + raise MCPSourceError("schema") + seen.add(tool.name) + if tool.name not in approved: + continue + for mapping in (self._config.search, self._config.read): + if mapping is not None and mapping.name == tool.name: + if ( + tool.inputSchema != mapping.input_schema + or tool.outputSchema != mapping.output_schema + ): + raise MCPSourceError("schema") + found.add(tool.name) + if len(seen) > self._config.limits.max_results: + raise MCPSourceError("limit") + cursor = result.nextCursor + if cursor is None: + break + _string(cursor) + else: + raise MCPSourceError("limit") + if found != approved: + raise MCPSourceError("unsupported") + assert self._discovery is not None + self._discovery = MCPDiscovery(self._discovery.resources, tuple(sorted(found))) + self._schema_changed = False + return self._discovery + + return await self._run(action) + + def _page_start(self, cursor: str | None, scope: tuple[str, str]) -> None: + if cursor is not None: + _string(cursor) + if self._issued_cursors.get(cursor) != scope or cursor in self._used_cursors: + raise MCPSourceError("denied") + self._used_cursors.add(cursor) + self._pages += 1 + if self._pages > self._config.limits.max_pages: + raise MCPSourceError("limit") + + def _page( + self, items: list[MCPEvidence], cursor: str | None, scope: tuple[str, str] + ) -> MCPPage: + self._results += len(items) + if self._results > self._config.limits.max_results: + raise MCPSourceError("limit") + if cursor is not None: + _string(cursor) + if cursor in self._issued_cursors: + raise MCPSourceError("protocol") + self._issued_cursors[cursor] = scope + return MCPPage(tuple(items), cursor, cursor is None) + + async def list_resources(self, cursor: str | None = None) -> MCPPage: + async def action(session: ClientSession) -> MCPPage: + if self._discovery is None or not self._discovery.resources: + raise MCPSourceError("unsupported") + self._page_start(cursor, ("resources", "")) + result = await session.list_resources( + params=types.PaginatedRequestParams(cursor=cursor) + ) + items = [] + for resource in result.resources: + identity = _string(str(resource.uri)) + title = _string(resource.title or resource.name) + items.append(MCPEvidence(identity, identity, title)) + self._resource_titles[identity] = title + return self._page(items, result.nextCursor, ("resources", "")) + + return await self._run(action) + + async def _tool( + self, session: ClientSession, mapping: MCPToolMapping, value: str, cursor: str | None = None + ) -> Any: + await self.discover() + if ( + self._schema_changed + or self._discovery is None + or mapping.name not in self._discovery.tools + ): + raise MCPSourceError("schema") + arguments = dict(mapping.fixed_arguments) + arguments[mapping.argument_name] = _string(value, 4096) + if cursor is not None: + if mapping.cursor_argument is None: + raise MCPSourceError("unsupported") + arguments[mapping.cursor_argument] = cursor + _validate(mapping.input_schema, arguments, 32_768) + result = await session.call_tool(mapping.name, arguments) + if self._schema_changed: + raise MCPSourceError("schema") + if result.isError or result.structuredContent is None: + raise MCPSourceError("protocol") + _validate( + mapping.output_schema, result.structuredContent, self._config.limits.max_content_bytes + ) + return result.structuredContent + + def _evidence(self, value: Any, mapping: MCPToolMapping) -> MCPEvidence: + identity = _string(_path(value, mapping.id_path)) + title = _string(_path(value, mapping.title_path, identity)) + text = _path(value, mapping.text_path) + if not isinstance(text, str) or len(text.encode()) > self._config.limits.max_content_bytes: + raise MCPSourceError("limit") + uri = _string(_path(value, mapping.uri_path, identity)) + try: + citation = urlsplit(uri) + if citation.username is not None or citation.password is not None: + raise MCPSourceError("schema") + except ValueError: + raise MCPSourceError("schema") from None + revision = _path(value, mapping.revision_path, None) + if revision is not None: + revision = _string(revision) + return MCPEvidence(identity, uri, title, text, revision=revision) + + async def search(self, query: str, cursor: str | None = None) -> MCPPage: + async def action(session: ClientSession) -> MCPPage: + mapping = self._config.search + if mapping is None: + raise MCPSourceError("unsupported") + self._page_start(cursor, ("search", query)) + result = await self._tool(session, mapping, query, cursor) + rows = _path(result, mapping.items_path) + if not isinstance(rows, list): + raise MCPSourceError("schema") + items = [self._evidence(row, mapping) for row in rows] + return self._page( + items, _path(result, mapping.next_cursor_path, None), ("search", query) + ) + + return await self._run(action) + + async def read(self, resource_id: str) -> MCPEvidence: + async def action(session: ClientSession) -> MCPEvidence: + identity = _string(resource_id) + if identity not in self._selected_ids: + raise MCPSourceError("denied") + if self._config.read is not None: + result = await self._tool(session, self._config.read, identity) + evidence = self._evidence( + _path(result, self._config.read.items_path), self._config.read + ) + if evidence.resource_id != identity: + raise MCPSourceError("protocol") + return self._with_receipt(evidence, "tools/call") + if self._discovery is None or not self._discovery.resources: + raise MCPSourceError("unsupported") + result = await session.read_resource(AnyUrl(identity)) + if not result.contents or len(result.contents) > self._config.limits.max_results: + raise MCPSourceError("limit") + texts: list[str] = [] + size = 0 + mime_type = result.contents[0].mimeType or "text/plain" + for content in result.contents: + if ( + not isinstance(content, types.TextResourceContents) + or str(content.uri) != identity + ): + raise MCPSourceError("unsupported") + if (content.mimeType or "text/plain") != mime_type: + raise MCPSourceError("unsupported") + size += len(content.text.encode()) + bool(texts) + if size > self._config.limits.max_content_bytes: + raise MCPSourceError("limit") + texts.append(content.text) + return self._with_receipt( + MCPEvidence( + identity, + identity, + self._resource_titles.get(identity, identity), + "\n".join(texts), + _string(mime_type, 128), + ), + "resources/read", + ) + + return await self._run(action) diff --git a/tests/unit/test_mcp_source_client.py b/tests/unit/test_mcp_source_client.py new file mode 100644 index 0000000000..f358b97a44 --- /dev/null +++ b/tests/unit/test_mcp_source_client.py @@ -0,0 +1,721 @@ +"""Synthetic official-SDK servers exercise the outbound read boundary without sockets.""" + +from __future__ import annotations + +import asyncio +import copy +import hashlib +import json +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager +from dataclasses import replace +from typing import Any + +import httpx +import pytest +from mcp import types +from mcp.server.lowlevel import Server +from mcp.server.streamable_http_manager import StreamableHTTPSessionManager +from mcp.server.transport_security import TransportSecuritySettings +from starlette.applications import Starlette +from starlette.routing import Route + +from server.clients import mcp_source as source + +ENDPOINT = "https://source.example/mcp" +IDENTITY = "doc://workspace/one" +OTHER = "doc://workspace/two" +TEXT = "Synthetic document body" +SECRET = "synthetic-upstream-secret" +STRING = {"type": "string", "maxLength": 2048} +DOCUMENT_SCHEMA = { + "type": "object", + "additionalProperties": False, + "properties": {key: dict(STRING) for key in ("id", "title", "text", "uri")}, + "required": ["id", "title", "text", "uri"], +} +INPUT_SCHEMA = { + "type": "object", + "additionalProperties": False, + "properties": { + "value": dict(STRING), + "workspace": {"type": "string", "const": "fixed", "maxLength": 8}, + "cursor": dict(STRING), + }, + "required": ["value", "workspace"], +} +SEARCH_SCHEMA = { + "type": "object", + "additionalProperties": False, + "properties": { + "documents": {"type": "array", "maxItems": 10, "items": DOCUMENT_SCHEMA}, + "cursor": dict(STRING), + }, + "required": ["documents"], +} + + +def mapping(name: str, *, search: bool = False) -> source.MCPToolMapping: + return source.MCPToolMapping( + name, + copy.deepcopy(INPUT_SCHEMA), + copy.deepcopy(SEARCH_SCHEMA if search else DOCUMENT_SCHEMA), + "value", + fixed_arguments={"workspace": "fixed"}, + items_path=("documents",) if search else (), + cursor_argument="cursor" if search else None, + next_cursor_path=None, + ) + + +def config(*, tools: bool = False, **kw: Any) -> source.MCPSourceConfig: + return source.MCPSourceConfig( + ENDPOINT, + ENDPOINT, + approved_tools=("find", "fetch") if tools else (), + search=mapping("find", search=True) if tools else None, + read=mapping("fetch") if tools else None, + **kw, + ) + + +async def access() -> None: + return None + + +@asynccontextmanager +async def synthetic_server( + monkeypatch: pytest.MonkeyPatch, *, tools: bool = False +) -> AsyncIterator[dict[str, Any]]: + state: dict[str, Any] = { + "requests": [], + "calls": [], + "drift": False, + "next": None, + "text": TEXT, + "read_entered": asyncio.Event(), + "read_cancelled": asyncio.Event(), + "hang": False, + } + + async def list_resources(ctx: Any, params: Any) -> types.ListResourcesResult: + return types.ListResourcesResult( + resources=[types.Resource(uri=IDENTITY, name="One")], + nextCursor=state["next"], + ) + + async def read_resource(ctx: Any, params: Any) -> types.ReadResourceResult: + state["calls"].append(("read", str(params.uri))) + state["read_entered"].set() + if state["hang"]: + try: + await asyncio.Event().wait() + finally: + state["read_cancelled"].set() + if "contents" in state: + return types.ReadResourceResult(contents=state["contents"]) + return types.ReadResourceResult( + contents=[ + types.TextResourceContents( + uri=state.get("return_uri", IDENTITY), + text=state["text"], + mimeType=state.get("mime_type", "text/plain"), + ) + ] + ) + + async def list_tools(ctx: Any, params: Any) -> types.ListToolsResult: + read = mapping("fetch") + if state["drift"]: + read.input_schema["properties"]["danger"] = dict(STRING) + return types.ListToolsResult( + tools=[ + types.Tool(name="find", inputSchema=INPUT_SCHEMA, outputSchema=SEARCH_SCHEMA), + types.Tool( + name="fetch", inputSchema=read.input_schema, outputSchema=DOCUMENT_SCHEMA + ), + types.Tool( + name="destroy", + inputSchema=INPUT_SCHEMA, + annotations=types.ToolAnnotations(readOnlyHint=True), + description="Pretends to be a read operation", + ), + ] + ) + + async def call_tool(ctx: Any, params: Any) -> types.CallToolResult: + state["calls"].append((params.name, params.arguments)) + document = { + "id": state.get("return_id", IDENTITY), + "uri": state.get("citation", IDENTITY), + "title": "One", + "text": state["text"], + } + result = {"documents": [document]} if params.name == "find" else document + return types.CallToolResult(content=[], structuredContent=result) + + server: Server[Any] = Server("synthetic-source") + + async def resource_listing(request: Any) -> types.ServerResult: + return types.ServerResult(await list_resources(None, request.params)) + + async def resource_read(request: Any) -> types.ServerResult: + return types.ServerResult(await read_resource(None, request.params)) + + async def tool_listing(request: Any) -> types.ServerResult: + return types.ServerResult(await list_tools(None, request.params)) + + async def tool_call(request: Any) -> types.ServerResult: + return types.ServerResult(await call_tool(None, request.params)) + + if tools: + server.request_handlers[types.ListToolsRequest] = tool_listing + server.request_handlers[types.CallToolRequest] = tool_call + else: + server.request_handlers[types.ListResourcesRequest] = resource_listing + server.request_handlers[types.ReadResourceRequest] = resource_read + manager = StreamableHTTPSessionManager( + server, + json_response=True, + stateless=True, + security_settings=TransportSecuritySettings(allowed_hosts=["source.example"]), + ) + + class Endpoint: + async def __call__(self, scope: Any, receive: Any, send: Any) -> None: + await manager.handle_request(scope, receive, send) + + app = Starlette(routes=[Route("/mcp", Endpoint(), methods=["GET", "POST", "DELETE"])]) + asgi = httpx.ASGITransport(app=app) + + class RecordingTransport(httpx.AsyncBaseTransport): + async def handle_async_request(self, request: httpx.Request) -> httpx.Response: + body = await request.aread() + state["requests"].append( + { + "url": str(request.url), + "method": request.method, + "headers": dict(request.headers), + "sni": request.extensions.get("sni_hostname"), + "body": json.loads(body) if body else None, + } + ) + if state.get("unauthorized"): + return httpx.Response(state["unauthorized"], request=request) + return await asgi.handle_async_request(request) + + async def aclose(self) -> None: + await asgi.aclose() + + async def pinned(url: str, **kw: Any) -> tuple[str, str, str, str]: + assert url == ENDPOINT + assert kw == {"schemes": ("https",)} + return "", "https://93.184.216.34/mcp", "source.example", "source.example" + + monkeypatch.setattr(source.httpx, "AsyncHTTPTransport", lambda **kw: RecordingTransport()) + monkeypatch.setattr(source, "pinned_target", pinned) + async with manager.run(): + yield state + + +def client(conf: source.MCPSourceConfig | None = None, **kw: Any) -> source.MCPSourceClient: + return source.MCPSourceClient( + conf or config(), source.MCPBearer(SECRET, ENDPOINT), validate_access=access, **kw + ) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("tools", [False, True]) +async def test_sdk_resources_and_mapped_tools_yield_the_same_evidence( + monkeypatch: pytest.MonkeyPatch, tools: bool +) -> None: + async with ( + synthetic_server(monkeypatch, tools=tools) as state, + client(config(tools=tools, approved_resource_ids=(IDENTITY,))) as remote, + ): + discovery = await remote.discover() + page = await remote.search("One") if tools else await remote.list_resources() + document = await remote.read(page.items[0].resource_id) + assert replace(document, receipt=None) == source.MCPEvidence( + IDENTITY, IDENTITY, "One", TEXT + ) + assert document.receipt == source.MCPReadReceipt( + "tools/call" if tools else "resources/read", + IDENTITY, + hashlib.sha256(TEXT.encode()).hexdigest(), + remote.config_sha256, + ) + assert all(item.receipt is None for item in page.items) + assert page.complete and page.next_cursor is None + assert discovery.tools == (("fetch", "find") if tools else ()) + assert all(request["url"] == "https://93.184.216.34/mcp" for request in state["requests"]) + assert all(request["headers"]["host"] == "source.example" for request in state["requests"]) + assert all(request["sni"] == "source.example" for request in state["requests"]) + assert all( + request["headers"]["authorization"] == "Bearer " + SECRET + for request in state["requests"] + ) + assert all("cookie" not in request["headers"] for request in state["requests"]) + assert all(name != "destroy" for name, _ in state["calls"]) + if tools: + assert all(args["workspace"] == "fixed" for _, args in state["calls"]) + + +@pytest.mark.asyncio +async def test_anonymous_transport_has_no_authorization(monkeypatch: pytest.MonkeyPatch) -> None: + async with synthetic_server(monkeypatch) as state: + conf = source.MCPSourceConfig(ENDPOINT) + async with source.MCPSourceClient(conf, None, validate_access=access) as remote: + await remote.list_resources() + assert all("authorization" not in request["headers"] for request in state["requests"]) + + +@pytest.mark.parametrize( + "endpoint", + [ + "http://source.example/mcp", + "https://user:pass@source.example/mcp", + "https://source.example/mcp?secret=x", + "https://source.example/mcp#fragment", + "https://source.example/a/../mcp", + "https://source.example/%2e/mcp", + "https://source.example\\@other.example/mcp", + ], +) +def test_endpoint_policy_rejects_ambiguous_or_insecure_urls(endpoint: str) -> None: + with pytest.raises(source.MCPSourceError): + client(replace(config(), endpoint=endpoint)) + + +def test_audience_and_fixed_argument_conflicts_are_rejected() -> None: + with pytest.raises(source.MCPSourceError): + client(replace(config(), bearer_audience="https://elsewhere.example/mcp")) + with pytest.raises(source.MCPSourceError): + source.MCPSourceClient( + config(), + source.MCPBearer(SECRET, "https://source.example/other"), + validate_access=access, + ) + conflicting = replace(mapping("fetch"), fixed_arguments={"value": "fixed"}) + with pytest.raises(source.MCPSourceError): + client( + source.MCPSourceConfig(ENDPOINT, ENDPOINT, approved_tools=("fetch",), read=conflicting) + ) + + +@pytest.mark.parametrize( + "keyword,value", + [ + ("$ref", "https://elsewhere.example/schema"), + ("pattern", "(a+)+$"), + ("oneOf", [{"type": "string"}]), + ], +) +def test_unsupported_schema_keywords_cannot_trigger_resolution_or_expensive_validation( + keyword: str, value: Any +) -> None: + read = mapping("fetch") + read.input_schema[keyword] = value + with pytest.raises(source.MCPSourceError): + client(source.MCPSourceConfig(ENDPOINT, ENDPOINT, approved_tools=("fetch",), read=read)) + + +@pytest.mark.asyncio +async def test_schema_drift_is_checked_before_tool_execution( + monkeypatch: pytest.MonkeyPatch, +) -> None: + conf = config(tools=True, approved_resource_ids=(IDENTITY,)) + async with synthetic_server(monkeypatch, tools=True) as state, client(conf) as remote: + await remote.discover() + state["drift"] = True + with pytest.raises(source.MCPSourceError, match="schema"): + await remote.read(IDENTITY) + assert state["calls"] == [] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("tools", [False, True]) +async def test_selected_identity_cannot_expand_through_listing( + monkeypatch: pytest.MonkeyPatch, tools: bool +) -> None: + async with ( + synthetic_server(monkeypatch, tools=tools) as state, + client(config(tools=tools, approved_resource_ids=(OTHER,))) as remote, + ): + await remote.discover() + await remote.search("One") if tools else await remote.list_resources() + before = len(state["calls"]) + with pytest.raises(source.MCPSourceError, match="denied"): + await remote.read(IDENTITY) + assert len(state["calls"]) == before + + +@pytest.mark.asyncio +async def test_partial_listing_and_cursor_replay_never_claim_completion( + monkeypatch: pytest.MonkeyPatch, +) -> None: + async with synthetic_server(monkeypatch) as state, client() as remote: + state["next"] = "next-page" + first = await remote.list_resources() + assert not first.complete + state["next"] = None + last = await remote.list_resources(first.next_cursor) + assert last.complete + before = len(state["requests"]) + with pytest.raises(source.MCPSourceError, match="denied"): + await remote.list_resources(first.next_cursor) + assert len(state["requests"]) == before + + +@pytest.mark.asyncio +async def test_page_limit_prevents_another_remote_request(monkeypatch: pytest.MonkeyPatch) -> None: + limits = source.MCPLimits(max_pages=1) + async with synthetic_server(monkeypatch) as state, client(config(limits=limits)) as remote: + state["next"] = "next-page" + first = await remote.list_resources() + before = len(state["requests"]) + with pytest.raises(source.MCPSourceError, match="limit"): + await remote.list_resources(first.next_cursor) + assert len(state["requests"]) == before + + +@pytest.mark.asyncio +@pytest.mark.parametrize("tools", [False, True]) +async def test_returned_identity_cannot_replace_selected_identity( + monkeypatch: pytest.MonkeyPatch, tools: bool +) -> None: + async with ( + synthetic_server(monkeypatch, tools=tools) as state, + client(config(tools=tools, approved_resource_ids=(IDENTITY,))) as remote, + ): + state["return_uri"], state["return_id"] = OTHER, OTHER + with pytest.raises(source.MCPSourceError): + await remote.read(IDENTITY) + + +@pytest.mark.asyncio +async def test_content_limit_is_enforced_without_truncating_evidence( + monkeypatch: pytest.MonkeyPatch, +) -> None: + limits = source.MCPLimits(max_content_bytes=4) + async with ( + synthetic_server(monkeypatch), + client(config(limits=limits, approved_resource_ids=(IDENTITY,))) as remote, + ): + with pytest.raises(source.MCPSourceError, match="limit"): + await remote.read(IDENTITY) + + +@pytest.mark.asyncio +async def test_revocation_prevents_the_next_read(monkeypatch: pytest.MonkeyPatch) -> None: + allowed = True + + async def recheck() -> None: + if not allowed: + raise source.MCPSourceError("denied") + + async with synthetic_server(monkeypatch) as state: + async with source.MCPSourceClient( + config(), source.MCPBearer(SECRET, ENDPOINT), validate_access=recheck + ) as remote: + await remote.list_resources() + allowed = False + before = len(state["requests"]) + with pytest.raises(source.MCPSourceError, match="denied"): + await remote.read(IDENTITY) + assert len(state["requests"]) == before + + +@pytest.mark.asyncio +async def test_cancellation_closes_the_sdk_request(monkeypatch: pytest.MonkeyPatch) -> None: + async with synthetic_server(monkeypatch) as state: + state["hang"] = True + + async def read() -> None: + async with client(config(approved_resource_ids=(IDENTITY,))) as remote: + await remote.read(IDENTITY) + + task = asyncio.create_task(read()) + await asyncio.wait_for(state["read_entered"].wait(), timeout=2) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + await asyncio.wait_for(state["read_cancelled"].wait(), timeout=2) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("status", [301, 302, 307, 308, 401, 403]) +async def test_transport_refuses_redirects_and_auth_challenges( + monkeypatch: pytest.MonkeyPatch, status: int +) -> None: + calls = [] + + async def reply(request: httpx.Request) -> httpx.Response: + calls.append(str(request.url)) + return httpx.Response(status, headers={"location": "https://source.example/other"}) + + monkeypatch.setattr(source.httpx, "AsyncHTTPTransport", lambda **kw: httpx.MockTransport(reply)) + + async def pinned(*args: Any, **kw: Any) -> tuple[str, str, str, str]: + return "", "https://93.184.216.34/mcp", "source.example", "source.example" + + monkeypatch.setattr(source, "pinned_target", pinned) + transport = source._PinnedTransport( + config(), source.MCPBearer(SECRET, ENDPOINT), asyncio.get_running_loop().time() + 2, access + ) + async with httpx.AsyncClient(transport=transport) as http: + with pytest.raises(source.MCPSourceError, match="denied"): + await http.post(ENDPOINT) + assert calls == ["https://93.184.216.34/mcp"] + + +@pytest.mark.asyncio +async def test_private_dns_refusal_sends_nothing(monkeypatch: pytest.MonkeyPatch) -> None: + calls = [] + + async def reply(request: httpx.Request) -> httpx.Response: + calls.append(request) + return httpx.Response(200) + + async def refused(*args: Any, **kw: Any) -> tuple[str, str, str, str]: + return "private host", "", "", "" + + monkeypatch.setattr(source.httpx, "AsyncHTTPTransport", lambda **kw: httpx.MockTransport(reply)) + monkeypatch.setattr(source, "pinned_target", refused) + transport = source._PinnedTransport( + config(), source.MCPBearer(SECRET, ENDPOINT), asyncio.get_running_loop().time() + 2, access + ) + async with httpx.AsyncClient(transport=transport) as http: + with pytest.raises(source.MCPSourceError, match="denied"): + await http.get(ENDPOINT) + assert calls == [] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("tools", [False, True]) +async def test_list_and_search_cannot_grant_read_authority( + monkeypatch: pytest.MonkeyPatch, tools: bool +) -> None: + async with ( + synthetic_server(monkeypatch, tools=tools) as state, + client(config(tools=tools)) as remote, + ): + await remote.search("One") if tools else await remote.list_resources() + before = len(state["calls"]) + with pytest.raises(source.MCPSourceError, match="denied"): + await remote.read(IDENTITY) + assert len(state["calls"]) == before + + +@pytest.mark.asyncio +async def test_configuration_and_schema_snapshots_cannot_be_mutated_by_the_caller( + monkeypatch: pytest.MonkeyPatch, +) -> None: + conf = config(tools=True, approved_resource_ids=(IDENTITY,)) + remote = client(conf) + fingerprint = remote.config_sha256 + assert conf.read is not None + conf.read.input_schema["properties"]["extra"] = dict(STRING) + snapshot = remote.config + assert snapshot.read is not None + snapshot.read.fixed_arguments["workspace"] = "changed" + async with synthetic_server(monkeypatch, tools=True) as state, remote: + assert remote.config_sha256 == fingerprint + document = await remote.read(IDENTITY) + assert document.receipt is not None + assert document.receipt.config_sha256 == fingerprint + assert state["calls"][-1][1]["workspace"] == "fixed" + + +@pytest.mark.asyncio +async def test_text_resource_media_type_is_preserved(monkeypatch: pytest.MonkeyPatch) -> None: + async with ( + synthetic_server(monkeypatch) as state, + client(config(approved_resource_ids=(IDENTITY,))) as remote, + ): + state["mime_type"] = "text/markdown" + document = await remote.read(IDENTITY) + assert document.mime_type == "text/markdown" + + +@pytest.mark.asyncio +async def test_deadline_preserves_timeout_category_and_cancels( + monkeypatch: pytest.MonkeyPatch, +) -> None: + conf = config(approved_resource_ids=(IDENTITY,), limits=source.MCPLimits(timeout_seconds=2)) + async with synthetic_server(monkeypatch) as state, client(conf) as remote: + state["hang"] = True + with pytest.raises(source.MCPSourceError) as error: + await remote.read(IDENTITY) + assert error.value.code == "timeout" + + +@pytest.mark.asyncio +async def test_wire_budget_preserves_limit_category(monkeypatch: pytest.MonkeyPatch) -> None: + conf = config(limits=source.MCPLimits(max_wire_bytes=32)) + async with synthetic_server(monkeypatch): + with pytest.raises(source.MCPSourceError) as error: + async with client(conf): + pass + assert error.value.code == "limit" + + +@pytest.mark.asyncio +async def test_upstream_metadata_and_content_never_reach_diagnostics( + monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + import logging + + from opentelemetry import context + from opentelemetry.context import _SUPPRESS_INSTRUMENTATION_KEY + + from server.core.diagnostics import codes_only + + caplog.set_level(logging.DEBUG) + async with ( + synthetic_server(monkeypatch), + client(config(approved_resource_ids=(IDENTITY,))) as remote, + ): + assert codes_only() + assert context.get_value(_SUPPRESS_INSTRUMENTATION_KEY) + await remote.list_resources() + await remote.read(IDENTITY) + logging.getLogger("mcp.client.streamable_http").error("%s %s %s", SECRET, TEXT, ENDPOINT) + assert SECRET not in caplog.text + assert TEXT not in caplog.text + assert ENDPOINT not in caplog.text + + +def test_nested_sdk_error_groups_keep_only_fixed_categories() -> None: + error = ExceptionGroup( + "private error", + [ValueError(SECRET), ExceptionGroup(TEXT, [source.MCPSourceError("denied")])], + ) + assert source._error_code(error) == "denied" + + +@pytest.mark.asyncio +@pytest.mark.parametrize("status", [401, 403]) +async def test_sdk_initial_auth_refusal_preserves_denied_and_closes( + monkeypatch: pytest.MonkeyPatch, status: int +) -> None: + async with synthetic_server(monkeypatch) as state: + state["unauthorized"] = status + with pytest.raises(source.MCPSourceError, match="denied"): + async with client(): + pytest.fail("a refused credential opened a session") + assert state["calls"] == [] + + +@pytest.mark.asyncio +async def test_sdk_upstream_revocation_leaves_no_extra_cleanup_failure( + monkeypatch: pytest.MonkeyPatch, +) -> None: + async with ( + synthetic_server(monkeypatch) as state, + client(config(approved_resource_ids=(IDENTITY,))) as remote, + ): + await remote.read(IDENTITY) + state["unauthorized"] = 403 + before = len(state["calls"]) + with pytest.raises(source.MCPSourceError, match="denied"): + await remote.read(IDENTITY) + assert len(state["calls"]) == before + + +@pytest.mark.asyncio +async def test_mapped_citation_can_differ_from_identity_without_becoming_an_endpoint( + monkeypatch: pytest.MonkeyPatch, +) -> None: + async with ( + synthetic_server(monkeypatch, tools=True) as state, + client(config(tools=True, approved_resource_ids=(IDENTITY,))) as remote, + ): + state["citation"] = "https://citation.example/document/one" + document = await remote.read(IDENTITY) + assert document.resource_id == IDENTITY + assert document.uri == state["citation"] + assert document.receipt is not None + assert document.receipt.requested_id == IDENTITY + assert all(request["url"] == "https://93.184.216.34/mcp" for request in state["requests"]) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("binary", [False, True]) +async def test_binary_or_mixed_media_resources_cannot_masquerade_as_text( + monkeypatch: pytest.MonkeyPatch, binary: bool +) -> None: + async with ( + synthetic_server(monkeypatch) as state, + client(config(approved_resource_ids=(IDENTITY,))) as remote, + ): + state["contents"] = ( + [types.BlobResourceContents(uri=IDENTITY, blob="YmluYXJ5")] + if binary + else [ + types.TextResourceContents(uri=IDENTITY, text="one", mimeType="text/plain"), + types.TextResourceContents(uri=IDENTITY, text="two", mimeType="text/markdown"), + ] + ) + with pytest.raises(source.MCPSourceError, match="unsupported"): + await remote.read(IDENTITY) + + +@pytest.mark.asyncio +async def test_resource_joining_separator_counts_towards_content_budget( + monkeypatch: pytest.MonkeyPatch, +) -> None: + conf = config(approved_resource_ids=(IDENTITY,), limits=source.MCPLimits(max_content_bytes=4)) + async with synthetic_server(monkeypatch) as state, client(conf) as remote: + state["contents"] = [ + types.TextResourceContents(uri=IDENTITY, text="aa"), + types.TextResourceContents(uri=IDENTITY, text="bb"), + ] + with pytest.raises(source.MCPSourceError, match="limit"): + await remote.read(IDENTITY) + + +@pytest.mark.asyncio +async def test_existing_pin_helper_is_used_once_and_transport_strips_foreign_headers( + monkeypatch: pytest.MonkeyPatch, +) -> None: + from server.core import webhooks + + resolutions = [] + requests = [] + + async def resolve(host: str, **kw: Any) -> tuple[str, str]: + resolutions.append((host, kw)) + return "", "93.184.216.34" + + async def reply(request: httpx.Request) -> httpx.Response: + requests.append(request) + return httpx.Response(200, text="synthetic") + + monkeypatch.setattr(webhooks, "vet_host", resolve) + transport = source._PinnedTransport( + config(), + source.MCPBearer(SECRET, ENDPOINT), + asyncio.get_running_loop().time() + 5, + access, + transport=httpx.MockTransport(reply), + ) + async with httpx.AsyncClient(transport=transport) as http: + for _ in range(2): + await http.get( + ENDPOINT, + headers={ + "authorization": "Bearer inbound-loom-token", + "cookie": "foreign", + "x-loom-org": "foreign", + "traceparent": "foreign", + }, + ) + assert resolutions == [("source.example", {"allow_private": False, "name_address": False})] + assert len(requests) == 2 + for request in requests: + assert str(request.url) == "https://93.184.216.34/mcp" + assert request.extensions["sni_hostname"] == "source.example" + assert request.headers["host"] == "source.example" + assert request.headers["authorization"] == "Bearer " + SECRET + assert all(name not in request.headers for name in ("cookie", "x-loom-org", "traceparent")) diff --git a/tests/unit/test_mcp_source_network.py b/tests/unit/test_mcp_source_network.py new file mode 100644 index 0000000000..951113d36a --- /dev/null +++ b/tests/unit/test_mcp_source_network.py @@ -0,0 +1,174 @@ +"""An owned TLS server checks the protocol client's actual HTTPS and SSE boundary.""" + +from __future__ import annotations + +import asyncio +import hashlib +import socket +import ssl +from collections.abc import AsyncIterator, Iterator +from contextlib import asynccontextmanager, contextmanager +from datetime import UTC, datetime, timedelta +from pathlib import Path +from typing import Any + +import httpx +import pytest +import uvicorn +from cryptography import x509 +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric import ec +from cryptography.x509.oid import NameOID +from mcp.server.fastmcp import FastMCP +from mcp.server.transport_security import TransportSecuritySettings + +from server.clients import mcp_source as source + +RESOURCE = "document://selected/one" +BODY = "Selected synthetic text delivered over TLS and SSE." +TOKEN = "synthetic-source-token" + + +def _certificate(directory: Path) -> tuple[Path, Path]: + key = ec.generate_private_key(ec.SECP256R1()) + name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "source.example")]) + now = datetime.now(UTC) + cert = ( + x509.CertificateBuilder() + .subject_name(name) + .issuer_name(name) + .public_key(key.public_key()) + .serial_number(x509.random_serial_number()) + .not_valid_before(now - timedelta(minutes=5)) + .not_valid_after(now + timedelta(days=1)) + .add_extension(x509.SubjectAlternativeName([x509.DNSName("source.example")]), False) + .sign(key, hashes.SHA256()) + ) + certificate, private_key = directory / "certificate.pem", directory / "key.pem" + certificate.write_bytes(cert.public_bytes(serialization.Encoding.PEM)) + private_key.write_bytes( + key.private_bytes( + serialization.Encoding.PEM, + serialization.PrivateFormat.PKCS8, + serialization.NoEncryption(), + ) + ) + return certificate, private_key + + +class _OwnedServer(uvicorn.Server): + @contextmanager + def capture_signals(self) -> Iterator[None]: + # The test supervisor owns signals; this temporary listener owns only its task. + yield + + +@asynccontextmanager +async def _serve(app: Any, certificate: Path, key: Path) -> AsyncIterator[int]: + listener = socket.socket() + listener.bind(("127.0.0.1", 0)) + server = _OwnedServer( + uvicorn.Config( + app, + log_config=None, + log_level="critical", + access_log=False, + ssl_certfile=str(certificate), + ssl_keyfile=str(key), + lifespan="on", + timeout_graceful_shutdown=1, + ) + ) + task = asyncio.create_task(server.serve(sockets=[listener])) + try: + async with asyncio.timeout(5): + while not server.started: + if task.done(): + await task + raise AssertionError("owned server stopped before startup") + await asyncio.sleep(0) + yield listener.getsockname()[1] + finally: + server.should_exit = True + try: + async with asyncio.timeout(5): + await task + finally: + if not task.done(): + task.cancel() + await asyncio.gather(task, return_exceptions=True) + listener.close() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("oversized", [False, True]) +async def test_official_sdk_reads_over_verified_tls_and_sse( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path, oversized: bool +) -> None: + certificate, key = _certificate(tmp_path) + sdk = FastMCP( + "Synthetic TLS source", + stateless_http=True, + json_response=False, + transport_security=TransportSecuritySettings(allowed_hosts=["source.example:*"]), + ) + + @sdk.resource(RESOURCE, name="Selected document", mime_type="text/plain") + async def resource() -> str: + return "x" * 32_768 if oversized else BODY + + app = sdk.streamable_http_app() + requests: list[dict[bytes, bytes]] = [] + content_types: list[bytes] = [] + + async def observed(scope: Any, receive: Any, send: Any) -> None: + if scope["type"] == "http": + requests.append(dict(scope["headers"])) + + async def response(message: Any) -> None: + if message["type"] == "http.response.start": + content_types.append(dict(message["headers"]).get(b"content-type", b"")) + await send(message) + + await app(scope, receive, response) + + async with _serve(observed, certificate, key) as port: + endpoint = f"https://source.example:{port}/mcp" + + async def pin(url: str, *, schemes: Any) -> tuple[str, str, str, str]: + assert url == endpoint + assert schemes == ("https",) + return "", f"https://127.0.0.1:{port}/mcp", f"source.example:{port}", "source.example" + + async def authority() -> None: + return None + + monkeypatch.setattr(source, "pinned_target", pin) + context = ssl.create_default_context(cafile=str(certificate)) + config = source.MCPSourceConfig( + endpoint, + bearer_audience=endpoint, + approved_resource_ids=(RESOURCE,), + limits=source.MCPLimits(timeout_seconds=5, request_seconds=2, max_wire_bytes=4096), + ) + async with source.MCPSourceClient( + config, + source.MCPBearer(TOKEN, endpoint), + validate_access=authority, + _transport=httpx.AsyncHTTPTransport(verify=context), + ) as client: + page = await client.list_resources() + assert page.items[0].receipt is None + if oversized: + with pytest.raises(source.MCPSourceError) as refusal: + await client.read(RESOURCE) + assert refusal.value.code == "limit" + else: + evidence = await client.read(RESOURCE) + assert evidence.text == BODY + assert evidence.receipt is not None + assert evidence.receipt.content_sha256 == hashlib.sha256(BODY.encode()).hexdigest() + assert requests + assert all(row[b"host"] == f"source.example:{port}".encode() for row in requests) + assert all(row[b"authorization"] == f"Bearer {TOKEN}".encode() for row in requests) + assert any(value.startswith(b"text/event-stream") for value in content_types) diff --git a/tests/unit/test_mcp_source_protocol.py b/tests/unit/test_mcp_source_protocol.py new file mode 100644 index 0000000000..ec1c949264 --- /dev/null +++ b/tests/unit/test_mcp_source_protocol.py @@ -0,0 +1,637 @@ +"""Exercise the outbound reader against official SDK servers over ASGI HTTP.""" + +from __future__ import annotations + +import asyncio +import copy +import hashlib +import json +from collections.abc import AsyncIterator, Callable +from contextlib import asynccontextmanager +from dataclasses import dataclass, field, replace +from typing import Any + +import httpx +import pytest +from mcp import types +from mcp.server.fastmcp import FastMCP +from mcp.server.fastmcp.tools.base import Tool +from mcp.server.fastmcp.utilities.func_metadata import ArgModelBase, FuncMetadata +from mcp.server.transport_security import TransportSecuritySettings +from pydantic import BaseModel, ConfigDict +from starlette.responses import JSONResponse +from starlette.types import Message, Receive, Scope, Send + +from server.clients import mcp_source as mcp + +ENDPOINT = "https://mcp.example/mcp" +APPROVED = "fixture://documents/approved" +EXTRA = "fixture://documents/extra" +BEARER = "synthetic-upstream-token" + + +def _object(properties: dict[str, Any], *required: str) -> dict[str, Any]: + return { + "type": "object", + "properties": properties, + "required": list(required), + "additionalProperties": False, + } + + +def _string() -> dict[str, Any]: + return {"type": "string", "maxLength": 4096} + + +DOCUMENT_SCHEMA = _object( + {key: _string() for key in ("id", "title", "text", "uri")}, "id", "title", "text", "uri" +) +SEARCH_INPUT = _object({"query": _string(), "tenant": _string()}, "query", "tenant") +READ_INPUT = _object({"id": _string(), "tenant": _string()}, "id", "tenant") +SEARCH_OUTPUT = _object( + {"items": {"type": "array", "items": DOCUMENT_SCHEMA, "maxItems": 4}}, "items" +) +PARTIAL_SEARCH_INPUT = _object( + {"query": _string(), "tenant": _string(), "cursor": _string()}, "query", "tenant" +) +PARTIAL_SEARCH_OUTPUT = _object( + {**SEARCH_OUTPUT["properties"], "next_cursor": _string()}, "items", "next_cursor" +) + + +class _Document(BaseModel): + model_config = ConfigDict(extra="forbid") + id: str + title: str + text: str + uri: str + + +class _SearchOutput(BaseModel): + model_config = ConfigDict(extra="forbid") + items: list[_Document] + + +class _PartialSearchOutput(_SearchOutput): + next_cursor: str + + +class _SearchArgs(ArgModelBase): + model_config = ConfigDict(extra="forbid") + query: str + tenant: str + cursor: str = "" + + +class _ReadArgs(ArgModelBase): + model_config = ConfigDict(extra="forbid") + id: str + tenant: str + + +def _document( + identity: str = APPROVED, *, text: str = "Complete selected document." +) -> dict[str, str]: + return { + "id": identity, + "title": "Selected document", + "text": text, + "uri": identity, + } + + +@dataclass +class _Fixture: + kind: str + authorized: bool = True + refusal_status: int = 403 + mismatch: bool = False + alternate_citation: bool = False + invalid_output: bool = False + drift: bool = False + partial: bool = False + json_response: bool = True + block_read: bool = False + calls: list[tuple[str, dict[str, Any]]] = field(default_factory=list) + requests: list[dict[str, Any]] = field(default_factory=list) + started: asyncio.Event = field(default_factory=asyncio.Event) + release: asyncio.Event = field(default_factory=asyncio.Event) + server: FastMCP = field(init=False) + + def __post_init__(self) -> None: + async def search(query: str, tenant: str, cursor: str = "") -> dict[str, Any]: + self.calls.append(("search_documents", {"query": query, "tenant": tenant})) + items = [ + _document(text="Search snippet."), + _document(EXTRA, text="Unselected snippet."), + ] + if self.partial: + return {"items": items[:1], "next_cursor": "incomplete-page"} + return {"items": items} + + async def read(id: str, tenant: str) -> dict[str, str]: + self.calls.append(("read_document", {"id": id, "tenant": tenant})) + await self._wait_for_read() + return _document(id) + + async def erase(id: str, tenant: str) -> str: + self.calls.append(("erase_document", {"id": id, "tenant": tenant})) + raise AssertionError("An unapproved action tool was executed") + + tools = [] + if self.kind == "tools": + for name, fn, args, input_schema, output_schema, output_model in ( + ( + "search_documents", + search, + _SearchArgs, + PARTIAL_SEARCH_INPUT if self.partial else SEARCH_INPUT, + PARTIAL_SEARCH_OUTPUT if self.partial else SEARCH_OUTPUT, + _PartialSearchOutput if self.partial else _SearchOutput, + ), + ("read_document", read, _ReadArgs, READ_INPUT, DOCUMENT_SCHEMA, _Document), + ): + tools.append( + Tool( + name=name, + description="Synthetic document operation", + fn=fn, + parameters=copy.deepcopy(input_schema), + fn_metadata=FuncMetadata( + arg_model=args, + output_schema=copy.deepcopy(output_schema), + output_model=output_model, + ), + is_async=True, + ) + ) + tools.append( + Tool.from_function( + erase, + name="erase_document", + annotations=types.ToolAnnotations(readOnlyHint=True), + description="Untrusted server claims this action is a safe read", + ) + ) + self.server = FastMCP( + "Synthetic document source", + tools=tools, + stateless_http=True, + json_response=self.json_response, + transport_security=TransportSecuritySettings(allowed_hosts=["mcp.example"]), + ) + if self.kind == "resources": + + @self.server.resource(APPROVED, name="Selected document", title="Selected document") + async def selected() -> str: + self.calls.append(("resource_read", {"uri": APPROVED})) + await self._wait_for_read() + return "Complete selected document." + + @self.server.resource(EXTRA, name="Unselected document") + async def extra() -> str: + self.calls.append(("resource_read", {"uri": EXTRA})) + return "Unselected content." + + async def _wait_for_read(self) -> None: + self.started.set() + if self.block_read: + await self.release.wait() + + def config(self) -> mcp.MCPSourceConfig: + kwargs: dict[str, Any] = {} + if self.kind == "tools": + kwargs = { + "approved_tools": ("search_documents", "read_document"), + "search": mcp.MCPToolMapping( + name="search_documents", + input_schema=copy.deepcopy( + PARTIAL_SEARCH_INPUT if self.partial else SEARCH_INPUT + ), + output_schema=copy.deepcopy( + PARTIAL_SEARCH_OUTPUT if self.partial else SEARCH_OUTPUT + ), + argument_name="query", + fixed_arguments={"tenant": "selected-tenant"}, + items_path=("items",), + cursor_argument="cursor" if self.partial else None, + next_cursor_path=("next_cursor",) if self.partial else None, + ), + "read": mcp.MCPToolMapping( + name="read_document", + input_schema=copy.deepcopy(READ_INPUT), + output_schema=copy.deepcopy(DOCUMENT_SCHEMA), + argument_name="id", + fixed_arguments={"tenant": "selected-tenant"}, + ), + } + return mcp.MCPSourceConfig( + endpoint=ENDPOINT, + bearer_audience=ENDPOINT, + approved_resource_ids=(APPROVED,), + limits=mcp.MCPLimits(timeout_seconds=5, request_seconds=1), + **kwargs, + ) + + def _change_response(self, request: dict[str, Any], response: dict[str, Any]) -> None: + result = response.get("result") + if not isinstance(result, dict): + return + method = request.get("method") + if method == "tools/list" and self.drift: + for tool in result["tools"]: + if tool["name"] == "read_document": + tool["inputSchema"]["properties"]["tenant"]["maxLength"] = 64 + if method == "resources/list" and self.partial: + result["resources"] = result["resources"][:1] + result["nextCursor"] = "incomplete-page" + if method == "resources/read" and self.mismatch: + result["contents"][0]["uri"] = EXTRA + if method == "tools/call" and request.get("params", {}).get("name") == "read_document": + if self.mismatch: + result["structuredContent"]["id"] = EXTRA + if self.alternate_citation: + result["structuredContent"]["uri"] = "https://citation.example/selected" + if self.invalid_output: + result["structuredContent"]["text"] = {"unexpected": "object"} + + @asynccontextmanager + async def application(self) -> AsyncIterator[Callable[..., Any]]: + app = self.server.streamable_http_app() + + async def wrapped(scope: Scope, receive: Receive, send: Send) -> None: + assert scope["server"] == ("203.0.113.8", None) + assert scope["path"] == "/mcp" + headers = dict(scope.get("headers", [])) + assert headers[b"host"] == b"mcp.example" + if ( + not self.authorized + or headers.get(b"authorization") != ("Bearer " + BEARER).encode() + ): + await JSONResponse( + {"error": "Synthetic credential refusal"}, status_code=self.refusal_status + )(scope, receive, send) + return + chunks = [] + while True: + message = await receive() + chunks.append(message.get("body", b"")) + if not message.get("more_body", False): + break + body = b"".join(chunks) + request = json.loads(body) if body else {} + self.requests.append(request) + response_messages: list[Message] = [] + consumed = False + + async def replay() -> Message: + nonlocal consumed + if not consumed: + consumed = True + return {"type": "http.request", "body": body, "more_body": False} + return await receive() + + async def capture(message: Message) -> None: + response_messages.append(message) + + await app(scope, replay, capture) + payload = b"".join(message.get("body", b"") for message in response_messages) + if ( + payload + and self.json_response + and any( + message["type"] == "http.response.start" and message["status"] == 200 + for message in response_messages + ) + ): + response = json.loads(payload) + self._change_response(request, response) + payload = json.dumps(response).encode() + start = next( + message + for message in response_messages + if message["type"] == "http.response.start" + ) + start["headers"] = [ + (key, value) for key, value in start["headers"] if key != b"content-length" + ] + start["headers"].append((b"content-length", str(len(payload)).encode())) + await send(start) + await send({"type": "http.response.body", "body": payload, "more_body": False}) + else: + for message in response_messages: + await send(message) + + async with app.router.lifespan_context(app): + yield wrapped + + +@asynccontextmanager +async def _source( + fixture: _Fixture, + monkeypatch: pytest.MonkeyPatch, + *, + config: mcp.MCPSourceConfig | None = None, + validate_access: Callable[..., Any] | None = None, + token: str = BEARER, +) -> AsyncIterator[mcp.MCPSourceClient]: + async def allowed() -> None: + return None + + async def pin(url: str, **kwargs: Any) -> tuple[str, str, str, str]: + assert url == ENDPOINT + assert kwargs == {"schemes": ("https",)} + return "", "https://203.0.113.8/mcp", "mcp.example", "mcp.example" + + lifecycle = fixture.application() + app = await lifecycle.__aenter__() + try: + monkeypatch.setattr(mcp, "pinned_target", pin) + async with mcp.MCPSourceClient( + config or fixture.config(), + mcp.MCPBearer(token, ENDPOINT), + validate_access=validate_access or allowed, + _transport=httpx.ASGITransport(app=app), + ) as source: + try: + yield source + finally: + fixture.release.set() + finally: + # The server task group must not wrap the client exception under test. + await lifecycle.__aexit__(None, None, None) + + +@pytest.mark.parametrize("kind", ["resources", "tools"]) +async def test_official_sdk_sources_read_selected_content( + kind: str, monkeypatch: pytest.MonkeyPatch +) -> None: + fixture = _Fixture(kind) + async with _source(fixture, monkeypatch) as source: + discovery = await source.discover() + page = await (source.list_resources() if kind == "resources" else source.search("selected")) + assert {item.resource_id for item in page.items} == {APPROVED, EXTRA} + assert page.complete is True + assert all(item.receipt is None for item in page.items) + if kind == "tools": + assert discovery.tools == ("read_document", "search_documents") + evidence = await source.read(APPROVED) + assert evidence.resource_id == APPROVED + assert evidence.text == "Complete selected document." + assert evidence.receipt is not None + assert evidence.receipt.requested_id == APPROVED + assert evidence.receipt.operation == ( + "resources/read" if kind == "resources" else "tools/call" + ) + assert evidence.receipt.content_sha256 == hashlib.sha256(evidence.text.encode()).hexdigest() + assert evidence.receipt.config_sha256 == source.config_sha256 + assert any(request.get("method") == "initialize" for request in fixture.requests) + assert not any(name == "erase_document" for name, _ in fixture.calls) + + +@pytest.mark.parametrize("kind", ["resources", "tools"]) +async def test_enumerated_extra_ids_cannot_expand_selected_reads( + kind: str, monkeypatch: pytest.MonkeyPatch +) -> None: + fixture = _Fixture(kind) + async with _source(fixture, monkeypatch) as source: + await (source.list_resources() if kind == "resources" else source.search("selected")) + assert (await source.read(APPROVED)).resource_id == APPROVED + before = list(fixture.calls) + with pytest.raises(mcp.MCPSourceError, match="denied"): + await source.read(EXTRA) + assert fixture.calls == before + + +@pytest.mark.parametrize("kind", ["resources", "tools"]) +async def test_empty_approved_selection_does_not_admit_listed_ids( + kind: str, monkeypatch: pytest.MonkeyPatch +) -> None: + fixture = _Fixture(kind) + config = replace(fixture.config(), approved_resource_ids=()) + async with _source(fixture, monkeypatch, config=config) as source: + await (source.list_resources() if kind == "resources" else source.search("selected")) + before = list(fixture.calls) + with pytest.raises(mcp.MCPSourceError, match="denied"): + await source.read(APPROVED) + assert fixture.calls == before + + +@pytest.mark.parametrize("kind", ["resources", "tools"]) +async def test_read_identity_mismatch_has_no_successful_result( + kind: str, monkeypatch: pytest.MonkeyPatch +) -> None: + fixture = _Fixture(kind, mismatch=True) + async with _source(fixture, monkeypatch) as source: + with pytest.raises(mcp.MCPSourceError): + await source.read(APPROVED) + assert len(fixture.calls) == 1 + + +async def test_changed_discovery_schema_stops_mapped_read(monkeypatch: pytest.MonkeyPatch) -> None: + fixture = _Fixture("tools") + async with _source(fixture, monkeypatch) as source: + await source.discover() + fixture.drift = True + with pytest.raises(mcp.MCPSourceError, match="schema"): + await source.read(APPROVED) + assert fixture.calls == [] + + +async def test_invalid_mapped_result_is_not_read_evidence(monkeypatch: pytest.MonkeyPatch) -> None: + fixture = _Fixture("tools", invalid_output=True) + async with _source(fixture, monkeypatch) as source: + with pytest.raises(mcp.MCPSourceError): + await source.read(APPROVED) + assert [name for name, _ in fixture.calls] == ["read_document"] + + +@pytest.mark.parametrize("kind", ["resources", "tools"]) +@pytest.mark.parametrize("status", [401, 403]) +async def test_upstream_credential_refusal_prevents_initialization( + kind: str, status: int, monkeypatch: pytest.MonkeyPatch +) -> None: + fixture = _Fixture(kind, refusal_status=status) + with pytest.raises(mcp.MCPSourceError) as caught: + async with _source(fixture, monkeypatch, token="synthetic-wrong-token"): + pytest.fail("An upstream credential refusal opened a source") + assert fixture.calls == [] + assert BEARER not in str(caught.value) + assert "synthetic-wrong-token" not in str(caught.value) + + +@pytest.mark.parametrize("kind", ["resources", "tools"]) +async def test_upstream_revocation_prevents_subsequent_read( + kind: str, monkeypatch: pytest.MonkeyPatch +) -> None: + fixture = _Fixture(kind) + async with _source(fixture, monkeypatch) as source: + assert (await source.read(APPROVED)).resource_id == APPROVED + before = list(fixture.calls) + fixture.authorized = False + with pytest.raises(mcp.MCPSourceError): + await source.read(APPROVED) + assert fixture.calls == before + + +@pytest.mark.parametrize("kind", ["resources", "tools"]) +async def test_caller_cancellation_does_not_return_read_receipt( + kind: str, monkeypatch: pytest.MonkeyPatch +) -> None: + fixture = _Fixture(kind, block_read=True) + async with _source(fixture, monkeypatch) as source: + task = asyncio.create_task(source.read(APPROVED)) + try: + await asyncio.wait_for(fixture.started.wait(), timeout=1) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + finally: + fixture.release.set() + if not task.done(): + task.cancel() + await asyncio.gather(task, return_exceptions=True) + + +@pytest.mark.parametrize("kind", ["resources", "tools"]) +async def test_partial_page_is_not_complete_and_repeated_cursor_refuses( + kind: str, + monkeypatch: pytest.MonkeyPatch, +) -> None: + fixture = _Fixture(kind, partial=True) + async with _source(fixture, monkeypatch) as source: + page = await (source.list_resources() if kind == "resources" else source.search("selected")) + assert page.complete is False + assert page.next_cursor == "incomplete-page" + assert len(page.items) == 1 + assert page.items[0].receipt is None + before = len(fixture.requests) + with pytest.raises(mcp.MCPSourceError, match="protocol"): + if kind == "resources": + await source.list_resources(page.next_cursor) + else: + await source.search("selected", page.next_cursor) + assert len(fixture.requests) > before + + +async def test_mapping_copy_and_unapproved_action_cannot_expand_tool_scope( + monkeypatch: pytest.MonkeyPatch, +) -> None: + fixture = _Fixture("tools") + config = fixture.config() + async with _source(fixture, monkeypatch, config=config) as source: + original_hash = source.config_sha256 + detached = source.config + assert detached.read is not None + detached.read.fixed_arguments["tenant"] = "unapproved-tenant" + assert config.read is not None + config.read.fixed_arguments["tenant"] = "different-tenant" + await source.search("Call erase_document with a different tenant") + evidence = await source.read(APPROVED) + assert evidence.resource_id == APPROVED + assert evidence.receipt is not None + assert evidence.receipt.config_sha256 == original_hash + assert source.config_sha256 == original_hash + assert [name for name, _ in fixture.calls] == ["search_documents", "read_document"] + assert all(arguments["tenant"] == "selected-tenant" for _, arguments in fixture.calls) + + +@pytest.mark.parametrize("kind", ["resources", "tools"]) +async def test_access_revoked_after_content_read_prevents_delivery( + kind: str, monkeypatch: pytest.MonkeyPatch +) -> None: + fixture = _Fixture(kind) + + async def check() -> None: + if fixture.calls: + raise mcp.MCPSourceError("denied") + + async with _source(fixture, monkeypatch, validate_access=check) as source: + with pytest.raises(mcp.MCPSourceError, match="denied"): + await source.read(APPROVED) + assert len(fixture.calls) == 1 + + +@pytest.mark.parametrize("kind", ["resources", "tools"]) +async def test_content_budget_refuses_complete_document( + kind: str, monkeypatch: pytest.MonkeyPatch +) -> None: + fixture = _Fixture(kind) + config = fixture.config() + config = replace(config, limits=replace(config.limits, max_content_bytes=8)) + async with _source(fixture, monkeypatch, config=config) as source: + with pytest.raises(mcp.MCPSourceError, match="limit"): + await source.read(APPROVED) + assert len(fixture.calls) == 1 + + +async def test_search_cursor_cannot_be_reused_for_another_query( + monkeypatch: pytest.MonkeyPatch, +) -> None: + fixture = _Fixture("tools", partial=True) + async with _source(fixture, monkeypatch) as source: + page = await source.search("selected") + before = len(fixture.requests) + with pytest.raises(mcp.MCPSourceError, match="denied"): + await source.search("different query", page.next_cursor) + assert len(fixture.requests) == before + + +async def test_mapped_citation_does_not_change_requested_identity_or_endpoint( + monkeypatch: pytest.MonkeyPatch, +) -> None: + fixture = _Fixture("tools", alternate_citation=True) + async with _source(fixture, monkeypatch) as source: + evidence = await source.read(APPROVED) + assert evidence.resource_id == APPROVED + assert evidence.uri == "https://citation.example/selected" + assert evidence.receipt is not None + assert evidence.receipt.requested_id == APPROVED + assert fixture.calls == [("read_document", {"id": APPROVED, "tenant": "selected-tenant"})] + reads = [request for request in fixture.requests if request.get("method") == "tools/call"] + assert len(reads) == 1 + assert reads[0]["params"]["arguments"]["id"] == APPROVED + + +@pytest.mark.parametrize("kind", ["resources", "tools"]) +async def test_read_receipt_changes_when_approved_scope_changes( + kind: str, monkeypatch: pytest.MonkeyPatch +) -> None: + receipts = [] + for selected_ids in ((APPROVED,), (APPROVED, EXTRA)): + fixture = _Fixture(kind) + config = replace(fixture.config(), approved_resource_ids=selected_ids) + async with _source(fixture, monkeypatch, config=config) as source: + evidence = await source.read(APPROVED) + assert evidence.receipt is not None + receipts.append(evidence.receipt) + assert receipts[0].content_sha256 == receipts[1].content_sha256 + assert receipts[0].config_sha256 != receipts[1].config_sha256 + + +@pytest.mark.parametrize("kind", ["resources", "tools"]) +async def test_invented_cursor_is_refused_before_upstream_request( + kind: str, monkeypatch: pytest.MonkeyPatch +) -> None: + fixture = _Fixture(kind) + async with _source(fixture, monkeypatch) as source: + before = len(fixture.requests) + with pytest.raises(mcp.MCPSourceError, match="denied"): + if kind == "resources": + await source.list_resources("invented-cursor") + else: + await source.search("selected", "invented-cursor") + assert len(fixture.requests) == before + + +@pytest.mark.parametrize("kind", ["resources", "tools"]) +async def test_official_sdk_sse_response_frames_produce_read_receipt( + kind: str, monkeypatch: pytest.MonkeyPatch +) -> None: + fixture = _Fixture(kind, json_response=False) + async with _source(fixture, monkeypatch) as source: + evidence = await source.read(APPROVED) + assert evidence.text == "Complete selected document." + assert evidence.receipt is not None + assert evidence.receipt.requested_id == APPROVED + assert evidence.receipt.content_sha256 == hashlib.sha256(evidence.text.encode()).hexdigest() diff --git a/uv.lock b/uv.lock index 49ba6c530f..6589242134 100644 --- a/uv.lock +++ b/uv.lock @@ -791,6 +791,8 @@ dependencies = [ { name = "google-re2" }, { name = "httpx", extra = ["http2"] }, { name = "idna" }, + { name = "jsonschema" }, + { name = "mcp" }, { name = "opentelemetry-api" }, { name = "opentelemetry-exporter-otlp-proto-http" }, { name = "opentelemetry-instrumentation-fastapi" }, @@ -843,6 +845,7 @@ dev = [ { name = "pytest-xdist" }, { name = "ruff" }, { name = "sqlglot" }, + { name = "types-jsonschema" }, { name = "types-pyyaml" }, ] extractor = [ @@ -883,10 +886,12 @@ requires-dist = [ { name = "google-re2", specifier = ">=1.1" }, { name = "httpx", extras = ["http2"], specifier = ">=0.27" }, { name = "idna", specifier = ">=3.7" }, + { name = "jsonschema", specifier = ">=4.20" }, { name = "lemmagen3", marker = "extra == 'dev'", specifier = ">=3.3" }, { name = "lemmagen3", marker = "extra == 'lemma'", specifier = ">=3.3" }, { name = "markdown", marker = "extra == 'dev'", specifier = "==3.11.2" }, { name = "markdown-it-py", marker = "extra == 'dev'", specifier = "==4.0.0" }, + { name = "mcp", specifier = ">=1.30.0,<2" }, { name = "mdx-truly-sane-lists", marker = "extra == 'dev'", specifier = "==1.3" }, { name = "mypy", marker = "extra == 'dev'", specifier = "==2.3.1" }, { name = "numpy", marker = "extra == 'code'", specifier = ">=1.26" }, @@ -924,6 +929,7 @@ requires-dist = [ { name = "tree-sitter-python", marker = "extra == 'code'", specifier = ">=0.23" }, { name = "tree-sitter-rust", marker = "extra == 'code'", specifier = ">=0.23" }, { name = "tree-sitter-typescript", marker = "extra == 'code'", specifier = ">=0.23" }, + { name = "types-jsonschema", marker = "extra == 'dev'", specifier = ">=4.20" }, { name = "types-pyyaml", marker = "extra == 'dev'", specifier = ">=6.0" }, { name = "uvicorn", extras = ["standard"], specifier = ">=0.50" }, ] @@ -1434,6 +1440,15 @@ http2 = [ { name = "h2" }, ] +[[package]] +name = "httpx-sse" +version = "0.4.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/0f/4c/751061ffa58615a32c31b2d82e8482be8dd4a89154f003147acee90f2be9/httpx_sse-0.4.3.tar.gz", hash = "sha256:9b1ed0127459a66014aec3c56bebd93da3c1bc8bb6618c8082039a44889a755d", size = 15943, upload-time = "2025-10-10T21:48:22.271Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d2/fd/6668e5aec43ab844de6fc74927e155a3b37bf40d7c3790e49fc0406b6578/httpx_sse-0.4.3-py3-none-any.whl", hash = "sha256:0ac1c9fe3c0afad2e0ebb25a934a59f4c7823b60792691f779fad2c5568830fc", size = 8960, upload-time = "2025-10-10T21:48:21.158Z" }, +] + [[package]] name = "huggingface-hub" version = "1.33.0" @@ -1490,6 +1505,33 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/14/2f/967ba146e6d58cf6a652da73885f52fc68001525b4197effc174321d70b4/jmespath-1.1.0-py3-none-any.whl", hash = "sha256:a5663118de4908c91729bea0acadca56526eb2698e83de10cd116ae0f4e97c64", size = 20419, upload-time = "2026-01-22T16:35:24.919Z" }, ] +[[package]] +name = "jsonschema" +version = "4.26.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "attrs" }, + { name = "jsonschema-specifications" }, + { name = "referencing" }, + { name = "rpds-py" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b3/fc/e067678238fa451312d4c62bf6e6cf5ec56375422aee02f9cb5f909b3047/jsonschema-4.26.0.tar.gz", hash = "sha256:0c26707e2efad8aa1bfc5b7ce170f3fccc2e4918ff85989ba9ffa9facb2be326", size = 366583, upload-time = "2026-01-07T13:41:07.246Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/69/90/f63fb5873511e014207a475e2bb4e8b2e570d655b00ac19a9a0ca0a385ee/jsonschema-4.26.0-py3-none-any.whl", hash = "sha256:d489f15263b8d200f8387e64b4c3a75f06629559fb73deb8fdfb525f2dab50ce", size = 90630, upload-time = "2026-01-07T13:41:05.306Z" }, +] + +[[package]] +name = "jsonschema-specifications" +version = "2025.9.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "referencing" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/19/74/a633ee74eb36c44aa6d1095e7cc5569bebf04342ee146178e2d36600708b/jsonschema_specifications-2025.9.1.tar.gz", hash = "sha256:b540987f239e745613c7a9176f3edb72b832a4ac465cf02712288397832b5e8d", size = 32855, upload-time = "2025-09-08T01:34:59.186Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/41/45/1a4ed80516f02155c51f51e8cedb3c1902296743db0bbc66608a0db2814f/jsonschema_specifications-2025.9.1-py3-none-any.whl", hash = "sha256:98802fee3a11ee76ecaca44429fda8a41bff98b00a0f2838151b113f210cc6fe", size = 18437, upload-time = "2025-09-08T01:34:57.871Z" }, +] + [[package]] name = "lemmagen3" version = "3.5.2" @@ -1700,6 +1742,31 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/94/54/e7d793b573f298e1c9013b8c4dade17d481164aa517d1d7148619c2cedbf/markdown_it_py-4.0.0-py3-none-any.whl", hash = "sha256:87327c59b172c5011896038353a81343b6754500a08cd7a4973bb48c6d578147", size = 87321, upload-time = "2025-08-11T12:57:51.923Z" }, ] +[[package]] +name = "mcp" +version = "1.30.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "anyio" }, + { name = "httpx" }, + { name = "httpx-sse" }, + { name = "jsonschema" }, + { name = "pydantic" }, + { name = "pydantic-settings" }, + { name = "pyjwt", extra = ["crypto"] }, + { name = "python-multipart" }, + { name = "pywin32", marker = "sys_platform == 'win32'" }, + { name = "sse-starlette" }, + { name = "starlette" }, + { name = "typing-extensions" }, + { name = "typing-inspection" }, + { name = "uvicorn", marker = "sys_platform != 'emscripten'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ba/93/0142dc84a666daf8ad51a34268f34c12fd6fda4f3810c4be2504eecc8212/mcp-1.30.0.tar.gz", hash = "sha256:445414625fce5c295faa505bb11bacece661ab6f4028d57c935db57820b7a3e4", size = 680511, upload-time = "2026-09-07T14:34:15.845Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f5/f4/e58bc33317c92a0203664daaf00bf6f41166cc0149e5d6870a03f7cd004a/mcp-1.30.0-py3-none-any.whl", hash = "sha256:666edb5009503e1047c9d60346a756f94b261f05cc2625f23d41c728ffc484d0", size = 234581, upload-time = "2026-09-07T14:34:14.266Z" }, +] + [[package]] name = "mdurl" version = "0.1.2" @@ -2952,6 +3019,34 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/0d/17/c5c6b53ddc18f297992099b3d9ec16c855c0ccc83263a21fe4d1c625ec6c/python_dotenv-1.2.3-py3-none-any.whl", hash = "sha256:904552145e8bfed22162c09dab1c2b9b54fefa7b23ba780f4f26ca0316b0f0d9", size = 22780, upload-time = "2026-08-16T16:54:52.473Z" }, ] +[[package]] +name = "python-multipart" +version = "0.0.34" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7e/c0/c753d487a83d873f6946cee6cbc26cea3fe59a476ad0de99a14938a2fbd8/python_multipart-0.0.34.tar.gz", hash = "sha256:b998ae90ca6e1e363261ce2e0e230281b8af53867b757970abd69ee9edcd843a", size = 52456, upload-time = "2026-11-16T10:40:38.261Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f5/0e/090c52b122d8ec5fa37942c1410fea9cf04ce98bca0c84dde7f0aa11594d/python_multipart-0.0.34-py3-none-any.whl", hash = "sha256:ebacd224bd686eee2f9aa1066a657affe07435a185834e05e5235e2e59173e91", size = 32585, upload-time = "2026-11-16T10:40:37.119Z" }, +] + +[[package]] +name = "pywin32" +version = "312" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/83/ff/32aa7d2ed0ab12b323aaa64f9b75e6ad4f8fd09f9ccfc28c79414d46838d/pywin32-312-cp312-cp312-win32.whl", hash = "sha256:dab4f65ac9c4e48400a2a0530c46c3c579cd5905ecd11b80692373915269208b", size = 6371877, upload-time = "2026-06-04T07:49:28.836Z" }, + { url = "https://files.pythonhosted.org/packages/03/d9/77040d3b43df3f3be32ea289433d660d2727f5ba327bc73be835127d9d60/pywin32-312-cp312-cp312-win_amd64.whl", hash = "sha256:b457f6d628a47e8a7346ce22acb7e1a46a4a78b52e1d17e1af56871bd19a93bc", size = 6914841, upload-time = "2026-06-04T07:49:31.85Z" }, + { url = "https://files.pythonhosted.org/packages/e3/cc/7b1ec671775756020a0ee7f4feeaf3c568f0ab86bd3900088cf986937a92/pywin32-312-cp312-cp312-win_arm64.whl", hash = "sha256:6017c58e12f6809fbb0555b75df144c2922a9ffd18e4b9b5afa863b6c1a9d950", size = 6727901, upload-time = "2026-06-04T07:49:34.244Z" }, + { url = "https://files.pythonhosted.org/packages/2d/41/12fbfd7f36ed2146d8bc9de96c2741296bf0d490b98508496cff322e274c/pywin32-312-cp313-cp313-win32.whl", hash = "sha256:7a27df850933d16a8eabfbaeb73d52b273e2da667f80d70b01a89d1f6828d02c", size = 6370184, upload-time = "2026-06-04T07:49:36.253Z" }, + { url = "https://files.pythonhosted.org/packages/ba/db/36a78e3403099d31d9746d13fdcde5accc43c1155f375a34d15983a479a7/pywin32-312-cp313-cp313-win_amd64.whl", hash = "sha256:c53e878d15a1c44788082bfe712a905433473aa38f86375b7cf8b45e3acbaaf9", size = 6914298, upload-time = "2026-06-04T07:49:38.876Z" }, + { url = "https://files.pythonhosted.org/packages/84/37/c1697194092b76de9ed47ca124323f02c57ffc8a45c06f88a3d5acaf01eb/pywin32-312-cp313-cp313-win_arm64.whl", hash = "sha256:59aba5d5940842075343a5ddc6b11f1cdf0d1567fe745290359dfbcc7c2eb831", size = 6727640, upload-time = "2026-06-04T07:49:41.083Z" }, + { url = "https://files.pythonhosted.org/packages/fc/2b/1f3cded5822fd49c02f40544cbb5f58c7cfd6b1694869fd476cb6170ee97/pywin32-312-cp314-cp314-win32.whl", hash = "sha256:a77a90fbb6881238d2ca9c6fd797b25817f3768fe78d214a90137ff055a75f5b", size = 6468928, upload-time = "2026-06-04T07:49:43.188Z" }, + { url = "https://files.pythonhosted.org/packages/21/82/3bf86d2e2808902013132e1ce905a7da0da53790f3836c64bf44d55e24f3/pywin32-312-cp314-cp314-win_amd64.whl", hash = "sha256:a4dd3a848290ef724347b19f301045831d8e802fa4464f491b98b1e0a081432e", size = 7024157, upload-time = "2026-06-04T07:49:45.34Z" }, + { url = "https://files.pythonhosted.org/packages/a4/0e/73f6d6800b4f27655abd9e9f6aaeaefcddb2b946e4674efa2bab184a7f7b/pywin32-312-cp314-cp314-win_arm64.whl", hash = "sha256:9fce94568364e0155e6dfb781ac5d95903be8baf28670632beab1b523f300daa", size = 6839598, upload-time = "2026-06-04T07:49:47.613Z" }, + { url = "https://files.pythonhosted.org/packages/eb/61/caa39686032d2ebdd04ff0ab5cbe163126c0066d98e00c9018646e42393b/pywin32-312-cp315-cp315-win32.whl", hash = "sha256:5c1fbe4a937a73ae9297384a3da38518cbc694c68ad8a809b2e19acd350f03ed", size = 6471159, upload-time = "2026-06-04T07:49:50.035Z" }, + { url = "https://files.pythonhosted.org/packages/0f/cd/7e1de64a4a6f69c04214169657ccab0d93a670ea50e35eb8f489d7378249/pywin32-312-cp315-cp315-win_amd64.whl", hash = "sha256:c2f03a0f73f804a13c2735b99392b0cd426bb4f2c4d0178e5ac966a0f21618d5", size = 7025293, upload-time = "2026-06-04T07:49:54.857Z" }, + { url = "https://files.pythonhosted.org/packages/23/ed/4532e9388e65fa16b46776ef47ad631a64eda1631884488af707666350ed/pywin32-312-cp315-cp315-win_arm64.whl", hash = "sha256:a8597d28f267b39074aef51fa593530082b39cbe5a074226096857b1fed2dfb9", size = 6840337, upload-time = "2026-06-04T07:49:57.531Z" }, +] + [[package]] name = "pyyaml" version = "6.0.3" @@ -2998,6 +3093,20 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/f1/12/de94a39c2ef588c7e6455cfbe7343d3b2dc9d6b6b2f40c4c6565744c873d/pyyaml-6.0.3-cp314-cp314t-win_arm64.whl", hash = "sha256:ebc55a14a21cb14062aa4162f906cd962b28e2e9ea38f9b4391244cd8de4ae0b", size = 149341, upload-time = "2025-09-25T21:32:56.828Z" }, ] +[[package]] +name = "referencing" +version = "0.37.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "attrs" }, + { name = "rpds-py" }, + { name = "typing-extensions", marker = "python_full_version < '3.13'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/22/f5/df4e9027acead3ecc63e50fe1e36aca1523e1719559c499951bb4b53188f/referencing-0.37.0.tar.gz", hash = "sha256:44aefc3142c5b842538163acb373e24cce6632bd54bdb01b21ad5863489f50d8", size = 78036, upload-time = "2025-10-13T15:30:48.871Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2c/58/ca301544e1fa93ed4f80d724bf5b194f6e4b945841c5bfd555878eea9fcb/referencing-0.37.0-py3-none-any.whl", hash = "sha256:381329a9f99628c9069361716891d34ad94af76e461dcb0335825aecc7692231", size = 26766, upload-time = "2025-10-13T15:30:47.625Z" }, +] + [[package]] name = "requests" version = "2.34.2" @@ -3013,6 +3122,114 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/a0/f4/c67b0b3f1b9245e8d266f0f112c500d50e5b4e83cb6f3b71b6528104182a/requests-2.34.2-py3-none-any.whl", hash = "sha256:2a0d60c172f83ac6ab31e4554906c0f3b3588d37b5cb939b1c061f4907e278e0", size = 73075, upload-time = "2026-05-14T19:25:26.443Z" }, ] +[[package]] +name = "rpds-py" +version = "2026.9.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/42/68/3bd46b8a5e01d3c2ebdf9c5e9497912e3fe0cde02bac21a7130ca866e403/rpds_py-2026.9.1.tar.gz", hash = "sha256:4793ef7f78268b124b73fa933440f01d258bbae01de9fa53e9080c9ab0425a12", size = 63948, upload-time = "2026-10-04T16:32:36.469Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5d/34/a828586ea3329fbb50895b50e9cf98ca3d924a9f41a0b26d443bff1b3794/rpds_py-2026.9.1-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:50906f5aea24b5a865cbd0a589698288631d9f3a54c3a937c83aefa95a0d14af", size = 346822, upload-time = "2026-10-04T16:29:16.258Z" }, + { url = "https://files.pythonhosted.org/packages/90/81/ac6a0d064982251856ce009c9e1dd51a34110b3c055aa7d1aad18b4899a3/rpds_py-2026.9.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:e21c1429e205828ea886a2293a4a2c8e01f4c25d9893ca330e97a6cf73f52e7b", size = 341380, upload-time = "2026-10-04T16:29:17.706Z" }, + { url = "https://files.pythonhosted.org/packages/42/ff/bf7d54f362748fd6a49277b9d6531c394074110fedf50ad791ec59133fbb/rpds_py-2026.9.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2693b2728bbcc48d09a981a356954b0c47c53ff25b545856f28a889ea619f69a", size = 373053, upload-time = "2026-10-04T16:29:19.063Z" }, + { url = "https://files.pythonhosted.org/packages/60/de/74b0ccdbbd28687b9b5fdb34c1cabed88352182facaced9d6f5486b8b9ed/rpds_py-2026.9.1-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:8601470267d938bcb7f3ab1a336100af51a4fd5b6ed030ef52461bb3ef5e7e07", size = 377742, upload-time = "2026-10-04T16:29:20.543Z" }, + { url = "https://files.pythonhosted.org/packages/c2/6d/b979775a3057b2a5c26d75ecbff60a20a24ef081db6dd76836fca3f20247/rpds_py-2026.9.1-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:3890a6aa36e6baa53d5258a2a25d3ef8b37ad165a6ab27a892d7c3e3a432cd69", size = 487289, upload-time = "2026-10-04T16:29:21.958Z" }, + { url = "https://files.pythonhosted.org/packages/1d/5d/7c34734ce3ece943d9d6ee0122a74a21bbc75b47acb5b7053c83f6efb1ed/rpds_py-2026.9.1-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:6b5b393eda5ea42cca1c1a6665f2a4882b4fd5d1777e41ce0545a107fb008c9d", size = 390710, upload-time = "2026-10-04T16:29:23.378Z" }, + { url = "https://files.pythonhosted.org/packages/1d/6d/b26eb1e75395925b3a142ed351cbed2ec8212f5c9d937aee3df32c701baa/rpds_py-2026.9.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:addeda51556dac7c1a2f14cda62db8b621cd12afba3091d03a96c72932387eab", size = 371261, upload-time = "2026-10-04T16:29:25.1Z" }, + { url = "https://files.pythonhosted.org/packages/7c/98/b2fdfe10301a9e27af21e634337fbba7baac0bc17fe44619a17c26bba2cb/rpds_py-2026.9.1-cp312-cp312-manylinux_2_31_riscv64.whl", hash = "sha256:d9edf30457d74eebfd76b045535e36f1cd89062566a128a0db2145ca042d787e", size = 376075, upload-time = "2026-10-04T16:29:26.748Z" }, + { url = "https://files.pythonhosted.org/packages/c5/b1/c4b8d954e49c3c69cf8063c0c9e0919c99f3d2cecc46311606a1cbe835dc/rpds_py-2026.9.1-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:815d26356930846a40c7bc1366e7b1b0320ab8a063e66c11298a208bed0fd237", size = 399358, upload-time = "2026-10-04T16:29:28.282Z" }, + { url = "https://files.pythonhosted.org/packages/b3/59/9559a7293c97dff0cbb293efffbd36644103883ecc27741af8ef90c84ca8/rpds_py-2026.9.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:3b5a6f40f0a1486b4b36c888123afc67acdbd9f33235927acf5ff295429a0ba3", size = 550267, upload-time = "2026-10-04T16:29:29.851Z" }, + { url = "https://files.pythonhosted.org/packages/6c/9d/6dc60e49511de4c8b00e74f9c1d43aed4d27f712cdb1ade92f2c199cbf64/rpds_py-2026.9.1-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:b5b8b0753718d258fd454283fbd57e14545d3b40583fa672e27cb4f987626bcc", size = 614018, upload-time = "2026-10-04T16:29:31.54Z" }, + { url = "https://files.pythonhosted.org/packages/fb/bc/92a4ecf27301b886232a413360f6b348a81d55ffef654f2ebda5970ebc3d/rpds_py-2026.9.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:46d80bc76b51a6c24f9944368c28d38b8bcbcea1da4f2f8d3ebc31a67e8c6ec6", size = 578509, upload-time = "2026-10-04T16:29:33.01Z" }, + { url = "https://files.pythonhosted.org/packages/08/53/efb97f2e6589b7ab8394385a73870e0b2ab2a195281c117b21fd6d7d4855/rpds_py-2026.9.1-cp312-cp312-win32.whl", hash = "sha256:befc2d6a953e563f8a7bfd87a42c22ebf8a3e980dcb7b6a4d17b70b0e914e8a3", size = 205401, upload-time = "2026-10-04T16:29:34.451Z" }, + { url = "https://files.pythonhosted.org/packages/1c/84/1700cc748d0eaa747486e4e82882d2575224e6e9a3148df583058850c629/rpds_py-2026.9.1-cp312-cp312-win_amd64.whl", hash = "sha256:5ce8943f79c2210f7abcc28e86367b03b28d95027fd01c46d2472373ae70c86f", size = 222923, upload-time = "2026-10-04T16:29:35.709Z" }, + { url = "https://files.pythonhosted.org/packages/c3/89/0302215373c2f8b4408b0fdfee955368cc378a98ff59508d47a7e0dc2dbf/rpds_py-2026.9.1-cp312-cp312-win_arm64.whl", hash = "sha256:501909f2e4a1e2dee528ef766fe3c469060ebc17e54a8383d404ba07a81a6f02", size = 218415, upload-time = "2026-10-04T16:29:37.263Z" }, + { url = "https://files.pythonhosted.org/packages/83/ea/ee88fd9e756ff93fb6b1182a47ec09504a242620e33ce1d20679efefe841/rpds_py-2026.9.1-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:a36b70596407634ca82d4b989a3729074a008537a0522e4c8046a67c729103e9", size = 346229, upload-time = "2026-10-04T16:29:38.82Z" }, + { url = "https://files.pythonhosted.org/packages/57/71/a097d6552f837500fc36e6b23d09cfb9890c3cc47531f9ca64e149799615/rpds_py-2026.9.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:eba5d173f7d5708b22a93815017a4611873ed54db9f268077c0dd1ed99cfc858", size = 340514, upload-time = "2026-10-04T16:29:40.405Z" }, + { url = "https://files.pythonhosted.org/packages/bd/b7/497e85768bf4e0d8ddbaa096a4cac31d1509251dee2728a8490aa367e0b5/rpds_py-2026.9.1-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:457866b85daf5034296666168b84a69e0b2e89dc4f1af102b46f6448a60b9063", size = 372611, upload-time = "2026-10-04T16:29:41.778Z" }, + { url = "https://files.pythonhosted.org/packages/52/4b/74ab4108916250b6e198e0d3af05bc6835eb046315f22f7a0ceb49667c5a/rpds_py-2026.9.1-cp313-cp313-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:a3a52a3ba86436ab3aef510fbe21512abc2ddd1993005dfe50514bd2284ef025", size = 377712, upload-time = "2026-10-04T16:29:43.242Z" }, + { url = "https://files.pythonhosted.org/packages/0c/8e/067e77d9d7b3cc793c9d909b7e97e7aadbbb1fb094093b6876902cc96d38/rpds_py-2026.9.1-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:d7841166b7fa64c9c56404617ae4341448847482d45933b13135d26c130519e5", size = 488106, upload-time = "2026-10-04T16:29:44.692Z" }, + { url = "https://files.pythonhosted.org/packages/3c/b4/c5aae6c2dde269bf955f6b7d35065c655a57e47750d9668052ad67e74dda/rpds_py-2026.9.1-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:926bdd3e3b5998ddf70cc64bc8cf57209571f9044542913afb673799fec77dd0", size = 390795, upload-time = "2026-10-04T16:29:46.129Z" }, + { url = "https://files.pythonhosted.org/packages/a0/36/76fab39973ee11e7f9f357c55138197bb01c86f6502cb76487e3b4f42db0/rpds_py-2026.9.1-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7868b85224291c6cb6759f9b5adb9745f486d226f62b16a614dd5a2a5ab2b35b", size = 370794, upload-time = "2026-10-04T16:29:47.603Z" }, + { url = "https://files.pythonhosted.org/packages/3d/fe/cd2a80e6d7b871937a60e935c5d507aa390d143f4ff3636f640b9733d5df/rpds_py-2026.9.1-cp313-cp313-manylinux_2_31_riscv64.whl", hash = "sha256:3cd182d7291d29b92c521a0069d9c01ba6193628a9a105531d11b40a6d731a33", size = 375673, upload-time = "2026-10-04T16:29:49.223Z" }, + { url = "https://files.pythonhosted.org/packages/6c/18/7464a9953724e55a3b3206062fa0ffdeaa519584c6aabf65d3956d94f131/rpds_py-2026.9.1-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:e6ea1cda8d8c688278430e4268a42f5e5da3bdd74578dfadc0820c3f1766ce83", size = 398758, upload-time = "2026-10-04T16:29:50.601Z" }, + { url = "https://files.pythonhosted.org/packages/c0/86/1534b436700fd49ff411063b7c4d7e938adfabf90895b6cf1622d5a7d1f6/rpds_py-2026.9.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:5943980471829f6de242a20b109de3111ba6b77e3af0ffc587028ac854b05e6c", size = 550370, upload-time = "2026-10-04T16:29:52.002Z" }, + { url = "https://files.pythonhosted.org/packages/57/1c/e1fa82a8a01e3c5820f3ba98a8b2673f642128eb368fa88871b01dd2c909/rpds_py-2026.9.1-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:76d3af9732d2dab69f28179b40ba2d87e2f1d5824b4a694780aa787d685e8f36", size = 613106, upload-time = "2026-10-04T16:29:53.655Z" }, + { url = "https://files.pythonhosted.org/packages/29/55/b20b8c4c3dde8755bfcd5b08492a02d0cd2e26929aedf6199ca2a377d42a/rpds_py-2026.9.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:78326f4cb4427a56ba4996c0762b63be45f06b85f086526420d2b3a66e40f84d", size = 578235, upload-time = "2026-10-04T16:29:55.157Z" }, + { url = "https://files.pythonhosted.org/packages/55/42/df3f7bbc3f7ab37a8a9db8d6c2ff2c985422899f1f7926afbf7ec3c0b8b4/rpds_py-2026.9.1-cp313-cp313-win32.whl", hash = "sha256:172e47169583f46ce118cbec68e6795d0da0f4606b488b6434f8276bca0a058c", size = 205293, upload-time = "2026-10-04T16:29:56.669Z" }, + { url = "https://files.pythonhosted.org/packages/31/9c/ba5a9569d719bfdd6ce863df4133ac6a1658cf1b07cc3534c31db729fbbc/rpds_py-2026.9.1-cp313-cp313-win_amd64.whl", hash = "sha256:3e93b2cd69a9830be33e03945cd7cda940a0a8bfcfbff41d6144f0cb0d3d8bd9", size = 222409, upload-time = "2026-10-04T16:29:58.049Z" }, + { url = "https://files.pythonhosted.org/packages/35/72/f28ca566f6c23c35bbf7445f65eb0364577b25a026305995e24f78b83d94/rpds_py-2026.9.1-cp313-cp313-win_arm64.whl", hash = "sha256:d151e148117294133bf8af7eeace085e7e87432db15ab6adf640330298a47f6f", size = 217681, upload-time = "2026-10-04T16:29:59.449Z" }, + { url = "https://files.pythonhosted.org/packages/8a/f2/67b94be1532767803415c1c5a1fd88ea487643d74a673cec1ba140af77bb/rpds_py-2026.9.1-cp314-cp314-macosx_10_12_x86_64.whl", hash = "sha256:c9d1aca01f49170fdcf5c92761b1fafe97f554b721ca4570c5949fff778f0d4b", size = 347178, upload-time = "2026-10-04T16:30:00.865Z" }, + { url = "https://files.pythonhosted.org/packages/04/37/b751de2b59b0197a1d92a5dd491de88e8a5e928c2e6562581974f1e85263/rpds_py-2026.9.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:3f0e9ac28fc067d4d34b88ae43c48e9489455c97fee9633d851f7eeed5a05d35", size = 341878, upload-time = "2026-10-04T16:30:02.564Z" }, + { url = "https://files.pythonhosted.org/packages/72/e2/5873bc4643c250db9e05d48dc0c93763d4aa68bc3b81164cb1af3b45b284/rpds_py-2026.9.1-cp314-cp314-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:07deecbfce94c78473018bc7d10b337cc651d12df87a1eb2cb3e4024bc9c33d0", size = 373963, upload-time = "2026-10-04T16:30:04.026Z" }, + { url = "https://files.pythonhosted.org/packages/51/03/5acf7632158247f3f6386ff0af3a1ee48167d575037e8d0920594b76d92b/rpds_py-2026.9.1-cp314-cp314-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:821b2755db9194409254012f429c56643416fb96ef9be090be82ec8826b7f477", size = 377975, upload-time = "2026-10-04T16:30:05.555Z" }, + { url = "https://files.pythonhosted.org/packages/e6/00/63fda451b8bffa5808fc8bb311ee7c073b340974b09f273c7b2a145d3d62/rpds_py-2026.9.1-cp314-cp314-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:3c91c210ae7645626c608400e3519b4a642f837cce09ca830db3beb2e9f274d4", size = 490347, upload-time = "2026-10-04T16:30:07.156Z" }, + { url = "https://files.pythonhosted.org/packages/a1/ae/c093ffd070ba0fb02f76c565d06fecc65ad6e4afdbae78f7031076d3cdac/rpds_py-2026.9.1-cp314-cp314-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:54ac2158a6f96cfbabff0b2eedaf94b90c5ec7ca8317fcadc61e1c2b2e0ff6ef", size = 392962, upload-time = "2026-10-04T16:30:08.77Z" }, + { url = "https://files.pythonhosted.org/packages/22/9d/d08a1128ab199b2f0cf25bfeb0639bd05119fff4b7c47bec24ef9a8ec23f/rpds_py-2026.9.1-cp314-cp314-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:eac2f5dbafd585dfe31f86a23ebf0d3ba480a9d49ebc87947267b5608d4ea0cd", size = 371623, upload-time = "2026-10-04T16:30:10.501Z" }, + { url = "https://files.pythonhosted.org/packages/53/c7/4758ddcbb75609414bbccfcb11d612436f9b3ee821bd2f33f0f1604ee648/rpds_py-2026.9.1-cp314-cp314-manylinux_2_31_riscv64.whl", hash = "sha256:8aa5dda18d39b6143eb24809d158f9252c88f402749b6f1b62a506cc7d96cc35", size = 376997, upload-time = "2026-10-04T16:30:12.124Z" }, + { url = "https://files.pythonhosted.org/packages/87/e4/947bd7f608ff60faf46dc9d389c3dffd0e3d767d78a0be19978448ef0ce7/rpds_py-2026.9.1-cp314-cp314-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:5c90e7fa02e8f5de0d10c17595c568ada48c5302e749462c0ea1a4c362111a86", size = 400169, upload-time = "2026-10-04T16:30:13.804Z" }, + { url = "https://files.pythonhosted.org/packages/4b/35/fe93e020a0543b5670472c18d7e6af3197c08da571240ce1965c84f85c0f/rpds_py-2026.9.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:e6d198bad4e49dd6732fbd636e2fc5c082f45c8cad0b4acb756b00c82c76072e", size = 551615, upload-time = "2026-10-04T16:30:15.332Z" }, + { url = "https://files.pythonhosted.org/packages/0d/4f/5d2a0136bb03b2a56a39dc6ff92d58a6e3e53a2e17079238b86228882f16/rpds_py-2026.9.1-cp314-cp314-musllinux_1_2_i686.whl", hash = "sha256:96beca19ec79de272e8668585380ff9092c47077c1d7a1e098e00bbd921f4785", size = 614655, upload-time = "2026-10-04T16:30:16.92Z" }, + { url = "https://files.pythonhosted.org/packages/09/1c/3f1025aaf70d9bf7272cc41f8b64ee76b48bf01726248138430e16f23b38/rpds_py-2026.9.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:a5cf77eb04f20b720be95265a3e00eb2a14814074255cc27069c551b2db53118", size = 579602, upload-time = "2026-10-04T16:30:18.555Z" }, + { url = "https://files.pythonhosted.org/packages/53/0d/5c72e6204f76610608706da32b6b7e11ef7e10317558a7bb15a122e008dc/rpds_py-2026.9.1-cp314-cp314-win32.whl", hash = "sha256:a03d57b86d2a51d0a66c92177e2be154ad015f357791d306e714569999cdb4cc", size = 206315, upload-time = "2026-10-04T16:30:20.05Z" }, + { url = "https://files.pythonhosted.org/packages/a4/0b/489d48abbcc7d70cf3fbf662d9d22abf1f4650761c0a9ae05260800800d3/rpds_py-2026.9.1-cp314-cp314-win_amd64.whl", hash = "sha256:837c6b305e26fe0f75b15c92cf3b2ba29e0ae19dc40b1c557b026cb426347d0c", size = 222852, upload-time = "2026-10-04T16:30:21.604Z" }, + { url = "https://files.pythonhosted.org/packages/91/16/bbb05a7e6a10cf79ba639be7f799d770ee15f64175cc61d081b218dd402a/rpds_py-2026.9.1-cp314-cp314-win_arm64.whl", hash = "sha256:fce4b85234a0cbad67bf8e6e1201ee815d172c9aebad75f25645bc4d834f8e31", size = 218709, upload-time = "2026-10-04T16:30:23.036Z" }, + { url = "https://files.pythonhosted.org/packages/22/ac/ac507a0a4ec478ca470440a09583db4be5259ba7670aeba0620822f1e57a/rpds_py-2026.9.1-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:3a72c11530d71abfb66c8d7696a2f86c43e63fca8b948f1a784ac490f4ec688e", size = 349596, upload-time = "2026-10-04T16:30:24.558Z" }, + { url = "https://files.pythonhosted.org/packages/e9/f2/817a46b658d5070f477f722c298ee9a24525b0e4017347964146ef5fdd0e/rpds_py-2026.9.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:068c37bba854ec2fe42f7365c640af11dd9895890ccbf2df5070d0c059bd7f96", size = 343114, upload-time = "2026-10-04T16:30:26.048Z" }, + { url = "https://files.pythonhosted.org/packages/6c/42/6ade976b13ac1b4cb3bf2eb603f1be2fe74df19a29988d4c2b386be59d6f/rpds_py-2026.9.1-cp314-cp314t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d7fca4eb6df565e2a928f1c7dad92d27db8f9df0f449e76423ed5d7e713ed445", size = 374197, upload-time = "2026-10-04T16:30:27.699Z" }, + { url = "https://files.pythonhosted.org/packages/d9/70/77cdf1d3f1a07faabe936016ae623aec7981f73108a8fe7a203ed2e21998/rpds_py-2026.9.1-cp314-cp314t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:c933c6678c6f116ff8af47a4c6db0868b8ace74af0343016c0ef00f00272ea69", size = 378025, upload-time = "2026-10-04T16:30:29.451Z" }, + { url = "https://files.pythonhosted.org/packages/3f/6b/18a44a3beaa9b7931acb04af7bd9539836477c630a794452d4826d6185d4/rpds_py-2026.9.1-cp314-cp314t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:028ad274ea951dac64491b5d1e65712a4aeabfdbdb9fccf797b57bd899b0c495", size = 491969, upload-time = "2026-10-04T16:30:30.995Z" }, + { url = "https://files.pythonhosted.org/packages/73/27/fb39cfd6bddaf741b024f813890374578ff8ac1f1adc473659c048b03b05/rpds_py-2026.9.1-cp314-cp314t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:740d0a99cf9de0b17a3943388e9294a59becf75e7c43421f387bd3c7a9901f7c", size = 393905, upload-time = "2026-10-04T16:30:32.628Z" }, + { url = "https://files.pythonhosted.org/packages/ed/71/0fa7bb77b57af0d710273964180d11b503f62b8a5c358eb2d8c3f62feff6/rpds_py-2026.9.1-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0da298fb372dc192610a4b9ecbc68a0cd8b675bbbd1fc519d01b41cfd658333e", size = 374569, upload-time = "2026-10-04T16:30:34.257Z" }, + { url = "https://files.pythonhosted.org/packages/54/22/f41cfac269af3b449513ef1bc3d7f32fde52abbbd2d01c7e76b47743acd9/rpds_py-2026.9.1-cp314-cp314t-manylinux_2_31_riscv64.whl", hash = "sha256:eb61be926bb81567c1f48bdc8aa22b9855048dc2efd53871f9f7e6e9a5632346", size = 377482, upload-time = "2026-10-04T16:30:35.997Z" }, + { url = "https://files.pythonhosted.org/packages/b4/fc/312b49006e7f8f9ca5f96647577b8aa6f3df30519c46bd448f5c425af0b2/rpds_py-2026.9.1-cp314-cp314t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:42e75466f83cd43f6026c81eab74246efb2bdadafb307b85700632d06c68f299", size = 400040, upload-time = "2026-10-04T16:30:37.76Z" }, + { url = "https://files.pythonhosted.org/packages/cf/a6/18cca7a878dc7fa95165a83343fd4d7b65643fd22e54e47340a451121d5c/rpds_py-2026.9.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:617f59cde379b4f648a09797b7f683d04b90a46344cddab85639da5aff0f5531", size = 551849, upload-time = "2026-10-04T16:30:39.443Z" }, + { url = "https://files.pythonhosted.org/packages/e4/6d/1f5685e20f39604691bdc3c05aaa6b8bd2f954e9e996477adf2376768e33/rpds_py-2026.9.1-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:3edae8c5ddfdb6985d49ae9d150516e5076888879022f91a26c2de9276ce0bdb", size = 614842, upload-time = "2026-10-04T16:30:41.231Z" }, + { url = "https://files.pythonhosted.org/packages/c6/25/98652109fd9f7e10268dd4571aa52b81987001b806f37ef1a18260de714a/rpds_py-2026.9.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:0f045bb053c9057720d72c56dffe30dffdc05997b2897a827b9325f0ab6623fa", size = 582606, upload-time = "2026-10-04T16:30:43.345Z" }, + { url = "https://files.pythonhosted.org/packages/19/03/11ca09099bab5f53373a80a334c424ec917c13d050760a59499d2af5171e/rpds_py-2026.9.1-cp314-cp314t-win32.whl", hash = "sha256:bf35d0568abda97233239ce32896d3ad53fccc537832c104e30c94aa5fb93569", size = 203341, upload-time = "2026-10-04T16:30:44.954Z" }, + { url = "https://files.pythonhosted.org/packages/6f/8a/88909e3ffd9f47f5b58211473875d8c3c09079f0058c46fb72c55a702a26/rpds_py-2026.9.1-cp314-cp314t-win_amd64.whl", hash = "sha256:1e8d4d79d828299bf44a55db22a9388ab967b49d17132c88eab0f4360b48da8e", size = 222843, upload-time = "2026-10-04T16:30:46.486Z" }, + { url = "https://files.pythonhosted.org/packages/f6/b7/a662f367d4896dd0a10cef2fc91f10b7f08af1c10858e287e019563f338d/rpds_py-2026.9.1-cp315-cp315-macosx_10_12_x86_64.whl", hash = "sha256:1d77b649e6f7cdf12ca5c2a98dad0ad37f9ea9b6f960408a92f0cb12bb3d04d9", size = 347463, upload-time = "2026-10-04T16:30:48.203Z" }, + { url = "https://files.pythonhosted.org/packages/ae/3f/ad45d03df4f84ebae5439577ee81f3999d182711e82235c8037b6528890e/rpds_py-2026.9.1-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:00ba2d8c7dd4ee537978ddf4b3fbd712bef2d8751603f7f3146b3f4287768e25", size = 342051, upload-time = "2026-10-04T16:30:49.872Z" }, + { url = "https://files.pythonhosted.org/packages/7e/31/3dcd68c13d4bcc59c1f7eb33ac8e80698f06f3eb0d8a1e06419836071c20/rpds_py-2026.9.1-cp315-cp315-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ec450527cbf485e13c8d3602a54f428ab0432fdade0ede75efd74b735421c871", size = 374143, upload-time = "2026-10-04T16:30:51.508Z" }, + { url = "https://files.pythonhosted.org/packages/cf/0d/68c1f058a250fbd1380ebda9fc227cbf50117adf8ffe8161ef383ea79f68/rpds_py-2026.9.1-cp315-cp315-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:306ee1850d8105b5baf977e78d45fcadd12c1a54678d614c9baf217708446e91", size = 378604, upload-time = "2026-10-04T16:30:53.206Z" }, + { url = "https://files.pythonhosted.org/packages/d7/d6/2d4c59b85397cb4800594fadf692688ccf5ce556adc930e7a5bf21061a5e/rpds_py-2026.9.1-cp315-cp315-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:ef6b65b03247c54692ad4fd9ee97cb772781927db72e3cb05e70b3db6d1ff14f", size = 490790, upload-time = "2026-10-04T16:30:54.925Z" }, + { url = "https://files.pythonhosted.org/packages/da/04/7e05dc3aebaf52f4e026766bd668fdd09a9d0e23f64a14686b36b3501892/rpds_py-2026.9.1-cp315-cp315-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:a575404ebc9cf2e91edd32eaf570ec1430eb900d4f56724ba7dd4bc1fc9c176d", size = 393146, upload-time = "2026-10-04T16:30:56.625Z" }, + { url = "https://files.pythonhosted.org/packages/57/ca/e2e9a0a46a74ed51a0498ba1fe10f4ea6b2d9a155f372a2f91e51f18cf10/rpds_py-2026.9.1-cp315-cp315-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2c16ab111bc27c646ba8aa005d0527754edc538ebb636f0b1bf8e244b48d1945", size = 372022, upload-time = "2026-10-04T16:30:58.295Z" }, + { url = "https://files.pythonhosted.org/packages/ba/cb/8f8774df5134e23424372838bcc5c7ed4127d723e1ff52f7bebd4dcb2563/rpds_py-2026.9.1-cp315-cp315-manylinux_2_31_riscv64.whl", hash = "sha256:7664419f27db41d4f1c43a78dccda7dd6e8ef2428df3ee01d0c2a07a6b071297", size = 377092, upload-time = "2026-10-04T16:30:59.984Z" }, + { url = "https://files.pythonhosted.org/packages/90/02/8d7095d73bf9114219be40230baa5df00611e0a82ed9517779ff9c19f82b/rpds_py-2026.9.1-cp315-cp315-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:4b26b03d9d2658ee2fa234f8f4f19f38a09773fe5261028025032e26d4d35af0", size = 400830, upload-time = "2026-10-04T16:31:01.721Z" }, + { url = "https://files.pythonhosted.org/packages/ec/02/8206856f8f363cd042a8315dc86b3912f5dcb6d3c66bbb24b69c2bfb0775/rpds_py-2026.9.1-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:be3e47e2d91aa3942ff9bf4077a505226005abfc39b6f7554a91c1b9393986b9", size = 551478, upload-time = "2026-10-04T16:31:03.472Z" }, + { url = "https://files.pythonhosted.org/packages/41/6b/36211f1bb1f0b0313f496d92f5905b74ea107f27cb16fa3355a82f04575e/rpds_py-2026.9.1-cp315-cp315-musllinux_1_2_i686.whl", hash = "sha256:6307a0da524939decb8ca4a3933b8ab62525794411d6984fca6726e732804af6", size = 615173, upload-time = "2026-10-04T16:31:05.281Z" }, + { url = "https://files.pythonhosted.org/packages/35/77/cda0c4a6f055446b692f0ed5692f73707cafd3dff82672ede31b1a9b59de/rpds_py-2026.9.1-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:159a7aab5c5e8b112c8830f54717ce56da1252ebdbb526f5be2df2309280b9e7", size = 579653, upload-time = "2026-10-04T16:31:07.065Z" }, + { url = "https://files.pythonhosted.org/packages/74/ec/d8385f446240aed643b9e92a5055cff3015cc04a13c61f73b2883c478ed5/rpds_py-2026.9.1-cp315-cp315-win32.whl", hash = "sha256:dbc2673f9223d420c91145599b3ba45a8a50c207d1976908e5fb5ddb0c9b9429", size = 206498, upload-time = "2026-10-04T16:31:08.989Z" }, + { url = "https://files.pythonhosted.org/packages/6d/a5/71b5cd00e0521e3b6b81828baea368c62b6b700ebdd9554cd7d41ddf12fa/rpds_py-2026.9.1-cp315-cp315-win_amd64.whl", hash = "sha256:75c38c50ab9aca840225d9a9a3810bf11d04bd5c1f186cabbb8aee56db3e9b15", size = 223121, upload-time = "2026-10-04T16:31:10.84Z" }, + { url = "https://files.pythonhosted.org/packages/33/58/dba857c3bc8221b31b62eb170a3080f4f191de79f047200389b7ed1b06a7/rpds_py-2026.9.1-cp315-cp315-win_arm64.whl", hash = "sha256:a431156bb41865fc14cd5d79bb9d7bbed83110b0159e34e62ae30951f96c0009", size = 218741, upload-time = "2026-10-04T16:31:12.592Z" }, + { url = "https://files.pythonhosted.org/packages/5b/d0/320ab28ccc1415eeb509d68682b0014fb74690cd49f1c2d29a232475af50/rpds_py-2026.9.1-cp315-cp315t-macosx_10_12_x86_64.whl", hash = "sha256:ef0d8c843e2827d6c120ab4687e9423fb1d893db1df27b7c1506615bcb9734a0", size = 349719, upload-time = "2026-10-04T16:31:14.48Z" }, + { url = "https://files.pythonhosted.org/packages/56/88/f5b12f1358f443c08b7ce3cc8391d82d335f4872580e2e097847fd36087a/rpds_py-2026.9.1-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:45bc6bccf78b20fd834237d18db64965d7ee68ba7f60440a26c7ab71e7b8d51a", size = 343267, upload-time = "2026-10-04T16:31:16.827Z" }, + { url = "https://files.pythonhosted.org/packages/f7/0c/c765b0059d532acb3b9c45d781ccc22f15a96dbe443d00903f643ba9df10/rpds_py-2026.9.1-cp315-cp315t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1d55198263bb51f557550c6ed2e6d1cb6a6fed6eb5c9120b741c5926bef8a45d", size = 374555, upload-time = "2026-10-04T16:31:18.931Z" }, + { url = "https://files.pythonhosted.org/packages/6b/8a/cafddfda77564a10cd21184640c3bffda6a2b8d20972fb5dedd5e0166328/rpds_py-2026.9.1-cp315-cp315t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:a8763f20692da7df39b0afdd1ba3042b004c50a45994f76c2d9a25641f7673db", size = 378346, upload-time = "2026-10-04T16:31:20.75Z" }, + { url = "https://files.pythonhosted.org/packages/b9/01/5e626016eff72c183bf6c96539240cace15d402468647a453ec08415b2fc/rpds_py-2026.9.1-cp315-cp315t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:e43d4a1f673e8a1cbd8533e809e02b4bf9d4f2280269bb640436556312121250", size = 492373, upload-time = "2026-10-04T16:31:22.614Z" }, + { url = "https://files.pythonhosted.org/packages/3b/9c/15a2469e9389242f46896b3f0a01d68caea8a5a35c011fcb05ef333aae73/rpds_py-2026.9.1-cp315-cp315t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:ea394a937f17a54c51239348bdbe2e3518124c8d4a8951ba04a311d3095bd18f", size = 394371, upload-time = "2026-10-04T16:31:24.768Z" }, + { url = "https://files.pythonhosted.org/packages/63/f5/c100ff77e1e6366e947c75969c258fdfc4b7bc5bbfe7351e62ffbf2a1228/rpds_py-2026.9.1-cp315-cp315t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:cdeaa99ce822dca76cfb1b993e9120c5ea212f2eb66d48950ad63c349668a018", size = 375132, upload-time = "2026-10-04T16:31:26.588Z" }, + { url = "https://files.pythonhosted.org/packages/dd/f4/fe0269c9de253e99c81cabc12b8971a5feaa083debdaff1221e06264d9e3/rpds_py-2026.9.1-cp315-cp315t-manylinux_2_31_riscv64.whl", hash = "sha256:b4f062343e7ad3fa94f2c66e5ae667dee47ee74dd41a9057c4fbe163236a123d", size = 377642, upload-time = "2026-10-04T16:31:28.677Z" }, + { url = "https://files.pythonhosted.org/packages/05/65/b34a7b257baccff8f4a24a722933166d4941d5ebdc9c3f4bc4ffcd5ce4f4/rpds_py-2026.9.1-cp315-cp315t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:22ffd29a63d71fb1b81552c21f2c2b734949b7ac751a9be70675a939a900839b", size = 400855, upload-time = "2026-10-04T16:31:30.802Z" }, + { url = "https://files.pythonhosted.org/packages/98/32/844e54176b6071b90b38a564e6940bc6eb8f97b2890dc709c19db9dec0f4/rpds_py-2026.9.1-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:08dae4a4095150a7c4545a1fb40b98e1ab1744fbc2770d92c977b9dadaa49ab6", size = 552573, upload-time = "2026-10-04T16:31:32.709Z" }, + { url = "https://files.pythonhosted.org/packages/17/73/6041d20729dffbfdf155c02d65be58bc225a1c1fb548fd87c23ef306138f/rpds_py-2026.9.1-cp315-cp315t-musllinux_1_2_i686.whl", hash = "sha256:9a0460d43603d1fd9ef59c30278531e15d78581721ddb538fa560aa7817ea4ad", size = 615840, upload-time = "2026-10-04T16:31:34.565Z" }, + { url = "https://files.pythonhosted.org/packages/af/9e/418094adaee6b056ce199051b255448ed872829051e341b2294c80da0977/rpds_py-2026.9.1-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:1c2d1f6da5128eabf34e963d7163a818846075a52568250d006c4c953b40f903", size = 582764, upload-time = "2026-10-04T16:31:36.665Z" }, + { url = "https://files.pythonhosted.org/packages/3d/9b/1698ebf6b840ddfe8b472198abbed6ace35c6e398faeecd6c47dae742a4e/rpds_py-2026.9.1-cp315-cp315t-win32.whl", hash = "sha256:5c6ee90dee3e85e055ddfd502d611643d9b0fd94c818220bda84ec3dacd9b27b", size = 203795, upload-time = "2026-10-04T16:31:38.53Z" }, + { url = "https://files.pythonhosted.org/packages/8a/e2/91f70d804c61f8eac39a417e82aa1024f655ab9e8bdd7393b196242bc41b/rpds_py-2026.9.1-cp315-cp315t-win_amd64.whl", hash = "sha256:fe5ad0664ec772b02c45859041aa17655709cced7a31005817fbbbd988c25567", size = 223037, upload-time = "2026-10-04T16:31:40.468Z" }, + { url = "https://files.pythonhosted.org/packages/a3/90/a9ba81408369d34c1aca73319c15adc91ed45c1d21e9e8ee4832ffb7fe0b/rpds_py-2026.9.1-pp312-pypy312_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6cdc537c8633d7fd92a82e2e0d2ab74320a3f63d5e59fb9cf08711e08fe151c4", size = 381109, upload-time = "2026-10-04T16:32:08.994Z" }, + { url = "https://files.pythonhosted.org/packages/b3/44/5192a0bed94cec86bd2a5e1cc5a1bb8f7eec3aec907eacd2deb13e87e326/rpds_py-2026.9.1-pp312-pypy312_pp73-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:10e208f2425d973938afcd56e28a7c4be32e27b6a60b5d381f49fb9d8acf9759", size = 388222, upload-time = "2026-10-04T16:32:11.321Z" }, + { url = "https://files.pythonhosted.org/packages/92/cd/5356549711448f18b52f7a11ffbe90f1228774996fbf3c6cd1b18d22abaf/rpds_py-2026.9.1-pp312-pypy312_pp73-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:6c0dbbcc19735fe5f8b0a54c07659d154a9e69f47e15d0a6ab7299215daf62cb", size = 500384, upload-time = "2026-10-04T16:32:13.478Z" }, + { url = "https://files.pythonhosted.org/packages/7a/88/ddda9d28adfe33119c75b2e733d4ba7e326f41d7e1b1093951771768ca48/rpds_py-2026.9.1-pp312-pypy312_pp73-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:684fd492fff4fead00587544e059be2bbcb6f93454f21fa2a91b66fc7508be82", size = 401661, upload-time = "2026-10-04T16:32:15.653Z" }, + { url = "https://files.pythonhosted.org/packages/32/c3/bb59ba16a6b4a57995d15b8c04c00f28df3b938c4dcdde48fbe0f73edb0c/rpds_py-2026.9.1-pp312-pypy312_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d1028417bb44037eb3069c1009bd7b7277212876cda22fbe565b0bca9fab6d2c", size = 380748, upload-time = "2026-10-04T16:32:17.727Z" }, + { url = "https://files.pythonhosted.org/packages/f5/b8/0580faa1c5a32ddc160130dd7ae54d2d007272a89a40a6b5db3e50f9f585/rpds_py-2026.9.1-pp312-pypy312_pp73-manylinux_2_31_riscv64.whl", hash = "sha256:492e5e428cbe126221611f47e068f01660352feec4ad18bc0f5ea9b2ae88fb14", size = 385731, upload-time = "2026-10-04T16:32:19.855Z" }, + { url = "https://files.pythonhosted.org/packages/bf/70/f73564642bbe3322c7eeef2c2f258cf040b71c41a430b532e59d04a1b838/rpds_py-2026.9.1-pp312-pypy312_pp73-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:88b5268892fde430d5531f95bc560b6efbbd67c929662c586afd729a96e7461c", size = 412131, upload-time = "2026-10-04T16:32:22.285Z" }, + { url = "https://files.pythonhosted.org/packages/8c/5d/17fff2e1f8f68721a2afb5cb48f7e442c751bb6b4883157c5abaf618cd08/rpds_py-2026.9.1-pp312-pypy312_pp73-musllinux_1_2_aarch64.whl", hash = "sha256:01445c8d194aa032a08e944f16567672da1c62dbdbefd8b6d0693032e290cf68", size = 558193, upload-time = "2026-10-04T16:32:24.4Z" }, + { url = "https://files.pythonhosted.org/packages/2a/d0/869ab6fb08531f97aae4a780b4d61b4190d8aef48fe054ee28bcf7114466/rpds_py-2026.9.1-pp312-pypy312_pp73-musllinux_1_2_i686.whl", hash = "sha256:eef6a03b0b6d08d0835ccfa8ec8d1bc70525e3801387567137b50c557695e6da", size = 622448, upload-time = "2026-10-04T16:32:26.844Z" }, + { url = "https://files.pythonhosted.org/packages/ba/a5/9672e532fe02cd3b92c78cfd8743abca939d96853006c63835009a1ecb6f/rpds_py-2026.9.1-pp312-pypy312_pp73-musllinux_1_2_x86_64.whl", hash = "sha256:6b9bf3135b4ad5981df9a73d71a35272d650a2985ae9c2746357b24d59de2448", size = 591126, upload-time = "2026-10-04T16:32:29.274Z" }, + { url = "https://files.pythonhosted.org/packages/80/ef/3a9f8e4279c7920af561deed4cb7ebebed2794a8f608cf404d5eef14a105/rpds_py-2026.9.1-pp312-pypy312_pp80-macosx_10_12_x86_64.whl", hash = "sha256:56c6952a9b15047466d0c2347c446a761d4527f89976156341e68f0ce5cc08b0", size = 357108, upload-time = "2026-10-04T16:32:31.641Z" }, + { url = "https://files.pythonhosted.org/packages/b7/55/4b2fa381a583760aea5c92841e4e928a358e1c6511b129219e9c2826a226/rpds_py-2026.9.1-pp312-pypy312_pp80-macosx_11_0_arm64.whl", hash = "sha256:b242c27c8f836305a4a72df9cdd564386ac57b807bd252a063223331c9316b37", size = 346877, upload-time = "2026-10-04T16:32:34.061Z" }, +] + [[package]] name = "ruff" version = "0.16.9" @@ -3077,6 +3294,19 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/8f/88/fb7ce53c23e171ad059fd3a5ff6889399da2804cf0cfda2a10c64f32fdf7/sqlglot-30.27.0-py3-none-any.whl", hash = "sha256:b630686fc167762e20960ad3d007ad03d81af0a804c9f7d117f1fe06433c839e", size = 801972, upload-time = "2026-10-30T18:18:57.65Z" }, ] +[[package]] +name = "sse-starlette" +version = "3.7.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "anyio" }, + { name = "starlette" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/41/43/a232e3cd804293bd4f6d01e8895bc0f6f83ea148d712baf9d783c7d93d23/sse_starlette-3.7.0.tar.gz", hash = "sha256:326416da2ab52e9a41b3f409d3ff897eda45aa68c9f3b7b17d0913aab8d219c3", size = 43869, upload-time = "2026-11-07T11:15:49.389Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/6a/11/25cabac0a24fa76f58637d8671b549c90d818d69d26beecf0c59a3b186e0/sse_starlette-3.7.0-py3-none-any.whl", hash = "sha256:f1d3136caa12d129284fca3d2ded79bc9af943320b6472712955fea52a6d3eea", size = 18432, upload-time = "2026-11-07T11:15:47.86Z" }, +] + [[package]] name = "starlette" version = "1.7.0" @@ -3295,6 +3525,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/9f/e4/81f9a935789233cf412a0ed5fe04c883841d2c8fb0b7e075958a35c65032/tree_sitter_typescript-0.23.2-cp39-abi3-win_arm64.whl", hash = "sha256:05db58f70b95ef0ea126db5560f3775692f609589ed6f8dd0af84b7f19f1cbb7", size = 274052, upload-time = "2024-11-11T02:36:09.514Z" }, ] +[[package]] +name = "types-jsonschema" +version = "4.26.0.20261006" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "referencing" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/29/d2/1f742605f5a6d39f993134885b8de41c98af606871d3ebddaf3e776bd1eb/types_jsonschema-4.26.0.20261006.tar.gz", hash = "sha256:3eb7db61b6819d40addfdaac7173e749071a7d4a9a4394f0c844598ec84b2500", size = 16843, upload-time = "2026-10-06T08:16:07.318Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/8b/a0/4f2e3c0dc3d5cad958006f2e0307065cc8fe4fbf0393ff0b69d55ee9bbe5/types_jsonschema-4.26.0.20261006-py3-none-any.whl", hash = "sha256:29301f4e65e3928540cdf5e23ad716e38bb0c0b416a48dada213edd3d70206ec", size = 16113, upload-time = "2026-10-06T08:16:06.355Z" }, +] + [[package]] name = "types-pyyaml" version = "6.0.12.20260906" From 035a5211c8db827529a3ac499c391fcaf089dc54 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sun, 22 Nov 2026 20:12:02 +0000 Subject: [PATCH 02/15] MCP cancellation drains its SDK session A cancelled response waiter leaves the SDK HTTP task alive. Give each open client a lifecycle owner, join its shutdown before returning cancellation, and retain the session deadline through idle time. Verify stream cleanup, repeated cancellation and isolation from other clients. Signed-off-by: zlareb1 --- docs/architecture/mcp-source-client.md | 7 +- pyproject.toml | 4 +- server/clients/mcp_source.py | 204 +++++++----- tests/unit/test_mcp_source_cancellation.py | 343 +++++++++++++++++++++ 4 files changed, 478 insertions(+), 80 deletions(-) create mode 100644 tests/unit/test_mcp_source_cancellation.py diff --git a/docs/architecture/mcp-source-client.md b/docs/architecture/mcp-source-client.md index f549e989bf..334e6dc02e 100644 --- a/docs/architecture/mcp-source-client.md +++ b/docs/architecture/mcp-source-client.md @@ -73,8 +73,11 @@ provenance. A citation address alone does not establish tenant or reader authori ## Bounds and cancellation Discovery, pagination, results, content and HTTP responses have finite limits. A session -has an overall deadline as well as request bounds. Cancellation ends owned protocol work; -it does not publish partial evidence as a successful read. Errors expose bounded error +has an overall deadline, including idle time, as well as request bounds. The SDK context +managers live in one task per open client. Cancelling an operation closes and joins that +task before returning cancellation; another client's SDK scope remains independent. +A cancelled client is terminal. Cancellation publishes no partial read evidence. +Closing a request does not prove that remote processing has stopped. Errors expose bounded error codes rather than upstream content, endpoints or credentials. A successful final page closes that listing operation. It does not establish a deletion diff --git a/pyproject.toml b/pyproject.toml index cdf2dc91b0..ab6322f200 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -30,8 +30,8 @@ dependencies = [ # Outbound MCP sources use the official protocol client; schemas constrain approved tool mappings. "mcp>=1.30.0,<2", "jsonschema>=4.20", - "idna>=3.7", # UTS 46 host names: server.settings.catalog.ascii_host - "dnspython>=2.6", # a cancellable lookup for names a tenant chooses: server.core.hosts + "idna>=3.7", # UTS 46 host names: server.settings.catalog.ascii_host + "dnspython>=2.6", # a cancellable lookup for names a tenant chooses: server.core.hosts "tenacity>=9.0", "pyjwt[crypto]>=2.10", # OpenTelemetry: ship spans + logs to HyperDX / ClickStack's OTLP diff --git a/server/clients/mcp_source.py b/server/clients/mcp_source.py index e0922d0067..5d4778457a 100644 --- a/server/clients/mcp_source.py +++ b/server/clients/mcp_source.py @@ -12,12 +12,13 @@ import json import math from collections.abc import AsyncIterator, Awaitable, Callable -from contextlib import AsyncExitStack +from contextlib import AsyncExitStack, ExitStack from dataclasses import asdict, dataclass, field, replace from datetime import timedelta from typing import Any, Literal, TypeVar from urllib.parse import urlsplit +import anyio import httpx from jsonschema import Draft202012Validator, SchemaError from mcp import ClientSession, types @@ -315,7 +316,9 @@ async def __aiter__(self) -> AsyncIterator[bytes]: raise MCPSourceError(self.owner.failure) from None async def aclose(self) -> None: - await self.stream.aclose() + # The SDK cancels its task group before joining HTTP stream finalizers. + with anyio.CancelScope(shield=True): + await self.stream.aclose() class _PinnedTransport(httpx.AsyncBaseTransport): @@ -500,7 +503,11 @@ def __init__( raise MCPSourceError("config") for part in path: _string(part, 128) - self._stack: AsyncExitStack | None = None + self._privacy: ExitStack | None = None + self._owner_task: asyncio.Task[None] | None = None + self._ready: asyncio.Future[None] | None = None + self._closing = False + self._owner_failure: ErrorCode | None = None self._session: ClientSession | None = None self._transport: _PinnedTransport | None = None self._operation_failure: ErrorCode | None = None @@ -540,88 +547,121 @@ def _with_receipt( return replace(evidence, receipt=receipt) async def __aenter__(self) -> MCPSourceClient: - if self._stack is not None or self._deadline: + if self._owner_task is not None or self._deadline: raise MCPSourceError("closed") - self._stack = AsyncExitStack() - self._stack.enter_context(private_work()) - self._deadline = asyncio.get_running_loop().time() + self._config.limits.timeout_seconds + self._privacy = ExitStack() + self._privacy.enter_context(private_work()) + loop = asyncio.get_running_loop() + self._deadline = loop.time() + self._config.limits.timeout_seconds + self._ready = loop.create_future() + self._owner_task = asyncio.create_task(self._serve_session()) try: - async with asyncio.timeout_at(self._deadline): - await self.validate_access() - transport = _PinnedTransport( - self._config, - self.credential, - self._deadline, - self.validate_access, - transport=self._test_transport, - ) - self._transport = transport - client = await self._stack.enter_async_context( - httpx.AsyncClient( - transport=transport, - trust_env=False, - follow_redirects=False, - timeout=httpx.Timeout(self._config.limits.request_seconds), - ) - ) - read, write, _ = await self._stack.enter_async_context( - streamable_http_client(self._config.endpoint, http_client=client) - ) - self._session = await self._stack.enter_async_context( - ClientSession( - read, - write, - read_timeout_seconds=timedelta(seconds=self._config.limits.request_seconds), - message_handler=self._message_handler, - ) - ) - result = await self._session.initialize() - self._discovery = MCPDiscovery(result.capabilities.resources is not None, ()) - await self.validate_access() + await self._ready return self - except asyncio.CancelledError as error: - code = self._transport.failure if self._transport else None + except asyncio.CancelledError: try: - await self._close(error) - except (Exception, asyncio.CancelledError): # noqa: BLE001 — SDK teardown repeats its transport refusal - if code is None: - raise asyncio.CancelledError from None - if code is not None: - raise MCPSourceError(code) from None + await self._close() + except asyncio.CancelledError: + pass + finally: + self._leave_private() raise - except Exception as error: # noqa: BLE001 — initialization errors contain untrusted server metadata - code = ( - self._transport.failure - if self._transport and self._transport.failure - else _error_code(error) - ) + except Exception as error: # noqa: BLE001 — only fixed initialization failures reach callers try: - await self._close(error) - except (Exception, asyncio.CancelledError): # noqa: BLE001 — cleanup must preserve the first fixed failure - pass - raise MCPSourceError(code) from None - - async def _close(self, error: BaseException | None = None) -> None: - stack, self._stack = self._stack, None - self._session = None - if stack is not None: - await stack.__aexit__( - type(error) if error else None, error, error.__traceback__ if error else None + await self._close() + finally: + self._leave_private() + raise MCPSourceError(self._owner_failure or _error_code(error)) from None + + async def _serve_session(self) -> None: + # SDK AnyIO scopes are entered and exited by this one lifecycle owner. + with private_work(): + try: + async with AsyncExitStack() as stack: + async with asyncio.timeout_at(self._deadline): + await self._initialize(stack) + assert self._ready is not None + if not self._ready.done(): + self._ready.set_result(None) + await asyncio.Future[None]() + except ( + Exception, # noqa: BLE001 — SDK lifecycle failures must remain fixed codes + asyncio.CancelledError, + ) as error: + failure = self._transport.failure if self._transport else None + expected_close = self._closing and isinstance(error, asyncio.CancelledError) + if failure is not None or not expected_close: + self._owner_failure = failure or _error_code(error) + if self._ready is not None and not self._ready.done(): + self._ready.set_exception(MCPSourceError(self._owner_failure or "closed")) + finally: + self._session = None + + async def _initialize(self, stack: AsyncExitStack) -> None: + await self.validate_access() + transport = _PinnedTransport( + self._config, + self.credential, + self._deadline, + self.validate_access, + transport=self._test_transport, + ) + self._transport = transport + client = await stack.enter_async_context( + httpx.AsyncClient( + transport=transport, + trust_env=False, + follow_redirects=False, + timeout=httpx.Timeout(self._config.limits.request_seconds), ) + ) + read, write, _ = await stack.enter_async_context( + streamable_http_client(self._config.endpoint, http_client=client) + ) + self._session = await stack.enter_async_context( + ClientSession( + read, + write, + read_timeout_seconds=timedelta(seconds=self._config.limits.request_seconds), + message_handler=self._message_handler, + ) + ) + result = await self._session.initialize() + self._discovery = MCPDiscovery(result.capabilities.resources is not None, ()) + await self.validate_access() + + async def _close(self) -> None: + set_query_tag("mcp-source.cleanup") + owner = self._owner_task + if owner is None: + return + if not self._closing: + self._closing = True + owner.cancel() + interrupted: asyncio.CancelledError | None = None + while not owner.done(): + try: + await asyncio.shield(owner) + except asyncio.CancelledError as error: + interrupted = error + if not owner.cancelled(): + owner.result() + if interrupted is not None: + raise interrupted + + def _leave_private(self) -> None: + privacy, self._privacy = self._privacy, None + if privacy is not None: + privacy.close() async def __aexit__(self, exc_type: Any, error: BaseException | None, traceback: Any) -> None: try: - await self._close(error) - except (Exception, asyncio.CancelledError) as cleanup: # Preserve the first fixed refusal. - code = ( - self._transport.failure - if self._transport and self._transport.failure - else _error_code(cleanup) - ) - if self._operation_failure != code: - if isinstance(cleanup, asyncio.CancelledError): - raise - raise MCPSourceError(code) from None + await self._close() + failure = self._owner_failure + if error is None and failure is not None and failure != self._operation_failure: + raise MCPSourceError(failure) + finally: + self._leave_private() async def _message_handler(self, message: Any) -> None: if isinstance(message, types.ServerNotification) and isinstance( @@ -630,9 +670,14 @@ async def _message_handler(self, message: Any) -> None: self._schema_changed = True async def _run(self, action: Callable[[ClientSession], Awaitable[_T]]) -> _T: + with private_work(): + return await self._execute(action) + + async def _execute(self, action: Callable[[ClientSession], Awaitable[_T]]) -> _T: set_query_tag("mcp-source") if self._session is None: - raise MCPSourceError("closed") + self._operation_failure = self._owner_failure or "closed" + raise MCPSourceError(self._operation_failure) if self._operation_failure is not None: raise MCPSourceError(self._operation_failure) try: @@ -640,11 +685,18 @@ async def _run(self, action: Callable[[ClientSession], Awaitable[_T]]) -> _T: await self.validate_access() result = await action(self._session) await self.validate_access() + if self._operation_failure is not None: + raise MCPSourceError(self._operation_failure) return result except asyncio.CancelledError: if self._transport and self._transport.failure: self._operation_failure = self._transport.failure raise MCPSourceError(self._operation_failure) from None + self._operation_failure = "closed" + try: + await self._close() + except asyncio.CancelledError: + pass raise except MCPSourceError as error: self._operation_failure = error.code diff --git a/tests/unit/test_mcp_source_cancellation.py b/tests/unit/test_mcp_source_cancellation.py new file mode 100644 index 0000000000..21da39b73a --- /dev/null +++ b/tests/unit/test_mcp_source_cancellation.py @@ -0,0 +1,343 @@ +"""Cancellation must drain owned HTTP work before the client context closes.""" + +from __future__ import annotations + +import asyncio +import json +from collections.abc import AsyncIterator +from dataclasses import dataclass, field +from typing import Any + +import httpx +import pytest + +from server.clients import mcp_source as source +from tests.unit.clock_fake import ManualClock + +ENDPOINT = "https://source.example/mcp" +IDENTITY = "doc://workspace/one" +TEXT = "selected body" +STRING = {"type": "string", "maxLength": 2048} +INPUT = { + "type": "object", + "additionalProperties": False, + "properties": {"id": STRING}, + "required": ["id"], +} +OUTPUT = { + "type": "object", + "additionalProperties": False, + "properties": {name: STRING for name in ("id", "uri", "title", "text")}, + "required": ["id", "uri", "title", "text"], +} + + +async def access() -> None: + return None + + +async def pin(*args: Any, **kwargs: Any) -> tuple[str, str, str, str]: + return "", "https://93.184.216.34/mcp", "source.example", "source.example" + + +@dataclass +class HTTPFixture: + kind: str + block: bool = True + phase: str = "headers" + hold_cleanup: bool = False + block_initialize: bool = False + started: asyncio.Event = field(default_factory=asyncio.Event) + stopped: asyncio.Event = field(default_factory=asyncio.Event) + release: asyncio.Event = field(default_factory=asyncio.Event) + reads: int = 0 + closing: asyncio.Event = field(default_factory=asyncio.Event) + cleanup_release: asyncio.Event = field(default_factory=asyncio.Event) + pool_closed: asyncio.Event = field(default_factory=asyncio.Event) + pool_closes: int = 0 + + async def cleanup(self) -> None: + self.closing.set() + if self.hold_cleanup: + await self.cleanup_release.wait() + self.stopped.set() + + def config(self) -> source.MCPSourceConfig: + mapping = source.MCPToolMapping("read_document", INPUT, OUTPUT, "id") + return source.MCPSourceConfig( + ENDPOINT, + approved_resource_ids=(IDENTITY,), + approved_tools=("read_document",) if self.kind == "tools" else (), + read=mapping if self.kind == "tools" else None, + limits=source.MCPLimits(timeout_seconds=5, request_seconds=2), + ) + + async def reply(self, request: httpx.Request) -> httpx.Response: + if request.method == "GET": + return httpx.Response(405) + payload = json.loads(await request.aread()) + method = payload["method"] + if method == "notifications/initialized": + return httpx.Response(202) + if method == "initialize": + if self.block_initialize: + self.started.set() + try: + await self.release.wait() + finally: + await self.cleanup() + result = { + "protocolVersion": "2025-11-25", + "capabilities": {self.kind: {}}, + "serverInfo": {"name": "synthetic", "version": "1"}, + } + elif method == "tools/list": + result = { + "tools": [{"name": "read_document", "inputSchema": INPUT, "outputSchema": OUTPUT}] + } + elif method in {"resources/read", "tools/call"}: + self.reads += 1 + if self.phase != "headers": + return httpx.Response( + 200, + stream=ReadStream(self, payload["id"]), + headers={ + "content-type": "text/event-stream" + if self.phase == "sse" + else "application/json" + }, + ) + self.started.set() + try: + if self.block: + await self.release.wait() + result = self.document() + finally: + await self.cleanup() + else: + raise AssertionError(method) + return httpx.Response(200, json={"jsonrpc": "2.0", "id": payload["id"], "result": result}) + + def document(self) -> dict[str, Any]: + if self.kind == "resources": + return {"contents": [{"uri": IDENTITY, "text": TEXT}]} + return { + "content": [], + "structuredContent": {"id": IDENTITY, "uri": IDENTITY, "title": "One", "text": TEXT}, + } + + def client(self) -> source.MCPSourceClient: + return source.MCPSourceClient( + self.config(), + None, + validate_access=access, + _transport=FixtureTransport(self), + ) + + +class ReadStream(httpx.AsyncByteStream): + def __init__(self, fixture: HTTPFixture, request_id: int) -> None: + self.fixture, self.request_id = fixture, request_id + + async def __aiter__(self) -> AsyncIterator[bytes]: + self.fixture.started.set() + if self.fixture.block: + await self.fixture.release.wait() + body = json.dumps( + {"jsonrpc": "2.0", "id": self.request_id, "result": self.fixture.document()} + ).encode() + yield b"event: message\ndata: " + body + b"\n\n" if self.fixture.phase == "sse" else body + + async def aclose(self) -> None: + await self.fixture.cleanup() + + +class FixtureTransport(httpx.MockTransport): + def __init__(self, fixture: HTTPFixture) -> None: + super().__init__(fixture.reply) + self.fixture = fixture + + async def aclose(self) -> None: + await super().aclose() + self.fixture.pool_closes += 1 + self.fixture.pool_closed.set() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["resources", "tools"]) +@pytest.mark.parametrize("phase", ["headers", "json", "sse"]) +async def test_cancelled_read_drains_http_before_context_close( + monkeypatch: pytest.MonkeyPatch, + kind: str, + phase: str, +) -> None: + monkeypatch.setattr(source, "pinned_target", pin) + fixture = HTTPFixture(kind, phase=phase) + async with fixture.client() as remote: + task = asyncio.create_task(remote.read(IDENTITY)) + try: + await asyncio.wait_for(fixture.started.wait(), timeout=1) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + # Capture the invariant before either releasing upstream or closing the client. + stopped_inside_open_context = fixture.stopped.is_set() + assert task.cancelled() + assert fixture.pool_closed.is_set() + before = fixture.reads + with pytest.raises(source.MCPSourceError, match="closed"): + await remote.read(IDENTITY) + assert fixture.reads == before + finally: + fixture.release.set() + if not task.done(): + task.cancel() + await asyncio.gather(task, return_exceptions=True) + assert stopped_inside_open_context, "cancelled read left its owned HTTP request running" + assert fixture.pool_closes == 1 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["resources", "tools"]) +@pytest.mark.parametrize("phase", ["headers", "json", "sse"]) +async def test_adjacent_normal_selected_read_returns_receipt( + monkeypatch: pytest.MonkeyPatch, + kind: str, + phase: str, +) -> None: + monkeypatch.setattr(source, "pinned_target", pin) + fixture = HTTPFixture(kind, block=False, phase=phase) + async with fixture.client() as remote: + evidence = await remote.read(IDENTITY) + assert evidence.text == TEXT + assert evidence.receipt is not None + assert evidence.receipt.requested_id == IDENTITY + assert fixture.stopped.is_set() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["resources", "tools"]) +async def test_repeated_cancellation_still_awaits_stream_cleanup( + monkeypatch: pytest.MonkeyPatch, + kind: str, +) -> None: + monkeypatch.setattr(source, "pinned_target", pin) + fixture = HTTPFixture(kind, phase="sse", hold_cleanup=True) + async with fixture.client() as remote: + task = asyncio.create_task(remote.read(IDENTITY)) + try: + await asyncio.wait_for(fixture.started.wait(), timeout=1) + task.cancel() + await asyncio.wait_for(fixture.closing.wait(), timeout=1) + assert not task.done() + task.cancel() + await asyncio.sleep(0) + assert not task.done() + assert not fixture.stopped.is_set() + fixture.cleanup_release.set() + with pytest.raises(asyncio.CancelledError): + await task + assert fixture.stopped.is_set() + assert fixture.pool_closed.is_set() + finally: + fixture.release.set() + fixture.cleanup_release.set() + if not task.done(): + task.cancel() + await asyncio.gather(task, return_exceptions=True) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["resources", "tools"]) +async def test_terminal_cancellation_does_not_stop_another_client( + monkeypatch: pytest.MonkeyPatch, + kind: str, +) -> None: + monkeypatch.setattr(source, "pinned_target", pin) + cancelled, neighbor = HTTPFixture(kind), HTTPFixture(kind) + async with cancelled.client() as first, neighbor.client() as second: + first_task = asyncio.create_task(first.read(IDENTITY)) + second_task = asyncio.create_task(second.read(IDENTITY)) + try: + await asyncio.wait_for(cancelled.started.wait(), timeout=1) + await asyncio.wait_for(neighbor.started.wait(), timeout=1) + first_task.cancel() + with pytest.raises(asyncio.CancelledError): + await first_task + assert cancelled.stopped.is_set() + assert not second_task.done() + assert not neighbor.stopped.is_set() + assert not neighbor.pool_closed.is_set() + neighbor.release.set() + evidence = await second_task + assert evidence.text == TEXT + assert evidence.receipt is not None + finally: + cancelled.release.set() + neighbor.release.set() + for task in (first_task, second_task): + if not task.done(): + task.cancel() + await asyncio.gather(first_task, second_task, return_exceptions=True) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["resources", "tools"]) +async def test_cancellation_during_initialize_drains_lifecycle_owner( + monkeypatch: pytest.MonkeyPatch, + kind: str, +) -> None: + monkeypatch.setattr(source, "pinned_target", pin) + fixture = HTTPFixture(kind, block_initialize=True) + + async def opening() -> None: + async with fixture.client(): + pytest.fail("a blocked initialize unexpectedly completed") + + task = asyncio.create_task(opening()) + try: + await asyncio.wait_for(fixture.started.wait(), timeout=1) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + assert fixture.stopped.is_set() + assert fixture.pool_closed.is_set() + assert fixture.reads == 0 + finally: + fixture.release.set() + if not task.done(): + task.cancel() + await asyncio.gather(task, return_exceptions=True) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["resources", "tools"]) +async def test_idle_session_deadline_closes_pool_before_context_exit( + monkeypatch: pytest.MonkeyPatch, kind: str +) -> None: + loop = asyncio.get_running_loop() + clock = ManualClock(t=loop.time()) + monkeypatch.setattr(loop, "time", clock.monotonic) + monkeypatch.setattr(source, "pinned_target", pin) + fixture = HTTPFixture(kind, block=False) + closed_inside = False + exit_failure = None + try: + async with fixture.client() as remote: + clock.advance(6) + # All fixture I/O is ready; let the expired timer and SDK cleanup run. + for _ in range(100): + await asyncio.sleep(0) + if fixture.pool_closed.is_set(): + break + closed_inside = fixture.pool_closed.is_set() + if closed_inside: + with pytest.raises(source.MCPSourceError) as refusal: + await remote.read(IDENTITY) + assert refusal.value.code == "timeout" + assert fixture.reads == 0 + except source.MCPSourceError as error: + exit_failure = error.code + assert closed_inside, "the session deadline left its idle HTTP pool open" + assert exit_failure is None, "cleanup repeated an already reported deadline refusal" + assert fixture.pool_closes == 1 From 56fca0af7df941f7b96e3fd3a38d92dd30f44ee5 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sun, 22 Nov 2026 20:35:05 +0000 Subject: [PATCH 03/15] Drain terminal MCP requests before returning Join the SDK lifecycle owner after every operation failure, including request deadlines and cancellation after a background refusal. Preserve the first caller cancellation while draining stream finalizers and the HTTP pool. Signed-off-by: zlareb1 --- docs/architecture/mcp-source-client.md | 7 +- server/clients/mcp_source.py | 46 ++-- tests/unit/test_mcp_source_cancellation.py | 252 ++++++++++++++++++++- 3 files changed, 277 insertions(+), 28 deletions(-) diff --git a/docs/architecture/mcp-source-client.md b/docs/architecture/mcp-source-client.md index 334e6dc02e..d5b6058187 100644 --- a/docs/architecture/mcp-source-client.md +++ b/docs/architecture/mcp-source-client.md @@ -74,9 +74,10 @@ provenance. A citation address alone does not establish tenant or reader authori Discovery, pagination, results, content and HTTP responses have finite limits. A session has an overall deadline, including idle time, as well as request bounds. The SDK context -managers live in one task per open client. Cancelling an operation closes and joins that -task before returning cancellation; another client's SDK scope remains independent. -A cancelled client is terminal. Cancellation publishes no partial read evidence. +managers live in one task per open client. A failed or cancelled operation makes its +client terminal and closes and joins that task before returning, including when an SDK +request deadline expires while HTTP response data is still arriving. Another client's +SDK scope remains independent. Cancellation publishes no partial read evidence. Closing a request does not prove that remote processing has stopped. Errors expose bounded error codes rather than upstream content, endpoints or credentials. diff --git a/server/clients/mcp_source.py b/server/clients/mcp_source.py index 5d4778457a..1f9e67ddbf 100644 --- a/server/clients/mcp_source.py +++ b/server/clients/mcp_source.py @@ -643,7 +643,7 @@ async def _close(self) -> None: try: await asyncio.shield(owner) except asyncio.CancelledError as error: - interrupted = error + interrupted = interrupted or error if not owner.cancelled(): owner.result() if interrupted is not None: @@ -658,7 +658,7 @@ async def __aexit__(self, exc_type: Any, error: BaseException | None, traceback: try: await self._close() failure = self._owner_failure - if error is None and failure is not None and failure != self._operation_failure: + if error is None and failure is not None and self._operation_failure is None: raise MCPSourceError(failure) finally: self._leave_private() @@ -675,12 +675,11 @@ async def _run(self, action: Callable[[ClientSession], Awaitable[_T]]) -> _T: async def _execute(self, action: Callable[[ClientSession], Awaitable[_T]]) -> _T: set_query_tag("mcp-source") - if self._session is None: - self._operation_failure = self._owner_failure or "closed" - raise MCPSourceError(self._operation_failure) - if self._operation_failure is not None: - raise MCPSourceError(self._operation_failure) try: + if self._session is None: + raise MCPSourceError(self._owner_failure or "closed") + if self._operation_failure is not None: + raise MCPSourceError(self._operation_failure) async with asyncio.timeout_at(self._deadline): await self.validate_access() result = await action(self._session) @@ -688,26 +687,25 @@ async def _execute(self, action: Callable[[ClientSession], Awaitable[_T]]) -> _T if self._operation_failure is not None: raise MCPSourceError(self._operation_failure) return result - except asyncio.CancelledError: - if self._transport and self._transport.failure: - self._operation_failure = self._transport.failure - raise MCPSourceError(self._operation_failure) from None - self._operation_failure = "closed" + except ( + Exception, # Terminal refusals must drain owned HTTP work before returning. + asyncio.CancelledError, + ) as error: + if isinstance(error, asyncio.CancelledError): + code: ErrorCode = "closed" + elif isinstance(error, MCPSourceError): + code = error.code + else: + code = (self._transport.failure if self._transport else None) or _error_code(error) + code = self._operation_failure or code + self._operation_failure = code try: await self._close() except asyncio.CancelledError: - pass - raise - except MCPSourceError as error: - self._operation_failure = error.code - raise - except Exception as error: # noqa: BLE001 — upstream errors may contain credentials or document content - code = ( - self._transport.failure - if self._transport and self._transport.failure - else _error_code(error) - ) - self._operation_failure = code + if not isinstance(error, asyncio.CancelledError): + raise + if isinstance(error, asyncio.CancelledError): + raise raise MCPSourceError(code) from None async def discover(self) -> MCPDiscovery: diff --git a/tests/unit/test_mcp_source_cancellation.py b/tests/unit/test_mcp_source_cancellation.py index 21da39b73a..f79fe79541 100644 --- a/tests/unit/test_mcp_source_cancellation.py +++ b/tests/unit/test_mcp_source_cancellation.py @@ -5,7 +5,7 @@ import asyncio import json from collections.abc import AsyncIterator -from dataclasses import dataclass, field +from dataclasses import dataclass, field, replace from typing import Any import httpx @@ -341,3 +341,253 @@ async def test_idle_session_deadline_closes_pool_before_context_exit( assert closed_inside, "the session deadline left its idle HTTP pool open" assert exit_failure is None, "cleanup repeated an already reported deadline refusal" assert fixture.pool_closes == 1 + + +class HeartbeatStream(ReadStream): + async def __aiter__(self) -> AsyncIterator[bytes]: + fixture = self.fixture + assert isinstance(fixture, HeartbeatFixture) + fixture.started.set() + while not fixture.release.is_set(): + fixture.beats += 1 + yield b": keepalive\n\n" if fixture.phase == "sse" else b" " + await asyncio.sleep(0.01) + + +@dataclass +class HeartbeatFixture(HTTPFixture): + beats: int = 0 + + async def reply(self, request: httpx.Request) -> httpx.Response: + response = await super().reply(request) + if request.method == "POST": + payload = json.loads(await request.aread()) + if payload["method"] in {"resources/read", "tools/call"}: + response.stream = HeartbeatStream(self, payload["id"]) + return response + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["resources", "tools"]) +@pytest.mark.parametrize("phase", ["json", "sse"]) +async def test_active_request_deadline_joins_http_before_return( + monkeypatch: pytest.MonkeyPatch, kind: str, phase: str +) -> None: + monkeypatch.setattr(source, "pinned_target", pin) + fixture = HeartbeatFixture(kind, phase=phase) + config = fixture.config() + config = replace(config, limits=replace(config.limits, request_seconds=0.15)) + async with source.MCPSourceClient( + config, None, validate_access=access, _transport=FixtureTransport(fixture) + ) as remote: + try: + with pytest.raises(source.MCPSourceError) as refusal: + await remote.read(IDENTITY) + assert refusal.value.code == "timeout" + assert fixture.beats >= 2 + assert fixture.stopped.is_set(), "request deadline left its HTTP stream active" + assert fixture.pool_closed.is_set() + beats, reads = fixture.beats, fixture.reads + await asyncio.sleep(0.03) + assert fixture.beats == beats + with pytest.raises(source.MCPSourceError, match="timeout"): + await remote.read(IDENTITY) + assert fixture.reads == reads + finally: + fixture.release.set() + assert fixture.pool_closes == 1 + + +class RefusalStream(httpx.AsyncByteStream): + def __init__(self, closed: asyncio.Event) -> None: + self.closed = closed + + async def __aiter__(self) -> AsyncIterator[bytes]: + yield b"" + + async def aclose(self) -> None: + self.closed.set() + + +@dataclass +class StatefulFixture(HTTPFixture): + refusal_closed: asyncio.Event = field(default_factory=asyncio.Event) + + async def reply(self, request: httpx.Request) -> httpx.Response: + if request.method == "GET": + await self.started.wait() + return httpx.Response(403, stream=RefusalStream(self.refusal_closed)) + response = await super().reply(request) + if json.loads(await request.aread())["method"] == "initialize": + response.headers["mcp-session-id"] = "synthetic-session" + return response + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["resources", "tools"]) +@pytest.mark.parametrize("repeat", [False, True]) +async def test_background_refusal_preserves_cancel_and_joins_cleanup( + monkeypatch: pytest.MonkeyPatch, kind: str, repeat: bool +) -> None: + monkeypatch.setattr(source, "pinned_target", pin) + fixture = StatefulFixture(kind, phase="sse", hold_cleanup=repeat) + async with fixture.client() as remote: + task = asyncio.create_task(remote.read(IDENTITY)) + try: + await asyncio.wait_for(fixture.started.wait(), 1) + await asyncio.wait_for(fixture.refusal_closed.wait(), 1) + assert remote._transport is not None and remote._transport.failure == "denied" + task.cancel("original caller cancellation") + if repeat: + await asyncio.wait_for(fixture.closing.wait(), 1) + task.cancel("second caller cancellation") + await asyncio.sleep(0) + assert not task.done() + assert not fixture.pool_closed.is_set() + fixture.cleanup_release.set() + with pytest.raises(asyncio.CancelledError) as cancelled: + await task + assert cancelled.value.args == ("original caller cancellation",) + assert task.cancelled() + assert fixture.stopped.is_set() + assert fixture.pool_closed.is_set() + finally: + fixture.release.set() + fixture.cleanup_release.set() + if not task.done(): + task.cancel() + await asyncio.gather(task, return_exceptions=True) + assert fixture.pool_closes == 1 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["resources", "tools"]) +@pytest.mark.parametrize("code", ["denied", "protocol"]) +async def test_terminal_failure_drains_only_its_client( + monkeypatch: pytest.MonkeyPatch, kind: str, code: str +) -> None: + monkeypatch.setattr(source, "pinned_target", pin) + failed, neighbor = HTTPFixture(kind, phase="sse"), HTTPFixture(kind, phase="sse") + revoked = False + + async def authorization() -> None: + if revoked: + if code == "denied": + raise source.MCPSourceError("denied") + raise RuntimeError("private upstream diagnostics") + + async with ( + source.MCPSourceClient( + failed.config(), + None, + validate_access=authorization, + _transport=FixtureTransport(failed), + ) as first, + neighbor.client() as second, + ): + first_task = asyncio.create_task(first.read(IDENTITY)) + second_task = asyncio.create_task(second.read(IDENTITY)) + try: + await asyncio.wait_for(failed.started.wait(), 1) + await asyncio.wait_for(neighbor.started.wait(), 1) + revoked = True + with pytest.raises(source.MCPSourceError) as refusal: + await first.discover() + assert refusal.value.code == code + assert str(refusal.value) == "MCP source " + code + assert failed.stopped.is_set() + assert failed.pool_closed.is_set() + assert not neighbor.stopped.is_set() + assert not neighbor.pool_closed.is_set() + assert not second_task.done() + neighbor.release.set() + evidence = await second_task + assert evidence.text == TEXT + assert evidence.receipt is not None + outcome = (await asyncio.gather(first_task, return_exceptions=True))[0] + assert isinstance(outcome, source.MCPSourceError) + finally: + failed.release.set() + neighbor.release.set() + for task in (first_task, second_task): + if not task.done(): + task.cancel() + await asyncio.gather(first_task, second_task, return_exceptions=True) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["resources", "tools"]) +@pytest.mark.parametrize("cancel_cleanup", [False, True]) +async def test_request_deadline_waits_for_finalizer_despite_repeated_cancel( + monkeypatch: pytest.MonkeyPatch, kind: str, cancel_cleanup: bool +) -> None: + monkeypatch.setattr(source, "pinned_target", pin) + fixture = HeartbeatFixture(kind, phase="sse", hold_cleanup=True) + config = fixture.config() + config = replace(config, limits=replace(config.limits, request_seconds=0.15)) + async with source.MCPSourceClient( + config, None, validate_access=access, _transport=FixtureTransport(fixture) + ) as remote: + task = asyncio.create_task(remote.read(IDENTITY)) + try: + await asyncio.wait_for(fixture.closing.wait(), 1) + assert fixture.beats >= 2 + assert not task.done() + assert not fixture.pool_closed.is_set() + if cancel_cleanup: + task.cancel("cleanup caller cancellation") + await asyncio.sleep(0) + task.cancel("repeated cleanup cancellation") + await asyncio.sleep(0) + assert not task.done() + fixture.cleanup_release.set() + if cancel_cleanup: + with pytest.raises(asyncio.CancelledError) as cancelled: + await task + assert cancelled.value.args == ("cleanup caller cancellation",) + assert task.cancelled() + else: + with pytest.raises(source.MCPSourceError, match="timeout"): + await task + assert fixture.stopped.is_set() + assert fixture.pool_closed.is_set() + finally: + fixture.release.set() + fixture.cleanup_release.set() + if not task.done(): + task.cancel() + await asyncio.gather(task, return_exceptions=True) + assert fixture.pool_closes == 1 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["resources", "tools"]) +async def test_total_deadline_drains_active_http_before_return( + monkeypatch: pytest.MonkeyPatch, kind: str +) -> None: + loop = asyncio.get_running_loop() + clock = ManualClock(t=loop.time()) + monkeypatch.setattr(loop, "time", clock.monotonic) + monkeypatch.setattr(source, "pinned_target", pin) + fixture = HTTPFixture(kind, phase="sse") + config = fixture.config() + config = replace(config, limits=replace(config.limits, request_seconds=10)) + async with source.MCPSourceClient( + config, None, validate_access=access, _transport=FixtureTransport(fixture) + ) as remote: + task = asyncio.create_task(remote.read(IDENTITY)) + try: + await asyncio.wait_for(fixture.started.wait(), 1) + assert not task.done() + clock.advance(6) + with pytest.raises(source.MCPSourceError, match="timeout"): + await task + assert fixture.stopped.is_set() + assert fixture.pool_closed.is_set() + assert fixture.reads == 1 + finally: + fixture.release.set() + if not task.done(): + task.cancel() + await asyncio.gather(task, return_exceptions=True) + assert fixture.pool_closes == 1 From 53f4a5bcf167cc2762a3e8476b70792efe96271f Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sun, 22 Nov 2026 21:00:17 +0000 Subject: [PATCH 04/15] Disable external schema retrieval and close unclaimed responses Reject schema keywords outside their declared type and validate with an explicit registry that cannot retrieve external resources. Retain response cleanup through authority checks and join its finalizer outside the work deadline when handoff fails or is cancelled. Signed-off-by: zlareb1 --- docs/architecture/mcp-source-client.md | 4 + pyproject.toml | 1 + server/clients/mcp_source.py | 193 ++++++++++--------- tests/unit/test_mcp_source_cancellation.py | 207 +++++++++++++++++++++ tests/unit/test_mcp_source_client.py | 83 +++++++++ uv.lock | 2 + 6 files changed, 391 insertions(+), 99 deletions(-) diff --git a/docs/architecture/mcp-source-client.md b/docs/architecture/mcp-source-client.md index d5b6058187..17205a4313 100644 --- a/docs/architecture/mcp-source-client.md +++ b/docs/architecture/mcp-source-client.md @@ -61,6 +61,8 @@ The qualified content profile is text resources and mapped structured tool outpu resource blobs and tools that return only unstructured text are unsupported. Approved tool schemas use a bounded subset with closed objects, bounded arrays and strings, and no references, regular expressions or combinatorial validators. +Keywords must belong to the schema's declared type. External schema retrieval is +disabled independently of configuration validation. Each read produces normalized evidence: resource identity, citation URI, title, media type, content and any supplied revision. A read receipt binds the requested identity, @@ -78,6 +80,8 @@ managers live in one task per open client. A failed or cancelled operation makes client terminal and closes and joins that task before returning, including when an SDK request deadline expires while HTTP response data is still arriving. Another client's SDK scope remains independent. Cancellation publishes no partial read evidence. +The transport retains cleanup ownership while checking authority after response headers +arrive and before handing the response to the protocol client. Closing a request does not prove that remote processing has stopped. Errors expose bounded error codes rather than upstream content, endpoints or credentials. diff --git a/pyproject.toml b/pyproject.toml index ab6322f200..6cf0314b3b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -30,6 +30,7 @@ dependencies = [ # Outbound MCP sources use the official protocol client; schemas constrain approved tool mappings. "mcp>=1.30.0,<2", "jsonschema>=4.20", + "referencing>=0.37.0", "idna>=3.7", # UTS 46 host names: server.settings.catalog.ascii_host "dnspython>=2.6", # a cancellable lookup for names a tenant chooses: server.core.hosts "tenacity>=9.0", diff --git a/server/clients/mcp_source.py b/server/clients/mcp_source.py index 1f9e67ddbf..f220945469 100644 --- a/server/clients/mcp_source.py +++ b/server/clients/mcp_source.py @@ -25,6 +25,8 @@ from mcp.client.streamable_http import streamable_http_client from mcp.shared.exceptions import McpError from pydantic import AnyUrl +from referencing import Registry +from referencing.exceptions import Unresolvable from server.core.ch import set_query_tag from server.core.diagnostics import private_work @@ -216,25 +218,16 @@ def _origin(url: str) -> tuple[str, str, int]: # This subset has no references, regular expressions or combinatorial validators. -_SCHEMA_KEYS = frozenset( - { - "type", - "properties", - "required", - "additionalProperties", - "items", - "maxItems", - "minItems", - "maxLength", - "minLength", - "minimum", - "maximum", - "enum", - "const", - "title", - "description", - } -) +_SCHEMA_KEYS = frozenset({"type", "enum", "const", "title", "description"}) +_SCHEMA_TYPE_KEYS = { + "object": {"properties", "required", "additionalProperties"}, + "array": {"items", "maxItems", "minItems"}, + "string": {"maxLength", "minLength"}, + "integer": {"minimum", "maximum"}, + "number": {"minimum", "maximum"}, + "boolean": set(), + "null": set(), +} def _schema(schema: dict[str, Any]) -> None: @@ -244,17 +237,12 @@ def _schema(schema: dict[str, Any]) -> None: def visit(node: Any, depth: int) -> None: nonlocal remaining remaining -= 1 - if remaining < 0 or depth > 8 or not isinstance(node, dict) or set(node) - _SCHEMA_KEYS: + if remaining < 0 or depth > 8 or not isinstance(node, dict): raise MCPSourceError("schema") - if not isinstance(node.get("type"), str) or node["type"] not in { - "object", - "array", - "string", - "integer", - "number", - "boolean", - "null", - }: + kind = node.get("type") + if not isinstance(kind, str) or kind not in _SCHEMA_TYPE_KEYS: + raise MCPSourceError("schema") + if set(node) - (_SCHEMA_KEYS | _SCHEMA_TYPE_KEYS[kind]): raise MCPSourceError("schema") if node["type"] == "object": if node.get("additionalProperties") is not False: @@ -284,7 +272,12 @@ def visit(node: Any, depth: int) -> None: def _validate(schema: dict[str, Any], value: Any, maximum: int) -> None: _json(value, maximum) - if not Draft202012Validator(schema).is_valid(value): + try: + # An explicit empty registry never retrieves external schema resources. + valid = Draft202012Validator(schema, registry=Registry()).is_valid(value) + except Unresolvable: + raise MCPSourceError("schema") from None + if not valid: raise MCPSourceError("schema") @@ -352,77 +345,79 @@ async def handle_async_request(self, request: httpx.Request) -> httpx.Response: raise MCPSourceError(self.failure) from None async def _handle(self, request: httpx.Request) -> httpx.Response: - async with asyncio.timeout_at(self.deadline): - if self.failure is not None: - raise MCPSourceError(self.failure) - if request.url != self.endpoint or request.method not in {"POST", "GET", "DELETE"}: - raise MCPSourceError("denied") - self.requests += 1 - if self.requests > self.limits.max_requests: - raise MCPSourceError("limit") - await self.validate_access() - if self.target is None: - async with self.pin_lock: - if self.target is None: - refusal, pinned, host, sni = await pinned_target( - str(self.endpoint), schemes=("https",) - ) - if refusal or not host or not sni: - raise MCPSourceError("denied") - self.target = pinned, host, sni - pinned, host, sni = self.target - # Construct an allowlist of protocol headers, never propagate inbound headers. - headers = { - key: value - for key, value in request.headers.items() - if key - in { - "accept", - "content-type", - "mcp-session-id", - "mcp-protocol-version", - "last-event-id", - "mcp-method", - "mcp-name", + response: httpx.Response | None = None + handed_off = False + try: + async with asyncio.timeout_at(self.deadline): + if self.failure is not None: + raise MCPSourceError(self.failure) + if request.url != self.endpoint or request.method not in {"POST", "GET", "DELETE"}: + raise MCPSourceError("denied") + self.requests += 1 + if self.requests > self.limits.max_requests: + raise MCPSourceError("limit") + await self.validate_access() + if self.target is None: + async with self.pin_lock: + if self.target is None: + refusal, pinned, host, sni = await pinned_target( + str(self.endpoint), schemes=("https",) + ) + if refusal or not host or not sni: + raise MCPSourceError("denied") + self.target = pinned, host, sni + pinned, host, sni = self.target + # Construct an allowlist of protocol headers, never propagate inbound headers. + headers = { + key: value + for key, value in request.headers.items() + if key + in { + "accept", + "content-type", + "mcp-session-id", + "mcp-protocol-version", + "last-event-id", + "mcp-method", + "mcp-name", + } } - } - if any(len(v) > 2048 for v in headers.values()): - raise MCPSourceError("limit") - headers.update({"host": host, "accept-encoding": "identity"}) - if self.credential is not None: - headers["authorization"] = "Bearer " + self.credential.token - body = await request.aread() - if len(body) > 32_768: - raise MCPSourceError("limit") - outgoing = httpx.Request( - request.method, - pinned, - headers=headers, - content=body, - extensions={"timeout": request.extensions.get("timeout", {}), "sni_hostname": sni}, - ) - await self.validate_access() - response = await self.inner.handle_async_request(outgoing) - try: + if any(len(v) > 2048 for v in headers.values()): + raise MCPSourceError("limit") + headers.update({"host": host, "accept-encoding": "identity"}) + if self.credential is not None: + headers["authorization"] = "Bearer " + self.credential.token + body = await request.aread() + if len(body) > 32_768: + raise MCPSourceError("limit") + outgoing = httpx.Request( + request.method, + pinned, + headers=headers, + content=body, + extensions={ + "timeout": request.extensions.get("timeout", {}), + "sni_hostname": sni, + }, + ) await self.validate_access() - except Exception as error: # noqa: BLE001 — a revoked response must close before returning its fixed refusal - await response.aclose() - raise MCPSourceError(_error_code(error)) from None - if response.is_redirect: - await response.aclose() - raise MCPSourceError("denied") - if response.status_code in {401, 403}: - await response.aclose() - raise MCPSourceError("denied") - # Reject compression so the wire budget also bounds decoded protocol bytes. - if response.headers.get("content-encoding", "identity") != "identity": - await response.aclose() - raise MCPSourceError("protocol") - if not isinstance(response.stream, httpx.AsyncByteStream): - await response.aclose() - raise MCPSourceError("protocol") - response.stream = _LimitedStream(response.stream, self) - return response + response = await self.inner.handle_async_request(outgoing) + await self.validate_access() + if response.is_redirect or response.status_code in {401, 403}: + raise MCPSourceError("denied") + # Reject compression so the wire budget bounds decoded protocol bytes. + if response.headers.get("content-encoding", "identity") != "identity": + raise MCPSourceError("protocol") + if not isinstance(response.stream, httpx.AsyncByteStream): + raise MCPSourceError("protocol") + response.stream = _LimitedStream(response.stream, self) + handed_off = True + return response + finally: + if response is not None and not handed_off: + # Leave the deadline scope before joining an unclaimed response's finalizer. + with anyio.CancelScope(shield=True): + await response.aclose() async def aclose(self) -> None: await self.inner.aclose() diff --git a/tests/unit/test_mcp_source_cancellation.py b/tests/unit/test_mcp_source_cancellation.py index f79fe79541..e6b86996ff 100644 --- a/tests/unit/test_mcp_source_cancellation.py +++ b/tests/unit/test_mcp_source_cancellation.py @@ -591,3 +591,210 @@ async def test_total_deadline_drains_active_http_before_return( task.cancel() await asyncio.gather(task, return_exceptions=True) assert fixture.pool_closes == 1 + + +@dataclass +class HandoffFixture(HTTPFixture): + acquired: asyncio.Event = field(default_factory=asyncio.Event) + checking: asyncio.Event = field(default_factory=asyncio.Event) + authority_release: asyncio.Event = field(default_factory=asyncio.Event) + private_failure: bool = False + response_closes: int = 0 + + async def reply(self, request: httpx.Request) -> httpx.Response: + response = await super().reply(request) + if request.method == "POST": + method = json.loads(await request.aread())["method"] + if method in {"resources/read", "tools/call"}: + self.acquired.set() + return response + + async def authority(self) -> None: + if self.acquired.is_set(): + self.checking.set() + if self.private_failure: + raise RuntimeError("private callback details") + await self.authority_release.wait() + + async def cleanup(self) -> None: + self.response_closes += 1 + await super().cleanup() + + def client(self) -> source.MCPSourceClient: + return source.MCPSourceClient( + self.config(), None, validate_access=self.authority, _transport=FixtureTransport(self) + ) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["resources", "tools"]) +@pytest.mark.parametrize("repeat", [False, True]) +async def test_response_handoff_cancel_awaits_acquired_finalizer( + monkeypatch: pytest.MonkeyPatch, kind: str, repeat: bool +) -> None: + monkeypatch.setattr(source, "pinned_target", pin) + fixture = HandoffFixture(kind, block=False, phase="sse", hold_cleanup=repeat) + async with fixture.client() as remote: + task = asyncio.create_task(remote.read(IDENTITY)) + try: + await asyncio.wait_for(fixture.checking.wait(), 1) + task.cancel("original handoff cancellation") + if repeat: + await asyncio.wait_for(fixture.closing.wait(), 1) + assert not task.done() + task.cancel("repeated handoff cancellation") + await asyncio.sleep(0) + assert not task.done() + assert not fixture.pool_closed.is_set() + fixture.cleanup_release.set() + with pytest.raises(asyncio.CancelledError) as cancelled: + await task + assert cancelled.value.args == ("original handoff cancellation",) + assert task.cancelled() + assert fixture.stopped.is_set(), "acquired response finalizer was abandoned" + assert fixture.response_closes == 1 + assert fixture.pool_closed.is_set() + assert not fixture.started.is_set(), "unapproved response reached body iteration" + finally: + fixture.cleanup_release.set() + fixture.authority_release.set() + if not task.done(): + task.cancel() + await asyncio.gather(task, return_exceptions=True) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["resources", "tools"]) +@pytest.mark.parametrize("deadline", ["request", "total"]) +async def test_response_handoff_deadline_awaits_acquired_finalizer( + monkeypatch: pytest.MonkeyPatch, kind: str, deadline: str +) -> None: + loop = asyncio.get_running_loop() + clock = ManualClock(t=loop.time()) + monkeypatch.setattr(loop, "time", clock.monotonic) + monkeypatch.setattr(source, "pinned_target", pin) + fixture = HandoffFixture(kind, block=False, phase="sse") + config = fixture.config() + config = replace( + config, limits=replace(config.limits, request_seconds=10 if deadline == "total" else 2) + ) + async with source.MCPSourceClient( + config, None, validate_access=fixture.authority, _transport=FixtureTransport(fixture) + ) as remote: + task = asyncio.create_task(remote.read(IDENTITY)) + try: + await asyncio.wait_for(fixture.checking.wait(), 1) + clock.advance(6 if deadline == "total" else 3) + with pytest.raises(source.MCPSourceError, match="timeout"): + await task + assert fixture.stopped.is_set(), "deadline abandoned the acquired response" + assert fixture.response_closes == 1 + assert fixture.pool_closed.is_set() + assert not fixture.started.is_set() + finally: + fixture.authority_release.set() + if not task.done(): + task.cancel() + await asyncio.gather(task, return_exceptions=True) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["resources", "tools"]) +async def test_response_handoff_private_failure_keeps_neighbor_independent( + monkeypatch: pytest.MonkeyPatch, kind: str +) -> None: + monkeypatch.setattr(source, "pinned_target", pin) + fixture = HandoffFixture( + kind, block=False, phase="sse", private_failure=True, hold_cleanup=True + ) + neighbor = HTTPFixture(kind, phase="sse") + async with fixture.client() as first, neighbor.client() as second: + other = asyncio.create_task(second.read(IDENTITY)) + failed = asyncio.create_task(first.read(IDENTITY)) + try: + await asyncio.wait_for(neighbor.started.wait(), 1) + await asyncio.wait_for(fixture.closing.wait(), 1) + assert not failed.done() + assert not neighbor.pool_closed.is_set() + assert not other.done() + neighbor.release.set() + evidence = await other + assert evidence.text == TEXT + assert evidence.receipt is not None + fixture.cleanup_release.set() + with pytest.raises(source.MCPSourceError) as refusal: + await failed + assert str(refusal.value) == "MCP source protocol" + assert fixture.stopped.is_set() + assert fixture.response_closes == 1 + assert fixture.pool_closed.is_set() + finally: + fixture.cleanup_release.set() + neighbor.release.set() + for task in (other, failed): + if not task.done(): + task.cancel() + await asyncio.gather(other, failed, return_exceptions=True) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["resources", "tools"]) +async def test_response_handoff_authorized_neighbor_returns_receipt( + monkeypatch: pytest.MonkeyPatch, kind: str +) -> None: + monkeypatch.setattr(source, "pinned_target", pin) + fixture = HandoffFixture(kind, block=False, phase="sse") + async with fixture.client() as remote: + task = asyncio.create_task(remote.read(IDENTITY)) + try: + await asyncio.wait_for(fixture.checking.wait(), 1) + assert fixture.response_closes == 0 + fixture.authority_release.set() + evidence = await task + assert evidence.text == TEXT + assert evidence.receipt is not None + assert fixture.response_closes == 1 + finally: + fixture.authority_release.set() + if not task.done(): + task.cancel() + await asyncio.gather(task, return_exceptions=True) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["resources", "tools"]) +async def test_response_handoff_cancel_finalizer_outlives_total_deadline( + monkeypatch: pytest.MonkeyPatch, kind: str +) -> None: + loop = asyncio.get_running_loop() + clock = ManualClock(t=loop.time()) + monkeypatch.setattr(loop, "time", clock.monotonic) + monkeypatch.setattr(source, "pinned_target", pin) + fixture = HandoffFixture(kind, block=False, phase="sse", hold_cleanup=True) + async with fixture.client() as remote: + task = asyncio.create_task(remote.read(IDENTITY)) + try: + await asyncio.wait_for(fixture.checking.wait(), 1) + task.cancel("original handoff cancellation") + await asyncio.wait_for(fixture.closing.wait(), 1) + clock.advance(6) + # Deliver all expired deadline callbacks while the finalizer is blocked. + for _ in range(100): + await asyncio.sleep(0) + if task.done(): + break + assert not task.done(), "the deadline interrupted acquired-response cleanup" + assert not fixture.pool_closed.is_set() + fixture.cleanup_release.set() + with pytest.raises(asyncio.CancelledError) as cancelled: + await task + assert cancelled.value.args == ("original handoff cancellation",) + assert fixture.stopped.is_set() + assert fixture.response_closes == 1 + assert fixture.pool_closed.is_set() + finally: + fixture.cleanup_release.set() + fixture.authority_release.set() + if not task.done(): + task.cancel() + await asyncio.gather(task, return_exceptions=True) diff --git a/tests/unit/test_mcp_source_client.py b/tests/unit/test_mcp_source_client.py index f358b97a44..95b7660610 100644 --- a/tests/unit/test_mcp_source_client.py +++ b/tests/unit/test_mcp_source_client.py @@ -5,7 +5,9 @@ import asyncio import copy import hashlib +import io import json +import urllib.request from collections.abc import AsyncIterator from contextlib import asynccontextmanager from dataclasses import replace @@ -719,3 +721,84 @@ async def reply(request: httpx.Request) -> httpx.Response: assert request.headers["host"] == "source.example" assert request.headers["authorization"] == "Bearer " + SECRET assert all(name not in request.headers for name in ("cookie", "x-loom-org", "traceparent")) + + +@pytest.mark.parametrize( + "node", + [ + {"type": "string", "maxLength": 10, "items": {"$ref": "urn:synthetic:hidden"}}, + {"type": "object", "additionalProperties": False, "items": {"$ref": "urn:hidden"}}, + {"type": "number", "properties": {"text": {"$ref": "urn:hidden"}}}, + {"type": "boolean", "additionalProperties": {"$ref": "urn:hidden"}}, + { + "type": "null", + "items": { + "type": "array", + "maxItems": 1, + "items": {"$ref": "https://reference.example/hidden"}, + }, + }, + { + "type": "array", + "maxItems": 1, + "items": STRING, + "properties": {"hidden": {"$ref": "urn:hidden"}}, + }, + {"type": "string", "maxLength": 10, "minimum": 0}, + {"type": "integer", "required": ["hidden"]}, + ], +) +def test_schema_hardening_rejects_type_inapplicable_keywords(node: dict[str, Any]) -> None: + read = mapping("fetch") + read.output_schema["properties"]["text"] = node + with pytest.raises(source.MCPSourceError, match="schema"): + client(source.MCPSourceConfig(ENDPOINT, ENDPOINT, approved_tools=("fetch",), read=read)) + + +@pytest.mark.parametrize("keyword", ["$ref", "$dynamicRef"]) +@pytest.mark.parametrize( + "uri", + ["urn:synthetic:no-retrieval", "https://reference.example/schema", "file:///synthetic/schema"], +) +def test_schema_hardening_runtime_never_retrieves_external_resources( + monkeypatch: pytest.MonkeyPatch, keyword: str, uri: str +) -> None: + attempted: list[str] = [] + + def intercepted(request: Any) -> io.BytesIO: + attempted.append(request.full_url) + return io.BytesIO(b'{"type":"string"}') + + monkeypatch.setattr(urllib.request, "urlopen", intercepted) + # Deliberately bypass admission: a future admission defect must still be safe. + schema = {keyword: uri, "type": "string", "maxLength": 10} + with pytest.raises(source.MCPSourceError, match="schema"): + source._validate(schema, "body", 1024) + assert attempted == [], "validation escaped the pinned HTTP boundary" + + +def test_schema_hardening_retains_supported_subset_validation() -> None: + schema = { + "type": "object", + "additionalProperties": False, + "properties": { + "rows": { + "type": "array", + "maxItems": 2, + "minItems": 1, + "items": {"type": "string", "maxLength": 10, "minLength": 1}, + }, + "count": {"type": "integer", "minimum": 1, "maximum": 2}, + "weight": {"type": "number", "minimum": 0, "maximum": 1}, + "present": {"type": "boolean", "const": True}, + "absent": {"type": "null"}, + }, + "required": ["rows", "count"], + } + source._schema(schema) + source._validate( + schema, {"rows": ["one"], "count": 1, "weight": 0.5, "present": True, "absent": None}, 1024 + ) + for invalid in ({"rows": [], "count": 1}, {"rows": ["one"], "count": 3}): + with pytest.raises(source.MCPSourceError, match="schema"): + source._validate(schema, invalid, 1024) diff --git a/uv.lock b/uv.lock index 6589242134..7a9bc9e048 100644 --- a/uv.lock +++ b/uv.lock @@ -803,6 +803,7 @@ dependencies = [ { name = "pydantic-settings" }, { name = "pyjwt", extra = ["crypto"] }, { name = "pyyaml" }, + { name = "referencing" }, { name = "snowballstemmer" }, { name = "tenacity" }, { name = "uvicorn", extra = ["standard"] }, @@ -916,6 +917,7 @@ requires-dist = [ { name = "pytest-rerunfailures", marker = "extra == 'dev'", specifier = ">=15.0" }, { name = "pytest-xdist", marker = "extra == 'dev'", specifier = ">=3.6" }, { name = "pyyaml", specifier = ">=6.0" }, + { name = "referencing", specifier = ">=0.37.0" }, { name = "ruff", marker = "extra == 'dev'", specifier = "==0.16.9" }, { name = "snowballstemmer", specifier = ">=2.2" }, { name = "sqlglot", marker = "extra == 'extractor'", specifier = ">=30.27,<31" }, From e601c273c59b5c085532a95ac068fdc4ec9777c5 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sun, 22 Nov 2026 22:16:24 +0000 Subject: [PATCH 05/15] Refuse MCP results after terminal transport failures Check session state and total expiry around authority callbacks and publication so background HTTP failures cannot yield successful read evidence. Scope issued cursors by operation and query and accept an absent optional final-page cursor. Signed-off-by: zlareb1 --- docs/architecture/mcp-source-client.md | 7 +- server/clients/mcp_source.py | 105 +++++-- tests/unit/test_mcp_source_cancellation.py | 344 +++++++++++++++++++++ tests/unit/test_mcp_source_client.py | 111 ++++++- 4 files changed, 535 insertions(+), 32 deletions(-) diff --git a/docs/architecture/mcp-source-client.md b/docs/architecture/mcp-source-client.md index 17205a4313..1aade6a10e 100644 --- a/docs/architecture/mcp-source-client.md +++ b/docs/architecture/mcp-source-client.md @@ -79,12 +79,17 @@ has an overall deadline, including idle time, as well as request bounds. The SDK managers live in one task per open client. A failed or cancelled operation makes its client terminal and closes and joins that task before returning, including when an SDK request deadline expires while HTTP response data is still arriving. Another client's -SDK scope remains independent. Cancellation publishes no partial read evidence. +SDK scope remains independent. A known background transport failure or an expired +deadline refuses discovery and result publication, including cached discovery. +Cancellation publishes no partial read evidence. The transport retains cleanup ownership while checking authority after response headers arrive and before handing the response to the protocol client. Closing a request does not prove that remote processing has stopped. Errors expose bounded error codes rather than upstream content, endpoints or credentials. +An omitted optional mapped cursor ends that listing. Issued cursors are bound to their +operation and query, so a cursor from one query cannot authorize another. Reusing a +cursor in the same listing is refused even when another listing uses the same text. A successful final page closes that listing operation. It does not establish a deletion history, complete reader permissions, revision support or a subscription contract. Partial pages, errors, refused access and notifications are never deletion evidence. diff --git a/server/clients/mcp_source.py b/server/clients/mcp_source.py index f220945469..ed333fe3bc 100644 --- a/server/clients/mcp_source.py +++ b/server/clients/mcp_source.py @@ -79,6 +79,15 @@ def _error_code(error: BaseException) -> ErrorCode: return "protocol" +def _guard_state(deadline: float, failure: ErrorCode | None, *, active: bool = True) -> None: + if failure is not None: + raise MCPSourceError(failure) + if not active: + raise MCPSourceError("closed") + if asyncio.get_running_loop().time() >= deadline: + raise MCPSourceError("timeout") + + @dataclass(frozen=True) class MCPLimits: timeout_seconds: float = 30 @@ -281,11 +290,17 @@ def _validate(schema: dict[str, Any], value: Any, maximum: int) -> None: raise MCPSourceError("schema") -def _path(value: Any, path: tuple[str, ...] | None, default: Any = "") -> Any: +def _path( + value: Any, path: tuple[str, ...] | None, default: Any = "", *, optional: bool = False +) -> Any: if path is None: return default for key in path: - if not isinstance(value, dict) or key not in value: + if not isinstance(value, dict): + raise MCPSourceError("schema") + if key not in value: + if optional: + return default raise MCPSourceError("schema") value = value[key] return value @@ -298,14 +313,15 @@ def __init__(self, stream: httpx.AsyncByteStream, owner: _PinnedTransport) -> No async def __aiter__(self) -> AsyncIterator[bytes]: try: async with asyncio.timeout_at(self.owner.deadline): + self.owner._check_state() async for chunk in self.stream: self.owner.received += len(chunk) if self.owner.received > self.owner.limits.max_wire_bytes: raise MCPSourceError("limit") - await self.owner.validate_access() + await self.owner._authorize() yield chunk except Exception as error: # noqa: BLE001 — only fixed diagnostics cross the transport boundary - self.owner.failure = _error_code(error) + self.owner.failure = self.owner.failure or _error_code(error) raise MCPSourceError(self.owner.failure) from None async def aclose(self) -> None: @@ -337,11 +353,19 @@ def __init__( self.pin_lock = asyncio.Lock() self.failure: ErrorCode | None = None + def _check_state(self) -> None: + _guard_state(self.deadline, self.failure) + + async def _authorize(self) -> None: + self._check_state() + await self.validate_access() + self._check_state() + async def handle_async_request(self, request: httpx.Request) -> httpx.Response: try: return await self._handle(request) except Exception as error: # noqa: BLE001 — HTTP exceptions may contain upstream credentials - self.failure = _error_code(error) + self.failure = self.failure or _error_code(error) raise MCPSourceError(self.failure) from None async def _handle(self, request: httpx.Request) -> httpx.Response: @@ -349,14 +373,13 @@ async def _handle(self, request: httpx.Request) -> httpx.Response: handed_off = False try: async with asyncio.timeout_at(self.deadline): - if self.failure is not None: - raise MCPSourceError(self.failure) + self._check_state() if request.url != self.endpoint or request.method not in {"POST", "GET", "DELETE"}: raise MCPSourceError("denied") self.requests += 1 if self.requests > self.limits.max_requests: raise MCPSourceError("limit") - await self.validate_access() + await self._authorize() if self.target is None: async with self.pin_lock: if self.target is None: @@ -400,9 +423,9 @@ async def _handle(self, request: httpx.Request) -> httpx.Response: "sni_hostname": sni, }, ) - await self.validate_access() + await self._authorize() response = await self.inner.handle_async_request(outgoing) - await self.validate_access() + await self._authorize() if response.is_redirect or response.status_code in {401, 403}: raise MCPSourceError("denied") # Reject compression so the wire budget bounds decoded protocol bytes. @@ -413,6 +436,9 @@ async def _handle(self, request: httpx.Request) -> httpx.Response: response.stream = _LimitedStream(response.stream, self) handed_off = True return response + except Exception as error: # noqa: BLE001 — poison the session before awaiting private failure cleanup + self.failure = self.failure or _error_code(error) + raise MCPSourceError(self.failure) from None finally: if response is not None and not handed_off: # Leave the deadline scope before joining an unclaimed response's finalizer. @@ -510,8 +536,8 @@ def __init__( self._discovery: MCPDiscovery | None = None self._schema_changed = False self._pages, self._results = 0, 0 - self._issued_cursors: dict[str, tuple[str, str]] = {} - self._used_cursors: set[str] = set() + self._issued_cursors: set[tuple[tuple[str, str], str]] = set() + self._used_cursors: set[tuple[tuple[str, str], str]] = set() if len(config.approved_resource_ids) > config.limits.max_results: raise MCPSourceError("config") self._selected_ids = frozenset( @@ -541,6 +567,26 @@ def _with_receipt( ) return replace(evidence, receipt=receipt) + def _check_state(self, *, require_session: bool = False) -> None: + owner = self._owner_task + failure = self._operation_failure or self._owner_failure + if failure is None and self._transport is not None: + failure = self._transport.failure + # The lifecycle owner may perform SDK session termination during cleanup. + lifecycle = not require_session and asyncio.current_task() is owner + active = ( + owner is not None + and not owner.done() + and (not self._closing or lifecycle) + and (not require_session or self._session is not None) + ) + _guard_state(self._deadline, failure, active=active) + + async def _authorize(self) -> None: + self._check_state() + await self.validate_access() + self._check_state() + async def __aenter__(self) -> MCPSourceClient: if self._owner_task is not None or self._deadline: raise MCPSourceError("closed") @@ -552,6 +598,7 @@ async def __aenter__(self) -> MCPSourceClient: self._owner_task = asyncio.create_task(self._serve_session()) try: await self._ready + self._check_state(require_session=True) return self except asyncio.CancelledError: try: @@ -593,12 +640,12 @@ async def _serve_session(self) -> None: self._session = None async def _initialize(self, stack: AsyncExitStack) -> None: - await self.validate_access() + await self._authorize() transport = _PinnedTransport( self._config, self.credential, self._deadline, - self.validate_access, + self._authorize, transport=self._test_transport, ) self._transport = transport @@ -623,7 +670,7 @@ async def _initialize(self, stack: AsyncExitStack) -> None: ) result = await self._session.initialize() self._discovery = MCPDiscovery(result.capabilities.resources is not None, ()) - await self.validate_access() + await self._authorize() async def _close(self) -> None: set_query_tag("mcp-source.cleanup") @@ -671,16 +718,14 @@ async def _run(self, action: Callable[[ClientSession], Awaitable[_T]]) -> _T: async def _execute(self, action: Callable[[ClientSession], Awaitable[_T]]) -> _T: set_query_tag("mcp-source") try: - if self._session is None: - raise MCPSourceError(self._owner_failure or "closed") - if self._operation_failure is not None: - raise MCPSourceError(self._operation_failure) + self._check_state(require_session=True) async with asyncio.timeout_at(self._deadline): - await self.validate_access() + await self._authorize() + self._check_state(require_session=True) + assert self._session is not None result = await action(self._session) - await self.validate_access() - if self._operation_failure is not None: - raise MCPSourceError(self._operation_failure) + await self._authorize() + self._check_state(require_session=True) return result except ( Exception, # Terminal refusals must drain owned HTTP work before returning. @@ -750,9 +795,10 @@ async def action(session: ClientSession) -> MCPDiscovery: def _page_start(self, cursor: str | None, scope: tuple[str, str]) -> None: if cursor is not None: _string(cursor) - if self._issued_cursors.get(cursor) != scope or cursor in self._used_cursors: + key = scope, cursor + if key not in self._issued_cursors or key in self._used_cursors: raise MCPSourceError("denied") - self._used_cursors.add(cursor) + self._used_cursors.add(key) self._pages += 1 if self._pages > self._config.limits.max_pages: raise MCPSourceError("limit") @@ -765,9 +811,10 @@ def _page( raise MCPSourceError("limit") if cursor is not None: _string(cursor) - if cursor in self._issued_cursors: + key = scope, cursor + if key in self._issued_cursors: raise MCPSourceError("protocol") - self._issued_cursors[cursor] = scope + self._issued_cursors.add(key) return MCPPage(tuple(items), cursor, cursor is None) async def list_resources(self, cursor: str | None = None) -> MCPPage: @@ -845,7 +892,9 @@ async def action(session: ClientSession) -> MCPPage: raise MCPSourceError("schema") items = [self._evidence(row, mapping) for row in rows] return self._page( - items, _path(result, mapping.next_cursor_path, None), ("search", query) + items, + _path(result, mapping.next_cursor_path, None, optional=True), + ("search", query), ) return await self._run(action) diff --git a/tests/unit/test_mcp_source_cancellation.py b/tests/unit/test_mcp_source_cancellation.py index e6b86996ff..32406b642b 100644 --- a/tests/unit/test_mcp_source_cancellation.py +++ b/tests/unit/test_mcp_source_cancellation.py @@ -51,6 +51,7 @@ class HTTPFixture: stopped: asyncio.Event = field(default_factory=asyncio.Event) release: asyncio.Event = field(default_factory=asyncio.Event) reads: int = 0 + requests: int = 0 closing: asyncio.Event = field(default_factory=asyncio.Event) cleanup_release: asyncio.Event = field(default_factory=asyncio.Event) pool_closed: asyncio.Event = field(default_factory=asyncio.Event) @@ -73,6 +74,7 @@ def config(self) -> source.MCPSourceConfig: ) async def reply(self, request: httpx.Request) -> httpx.Response: + self.requests += 1 if request.method == "GET": return httpx.Response(405) payload = json.loads(await request.aread()) @@ -798,3 +800,345 @@ async def test_response_handoff_cancel_finalizer_outlives_total_deadline( if not task.done(): task.cancel() await asyncio.gather(task, return_exceptions=True) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["resources", "tools"]) +async def test_state_guard_background_denial_refuses_receipt_without_caller_cancel( + monkeypatch: pytest.MonkeyPatch, kind: str +) -> None: + monkeypatch.setattr(source, "pinned_target", pin) + fixture, neighbor = StatefulFixture(kind, phase="sse"), HTTPFixture(kind, phase="sse") + async with fixture.client() as first, neighbor.client() as second: + failed, other = ( + asyncio.create_task(first.read(IDENTITY)), + asyncio.create_task(second.read(IDENTITY)), + ) + try: + await asyncio.wait_for(fixture.started.wait(), 1) + await asyncio.wait_for(neighbor.started.wait(), 1) + await asyncio.wait_for(fixture.refusal_closed.wait(), 1) + assert first._transport is not None and first._transport.failure == "denied" + assert not neighbor.pool_closed.is_set() and not other.done() + fixture.release.set() + neighbor.release.set() + evidence = await other + assert evidence.receipt is not None and evidence.text == TEXT + with pytest.raises(source.MCPSourceError, match="denied"): + await failed + assert fixture.stopped.is_set() and fixture.pool_closed.is_set() + reads = fixture.reads + with pytest.raises(source.MCPSourceError, match="denied"): + await first.read(IDENTITY) + assert fixture.reads == reads + finally: + fixture.release.set() + neighbor.release.set() + for task in (failed, other): + if not task.done(): + task.cancel() + await asyncio.gather(failed, other, return_exceptions=True) + + +class HeldRefusalStream(RefusalStream): + def __init__(self, closed: asyncio.Event, release: asyncio.Event) -> None: + super().__init__(closed) + self.release = release + + async def aclose(self) -> None: + self.closed.set() + await self.release.wait() + + +@dataclass +class StateRaceFixture(HTTPFixture): + pause_at: str = "handoff" + hold_refusal: bool = False + refusal_release: asyncio.Event = field(default_factory=asyncio.Event) + armed: bool = False + acquired: bool = False + sdk_checks: int = 0 + caller: asyncio.Task[Any] | None = None + checking: asyncio.Event = field(default_factory=asyncio.Event) + resume: asyncio.Event = field(default_factory=asyncio.Event) + denied: asyncio.Event = field(default_factory=asyncio.Event) + initialized: asyncio.Event = field(default_factory=asyncio.Event) + get_started: asyncio.Event = field(default_factory=asyncio.Event) + + async def reply(self, request: httpx.Request) -> httpx.Response: + if request.method == "GET": + self.get_started.set() + await self.checking.wait() + stream = ( + HeldRefusalStream(self.denied, self.refusal_release) + if self.hold_refusal + else RefusalStream(self.denied) + ) + return httpx.Response(403, stream=stream) + if request.method == "DELETE": + return httpx.Response(204) + response = await super().reply(request) + method = json.loads(await request.aread())["method"] + if method == "initialize": + response.headers["mcp-session-id"] = "synthetic-session" + elif method == "notifications/initialized": + self.initialized.set() + elif method in {"resources/read", "tools/call"}: + self.acquired = True + return response + + async def authority(self) -> None: + if not self.armed or self.checking.is_set(): + return + caller = asyncio.current_task() is self.caller + if not caller and not self.acquired: + self.sdk_checks += 1 + matches = { + "operation": caller and not self.acquired, + "dispatch": not caller and not self.acquired and self.sdk_checks == 2, + "handoff": self.acquired and not self.started.is_set(), + "chunk": self.started.is_set() and not self.stopped.is_set(), + "publication": caller and self.stopped.is_set(), + } + if matches[self.pause_at]: + self.checking.set() + await self.resume.wait() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["resources", "tools"]) +@pytest.mark.parametrize("phase", ["operation", "dispatch", "handoff", "chunk", "publication"]) +async def test_state_guard_rechecks_denial_after_suspended_authority( + monkeypatch: pytest.MonkeyPatch, kind: str, phase: str +) -> None: + monkeypatch.setattr(source, "pinned_target", pin) + fixture = StateRaceFixture(kind, block=False, phase="sse", pause_at=phase) + config = fixture.config() + config = replace(config, limits=replace(config.limits, request_seconds=0.3)) + async with source.MCPSourceClient( + config, None, validate_access=fixture.authority, _transport=FixtureTransport(fixture) + ) as remote: + await asyncio.wait_for(fixture.initialized.wait(), 1) + await asyncio.wait_for(fixture.get_started.wait(), 1) + fixture.armed = True + requests_before = fixture.requests + task = asyncio.create_task(remote.read(IDENTITY)) + fixture.caller = task + try: + await asyncio.wait_for(fixture.checking.wait(), 1) + await asyncio.wait_for(fixture.denied.wait(), 1) + assert remote._transport is not None and remote._transport.failure == "denied" + fixture.resume.set() + with pytest.raises(source.MCPSourceError, match="denied"): + await task + assert fixture.pool_closed.is_set() + if phase in {"operation", "dispatch"}: + assert fixture.reads == 0 + assert fixture.requests == requests_before + else: + assert fixture.stopped.is_set() + if phase == "handoff": + assert not fixture.started.is_set() + reads = fixture.reads + with pytest.raises(source.MCPSourceError, match="denied"): + await remote.read(IDENTITY) + assert fixture.reads == reads + finally: + fixture.resume.set() + if not task.done(): + task.cancel() + await asyncio.gather(task, return_exceptions=True) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("when", ["before", "authority", "publication"]) +async def test_state_guard_synchronous_discovery_refuses_elapsed_deadline( + monkeypatch: pytest.MonkeyPatch, when: str +) -> None: + loop = asyncio.get_running_loop() + clock = ManualClock(t=loop.time()) + monkeypatch.setattr(loop, "time", clock.monotonic) + monkeypatch.setattr(source, "pinned_target", pin) + fixture = HTTPFixture("resources") + armed = False + checks = 0 + + async def authority() -> None: + nonlocal checks + if armed: + checks += 1 + if when != "publication" or checks == 2: + clock.advance(6) + + async with source.MCPSourceClient( + fixture.config(), None, validate_access=authority, _transport=FixtureTransport(fixture) + ) as remote: + before = fixture.requests + if when == "before": + clock.advance(6) + else: + armed = True + with pytest.raises(source.MCPSourceError, match="timeout"): + await remote.discover() + assert fixture.pool_closed.is_set() + assert fixture.requests == before + + +@pytest.mark.asyncio +@pytest.mark.parametrize("code", ["denied", "limit", "protocol"]) +async def test_state_guard_cached_publication_rechecks_terminal_failure( + monkeypatch: pytest.MonkeyPatch, code: source.ErrorCode +) -> None: + monkeypatch.setattr(source, "pinned_target", pin) + fixture = HTTPFixture("resources") + checks = 0 + armed = False + + async def authority() -> None: + nonlocal checks + if armed: + checks += 1 + if checks == 2: + assert remote._transport is not None + remote._transport.failure = code + + async with source.MCPSourceClient( + fixture.config(), None, validate_access=authority, _transport=FixtureTransport(fixture) + ) as remote: + armed = True + with pytest.raises(source.MCPSourceError, match=code): + await remote.discover() + assert fixture.pool_closed.is_set() + assert fixture.reads == 0 + + +@pytest.mark.asyncio +async def test_state_guard_closing_owner_cannot_publish_cached_discovery( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setattr(source, "pinned_target", pin) + fixture = HTTPFixture("resources") + checks = 0 + armed = False + + async def authority() -> None: + nonlocal checks + if armed: + checks += 1 + if checks == 2: + await remote._close() + + async with source.MCPSourceClient( + fixture.config(), None, validate_access=authority, _transport=FixtureTransport(fixture) + ) as remote: + armed = True + with pytest.raises(source.MCPSourceError, match="closed"): + await remote.discover() + assert fixture.pool_closed.is_set() + assert fixture.reads == 0 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["resources", "tools"]) +async def test_state_guard_caller_cancel_keeps_identity_after_background_denial( + monkeypatch: pytest.MonkeyPatch, kind: str +) -> None: + monkeypatch.setattr(source, "pinned_target", pin) + fixture = StateRaceFixture(kind, block=False, phase="sse", hold_cleanup=True) + async with source.MCPSourceClient( + fixture.config(), + None, + validate_access=fixture.authority, + _transport=FixtureTransport(fixture), + ) as remote: + await asyncio.wait_for(fixture.initialized.wait(), 1) + await asyncio.wait_for(fixture.get_started.wait(), 1) + fixture.armed = True + task = asyncio.create_task(remote.read(IDENTITY)) + fixture.caller = task + try: + await asyncio.wait_for(fixture.checking.wait(), 1) + await asyncio.wait_for(fixture.denied.wait(), 1) + task.cancel("original state-guard cancellation") + await asyncio.wait_for(fixture.closing.wait(), 1) + task.cancel("repeated state-guard cancellation") + await asyncio.sleep(0) + assert not task.done() + fixture.cleanup_release.set() + with pytest.raises(asyncio.CancelledError) as cancelled: + await task + assert cancelled.value.args == ("original state-guard cancellation",) + assert fixture.stopped.is_set() and fixture.pool_closed.is_set() + finally: + fixture.resume.set() + fixture.cleanup_release.set() + if not task.done(): + task.cancel() + await asyncio.gather(task, return_exceptions=True) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["resources", "tools"]) +async def test_state_guard_ordinary_stateful_session_still_returns_receipt_and_closes( + monkeypatch: pytest.MonkeyPatch, kind: str +) -> None: + monkeypatch.setattr(source, "pinned_target", pin) + fixture = StateRaceFixture(kind, block=False, phase="sse") + async with source.MCPSourceClient( + fixture.config(), + None, + validate_access=fixture.authority, + _transport=FixtureTransport(fixture), + ) as remote: + await asyncio.wait_for(fixture.initialized.wait(), 1) + await asyncio.wait_for(fixture.get_started.wait(), 1) + evidence = await remote.read(IDENTITY) + assert evidence.receipt is not None and evidence.text == TEXT + assert fixture.stopped.is_set() + assert not fixture.pool_closed.is_set() + assert fixture.pool_closed.is_set() and fixture.pool_closes == 1 + assert remote._transport is not None and remote._transport.failure is None + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["resources", "tools"]) +async def test_state_guard_refusal_poison_precedes_held_response_cleanup( + monkeypatch: pytest.MonkeyPatch, kind: str +) -> None: + loop = asyncio.get_running_loop() + clock = ManualClock(t=loop.time()) + monkeypatch.setattr(loop, "time", clock.monotonic) + monkeypatch.setattr(source, "pinned_target", pin) + fixture = StateRaceFixture(kind, block=False, phase="sse", pause_at="chunk", hold_refusal=True) + config = fixture.config() + config = replace(config, limits=replace(config.limits, request_seconds=0.3)) + async with source.MCPSourceClient( + config, None, validate_access=fixture.authority, _transport=FixtureTransport(fixture) + ) as remote: + await asyncio.wait_for(fixture.initialized.wait(), 1) + await asyncio.wait_for(fixture.get_started.wait(), 1) + fixture.armed = True + task = asyncio.create_task(remote.read(IDENTITY)) + fixture.caller = task + try: + await asyncio.wait_for(fixture.denied.wait(), 1) + assert remote._transport is not None and remote._transport.failure == "denied" + fixture.resume.set() + await asyncio.wait_for(fixture.stopped.wait(), 1) + clock.advance(0.4) + for _ in range(100): + await asyncio.sleep(0) + if remote._closing: + break + assert remote._closing and not task.done() + assert not fixture.pool_closed.is_set() + fixture.refusal_release.set() + with pytest.raises(source.MCPSourceError, match="denied"): + await task + assert fixture.pool_closed.is_set() + finally: + fixture.resume.set() + fixture.refusal_release.set() + if not task.done(): + task.cancel() + await asyncio.gather(task, return_exceptions=True) diff --git a/tests/unit/test_mcp_source_client.py b/tests/unit/test_mcp_source_client.py index 95b7660610..9d1bd5b034 100644 --- a/tests/unit/test_mcp_source_client.py +++ b/tests/unit/test_mcp_source_client.py @@ -87,7 +87,7 @@ async def access() -> None: @asynccontextmanager async def synthetic_server( - monkeypatch: pytest.MonkeyPatch, *, tools: bool = False + monkeypatch: pytest.MonkeyPatch, *, tools: bool = False, both: bool = False ) -> AsyncIterator[dict[str, Any]]: state: dict[str, Any] = { "requests": [], @@ -154,6 +154,8 @@ async def call_tool(ctx: Any, params: Any) -> types.CallToolResult: "text": state["text"], } result = {"documents": [document]} if params.name == "find" else document + if params.name == "find" and state.get("paginate") and "cursor" not in params.arguments: + result["cursor"] = state.get("page_cursor", "page-2") return types.CallToolResult(content=[], structuredContent=result) server: Server[Any] = Server("synthetic-source") @@ -170,10 +172,10 @@ async def tool_listing(request: Any) -> types.ServerResult: async def tool_call(request: Any) -> types.ServerResult: return types.ServerResult(await call_tool(None, request.params)) - if tools: + if tools or both: server.request_handlers[types.ListToolsRequest] = tool_listing server.request_handlers[types.CallToolRequest] = tool_call - else: + if not tools or both: server.request_handlers[types.ListResourcesRequest] = resource_listing server.request_handlers[types.ReadResourceRequest] = resource_read manager = StreamableHTTPSessionManager( @@ -802,3 +804,106 @@ def test_schema_hardening_retains_supported_subset_validation() -> None: for invalid in ({"rows": [], "count": 1}, {"rows": ["one"], "count": 3}): with pytest.raises(source.MCPSourceError, match="schema"): source._validate(schema, invalid, 1024) + + +def paginated_config() -> source.MCPSourceConfig: + conf = config(tools=True) + assert conf.search is not None + return replace(conf, search=replace(conf.search, next_cursor_path=("cursor",))) + + +@pytest.mark.asyncio +async def test_state_guard_mapped_search_accepts_final_optional_cursor_omission( + monkeypatch: pytest.MonkeyPatch, +) -> None: + async with ( + synthetic_server(monkeypatch, tools=True) as state, + client(paginated_config()) as remote, + ): + state["paginate"] = True + first = await remote.search("alpha") + assert first.next_cursor == "page-2" and not first.complete + final = await remote.search("alpha", first.next_cursor) + assert final.next_cursor is None and final.complete + assert len(final.items) == 1 + assert all(item.receipt is None for item in final.items) + + +@pytest.mark.asyncio +async def test_state_guard_same_cursor_text_is_independent_across_scopes( + monkeypatch: pytest.MonkeyPatch, +) -> None: + async with ( + synthetic_server(monkeypatch, tools=True, both=True) as state, + client(paginated_config()) as remote, + ): + state["paginate"], state["next"] = True, "page-2" + alpha = await remote.search("alpha") + beta = await remote.search("beta") + resources = await remote.list_resources() + assert alpha.next_cursor == beta.next_cursor == resources.next_cursor == "page-2" + assert (await remote.search("alpha", alpha.next_cursor)).complete + assert (await remote.search("beta", beta.next_cursor)).complete + state["next"] = None + assert (await remote.list_resources(resources.next_cursor)).complete + + +@pytest.mark.asyncio +@pytest.mark.parametrize("mode", ["replay", "cross-scope", "reissue"]) +async def test_state_guard_scoped_cursor_still_refuses_replay_or_unissued_scope( + monkeypatch: pytest.MonkeyPatch, mode: str +) -> None: + async with ( + synthetic_server(monkeypatch, tools=True) as state, + client(paginated_config()) as remote, + ): + state["paginate"] = True + first = await remote.search("alpha") + if mode == "replay": + assert (await remote.search("alpha", first.next_cursor)).complete + query = "beta" if mode == "cross-scope" else "alpha" + cursor = None if mode == "reissue" else first.next_cursor + with pytest.raises( + source.MCPSourceError, match="protocol" if mode == "reissue" else "denied" + ): + await remote.search(query, cursor) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("cursor", ["", None, 17]) +async def test_state_guard_present_invalid_cursor_is_never_completion( + monkeypatch: pytest.MonkeyPatch, cursor: Any +) -> None: + async with ( + synthetic_server(monkeypatch, tools=True) as state, + client(paginated_config()) as remote, + ): + state["paginate"], state["page_cursor"] = True, cursor + with pytest.raises(source.MCPSourceError): + await remote.search("alpha") + + +@pytest.mark.asyncio +@pytest.mark.parametrize("code", ["denied", "limit", "protocol"]) +async def test_state_guard_search_cannot_publish_after_terminal_failure( + monkeypatch: pytest.MonkeyPatch, code: source.ErrorCode +) -> None: + task: asyncio.Task[source.MCPPage] | None = None + + async def authority() -> None: + if asyncio.current_task() is task and state["calls"]: + assert remote._transport is not None + remote._transport.failure = code + + async with synthetic_server(monkeypatch, tools=True) as state: + async with source.MCPSourceClient( + config(tools=True), source.MCPBearer(SECRET, ENDPOINT), validate_access=authority + ) as remote: + task = asyncio.create_task(remote.search("alpha")) + with pytest.raises(source.MCPSourceError, match=code): + await task + assert state["calls"][-1][0] == "find" + before = len(state["requests"]) + with pytest.raises(source.MCPSourceError, match=code): + await remote.search("beta") + assert len(state["requests"]) == before From 3da517af104f87f7afa39de901dc798544f18f11 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sun, 22 Nov 2026 23:01:59 +0000 Subject: [PATCH 06/15] Refuse unexpected MCP responses before protocol handoff Record HTTP status and media failures before the SDK can consume background errors. Preserve optional GET and DELETE responses with status 405. Distinguish omitted mapped cursors from present invalid values during page normalization. Signed-off-by: zlareb1 --- docs/architecture/mcp-source-client.md | 5 +- server/clients/mcp_source.py | 31 ++- tests/unit/test_mcp_source_cancellation.py | 251 ++++++++++++++++++++- tests/unit/test_mcp_source_client.py | 94 +++++++- 4 files changed, 373 insertions(+), 8 deletions(-) diff --git a/docs/architecture/mcp-source-client.md b/docs/architecture/mcp-source-client.md index 1aade6a10e..3f86da29c8 100644 --- a/docs/architecture/mcp-source-client.md +++ b/docs/architecture/mcp-source-client.md @@ -81,13 +81,16 @@ client terminal and closes and joins that task before returning, including when request deadline expires while HTTP response data is still arriving. Another client's SDK scope remains independent. A known background transport failure or an expired deadline refuses discovery and result publication, including cached discovery. +Unexpected HTTP status or response media types are terminal before protocol handoff. +Optional GET and DELETE responses with status 405 remain supported. Cancellation publishes no partial read evidence. The transport retains cleanup ownership while checking authority after response headers arrive and before handing the response to the protocol client. Closing a request does not prove that remote processing has stopped. Errors expose bounded error codes rather than upstream content, endpoints or credentials. -An omitted optional mapped cursor ends that listing. Issued cursors are bound to their +Only an omitted optional mapped cursor ends that listing. Every present mapped cursor +must be a nonempty bounded string; an explicit null is refused. Issued cursors are bound to their operation and query, so a cursor from one query cannot authorize another. Reusing a cursor in the same listing is refused even when another listing uses the same text. A successful final page closes that listing operation. It does not establish a deletion diff --git a/server/clients/mcp_source.py b/server/clients/mcp_source.py index ed333fe3bc..58f4df3e4c 100644 --- a/server/clients/mcp_source.py +++ b/server/clients/mcp_source.py @@ -88,6 +88,28 @@ def _guard_state(deadline: float, failure: ErrorCode | None, *, active: bool = T raise MCPSourceError("timeout") +def _check_response(method: str, response: httpx.Response) -> None: + status = response.status_code + if response.is_redirect or status in {401, 403}: + raise MCPSourceError("denied") + if status == 405 and method in {"GET", "DELETE"}: + return + if method == "DELETE": + if status not in {200, 204}: + raise MCPSourceError("protocol") + return + if method == "POST" and status == 202: + return + if status != 200: + raise MCPSourceError("protocol") + media = response.headers.get("content-type", "").partition(";")[0].strip().lower() + allowed = ( + {"text/event-stream"} if method == "GET" else {"application/json", "text/event-stream"} + ) + if media not in allowed: + raise MCPSourceError("protocol") + + @dataclass(frozen=True) class MCPLimits: timeout_seconds: float = 30 @@ -290,6 +312,9 @@ def _validate(schema: dict[str, Any], value: Any, maximum: int) -> None: raise MCPSourceError("schema") +_MISSING_CURSOR = object() + + def _path( value: Any, path: tuple[str, ...] | None, default: Any = "", *, optional: bool = False ) -> Any: @@ -426,8 +451,7 @@ async def _handle(self, request: httpx.Request) -> httpx.Response: await self._authorize() response = await self.inner.handle_async_request(outgoing) await self._authorize() - if response.is_redirect or response.status_code in {401, 403}: - raise MCPSourceError("denied") + _check_response(request.method, response) # Reject compression so the wire budget bounds decoded protocol bytes. if response.headers.get("content-encoding", "identity") != "identity": raise MCPSourceError("protocol") @@ -891,9 +915,10 @@ async def action(session: ClientSession) -> MCPPage: if not isinstance(rows, list): raise MCPSourceError("schema") items = [self._evidence(row, mapping) for row in rows] + next_cursor = _path(result, mapping.next_cursor_path, _MISSING_CURSOR, optional=True) return self._page( items, - _path(result, mapping.next_cursor_path, None, optional=True), + None if next_cursor is _MISSING_CURSOR else _string(next_cursor), ("search", query), ) diff --git a/tests/unit/test_mcp_source_cancellation.py b/tests/unit/test_mcp_source_cancellation.py index 32406b642b..612cd44b77 100644 --- a/tests/unit/test_mcp_source_cancellation.py +++ b/tests/unit/test_mcp_source_cancellation.py @@ -853,6 +853,11 @@ async def aclose(self) -> None: @dataclass class StateRaceFixture(HTTPFixture): pause_at: str = "handoff" + background_status: int = 403 + background_content_type: str = "text/event-stream" + read_status: int = 200 + delete_status: int = 204 + deletes: int = 0 hold_refusal: bool = False refusal_release: asyncio.Event = field(default_factory=asyncio.Event) armed: bool = False @@ -874,9 +879,17 @@ async def reply(self, request: httpx.Request) -> httpx.Response: if self.hold_refusal else RefusalStream(self.denied) ) - return httpx.Response(403, stream=stream) + return httpx.Response( + self.background_status, + stream=stream, + headers={ + "content-type": self.background_content_type, + "x-private-upstream": "synthetic-private-header", + }, + ) if request.method == "DELETE": - return httpx.Response(204) + self.deletes += 1 + return httpx.Response(self.delete_status) response = await super().reply(request) method = json.loads(await request.aread())["method"] if method == "initialize": @@ -885,6 +898,7 @@ async def reply(self, request: httpx.Request) -> httpx.Response: self.initialized.set() elif method in {"resources/read", "tools/call"}: self.acquired = True + response.status_code = self.read_status return response async def authority(self) -> None: @@ -1142,3 +1156,236 @@ async def test_state_guard_refusal_poison_precedes_held_response_cleanup( if not task.done(): task.cancel() await asyncio.gather(task, return_exceptions=True) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["resources", "tools"]) +@pytest.mark.parametrize("operation", ["discover", "read"]) +@pytest.mark.parametrize( + "status,media", + [ + (404, "text/event-stream"), + (500, "text/event-stream"), + (429, "text/event-stream"), + (200, "application/json"), + (204, "text/event-stream"), + ], +) +async def test_status_cursor_background_failure_poison_precedes_drain( + monkeypatch: pytest.MonkeyPatch, kind: str, operation: str, status: int, media: str +) -> None: + loop = asyncio.get_running_loop() + clock = ManualClock(t=loop.time()) + monkeypatch.setattr(loop, "time", clock.monotonic) + monkeypatch.setattr(source, "pinned_target", pin) + fixture = StateRaceFixture( + kind, + block=False, + phase="sse", + pause_at="operation" if operation == "discover" else "chunk", + hold_refusal=True, + background_status=status, + background_content_type=media, + ) + config = fixture.config() + config = replace(config, limits=replace(config.limits, request_seconds=0.3)) + neighbor = HTTPFixture(kind, block=False, phase="sse") + async with ( + source.MCPSourceClient( + config, None, validate_access=fixture.authority, _transport=FixtureTransport(fixture) + ) as remote, + neighbor.client() as independent, + ): + await asyncio.wait_for(fixture.initialized.wait(), 1) + await asyncio.wait_for(fixture.get_started.wait(), 1) + fixture.armed = True + task = asyncio.create_task( + remote.discover() if operation == "discover" else remote.read(IDENTITY) + ) + fixture.caller = task + try: + await asyncio.wait_for(fixture.denied.wait(), 1) + assert remote._transport is not None and remote._transport.failure == "protocol" + fixture.resume.set() + clock.advance(0.4) + for _ in range(100): + await asyncio.sleep(0) + if remote._closing: + break + assert remote._closing and not task.done() + assert not fixture.pool_closed.is_set() + evidence = await independent.read(IDENTITY) + assert evidence.receipt is not None and evidence.text == TEXT + fixture.refusal_release.set() + with pytest.raises(source.MCPSourceError) as refusal: + await task + assert str(refusal.value) == "MCP source protocol" + assert fixture.pool_closed.is_set() + if operation == "read": + assert fixture.stopped.is_set() + requests = fixture.requests + with pytest.raises(source.MCPSourceError, match="protocol"): + await remote.discover() + assert fixture.requests == requests + assert remote._transport.requests <= config.limits.max_requests + assert remote._transport.failure == "protocol" + finally: + fixture.resume.set() + fixture.refusal_release.set() + if not task.done(): + task.cancel() + await asyncio.gather(task, return_exceptions=True) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["resources", "tools"]) +async def test_status_cursor_optional_get_and_delete_405_are_allowed( + monkeypatch: pytest.MonkeyPatch, kind: str +) -> None: + monkeypatch.setattr(source, "pinned_target", pin) + fixture = StateRaceFixture( + kind, block=False, phase="sse", background_status=405, delete_status=405 + ) + async with source.MCPSourceClient( + fixture.config(), + None, + validate_access=fixture.authority, + _transport=FixtureTransport(fixture), + ) as remote: + fixture.checking.set() + await asyncio.wait_for(fixture.denied.wait(), 1) + assert remote._transport is not None and remote._transport.failure is None + discovery = await remote.discover() + assert discovery.resources is (kind == "resources") + evidence = await remote.read(IDENTITY) + assert evidence.receipt is not None and evidence.text == TEXT + assert fixture.deletes == 1 + assert fixture.pool_closed.is_set() and fixture.pool_closes == 1 + assert remote._transport.failure is None + + +@pytest.mark.asyncio +@pytest.mark.parametrize("status", [405, 201, 204, 206]) +async def test_status_cursor_post_unexpected_status_is_terminal_protocol( + monkeypatch: pytest.MonkeyPatch, status: int +) -> None: + monkeypatch.setattr(source, "pinned_target", pin) + fixture = StateRaceFixture( + "resources", block=False, phase="sse", background_status=405, read_status=status + ) + config = fixture.config() + config = replace(config, limits=replace(config.limits, request_seconds=0.1)) + async with source.MCPSourceClient( + config, None, validate_access=fixture.authority, _transport=FixtureTransport(fixture) + ) as remote: + fixture.checking.set() + await asyncio.wait_for(fixture.denied.wait(), 1) + with pytest.raises(source.MCPSourceError, match="protocol"): + await remote.read(IDENTITY) + assert remote._transport is not None and remote._transport.failure == "protocol" + assert fixture.stopped.is_set() and fixture.pool_closed.is_set() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("status", [202, 404, 500]) +async def test_status_cursor_delete_unexpected_status_is_not_silently_ignored( + monkeypatch: pytest.MonkeyPatch, status: int +) -> None: + monkeypatch.setattr(source, "pinned_target", pin) + fixture = StateRaceFixture( + "resources", block=False, phase="sse", background_status=405, delete_status=status + ) + with pytest.raises(source.MCPSourceError, match="protocol"): + async with source.MCPSourceClient( + fixture.config(), + None, + validate_access=fixture.authority, + _transport=FixtureTransport(fixture), + ) as remote: + fixture.checking.set() + await asyncio.wait_for(fixture.denied.wait(), 1) + evidence = await remote.read(IDENTITY) + assert evidence.receipt is not None + assert fixture.deletes == 1 and fixture.pool_closed.is_set() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["resources", "tools"]) +async def test_status_cursor_cancellation_identity_survives_held_http_500( + monkeypatch: pytest.MonkeyPatch, kind: str +) -> None: + monkeypatch.setattr(source, "pinned_target", pin) + fixture = StateRaceFixture( + kind, block=False, phase="sse", pause_at="chunk", background_status=500, hold_refusal=True + ) + async with source.MCPSourceClient( + fixture.config(), + None, + validate_access=fixture.authority, + _transport=FixtureTransport(fixture), + ) as remote: + await asyncio.wait_for(fixture.initialized.wait(), 1) + await asyncio.wait_for(fixture.get_started.wait(), 1) + fixture.armed = True + task = asyncio.create_task(remote.read(IDENTITY)) + fixture.caller = task + try: + await asyncio.wait_for(fixture.denied.wait(), 1) + assert remote._transport is not None and remote._transport.failure == "protocol" + task.cancel("original HTTP status cancellation") + await asyncio.wait_for(fixture.stopped.wait(), 1) + task.cancel("repeated HTTP status cancellation") + await asyncio.sleep(0) + assert not task.done() + assert not fixture.pool_closed.is_set() + fixture.refusal_release.set() + with pytest.raises(asyncio.CancelledError) as cancelled: + await task + assert cancelled.value.args == ("original HTTP status cancellation",) + assert fixture.pool_closed.is_set() + assert remote._transport.failure == "protocol" + finally: + fixture.resume.set() + fixture.refusal_release.set() + if not task.done(): + task.cancel() + await asyncio.gather(task, return_exceptions=True) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["resources", "tools"]) +async def test_status_cursor_valid_background_sse_keeps_normal_receipt( + monkeypatch: pytest.MonkeyPatch, kind: str +) -> None: + monkeypatch.setattr(source, "pinned_target", pin) + fixture = StateRaceFixture(kind, block=False, phase="sse") + streaming, closed = asyncio.Event(), asyncio.Event() + + class Background(httpx.AsyncByteStream): + async def __aiter__(self) -> AsyncIterator[bytes]: + streaming.set() + yield b": keepalive\n\n" + await asyncio.Future[None]() + + async def aclose(self) -> None: + closed.set() + + async def reply(request: httpx.Request) -> httpx.Response: + if request.method == "GET": + return httpx.Response( + 200, + stream=Background(), + headers={"content-type": "text/event-stream; charset=utf-8"}, + ) + return await fixture.reply(request) + + transport = FixtureTransport(fixture) + transport.handler = reply + async with source.MCPSourceClient( + fixture.config(), None, validate_access=fixture.authority, _transport=transport + ) as remote: + await asyncio.wait_for(streaming.wait(), 1) + evidence = await remote.read(IDENTITY) + assert evidence.text == TEXT and evidence.receipt is not None + assert remote._transport is not None and remote._transport.failure is None + assert closed.is_set() and fixture.pool_closed.is_set() diff --git a/tests/unit/test_mcp_source_client.py b/tests/unit/test_mcp_source_client.py index 9d1bd5b034..650f269402 100644 --- a/tests/unit/test_mcp_source_client.py +++ b/tests/unit/test_mcp_source_client.py @@ -132,7 +132,11 @@ async def list_tools(ctx: Any, params: Any) -> types.ListToolsResult: read.input_schema["properties"]["danger"] = dict(STRING) return types.ListToolsResult( tools=[ - types.Tool(name="find", inputSchema=INPUT_SCHEMA, outputSchema=SEARCH_SCHEMA), + types.Tool( + name="find", + inputSchema=INPUT_SCHEMA, + outputSchema=state.get("search_output_schema", SEARCH_SCHEMA), + ), types.Tool( name="fetch", inputSchema=read.input_schema, outputSchema=DOCUMENT_SCHEMA ), @@ -154,6 +158,8 @@ async def call_tool(ctx: Any, params: Any) -> types.CallToolResult: "text": state["text"], } result = {"documents": [document]} if params.name == "find" else document + if params.name == "find": + result.update(state.get("search_extra", {})) if params.name == "find" and state.get("paginate") and "cursor" not in params.arguments: result["cursor"] = state.get("page_cursor", "page-2") return types.CallToolResult(content=[], structuredContent=result) @@ -694,7 +700,7 @@ async def resolve(host: str, **kw: Any) -> tuple[str, str]: async def reply(request: httpx.Request) -> httpx.Response: requests.append(request) - return httpx.Response(200, text="synthetic") + return httpx.Response(200, text="synthetic", headers={"content-type": "text/event-stream"}) monkeypatch.setattr(webhooks, "vet_host", resolve) transport = source._PinnedTransport( @@ -907,3 +913,87 @@ async def authority() -> None: with pytest.raises(source.MCPSourceError, match=code): await remote.search("beta") assert len(state["requests"]) == before + + +@pytest.mark.asyncio +@pytest.mark.parametrize("present", [False, True]) +async def test_status_cursor_null_schema_distinguishes_presence_from_omission( + monkeypatch: pytest.MonkeyPatch, present: bool +) -> None: + conf = paginated_config() + assert conf.search is not None + conf.search.output_schema["properties"]["cursor"] = {"type": "null"} + async with synthetic_server(monkeypatch, tools=True) as state, client(conf) as remote: + state["search_output_schema"] = conf.search.output_schema + state["paginate"], state["page_cursor"] = present, None + if present: + with pytest.raises(source.MCPSourceError, match="schema"): + await remote.search("alpha") + assert state["calls"][-1][0] == "find" + assert remote._owner_task is not None and remote._owner_task.done() + requests = len(state["requests"]) + with pytest.raises(source.MCPSourceError, match="schema"): + await remote.search("beta") + assert len(state["requests"]) == requests + else: + final = await remote.search("alpha") + assert final.complete and final.next_cursor is None + assert all(item.receipt is None for item in final.items) + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "cursor,schema", + [ + (False, {"type": "boolean"}), + (17, {"type": "integer"}), + ([], {"type": "array", "maxItems": 1, "items": STRING}), + ({}, {"type": "object", "additionalProperties": False}), + ("", STRING), + ], +) +async def test_status_cursor_schema_admitted_invalid_values_refuse( + monkeypatch: pytest.MonkeyPatch, cursor: Any, schema: dict[str, Any] +) -> None: + conf = paginated_config() + assert conf.search is not None + conf.search.output_schema["properties"]["cursor"] = schema + async with synthetic_server(monkeypatch, tools=True) as state, client(conf) as remote: + state["search_output_schema"] = conf.search.output_schema + state["paginate"], state["page_cursor"] = True, cursor + with pytest.raises(source.MCPSourceError, match="schema"): + await remote.search("alpha") + + +@pytest.mark.asyncio +@pytest.mark.parametrize("parent,schema", [(None, {"type": "null"}), (17, {"type": "integer"})]) +async def test_status_cursor_malformed_nested_parent_never_counts_as_missing( + monkeypatch: pytest.MonkeyPatch, parent: Any, schema: dict[str, Any] +) -> None: + conf = paginated_config() + assert conf.search is not None + output = copy.deepcopy(conf.search.output_schema) + output["properties"]["page"] = schema + conf = replace( + conf, search=replace(conf.search, output_schema=output, next_cursor_path=("page", "cursor")) + ) + async with synthetic_server(monkeypatch, tools=True) as state, client(conf) as remote: + state["search_output_schema"] = output + state["search_extra"] = {"page": parent} + with pytest.raises(source.MCPSourceError, match="schema"): + await remote.search("alpha") + + +@pytest.mark.asyncio +async def test_status_cursor_schema_admitted_string_still_has_normalized_bound( + monkeypatch: pytest.MonkeyPatch, +) -> None: + conf = paginated_config() + assert conf.search is not None + conf.search.output_schema["properties"]["cursor"] = {"type": "string", "maxLength": 4096} + async with synthetic_server(monkeypatch, tools=True) as state, client(conf) as remote: + state["search_output_schema"] = conf.search.output_schema + state["paginate"], state["page_cursor"] = True, "x" * 2049 + with pytest.raises(source.MCPSourceError, match="limit"): + await remote.search("alpha") + assert state["calls"][-1][0] == "find" From 44e976444b0f7878ff31f28a8dac91075d7897c1 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Mon, 23 Nov 2026 00:02:39 +0000 Subject: [PATCH 07/15] Bind MCP credential origins to the dispatched hostname Use the HTTP client normalization for audience and endpoint checks and refuse pin helpers that change the authorized Host or TLS name. Signed-off-by: zlareb1 --- docs/architecture/mcp-source-client.md | 4 +- server/clients/mcp_source.py | 22 ++- tests/unit/test_mcp_source_client.py | 225 +++++++++++++++++++++++++ 3 files changed, 244 insertions(+), 7 deletions(-) diff --git a/docs/architecture/mcp-source-client.md b/docs/architecture/mcp-source-client.md index 3f86da29c8..ff25e330fc 100644 --- a/docs/architecture/mcp-source-client.md +++ b/docs/architecture/mcp-source-client.md @@ -27,7 +27,9 @@ and approving the endpoint through operator policy before constructing a client. The transport uses `server/core/webhooks.py` (`pinned_target`) to validate public DNS addresses and preserve the configured Host header and TLS server name while connecting -to a validated address. Proxy environment variables do not select another route. +to a validated address. Endpoint and credential-origin checks use the same HTTPX ASCII +hostname as dispatch. The pinned Host header and TLS server name must match it exactly; +trailing-dot aliases remain distinct. Proxy environment variables do not select another route. Requests outside the configured endpoint are refused. A server response cannot select a different server, credential or connection. diff --git a/server/clients/mcp_source.py b/server/clients/mcp_source.py index 58f4df3e4c..0135aee475 100644 --- a/server/clients/mcp_source.py +++ b/server/clients/mcp_source.py @@ -225,9 +225,9 @@ def _string(value: Any, maximum: int = 2048, *, empty: bool = False) -> str: return value -def _origin(url: str) -> tuple[str, str, int]: - _string(url, 2048) +def _endpoint_url(url: str) -> httpx.URL: try: + _string(url, 2048) parts = urlsplit(url) if ( parts.scheme != "https" @@ -243,11 +243,17 @@ def _origin(url: str) -> tuple[str, str, int]: or any(p in (".", "..") for p in parts.path.split("/")) ): raise MCPSourceError("config") - return parts.scheme, parts.hostname.encode("idna").decode().lower(), parts.port or 443 - except (ValueError, UnicodeError): + # HTTPX must authorize the same ASCII hostname that it sends on the wire. + return httpx.URL(url) + except (httpx.InvalidURL, ValueError, UnicodeError): raise MCPSourceError("config") from None +def _origin(url: str) -> tuple[str, str, int]: + endpoint = _endpoint_url(url) + return endpoint.scheme, endpoint.raw_host.decode("ascii"), endpoint.port or 443 + + # This subset has no references, regular expressions or combinatorial validators. _SCHEMA_KEYS = frozenset({"type", "enum", "const", "title", "description"}) _SCHEMA_TYPE_KEYS = { @@ -365,7 +371,7 @@ def __init__( *, transport: httpx.AsyncBaseTransport | None = None, ) -> None: - self.endpoint = httpx.URL(config.endpoint) + self.endpoint = _endpoint_url(config.endpoint) self.credential, self.deadline, self.limits = credential, deadline, config.limits self.validate_access = validate_access self.inner = ( @@ -411,7 +417,11 @@ async def _handle(self, request: httpx.Request) -> httpx.Response: refusal, pinned, host, sni = await pinned_target( str(self.endpoint), schemes=("https",) ) - if refusal or not host or not sni: + if ( + refusal + or host != self.endpoint.netloc.decode("ascii") + or sni != self.endpoint.raw_host.decode("ascii") + ): raise MCPSourceError("denied") self.target = pinned, host, sni pinned, host, sni = self.target diff --git a/tests/unit/test_mcp_source_client.py b/tests/unit/test_mcp_source_client.py index 650f269402..4b1858b55e 100644 --- a/tests/unit/test_mcp_source_client.py +++ b/tests/unit/test_mcp_source_client.py @@ -997,3 +997,228 @@ async def test_status_cursor_schema_admitted_string_still_has_normalized_bound( with pytest.raises(source.MCPSourceError, match="limit"): await remote.search("alpha") assert state["calls"][-1][0] == "find" + + +@pytest.mark.parametrize( + "endpoint,audience", + [ + ("https://faß.example/mcp", "https://fass.example/mcp"), + ("https://fass.example/mcp", "https://faß.example/mcp"), + ("https://ς.example/mcp", "https://σ.example/mcp"), + ("https://σ.example/mcp", "https://ς.example/mcp"), + ("https://xn--fa-hia.example/mcp", "https://fass.example/mcp"), + ("https://source.example/mcp", "https://other.example/mcp"), + ("https://source.example./mcp", "https://source.example/mcp"), + ("https://source.example/mcp", "https://source.example./mcp"), + ("https://source.example:444/mcp", "https://source.example:443/mcp"), + ("https://[2001:db8::1]/mcp", "https://[2001:db8::2]/mcp"), + ("https://[2001:0db8:0:0::1]/mcp", "https://[2001:db8::1]/mcp"), + ], +) +@pytest.mark.asyncio +async def test_origin_wire_distinct_hosts_refuse_before_pin_or_dispatch( + monkeypatch: pytest.MonkeyPatch, endpoint: str, audience: str +) -> None: + calls = [] + + async def pin(*args: Any, **kw: Any) -> tuple[str, str, str, str]: + calls.append("pin") + raise AssertionError("invalid binding reached DNS pin") + + async def reply(request: httpx.Request) -> httpx.Response: + calls.append("http") + raise AssertionError("invalid binding reached HTTP") + + monkeypatch.setattr(source, "pinned_target", pin) + async with httpx.MockTransport(reply) as transport: + with pytest.raises(source.MCPSourceError, match="^MCP source config$") as refused: + source.MCPSourceClient( + source.MCPSourceConfig(endpoint, audience), + source.MCPBearer(SECRET, audience), + validate_access=access, + _transport=transport, + ) + assert SECRET not in str(refused.value) + assert calls == [] + + +@pytest.mark.parametrize( + "endpoint,audience,ascii_host,host_header", + [ + (ENDPOINT, ENDPOINT, "source.example", "source.example"), + ("https://SOURCE.EXAMPLE:443/mcp", ENDPOINT, "source.example", "source.example"), + ( + "https://faß.example/mcp", + "https://xn--fa-hia.example/mcp", + "xn--fa-hia.example", + "xn--fa-hia.example", + ), + ( + "https://XN--FA-HIA.EXAMPLE/mcp", + "https://faß.example/mcp", + "xn--fa-hia.example", + "xn--fa-hia.example", + ), + ( + "https://ς.example/mcp", + "https://xn--3xa.example/mcp", + "xn--3xa.example", + "xn--3xa.example", + ), + ( + "https://σ.example/mcp", + "https://XN--4XA.EXAMPLE/mcp", + "xn--4xa.example", + "xn--4xa.example", + ), + ( + "https://BÜCHER.example/mcp", + "https://xn--bcher-kva.example/mcp", + "xn--bcher-kva.example", + "xn--bcher-kva.example", + ), + ( + "https://source.example:8443/mcp", + "https://SOURCE.EXAMPLE:8443/profile", + "source.example", + "source.example:8443", + ), + ( + "https://[2001:db8::1]:443/mcp", + "https://[2001:db8::1]/mcp", + "2001:db8::1", + "[2001:db8::1]", + ), + ], +) +@pytest.mark.asyncio +async def test_origin_canonical_binding_matches_pin_and_actual_dispatch( + monkeypatch: pytest.MonkeyPatch, + endpoint: str, + audience: str, + ascii_host: str, + host_header: str, +) -> None: + from server.core import webhooks + + pins = [] + resolutions = [] + requests = [] + existing_pin = source.pinned_target + + async def resolve(host: str, **kw: Any) -> tuple[str, str]: + resolutions.append((host, kw)) + return "", "93.184.216.34" + + async def pin(url: str, **kw: Any) -> tuple[str, str, str, str]: + pins.append(url) + assert httpx.URL(url).raw_host == ascii_host.encode("ascii") + assert url.isascii() + return await existing_pin(url, **kw) + + async def reply(request: httpx.Request) -> httpx.Response: + requests.append(request) + assert pins and resolutions + assert request.headers["host"] == host_header + assert request.extensions["sni_hostname"] == ascii_host + assert request.headers["authorization"] == "Bearer " + SECRET + assert request.url.raw_host == b"93.184.216.34" + return httpx.Response( + 200, headers={"content-type": "text/event-stream"}, content=b": ok\n\n" + ) + + monkeypatch.setattr(webhooks, "vet_host", resolve) + monkeypatch.setattr(source, "pinned_target", pin) + conf = source.MCPSourceConfig(endpoint, audience) + credential = source.MCPBearer(SECRET, audience) + admitted = source.MCPSourceClient(conf, credential, validate_access=access) + assert source._origin(endpoint) == ("https", ascii_host, httpx.URL(endpoint).port or 443) + transport = source._PinnedTransport( + admitted.config, + admitted.credential, + asyncio.get_running_loop().time() + 5, + access, + transport=httpx.MockTransport(reply), + ) + async with httpx.AsyncClient(transport=transport, trust_env=False) as http: + response = await http.get(endpoint) + assert response.content == b": ok\n\n" + assert pins == [str(httpx.URL(endpoint))] + assert resolutions == [(ascii_host, {"allow_private": False, "name_address": False})] + assert len(requests) == 1 + assert admitted.config.endpoint == endpoint + assert admitted.config.bearer_audience == audience + + +@pytest.mark.parametrize( + "endpoint", + [ + "https://\ud800.example/mcp", + "https://☃.example/mcp", + "https://[broken]/mcp", + "https://source.example:bad/mcp", + "https://source.example:65536/mcp", + "https://source.example:0/mcp", + "https://@source.example/mcp", + "https://source.example/mcp?private", + "https://source.example/mcp#private", + "https://source.example/./mcp", + "https://source.example/%2e/mcp", + "https://source.example/white space", + "https://source.example/\tprivate", + "https://source.example/\x7fprivate", + ], +) +def test_origin_bad_urls_have_only_fixed_private_failures(endpoint: str) -> None: + with pytest.raises(source.MCPSourceError) as refused: + source.MCPSourceClient( + source.MCPSourceConfig(endpoint, endpoint), + source.MCPBearer(SECRET, endpoint), + validate_access=access, + ) + assert str(refused.value) in {"MCP source " + code for code in ("config", "schema", "limit")} + assert SECRET not in str(refused.value) + + +@pytest.mark.parametrize( + "endpoint,pinned_host,pinned_sni", + [ + (ENDPOINT, "other.example", "source.example"), + (ENDPOINT, "source.example", "other.example"), + (ENDPOINT, "source.example:444", "source.example"), + ("https://source.example./mcp", "source.example", "source.example"), + ], +) +@pytest.mark.asyncio +async def test_origin_pin_alias_refuses_before_credential_dispatch( + monkeypatch: pytest.MonkeyPatch, endpoint: str, pinned_host: str, pinned_sni: str +) -> None: + requests = [] + pins = [] + + async def pin(url: str, **kw: Any) -> tuple[str, str, str, str]: + pins.append(url) + return "", "https://93.184.216.34/mcp", pinned_host, pinned_sni + + async def reply(request: httpx.Request) -> httpx.Response: + requests.append(request) + return httpx.Response(200, headers={"content-type": "text/event-stream"}) + + monkeypatch.setattr(source, "pinned_target", pin) + conf = source.MCPSourceConfig(endpoint, endpoint) + credential = source.MCPBearer(SECRET, endpoint) + admitted = source.MCPSourceClient(conf, credential, validate_access=access) + assert source._origin(endpoint)[1] == httpx.URL(endpoint).raw_host.decode("ascii") + transport = source._PinnedTransport( + admitted.config, + admitted.credential, + asyncio.get_running_loop().time() + 5, + access, + transport=httpx.MockTransport(reply), + ) + async with httpx.AsyncClient(transport=transport, trust_env=False) as http: + with pytest.raises(source.MCPSourceError, match="^MCP source denied$"): + await http.get(endpoint) + assert pins == [str(httpx.URL(endpoint))] + assert requests == [] + assert transport.failure == "denied" From 655ac4fa1ca1643e9a586b04317a4e276fb10bd1 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Mon, 23 Nov 2026 04:37:28 +0000 Subject: [PATCH 08/15] Cancel queued notifications during normal MCP shutdown Keep foreground closed-session calls terminal while joining pending SDK notification work. Cover discovery-only resource and action-only servers without extra RPCs. Signed-off-by: zlareb1 --- server/clients/mcp_source.py | 15 ++++++++++++++- tests/unit/test_mcp_source_client.py | 16 ++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/server/clients/mcp_source.py b/server/clients/mcp_source.py index 0135aee475..26233f9389 100644 --- a/server/clients/mcp_source.py +++ b/server/clients/mcp_source.py @@ -621,6 +621,19 @@ async def _authorize(self) -> None: await self.validate_access() self._check_state() + async def _transport_authorize(self) -> None: + try: + await self._authorize() + except MCPSourceError as error: + if ( + error.code == "closed" + and self._closing + and asyncio.current_task() is not self._owner_task + ): + # Pending SDK notifications stop without poisoning expected shutdown. + raise asyncio.CancelledError from None + raise + async def __aenter__(self) -> MCPSourceClient: if self._owner_task is not None or self._deadline: raise MCPSourceError("closed") @@ -679,7 +692,7 @@ async def _initialize(self, stack: AsyncExitStack) -> None: self._config, self.credential, self._deadline, - self._authorize, + self._transport_authorize, transport=self._test_transport, ) self._transport = transport diff --git a/tests/unit/test_mcp_source_client.py b/tests/unit/test_mcp_source_client.py index 4b1858b55e..3e50406a2f 100644 --- a/tests/unit/test_mcp_source_client.py +++ b/tests/unit/test_mcp_source_client.py @@ -1222,3 +1222,19 @@ async def reply(request: httpx.Request) -> httpx.Response: assert pins == [str(httpx.URL(endpoint))] assert requests == [] assert transport.failure == "denied" + + +@pytest.mark.asyncio +@pytest.mark.parametrize("actions_only", [False, True]) +async def test_discovery_without_an_approved_tool_rpc_closes_cleanly( + monkeypatch: pytest.MonkeyPatch, actions_only: bool +) -> None: + async with synthetic_server(monkeypatch, tools=actions_only) as state: + opened = client() + async with opened: + discovered = await opened.discover() + assert discovered.resources is (not actions_only) + assert discovered.tools == () + assert state["calls"] == [] + assert opened._owner_task is not None and opened._owner_task.done() + assert opened._transport is not None and opened._transport.failure is None From b1371b71b4948c93a2d8d20da0e7dc4b5ea02890 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Wed, 25 Nov 2026 10:32:00 +0000 Subject: [PATCH 09/15] MCP callers join a session that is already closing A session deadline can start closing the SDK and HTTP pool before a caller exits or tries another read. Joining the existing teardown keeps that caller from cancelling the pool finalizer and losing the timeout. Signed-off-by: zlareb1 --- server/clients/mcp_source.py | 20 ++++--- tests/unit/test_mcp_source_cancellation.py | 63 ++++++++++++++++++++++ 2 files changed, 76 insertions(+), 7 deletions(-) diff --git a/server/clients/mcp_source.py b/server/clients/mcp_source.py index 26233f9389..9797287d47 100644 --- a/server/clients/mcp_source.py +++ b/server/clients/mcp_source.py @@ -562,6 +562,7 @@ def __init__( self._owner_task: asyncio.Task[None] | None = None self._ready: asyncio.Future[None] | None = None self._closing = False + self._draining = False self._owner_failure: ErrorCode | None = None self._session: ClientSession | None = None self._transport: _PinnedTransport | None = None @@ -667,12 +668,15 @@ async def _serve_session(self) -> None: with private_work(): try: async with AsyncExitStack() as stack: - async with asyncio.timeout_at(self._deadline): - await self._initialize(stack) - assert self._ready is not None - if not self._ready.done(): - self._ready.set_result(None) - await asyncio.Future[None]() + try: + async with asyncio.timeout_at(self._deadline): + await self._initialize(stack) + assert self._ready is not None + if not self._ready.done(): + self._ready.set_result(None) + await asyncio.Future[None]() + finally: + self._draining = True except ( Exception, # noqa: BLE001 — SDK lifecycle failures must remain fixed codes asyncio.CancelledError, @@ -726,7 +730,9 @@ async def _close(self) -> None: return if not self._closing: self._closing = True - owner.cancel() + # A deadline can start unwinding the SDK and HTTP pool before the caller joins. + if not self._draining: + owner.cancel() interrupted: asyncio.CancelledError | None = None while not owner.done(): try: diff --git a/tests/unit/test_mcp_source_cancellation.py b/tests/unit/test_mcp_source_cancellation.py index 612cd44b77..b92e918c65 100644 --- a/tests/unit/test_mcp_source_cancellation.py +++ b/tests/unit/test_mcp_source_cancellation.py @@ -345,6 +345,69 @@ async def test_idle_session_deadline_closes_pool_before_context_exit( assert fixture.pool_closes == 1 +@pytest.mark.asyncio +@pytest.mark.parametrize("read_after_deadline", [False, True], ids=["exit", "read"]) +async def test_caller_joins_pool_close_started_by_deadline( + monkeypatch: pytest.MonkeyPatch, read_after_deadline: bool +) -> None: + loop = asyncio.get_running_loop() + clock = ManualClock(t=loop.time()) + monkeypatch.setattr(loop, "time", clock.monotonic) + monkeypatch.setattr(source, "pinned_target", pin) + fixture = HTTPFixture("resources", block=False) + pool_closing = asyncio.Event() + release_pool = asyncio.Event() + proceed = asyncio.Event() + joining = asyncio.Event() + ready = asyncio.Event() + + class HeldPool(FixtureTransport): + async def aclose(self) -> None: + pool_closing.set() + await release_pool.wait() + await super().aclose() + + async def use_client() -> None: + async with source.MCPSourceClient( + fixture.config(), None, validate_access=access, _transport=HeldPool(fixture) + ) as client: + ready.set() + await proceed.wait() + joining.set() + if read_after_deadline: + with pytest.raises(source.MCPSourceError) as refusal: + await client.read(IDENTITY) + assert refusal.value.code == "timeout" + + task = asyncio.create_task(use_client()) + try: + await ready.wait() + clock.advance(6) + for _ in range(100): + if pool_closing.is_set(): + break + await asyncio.sleep(0) + assert pool_closing.is_set(), "the deadline did not start closing the pool" + proceed.set() + await joining.wait() + for _ in range(10): + await asyncio.sleep(0) + assert not task.done(), "the caller returned before the pool closed" + release_pool.set() + if read_after_deadline: + await task + else: + with pytest.raises(source.MCPSourceError) as refusal: + await task + assert refusal.value.code == "timeout" + assert fixture.pool_closes == 1 + assert fixture.reads == 0 + finally: + proceed.set() + release_pool.set() + await asyncio.gather(task, return_exceptions=True) + + class HeartbeatStream(ReadStream): async def __aiter__(self) -> AsyncIterator[bytes]: fixture = self.fixture From 1f30d8b1e8eaf02f083663fb7b2dc05dd02c6262 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Wed, 25 Nov 2026 10:42:59 +0000 Subject: [PATCH 10/15] Send the negotiated MCP protocol version as a header string The SDK types the negotiated version as a string or integer. Session termination sends that value in an HTTP header, which accepts text. Signed-off-by: zlareb1 --- server/clients/mcp_source.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/clients/mcp_source.py b/server/clients/mcp_source.py index e3c465428a..b4ea77ffee 100644 --- a/server/clients/mcp_source.py +++ b/server/clients/mcp_source.py @@ -739,7 +739,7 @@ async def terminate() -> None: ) ) result = await self._session.initialize() - protocol_version = result.protocolVersion + protocol_version = str(result.protocolVersion) self._discovery = MCPDiscovery(result.capabilities.resources is not None, ()) await self._authorize() From 30593c87b32640bbda43ad65042fd5f81b39f052 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Thu, 26 Nov 2026 15:48:25 +0000 Subject: [PATCH 11/15] Pin outbound MCP reads to the approved configuration A catalog change invalidates discovery, and a rejected read keeps its original failure through session cleanup. Validate tool mappings before opening a session so the read receipt can identify the approved configuration. Signed-off-by: zlareb1 --- server/clients/mcp_source.py | 149 ++++++++++++--------- tests/unit/test_mcp_source_cancellation.py | 120 ++++++++++++++++- tests/unit/test_mcp_source_client.py | 71 +++++++++- 3 files changed, 271 insertions(+), 69 deletions(-) diff --git a/server/clients/mcp_source.py b/server/clients/mcp_source.py index b4ea77ffee..16318835b5 100644 --- a/server/clients/mcp_source.py +++ b/server/clients/mcp_source.py @@ -88,7 +88,7 @@ def _guard_state(deadline: float, failure: ErrorCode | None, *, active: bool = T raise MCPSourceError("timeout") -def _check_response(method: str, response: httpx.Response) -> None: +def _check_response(method: str, response: httpx.Response, body: bytes) -> None: status = response.status_code if response.is_redirect or status in {401, 403}: raise MCPSourceError("denied") @@ -99,6 +99,8 @@ def _check_response(method: str, response: httpx.Response) -> None: raise MCPSourceError("protocol") return if method == "POST" and status == 202: + if isinstance(types.JSONRPCMessage.model_validate_json(body).root, types.JSONRPCRequest): + raise MCPSourceError("protocol") return if status != 200: raise MCPSourceError("protocol") @@ -205,13 +207,17 @@ class MCPDiscovery: tools: tuple[str, ...] -def _json(value: Any, maximum: int) -> bytes: +def _canonical_json(value: Any) -> bytes: try: - encoded = json.dumps( + return json.dumps( value, ensure_ascii=True, allow_nan=False, separators=(",", ":"), sort_keys=True ).encode() except (ValueError, TypeError, RecursionError): raise MCPSourceError("schema") from None + + +def _json(value: Any, maximum: int) -> bytes: + encoded = _canonical_json(value) if len(encoded) > maximum: raise MCPSourceError("limit") return encoded @@ -465,7 +471,7 @@ async def _handle(self, request: httpx.Request) -> httpx.Response: await self._authorize() response = await self.inner.handle_async_request(outgoing) await self._authorize() - _check_response(request.method, response) + _check_response(request.method, response, body) # Reject compression so the wire budget bounds decoded protocol bytes. if response.headers.get("content-encoding", "identity") != "identity": raise MCPSourceError("protocol") @@ -487,6 +493,42 @@ async def aclose(self) -> None: await self.inner.aclose() +def _validate_tool_mapping(mapping: MCPToolMapping) -> None: + _string(mapping.name, 128) + _string(mapping.argument_name, 128) + _schema(mapping.input_schema) + _schema(mapping.output_schema) + if mapping.input_schema["type"] != "object" or mapping.output_schema["type"] != "object": + raise MCPSourceError("config") + if not isinstance(mapping.fixed_arguments, dict): + raise MCPSourceError("config") + if mapping.cursor_argument is not None: + _string(mapping.cursor_argument, 128) + _json(mapping.fixed_arguments, 16_384) + if mapping.argument_name in mapping.fixed_arguments or ( + mapping.cursor_argument is not None + and ( + mapping.cursor_argument == mapping.argument_name + or mapping.cursor_argument in mapping.fixed_arguments + ) + ): + raise MCPSourceError("config") + for path in ( + mapping.items_path, + mapping.id_path, + mapping.title_path, + mapping.text_path, + mapping.uri_path, + mapping.revision_path, + mapping.next_cursor_path, + ): + if path is not None: + if not isinstance(path, tuple) or len(path) > 8: + raise MCPSourceError("config") + for part in path: + _string(part, 128) + + _T = TypeVar("_T") @@ -525,43 +567,10 @@ def __init__( mappings = [m for m in (self._config.search, self._config.read) if m is not None] if set(config.approved_tools) != {m.name for m in mappings}: raise MCPSourceError("config") + if self._config.read is not None and not self._config.read.text_path: + raise MCPSourceError("config") for mapping in mappings: - _string(mapping.name, 128) - _string(mapping.argument_name, 128) - _schema(mapping.input_schema) - _schema(mapping.output_schema) - if ( - mapping.input_schema["type"] != "object" - or mapping.output_schema["type"] != "object" - ): - raise MCPSourceError("config") - if not isinstance(mapping.fixed_arguments, dict): - raise MCPSourceError("config") - if mapping.cursor_argument is not None: - _string(mapping.cursor_argument, 128) - _json(mapping.fixed_arguments, 16_384) - if mapping.argument_name in mapping.fixed_arguments or ( - mapping.cursor_argument is not None - and ( - mapping.cursor_argument == mapping.argument_name - or mapping.cursor_argument in mapping.fixed_arguments - ) - ): - raise MCPSourceError("config") - for path in ( - mapping.items_path, - mapping.id_path, - mapping.title_path, - mapping.text_path, - mapping.uri_path, - mapping.revision_path, - mapping.next_cursor_path, - ): - if path is not None: - if not isinstance(path, tuple) or len(path) > 8: - raise MCPSourceError("config") - for part in path: - _string(part, 128) + _validate_tool_mapping(mapping) self._privacy: ExitStack | None = None self._owner_task: asyncio.Task[None] | None = None self._ready: asyncio.Future[None] | None = None @@ -573,7 +582,8 @@ def __init__( self._operation_failure: ErrorCode | None = None self._deadline = 0.0 self._discovery: MCPDiscovery | None = None - self._schema_changed = False + self._tools_supported = False + self._tool_catalog_generation = 0 self._pages, self._results = 0, 0 self._issued_cursors: set[tuple[tuple[str, str], str]] = set() self._used_cursors: set[tuple[tuple[str, str], str]] = set() @@ -583,6 +593,7 @@ def __init__( _string(identity) for identity in config.approved_resource_ids ) self._resource_titles: dict[str, str] = {} + self._config_sha256 = hashlib.sha256(_json(asdict(self._config), 131_072)).hexdigest() def __repr__(self) -> str: return "MCPSourceClient()" @@ -593,7 +604,7 @@ def config(self) -> MCPSourceConfig: @property def config_sha256(self) -> str: - return hashlib.sha256(_json(asdict(self._config), 131_072)).hexdigest() + return self._config_sha256 def _with_receipt( self, evidence: MCPEvidence, operation: Literal["resources/read", "tools/call"] @@ -608,11 +619,11 @@ def _with_receipt( def _check_state(self, *, require_session: bool = False) -> None: owner = self._owner_task - failure = self._operation_failure or self._owner_failure - if failure is None and self._transport is not None: - failure = self._transport.failure # The lifecycle owner may perform SDK session termination during cleanup. lifecycle = not require_session and asyncio.current_task() is owner + failure = self._operation_failure or (None if lifecycle else self._owner_failure) + if failure is None and self._transport is not None: + failure = self._transport.failure active = ( owner is not None and not owner.done() @@ -679,21 +690,28 @@ async def _serve_session(self) -> None: if not self._ready.done(): self._ready.set_result(None) await asyncio.Future[None]() + except Exception as error: + self._owner_failure = self._lifecycle_failure(error) + raise finally: self._draining = True except ( Exception, # noqa: BLE001 — SDK lifecycle failures must remain fixed codes asyncio.CancelledError, ) as error: - failure = self._transport.failure if self._transport else None - expected_close = self._closing and isinstance(error, asyncio.CancelledError) - if failure is not None or not expected_close: - self._owner_failure = failure or _error_code(error) + self._owner_failure = self._owner_failure or self._lifecycle_failure(error) if self._ready is not None and not self._ready.done(): self._ready.set_exception(MCPSourceError(self._owner_failure or "closed")) finally: self._session = None + def _lifecycle_failure(self, error: BaseException) -> ErrorCode | None: + if self._transport is not None and self._transport.failure is not None: + return self._transport.failure + if self._closing and isinstance(error, asyncio.CancelledError): + return None + return _error_code(error) + async def _initialize(self, stack: AsyncExitStack) -> None: await self._authorize() transport = _PinnedTransport( @@ -741,6 +759,7 @@ async def terminate() -> None: result = await self._session.initialize() protocol_version = str(result.protocolVersion) self._discovery = MCPDiscovery(result.capabilities.resources is not None, ()) + self._tools_supported = result.capabilities.tools is not None await self._authorize() async def _close(self) -> None: @@ -782,7 +801,7 @@ async def _message_handler(self, message: Any) -> None: if isinstance(message, types.ServerNotification) and isinstance( message.root, types.ToolListChangedNotification ): - self._schema_changed = True + self._tool_catalog_generation += 1 async def _run(self, action: Callable[[ClientSession], Awaitable[_T]]) -> _T: with private_work(): @@ -805,7 +824,11 @@ async def _execute(self, action: Callable[[ClientSession], Awaitable[_T]]) -> _T asyncio.CancelledError, ) as error: if isinstance(error, asyncio.CancelledError): - code: ErrorCode = "closed" + code: ErrorCode = ( + self._owner_failure + or (self._transport.failure if self._transport else None) + or "closed" + ) elif isinstance(error, MCPSourceError): code = error.code else: @@ -828,10 +851,15 @@ async def action(session: ClientSession) -> MCPDiscovery: cursor: str | None = None seen: set[str] = set() if approved: + if not self._tools_supported: + raise MCPSourceError("unsupported") + generation = self._tool_catalog_generation for _ in range(self._config.limits.max_pages): result = await session.list_tools( params=types.PaginatedRequestParams(cursor=cursor) ) + if generation != self._tool_catalog_generation: + raise MCPSourceError("schema") if len(result.tools) > self._config.limits.max_results: raise MCPSourceError("limit") for tool in result.tools: @@ -842,10 +870,9 @@ async def action(session: ClientSession) -> MCPDiscovery: continue for mapping in (self._config.search, self._config.read): if mapping is not None and mapping.name == tool.name: - if ( - tool.inputSchema != mapping.input_schema - or tool.outputSchema != mapping.output_schema - ): + if _canonical_json( + (tool.inputSchema, tool.outputSchema) + ) != _canonical_json((mapping.input_schema, mapping.output_schema)): raise MCPSourceError("schema") found.add(tool.name) if len(seen) > self._config.limits.max_results: @@ -860,7 +887,6 @@ async def action(session: ClientSession) -> MCPDiscovery: raise MCPSourceError("unsupported") assert self._discovery is not None self._discovery = MCPDiscovery(self._discovery.resources, tuple(sorted(found))) - self._schema_changed = False return self._discovery return await self._run(action) @@ -911,12 +937,9 @@ async def action(session: ClientSession) -> MCPPage: async def _tool( self, session: ClientSession, mapping: MCPToolMapping, value: str, cursor: str | None = None ) -> Any: - await self.discover() - if ( - self._schema_changed - or self._discovery is None - or mapping.name not in self._discovery.tools - ): + generation = self._tool_catalog_generation + discovery = await self.discover() + if generation != self._tool_catalog_generation or mapping.name not in discovery.tools: raise MCPSourceError("schema") arguments = dict(mapping.fixed_arguments) arguments[mapping.argument_name] = _string(value, 4096) @@ -926,7 +949,7 @@ async def _tool( arguments[mapping.cursor_argument] = cursor _validate(mapping.input_schema, arguments, 32_768) result = await session.call_tool(mapping.name, arguments) - if self._schema_changed: + if generation != self._tool_catalog_generation: raise MCPSourceError("schema") if result.isError or result.structuredContent is None: raise MCPSourceError("protocol") diff --git a/tests/unit/test_mcp_source_cancellation.py b/tests/unit/test_mcp_source_cancellation.py index 59eb97afe6..bf3232e1ee 100644 --- a/tests/unit/test_mcp_source_cancellation.py +++ b/tests/unit/test_mcp_source_cancellation.py @@ -165,6 +165,86 @@ async def aclose(self) -> None: self.fixture.pool_closed.set() +@pytest.mark.asyncio +@pytest.mark.parametrize("changed", [False, True], ids=["stable", "list-changed"]) +async def test_tool_catalog_invalidated_between_pages( + monkeypatch: pytest.MonkeyPatch, changed: bool +) -> None: + monkeypatch.setattr(source, "pinned_target", pin) + fixture = HTTPFixture("tools", block=False) + cursors: list[str | None] = [] + + async def reply(request: httpx.Request) -> httpx.Response: + if request.method != "POST": + return await fixture.reply(request) + payload = json.loads(request.content) + if payload["method"] != "tools/list": + return await fixture.reply(request) + cursor = payload.get("params", {}).get("cursor") + cursors.append(cursor) + if cursor is None: + response = (await fixture.reply(request)).json() + response["result"]["nextCursor"] = "page-two" + return httpx.Response(200, json=response) + final = {"jsonrpc": "2.0", "id": payload["id"], "result": {"tools": []}} + if not changed: + return httpx.Response(200, json=final) + notification = {"jsonrpc": "2.0", "method": "notifications/tools/list_changed"} + events = "".join( + f"event: message\ndata: {json.dumps(item)}\n\n" for item in (notification, final) + ) + return httpx.Response(200, text=events, headers={"content-type": "text/event-stream"}) + + transport = FixtureTransport(fixture) + transport.handler = reply + async with source.MCPSourceClient( + fixture.config(), None, validate_access=access, _transport=transport + ) as remote: + if changed: + with pytest.raises(source.MCPSourceError, match="^MCP source schema$"): + await remote.read(IDENTITY) + else: + evidence = await remote.read(IDENTITY) + assert evidence.text == TEXT and evidence.receipt is not None + assert cursors == [None, "page-two"] + assert fixture.reads == (0 if changed else 1) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("discover_only", [False, True], ids=["read", "discover"]) +async def test_tool_rpc_requires_negotiated_capability( + monkeypatch: pytest.MonkeyPatch, discover_only: bool +) -> None: + monkeypatch.setattr(source, "pinned_target", pin) + fixture = HTTPFixture("tools", block=False) + methods: list[str] = [] + + async def reply(request: httpx.Request) -> httpx.Response: + response = await fixture.reply(request) + if request.method != "POST": + return response + method = json.loads(request.content)["method"] + methods.append(method) + if method == "initialize": + payload = response.json() + payload["result"]["capabilities"] = {"resources": {}} + return httpx.Response(200, json=payload) + return response + + transport = FixtureTransport(fixture) + transport.handler = reply + async with source.MCPSourceClient( + fixture.config(), None, validate_access=access, _transport=transport + ) as remote: + with pytest.raises(source.MCPSourceError, match="^MCP source unsupported$"): + if discover_only: + await remote.discover() + else: + await remote.read(IDENTITY) + assert [method for method in methods if method.startswith("tools/")] == [] + assert fixture.reads == 0 + + @pytest.mark.asyncio @pytest.mark.parametrize("kind", ["resources", "tools"]) @pytest.mark.parametrize("phase", ["headers", "json", "sse"]) @@ -347,8 +427,9 @@ async def test_idle_session_deadline_closes_pool_before_context_exit( @pytest.mark.asyncio @pytest.mark.parametrize("read_after_deadline", [False, True], ids=["exit", "read"]) +@pytest.mark.parametrize("pool_raises", [False, True], ids=["clean-pool", "failing-pool"]) async def test_caller_joins_pool_close_started_by_deadline( - monkeypatch: pytest.MonkeyPatch, read_after_deadline: bool + monkeypatch: pytest.MonkeyPatch, read_after_deadline: bool, pool_raises: bool ) -> None: loop = asyncio.get_running_loop() clock = ManualClock(t=loop.time()) @@ -366,6 +447,8 @@ async def aclose(self) -> None: pool_closing.set() await release_pool.wait() await super().aclose() + if pool_raises: + raise RuntimeError("synthetic-private-pool-failure") async def use_client() -> None: async with source.MCPSourceClient( @@ -375,9 +458,8 @@ async def use_client() -> None: await proceed.wait() joining.set() if read_after_deadline: - with pytest.raises(source.MCPSourceError) as refusal: + with pytest.raises(source.MCPSourceError, match="^MCP source timeout$"): await client.read(IDENTITY) - assert refusal.value.code == "timeout" task = asyncio.create_task(use_client()) try: @@ -397,9 +479,8 @@ async def use_client() -> None: if read_after_deadline: await task else: - with pytest.raises(source.MCPSourceError) as refusal: + with pytest.raises(source.MCPSourceError, match="^MCP source timeout$"): await task - assert refusal.value.code == "timeout" assert fixture.pool_closes == 1 assert fixture.reads == 0 finally: @@ -516,6 +597,8 @@ async def test_background_refusal_preserves_cancel_and_joins_cleanup( assert task.cancelled() assert fixture.stopped.is_set() assert fixture.pool_closed.is_set() + with pytest.raises(source.MCPSourceError, match="denied"): + await remote.discover() finally: fixture.release.set() fixture.cleanup_release.set() @@ -1349,6 +1432,33 @@ async def test_status_cursor_post_unexpected_status_is_terminal_protocol( assert fixture.stopped.is_set() and fixture.pool_closed.is_set() +@pytest.mark.asyncio +async def test_accepted_notification_does_not_allow_accepted_read_request( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setattr(source, "pinned_target", pin) + + class AcceptedRead(HTTPFixture): + async def reply(self, request: httpx.Request) -> httpx.Response: + if ( + request.method == "POST" + and json.loads(await request.aread())["method"] == "resources/read" + ): + self.reads += 1 + return httpx.Response(202) + return await super().reply(request) + + fixture = AcceptedRead("resources") + conf = replace(fixture.config(), limits=source.MCPLimits(request_seconds=0.25)) + async with source.MCPSourceClient( + conf, None, validate_access=access, _transport=FixtureTransport(fixture) + ) as remote: + with pytest.raises(source.MCPSourceError, match="protocol"): + await remote.read(IDENTITY) + assert fixture.reads == 1 + assert fixture.pool_closes == 1 + + @pytest.mark.asyncio @pytest.mark.parametrize("status", [202, 404, 500]) async def test_status_cursor_delete_unexpected_status_is_not_silently_ignored( diff --git a/tests/unit/test_mcp_source_client.py b/tests/unit/test_mcp_source_client.py index 3e50406a2f..db65fb5a6a 100644 --- a/tests/unit/test_mcp_source_client.py +++ b/tests/unit/test_mcp_source_client.py @@ -138,7 +138,9 @@ async def list_tools(ctx: Any, params: Any) -> types.ListToolsResult: outputSchema=state.get("search_output_schema", SEARCH_SCHEMA), ), types.Tool( - name="fetch", inputSchema=read.input_schema, outputSchema=DOCUMENT_SCHEMA + name="fetch", + inputSchema=state.get("read_input_schema", read.input_schema), + outputSchema=state.get("read_output_schema", DOCUMENT_SCHEMA), ), types.Tool( name="destroy", @@ -343,6 +345,66 @@ async def test_schema_drift_is_checked_before_tool_execution( assert state["calls"] == [] +@pytest.mark.asyncio +@pytest.mark.parametrize("schema_side", ["input", "output"]) +async def test_pinned_schema_distinguishes_booleans_from_numbers( + monkeypatch: pytest.MonkeyPatch, schema_side: str +) -> None: + read = mapping("fetch") + if schema_side == "input": + pinned = read.input_schema + pinned["properties"]["flag"] = {"type": "boolean", "const": False} + read.fixed_arguments["flag"] = False + advertised = copy.deepcopy(pinned) + advertised["properties"]["flag"]["const"] = 0 + else: + pinned = read.output_schema + pinned["properties"]["flag"] = {"type": "boolean", "enum": [True]} + advertised = copy.deepcopy(pinned) + advertised["properties"]["flag"]["enum"] = [1] + conf = replace(config(tools=True, approved_resource_ids=(IDENTITY,)), read=read) + async with synthetic_server(monkeypatch, tools=True) as state, client(conf) as remote: + state[f"read_{schema_side}_schema"] = advertised + with pytest.raises(source.MCPSourceError, match="^MCP source schema$"): + await remote.read(IDENTITY) + assert state["calls"] == [] + assert [ + request["body"]["method"] + for request in state["requests"] + if request["body"] and request["body"]["method"].startswith("tools/") + ] == ["tools/list"] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("selector", [None, ()], ids=["omitted", "empty-path"]) +async def test_mapped_read_requires_text_selector( + monkeypatch: pytest.MonkeyPatch, selector: tuple[str, ...] | None +) -> None: + read = replace(mapping("fetch"), text_path=selector) + conf = replace(config(tools=True, approved_resource_ids=(IDENTITY,)), read=read) + async with synthetic_server(monkeypatch, tools=True) as state: + with pytest.raises(source.MCPSourceError, match="^MCP source config$"): + async with client(conf) as remote: + await remote.read(IDENTITY) + assert state["requests"] == [] + + +@pytest.mark.asyncio +async def test_mapped_read_receipts_selected_empty_text_and_search_can_omit_snippet( + monkeypatch: pytest.MonkeyPatch, +) -> None: + search = replace(mapping("find", search=True), text_path=None) + conf = replace(config(tools=True, approved_resource_ids=(IDENTITY,)), search=search) + async with synthetic_server(monkeypatch, tools=True) as state, client(conf) as remote: + page = await remote.search("query") + assert len(page.items) == 1 + assert page.items[0].text == "" and page.items[0].receipt is None + state["text"] = "" + evidence = await remote.read(IDENTITY) + assert evidence.text == "" and evidence.receipt is not None + assert evidence.receipt.content_sha256 == hashlib.sha256(b"").hexdigest() + + @pytest.mark.asyncio @pytest.mark.parametrize("tools", [False, True]) async def test_selected_identity_cannot_expand_through_listing( @@ -517,6 +579,13 @@ async def test_list_and_search_cannot_grant_read_authority( assert len(state["calls"]) == before +def test_configuration_must_fit_receipt_fingerprint_before_contact() -> None: + ids = tuple(f"doc://workspace/{index}/" + "x" * 1900 for index in range(73)) + assert len(client(config(approved_resource_ids=ids[:64])).config_sha256) == 64 + with pytest.raises(source.MCPSourceError, match="limit"): + client(config(approved_resource_ids=ids)) + + @pytest.mark.asyncio async def test_configuration_and_schema_snapshots_cannot_be_mutated_by_the_caller( monkeypatch: pytest.MonkeyPatch, From af3968041a3690cd4a75a722d194d5a08e9039b2 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Thu, 26 Nov 2026 16:05:26 +0000 Subject: [PATCH 12/15] Keep native MCP resource identities exact Signed-off-by: zlareb1 --- docs/architecture/mcp-source-client.md | 12 +- server/clients/mcp_source.py | 75 ++++++++--- tests/unit/test_mcp_source_cancellation.py | 142 +++++++++++++++++++++ tests/unit/test_mcp_source_client.py | 6 + 4 files changed, 216 insertions(+), 19 deletions(-) diff --git a/docs/architecture/mcp-source-client.md b/docs/architecture/mcp-source-client.md index 783a2ac1c7..1b1f790fd8 100644 --- a/docs/architecture/mcp-source-client.md +++ b/docs/architecture/mcp-source-client.md @@ -45,16 +45,19 @@ and [authorization contract](https://modelcontextprotocol.io/specification/2025- ## Read operations and capabilities Standard resource listing and reading use `resources/list` and `resources/read` when the -server advertises resources. Tool-based reads require an explicit mapping approved by -the caller's control plane. A mapping names the exact tool, its argument and result -schemas, fixed scope arguments and result selectors. Search text, a selected resource +server advertises resources. Native resource URIs must retain their exact spelling through +SDK parsing and cannot contain URL credentials. Tool-based reads require an explicit +mapping approved by the caller's control plane. A mapping names the exact tool, its +argument and result schemas, fixed scope arguments and result selectors. Searches +require a selector for the result list. Search text, a selected resource identity or a pagination cursor fills only its configured argument. It cannot replace a fixed scope argument or choose another tool. Discovery verifies the configured schemas before execution. Tool descriptions and `readOnlyHint` are untrusted descriptive fields, never approval to call a tool. Unknown capabilities remain unsupported; an action-only server supplies no usable document source. -Schema drift refuses the configured operation rather than guessing another result shape. +Schema drift refuses the configured operation. A catalog change before the final access +check completes also refuses tool discovery and mapped results. Returned resource links are evidence, never instructions to fetch an arbitrary URL. Listing and search do not expand the explicitly approved resource identities. An empty selection grants no read authority. @@ -84,6 +87,7 @@ request deadline expires while HTTP response data is still arriving. Another cli SDK scope remains independent. A known background transport failure or an expired deadline refuses discovery and result publication, including cached discovery. Unexpected HTTP status or response media types are terminal before protocol handoff. +A JSON-RPC request expects HTTP 200; a notification or response expects HTTP 202. Optional GET and DELETE responses with status 405 remain supported. Cancellation publishes no partial read evidence. The transport retains cleanup ownership while checking authority after response headers diff --git a/server/clients/mcp_source.py b/server/clients/mcp_source.py index 16318835b5..73c4551acf 100644 --- a/server/clients/mcp_source.py +++ b/server/clients/mcp_source.py @@ -24,7 +24,7 @@ from mcp import ClientSession, types from mcp.client.streamable_http import streamable_http_client from mcp.shared.exceptions import McpError -from pydantic import AnyUrl +from pydantic import AnyUrl, field_validator from referencing import Registry from referencing.exceptions import Unresolvable @@ -98,10 +98,12 @@ def _check_response(method: str, response: httpx.Response, body: bytes) -> None: if status not in {200, 204}: raise MCPSourceError("protocol") return - if method == "POST" and status == 202: - if isinstance(types.JSONRPCMessage.model_validate_json(body).root, types.JSONRPCRequest): - raise MCPSourceError("protocol") - return + if method == "POST" and status in {200, 202}: + message = types.JSONRPCMessage.model_validate_json(body).root + if not isinstance(message, types.JSONRPCRequest): + if status != 202: + raise MCPSourceError("protocol") + return if status != 200: raise MCPSourceError("protocol") media = response.headers.get("content-type", "").partition(";")[0].strip().lower() @@ -112,6 +114,30 @@ def _check_response(method: str, response: httpx.Response, body: bytes) -> None: raise MCPSourceError("protocol") +def _resource_uri(identity: str) -> AnyUrl: + uri = AnyUrl(_string(identity)) + if str(uri) != identity or uri.username is not None or uri.password is not None: + raise MCPSourceError("unsupported") + return uri + + +def _check_resource_uris(rows: Any) -> Any: + # Check the spelling before the SDK converts each URI to AnyUrl. + if isinstance(rows, list): + for row in rows: + if isinstance(row, dict) and isinstance(row.get("uri"), str): + _resource_uri(row["uri"]) + return rows + + +class _ListResourcesResult(types.ListResourcesResult): + _check_uris = field_validator("resources", mode="before")(_check_resource_uris) + + +class _ReadResourceResult(types.ReadResourceResult): + _check_uris = field_validator("contents", mode="before")(_check_resource_uris) + + @dataclass(frozen=True) class MCPLimits: timeout_seconds: float = 30 @@ -567,7 +593,9 @@ def __init__( mappings = [m for m in (self._config.search, self._config.read) if m is not None] if set(config.approved_tools) != {m.name for m in mappings}: raise MCPSourceError("config") - if self._config.read is not None and not self._config.read.text_path: + if (self._config.read is not None and not self._config.read.text_path) or ( + self._config.search is not None and not self._config.search.items_path + ): raise MCPSourceError("config") for mapping in mappings: _validate_tool_mapping(mapping) @@ -803,11 +831,16 @@ async def _message_handler(self, message: Any) -> None: ): self._tool_catalog_generation += 1 - async def _run(self, action: Callable[[ClientSession], Awaitable[_T]]) -> _T: + async def _run( + self, action: Callable[[ClientSession], Awaitable[_T]], *, pins_tools: bool = False + ) -> _T: with private_work(): - return await self._execute(action) + return await self._execute(action, pins_tools=pins_tools) - async def _execute(self, action: Callable[[ClientSession], Awaitable[_T]]) -> _T: + async def _execute( + self, action: Callable[[ClientSession], Awaitable[_T]], *, pins_tools: bool + ) -> _T: + generation = self._tool_catalog_generation set_query_tag("mcp-source") try: self._check_state(require_session=True) @@ -818,6 +851,8 @@ async def _execute(self, action: Callable[[ClientSession], Awaitable[_T]]) -> _T result = await action(self._session) await self._authorize() self._check_state(require_session=True) + if pins_tools and generation != self._tool_catalog_generation: + raise MCPSourceError("schema") return result except ( Exception, # Terminal refusals must drain owned HTTP work before returning. @@ -889,7 +924,7 @@ async def action(session: ClientSession) -> MCPDiscovery: self._discovery = MCPDiscovery(self._discovery.resources, tuple(sorted(found))) return self._discovery - return await self._run(action) + return await self._run(action, pins_tools=bool(self._config.approved_tools)) def _page_start(self, cursor: str | None, scope: tuple[str, str]) -> None: if cursor is not None: @@ -921,8 +956,11 @@ async def action(session: ClientSession) -> MCPPage: if self._discovery is None or not self._discovery.resources: raise MCPSourceError("unsupported") self._page_start(cursor, ("resources", "")) - result = await session.list_resources( - params=types.PaginatedRequestParams(cursor=cursor) + result = await session.send_request( + types.ClientRequest( + types.ListResourcesRequest(params=types.PaginatedRequestParams(cursor=cursor)) + ), + _ListResourcesResult, ) items = [] for resource in result.resources: @@ -994,7 +1032,7 @@ async def action(session: ClientSession) -> MCPPage: ("search", query), ) - return await self._run(action) + return await self._run(action, pins_tools=self._config.search is not None) async def read(self, resource_id: str) -> MCPEvidence: async def action(session: ClientSession) -> MCPEvidence: @@ -1011,7 +1049,14 @@ async def action(session: ClientSession) -> MCPEvidence: return self._with_receipt(evidence, "tools/call") if self._discovery is None or not self._discovery.resources: raise MCPSourceError("unsupported") - result = await session.read_resource(AnyUrl(identity)) + result = await session.send_request( + types.ClientRequest( + types.ReadResourceRequest( + params=types.ReadResourceRequestParams(uri=_resource_uri(identity)) + ) + ), + _ReadResourceResult, + ) if not result.contents or len(result.contents) > self._config.limits.max_results: raise MCPSourceError("limit") texts: list[str] = [] @@ -1040,4 +1085,4 @@ async def action(session: ClientSession) -> MCPEvidence: "resources/read", ) - return await self._run(action) + return await self._run(action, pins_tools=self._config.read is not None) diff --git a/tests/unit/test_mcp_source_cancellation.py b/tests/unit/test_mcp_source_cancellation.py index bf3232e1ee..3ecc9d4066 100644 --- a/tests/unit/test_mcp_source_cancellation.py +++ b/tests/unit/test_mcp_source_cancellation.py @@ -1651,3 +1651,145 @@ async def reply(request: httpx.Request) -> httpx.Response: await asyncio.wait_for(started.wait(), 1) assert stopped.is_set() and fixture.pool_closed.is_set() assert drained_at_delete == [True] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("phase", ["list", "request", "response"]) +async def test_native_resource_identity_is_not_normalized( + monkeypatch: pytest.MonkeyPatch, phase: str +) -> None: + monkeypatch.setattr(source, "pinned_target", pin) + canonical = "https://docs.example/a" + noncanonical = "https://docs.example:443/a" + + class ResourceURIs(HTTPFixture): + async def reply(self, request: httpx.Request) -> httpx.Response: + if request.method == "POST": + payload = json.loads(await request.aread()) + if payload["method"] == "resources/list": + return httpx.Response( + 200, + json={ + "jsonrpc": "2.0", + "id": payload["id"], + "result": {"resources": [{"uri": noncanonical, "name": "One"}]}, + }, + ) + return await super().reply(request) + + def document(self) -> dict[str, Any]: + return { + "contents": [ + {"uri": noncanonical if phase == "response" else canonical, "text": TEXT} + ] + } + + fixture = ResourceURIs("resources", block=False) + selected = noncanonical if phase == "request" else canonical + config = replace(fixture.config(), approved_resource_ids=(selected,)) + async with source.MCPSourceClient( + config, None, validate_access=access, _transport=FixtureTransport(fixture) + ) as remote: + with pytest.raises(source.MCPSourceError, match="unsupported"): + if phase == "list": + await remote.list_resources() + else: + await remote.read(selected) + assert fixture.reads == (1 if phase == "response" else 0) + + +@pytest.mark.asyncio +async def test_catalog_change_during_final_access_refuses_mapped_read( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setattr(source, "pinned_target", pin) + fixture = HTTPFixture("tools", block=False) + entered = asyncio.Event() + release = asyncio.Event() + + async def authority() -> None: + if asyncio.current_task() is operation and fixture.reads: + entered.set() + await release.wait() + + operation: asyncio.Task[source.MCPEvidence] | None = None + async with source.MCPSourceClient( + fixture.config(), None, validate_access=authority, _transport=FixtureTransport(fixture) + ) as remote: + operation = asyncio.create_task(remote.read(IDENTITY)) + try: + await asyncio.wait_for(entered.wait(), 1) + await remote._message_handler( + source.types.ServerNotification(source.types.ToolListChangedNotification()) + ) + finally: + release.set() + with pytest.raises(source.MCPSourceError, match="schema"): + await operation + assert fixture.reads == 1 + + +@pytest.mark.asyncio +async def test_initialized_notification_requires_accepted_status( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setattr(source, "pinned_target", pin) + + class OKNotification(HTTPFixture): + async def reply(self, request: httpx.Request) -> httpx.Response: + if ( + request.method == "POST" + and json.loads(await request.aread())["method"] == "notifications/initialized" + ): + return httpx.Response(200, json={}) + return await super().reply(request) + + fixture = OKNotification("resources", block=False) + with pytest.raises(source.MCPSourceError, match="protocol"): + async with fixture.client() as remote: + await remote.read(IDENTITY) + assert fixture.reads == 0 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "identity", + ["file:///local/example", "urn:example:document", "https://user:secret@docs.example/a"], +) +async def test_native_resource_uri_profile(monkeypatch: pytest.MonkeyPatch, identity: str) -> None: + monkeypatch.setattr(source, "pinned_target", pin) + + class Resource(HTTPFixture): + async def reply(self, request: httpx.Request) -> httpx.Response: + if request.method == "POST": + payload = json.loads(await request.aread()) + if payload["method"] == "resources/list": + return httpx.Response( + 200, + json={ + "jsonrpc": "2.0", + "id": payload["id"], + "result": {"resources": [{"uri": identity, "name": "One"}]}, + }, + ) + if payload["method"] == "resources/read": + assert payload["params"]["uri"] == identity + return await super().reply(request) + + def document(self) -> dict[str, Any]: + return {"contents": [{"uri": identity, "text": TEXT}]} + + fixture = Resource("resources", block=False) + config = replace(fixture.config(), approved_resource_ids=(identity,)) + async with source.MCPSourceClient( + config, None, validate_access=access, _transport=FixtureTransport(fixture) + ) as remote: + if identity.startswith("https:"): + with pytest.raises(source.MCPSourceError, match="unsupported"): + await remote.list_resources() + else: + page = await remote.list_resources() + assert page.items[0].resource_id == identity + evidence = await remote.read(identity) + assert evidence.resource_id == identity and evidence.receipt is not None + assert fixture.reads == (0 if identity.startswith("https:") else 1) diff --git a/tests/unit/test_mcp_source_client.py b/tests/unit/test_mcp_source_client.py index db65fb5a6a..951bc08b99 100644 --- a/tests/unit/test_mcp_source_client.py +++ b/tests/unit/test_mcp_source_client.py @@ -1307,3 +1307,9 @@ async def test_discovery_without_an_approved_tool_rpc_closes_cleanly( assert state["calls"] == [] assert opened._owner_task is not None and opened._owner_task.done() assert opened._transport is not None and opened._transport.failure is None + + +def test_search_mapping_requires_items_selector() -> None: + search = replace(mapping("find", search=True), items_path=()) + with pytest.raises(source.MCPSourceError, match="^MCP source config$"): + client(replace(config(tools=True), search=search)) From 24c37ea1b0ad2697b88014727946f7de6d53e77b Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Thu, 26 Nov 2026 16:14:19 +0000 Subject: [PATCH 13/15] Refuse stale MCP tool calls before dispatch Signed-off-by: zlareb1 --- server/clients/mcp_source.py | 25 +++++++++++++- tests/unit/test_mcp_source_cancellation.py | 40 ++++++++++++++++++++++ 2 files changed, 64 insertions(+), 1 deletion(-) diff --git a/server/clients/mcp_source.py b/server/clients/mcp_source.py index 73c4551acf..33505a1e71 100644 --- a/server/clients/mcp_source.py +++ b/server/clients/mcp_source.py @@ -406,7 +406,9 @@ def __init__( validate_access: Callable[[], Awaitable[None]], *, transport: httpx.AsyncBaseTransport | None = None, + guard_tool_dispatch: Callable[[], None] | None = None, ) -> None: + self.guard_tool_dispatch = guard_tool_dispatch self.endpoint = _endpoint_url(config.endpoint) self.credential, self.deadline, self.limits = credential, deadline, config.limits self.validate_access = validate_access @@ -435,6 +437,12 @@ async def handle_async_request(self, request: httpx.Request) -> httpx.Response: self.failure = self.failure or _error_code(error) raise MCPSourceError(self.failure) from None + def _check_tool_dispatch(self, method: str, body: bytes) -> None: + if method == "POST" and body and self.guard_tool_dispatch is not None: + message = types.JSONRPCMessage.model_validate_json(body).root + if isinstance(message, types.JSONRPCRequest) and message.method == "tools/call": + self.guard_tool_dispatch() + async def _handle(self, request: httpx.Request) -> httpx.Response: response: httpx.Response | None = None handed_off = False @@ -495,6 +503,7 @@ async def _handle(self, request: httpx.Request) -> httpx.Response: }, ) await self._authorize() + self._check_tool_dispatch(request.method, body) response = await self.inner.handle_async_request(outgoing) await self._authorize() _check_response(request.method, response, body) @@ -612,6 +621,8 @@ def __init__( self._discovery: MCPDiscovery | None = None self._tools_supported = False self._tool_catalog_generation = 0 + self._tool_dispatch_lock = asyncio.Lock() + self._tool_dispatch_generation: int | None = None self._pages, self._results = 0, 0 self._issued_cursors: set[tuple[tuple[str, str], str]] = set() self._used_cursors: set[tuple[tuple[str, str], str]] = set() @@ -748,6 +759,7 @@ async def _initialize(self, stack: AsyncExitStack) -> None: self._deadline, self._transport_authorize, transport=self._test_transport, + guard_tool_dispatch=self._check_tool_generation, ) self._transport = transport client = await stack.enter_async_context( @@ -972,6 +984,10 @@ async def action(session: ClientSession) -> MCPPage: return await self._run(action) + def _check_tool_generation(self) -> None: + if self._tool_dispatch_generation != self._tool_catalog_generation: + raise MCPSourceError("schema") + async def _tool( self, session: ClientSession, mapping: MCPToolMapping, value: str, cursor: str | None = None ) -> Any: @@ -986,7 +1002,14 @@ async def _tool( raise MCPSourceError("unsupported") arguments[mapping.cursor_argument] = cursor _validate(mapping.input_schema, arguments, 32_768) - result = await session.call_tool(mapping.name, arguments) + async with self._tool_dispatch_lock: + self._check_state(require_session=True) + self._tool_dispatch_generation = generation + try: + self._check_tool_generation() + result = await session.call_tool(mapping.name, arguments) + finally: + self._tool_dispatch_generation = None if generation != self._tool_catalog_generation: raise MCPSourceError("schema") if result.isError or result.structuredContent is None: diff --git a/tests/unit/test_mcp_source_cancellation.py b/tests/unit/test_mcp_source_cancellation.py index 3ecc9d4066..aaa6df602d 100644 --- a/tests/unit/test_mcp_source_cancellation.py +++ b/tests/unit/test_mcp_source_cancellation.py @@ -1793,3 +1793,43 @@ def document(self) -> dict[str, Any]: evidence = await remote.read(identity) assert evidence.resource_id == identity and evidence.receipt is not None assert fixture.reads == (0 if identity.startswith("https:") else 1) + + +@pytest.mark.asyncio +async def test_catalog_change_during_transport_access_prevents_tool_dispatch( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setattr(source, "pinned_target", pin) + fixture = HTTPFixture("tools", block=False) + entered = asyncio.Event() + release = asyncio.Event() + dispatch_task: asyncio.Task[Any] | None = None + original_aread = httpx.Request.aread + + async def mark_tool_request(request: httpx.Request) -> bytes: + nonlocal dispatch_task + data = await original_aread(request) + if request.method == "POST" and json.loads(data)["method"] == "tools/call": + dispatch_task = asyncio.current_task() + return data + + async def authority() -> None: + if asyncio.current_task() is dispatch_task and not entered.is_set(): + entered.set() + await release.wait() + + monkeypatch.setattr(httpx.Request, "aread", mark_tool_request) + async with source.MCPSourceClient( + fixture.config(), None, validate_access=authority, _transport=FixtureTransport(fixture) + ) as remote: + operation = asyncio.create_task(remote.read(IDENTITY)) + try: + await asyncio.wait_for(entered.wait(), 1) + await remote._message_handler( + source.types.ServerNotification(source.types.ToolListChangedNotification()) + ) + finally: + release.set() + with pytest.raises(source.MCPSourceError, match="schema"): + await operation + assert fixture.reads == 0 From 867da43730f8c53e71408552c5112752060e3e54 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Thu, 26 Nov 2026 16:21:03 +0000 Subject: [PATCH 14/15] Refuse nonempty MCP POST acknowledgments Signed-off-by: zlareb1 --- server/clients/mcp_source.py | 29 +++++++++++++++------- tests/unit/test_mcp_source_cancellation.py | 15 +++++++---- 2 files changed, 30 insertions(+), 14 deletions(-) diff --git a/server/clients/mcp_source.py b/server/clients/mcp_source.py index 33505a1e71..98e035392d 100644 --- a/server/clients/mcp_source.py +++ b/server/clients/mcp_source.py @@ -443,6 +443,23 @@ def _check_tool_dispatch(self, method: str, body: bytes) -> None: if isinstance(message, types.JSONRPCRequest) and message.method == "tools/call": self.guard_tool_dispatch() + async def _validated_response( + self, method: str, response: httpx.Response, body: bytes + ) -> httpx.Response: + _check_response(method, response, body) + # Reject compression so the wire budget bounds decoded protocol bytes. + if response.headers.get("content-encoding", "identity") != "identity": + raise MCPSourceError("protocol") + if not isinstance(response.stream, httpx.AsyncByteStream): + raise MCPSourceError("protocol") + response.stream = _LimitedStream(response.stream, self) + if method == "POST" and response.status_code == 202: + async for chunk in response.stream: + if chunk: + raise MCPSourceError("protocol") + return httpx.Response(202, headers=response.headers, content=b"") + return response + async def _handle(self, request: httpx.Request) -> httpx.Response: response: httpx.Response | None = None handed_off = False @@ -506,15 +523,9 @@ async def _handle(self, request: httpx.Request) -> httpx.Response: self._check_tool_dispatch(request.method, body) response = await self.inner.handle_async_request(outgoing) await self._authorize() - _check_response(request.method, response, body) - # Reject compression so the wire budget bounds decoded protocol bytes. - if response.headers.get("content-encoding", "identity") != "identity": - raise MCPSourceError("protocol") - if not isinstance(response.stream, httpx.AsyncByteStream): - raise MCPSourceError("protocol") - response.stream = _LimitedStream(response.stream, self) - handed_off = True - return response + validated = await self._validated_response(request.method, response, body) + handed_off = validated is response + return validated except Exception as error: # noqa: BLE001 — poison the session before awaiting private failure cleanup self.failure = self.failure or _error_code(error) raise MCPSourceError(self.failure) from None diff --git a/tests/unit/test_mcp_source_cancellation.py b/tests/unit/test_mcp_source_cancellation.py index aaa6df602d..01febd47ea 100644 --- a/tests/unit/test_mcp_source_cancellation.py +++ b/tests/unit/test_mcp_source_cancellation.py @@ -1730,21 +1730,26 @@ async def authority() -> None: @pytest.mark.asyncio -async def test_initialized_notification_requires_accepted_status( - monkeypatch: pytest.MonkeyPatch, +@pytest.mark.parametrize("status", [200, 202]) +async def test_initialized_notification_requires_empty_accepted_response( + monkeypatch: pytest.MonkeyPatch, status: int ) -> None: monkeypatch.setattr(source, "pinned_target", pin) - class OKNotification(HTTPFixture): + class NotificationWithBody(HTTPFixture): async def reply(self, request: httpx.Request) -> httpx.Response: if ( request.method == "POST" and json.loads(await request.aread())["method"] == "notifications/initialized" ): - return httpx.Response(200, json={}) + return httpx.Response( + status, + stream=httpx.ByteStream(b'{"unexpected":true}'), + headers={"content-type": "application/json"}, + ) return await super().reply(request) - fixture = OKNotification("resources", block=False) + fixture = NotificationWithBody("resources", block=False) with pytest.raises(source.MCPSourceError, match="protocol"): async with fixture.client() as remote: await remote.read(IDENTITY) From 6526e620d44d236674ad7292046e2bc6bf653432 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sat, 28 Nov 2026 08:52:50 +0000 Subject: [PATCH 15/15] Refuse MCP source reads after SDK protocol errors The SDK can report a protocol error and continue to deliver messages. Record the error in the session failure state so a later result cannot produce a read receipt. Signed-off-by: zlareb1 --- server/clients/mcp_source.py | 5 +++- tests/unit/test_mcp_source_cancellation.py | 28 ++++++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/server/clients/mcp_source.py b/server/clients/mcp_source.py index 98e035392d..1b0c385774 100644 --- a/server/clients/mcp_source.py +++ b/server/clients/mcp_source.py @@ -849,7 +849,10 @@ async def __aexit__(self, exc_type: Any, error: BaseException | None, traceback: self._leave_private() async def _message_handler(self, message: Any) -> None: - if isinstance(message, types.ServerNotification) and isinstance( + if isinstance(message, Exception): + assert self._transport is not None + self._transport.failure = self._transport.failure or _error_code(message) + elif isinstance(message, types.ServerNotification) and isinstance( message.root, types.ToolListChangedNotification ): self._tool_catalog_generation += 1 diff --git a/tests/unit/test_mcp_source_cancellation.py b/tests/unit/test_mcp_source_cancellation.py index 01febd47ea..32873fc98d 100644 --- a/tests/unit/test_mcp_source_cancellation.py +++ b/tests/unit/test_mcp_source_cancellation.py @@ -1729,6 +1729,34 @@ async def authority() -> None: assert fixture.reads == 1 +@pytest.mark.asyncio +@pytest.mark.parametrize("during_read", [True, False], ids=["read", "idle"]) +async def test_sdk_callback_error_refuses_read_or_close( + monkeypatch: pytest.MonkeyPatch, during_read: bool +) -> None: + monkeypatch.setattr(source, "pinned_target", pin) + fixture = HTTPFixture("resources", block=False) + caller = asyncio.current_task() + + async def authority() -> None: + if asyncio.current_task() is caller and fixture.reads: + await remote._message_handler(ValueError(TEXT)) + + remote = source.MCPSourceClient( + fixture.config(), None, validate_access=authority, _transport=FixtureTransport(fixture) + ) + refusal = pytest.raises(source.MCPSourceError, match=r"^MCP source protocol$") + if during_read: + async with remote: + with refusal: + await remote.read(IDENTITY) + else: + with refusal: + async with remote: + await remote._message_handler(RuntimeError(TEXT)) + assert fixture.reads == int(during_read) + + @pytest.mark.asyncio @pytest.mark.parametrize("status", [200, 202]) async def test_initialized_notification_requires_empty_accepted_response(