From 3b8576fc9d7db471ae14a92c7d5730b71ef7fd35 Mon Sep 17 00:00:00 2001 From: S2D2 Date: Tue, 10 Nov 2026 20:51:15 +0000 Subject: [PATCH 1/6] refactor: share the MCP session and end-user retry plumbing fetch_mcp_tools and call_mcp_tool each opened the transport, built a ClientSession, initialized it under the same deadline and mapped failures through _raise_mcp_failure. That now lives in one _run_mcp_session helper, import guard included; each function keeps only its own exchange. The retry-once-with-the-looked-up-end-user logic was written three times (per-account listing, search/execute listing, tool execution). It is now retry_for_end_user, with the same rules: only a 400 naming an account that was sent without an end user, and only if the lookup finds one. No behaviour change. Co-Authored-By: Claude Opus 5.5 Co-authored-by: Guillaume Lebedel <10488548+glebedel@users.noreply.github.com> --- stackone_ai/tools.py | 175 ++++++++++++++++++++--------------------- stackone_ai/toolset.py | 24 ++---- 2 files changed, 95 insertions(+), 104 deletions(-) diff --git a/stackone_ai/tools.py b/stackone_ai/tools.py index 486b6aa..4fccfe2 100644 --- a/stackone_ai/tools.py +++ b/stackone_ai/tools.py @@ -658,66 +658,81 @@ async def _mcp_transport( yield streams -def fetch_mcp_tools( - endpoint: str, headers: dict[str, str], *, timeout: float = 60.0 -) -> list[McpToolDefinition]: - """List every tool the MCP endpoint serves, following pagination. - - ``timeout`` bounds the whole exchange, handshake included. +def _run_mcp_session( + endpoint: str, + headers: dict[str, str], + timeout: float, + work: Callable[[Any], Coroutine[Any, Any, T]], +) -> T: + """Open an initialized MCP session to ``endpoint``, run ``work`` on it and close it. + + ``timeout`` bounds the whole exchange, handshake included. Any failure is raised + through :func:`_raise_mcp_failure`. """ try: from mcp import types as mcp_types # ty: ignore[unresolved-import] from mcp.client.session import ClientSession # ty: ignore[unresolved-import] - except ImportError as exc: # pragma: no cover - depends on optional extra + except ImportError as exc: # pragma: no cover - only a broken install gets here raise ToolsetConfigError( "mcp is a core dependency of stackone-ai but could not be imported — reinstall the package." ) from exc throttle = _Throttle() - async def _list() -> list[McpToolDefinition]: + async def _run() -> T: with anyio.fail_after(timeout): - return await _list_within_deadline() - - async def _list_within_deadline() -> list[McpToolDefinition]: - async with _mcp_transport(endpoint, headers, timeout, throttle) as ( - read_stream, - write_stream, - _, - ): - session = ClientSession( + async with _mcp_transport(endpoint, headers, timeout, throttle) as ( read_stream, write_stream, - client_info=mcp_types.Implementation(name="stackone-ai-python", version=_SDK_VERSION), - ) - async with session: - await session.initialize() - cursor: str | None = None - collected: list[McpToolDefinition] = [] - while True: - result = await session.list_tools(cursor) - for tool in result.tools: - input_schema = tool.inputSchema or {} - collected.append( - McpToolDefinition( - name=tool.name, - description=tool.description, - input_schema=dict(input_schema), - ) - ) - cursor = result.nextCursor - if cursor is None: - break - return collected + _, + ): + session = ClientSession( + read_stream, + write_stream, + client_info=mcp_types.Implementation(name="stackone-ai-python", version=_SDK_VERSION), + ) + async with session: + await session.initialize() + return await work(session) try: - return run_async(_list()) + return run_async(_run()) except Exception as exc: # Exception, not BaseException: Ctrl-C and SystemExit must stop the caller, not come # back as a ToolsetLoadError that an agent framework hands the model as a tool result. _raise_mcp_failure(exc, endpoint, timeout, throttle) +def fetch_mcp_tools( + endpoint: str, headers: dict[str, str], *, timeout: float = 60.0 +) -> list[McpToolDefinition]: + """List every tool the MCP endpoint serves, following pagination. + + ``timeout`` bounds the whole exchange, handshake included. + """ + + async def _list(session: Any) -> list[McpToolDefinition]: + cursor: str | None = None + collected: list[McpToolDefinition] = [] + while True: + result = await session.list_tools(cursor) + for tool in result.tools: + input_schema = tool.inputSchema or {} + collected.append( + McpToolDefinition( + name=tool.name, + description=tool.description, + input_schema=dict(input_schema), + ) + ) + cursor = result.nextCursor + if cursor is None: + break + return collected + + return _run_mcp_session(endpoint, headers, timeout, _list) + + def _response_body(response: httpx.Response) -> str: """Best-effort read of an error body. @@ -937,44 +952,21 @@ def call_mcp_tool( ``arguments`` are sent exactly as given; the server maps them onto the action. """ from mcp import types as mcp_types # ty: ignore[unresolved-import] - from mcp.client.session import ClientSession # ty: ignore[unresolved-import] - - throttle = _Throttle() - async def _call() -> JsonDict: - with anyio.fail_after(timeout): - return await _call_within_deadline() - - async def _call_within_deadline() -> JsonDict: - async with _mcp_transport(endpoint, headers, timeout, throttle) as ( - read_stream, - write_stream, - _, - ): - session = ClientSession( - read_stream, - write_stream, - client_info=mcp_types.Implementation(name="stackone-ai-python", version=_SDK_VERSION), + async def _call(session: Any) -> JsonDict: + # send_request rather than call_tool: call_tool validates structuredContent + # against the tool's output schema, and on a fresh session that means a + # tools/list first — relisting the whole catalog on every call, which the + # Node SDK never does. The result is parsed below either way. + request = mcp_types.ClientRequest( + mcp_types.CallToolRequest( + params=mcp_types.CallToolRequestParams(name=name, arguments=arguments), ) - async with session: - await session.initialize() - # send_request rather than call_tool: call_tool validates structuredContent - # against the tool's output schema, and on a fresh session that means a - # tools/list first — relisting the whole catalog on every call, which the - # Node SDK never does. The result is parsed below either way. - request = mcp_types.ClientRequest( - mcp_types.CallToolRequest( - params=mcp_types.CallToolRequestParams(name=name, arguments=arguments), - ) - ) - result = await session.send_request(request, mcp_types.CallToolResult) - return parse_tool_result(result, name) + ) + result = await session.send_request(request, mcp_types.CallToolResult) + return parse_tool_result(result, name) - try: - return run_async(_call()) - except Exception as exc: - # Not BaseException, as in fetch_mcp_tools: KeyboardInterrupt and SystemExit propagate. - _raise_mcp_failure(exc, endpoint, timeout, throttle) + return _run_mcp_session(endpoint, headers, timeout, _call) def is_end_user_refusal(exc: BaseException, account_id: str) -> bool: @@ -1001,6 +993,21 @@ def is_end_user_refusal(exc: BaseException, account_id: str) -> bool: return message.rstrip().rsplit(" ", 1)[-1].strip("\"'") == account_id +def retry_for_end_user( + call: Callable[[], T], accounts: Iterable[str], look_up: Callable[[str, Exception], bool] | None +) -> T: + """``call()``, made once more if the API refused it for want of the end user of one of + ``accounts`` (those it was sent without one for) and ``look_up`` then finds that end user. + """ + try: + return call() + except StackOneAPIError as exc: + refused = next((account for account in accounts if is_end_user_refusal(exc, account)), None) + if refused is None or look_up is None or not look_up(refused, exc): + raise + return call() + + def _strip_internal_keys(schema: Any) -> Any: """Recursively drop the SDK's internal markers from a property schema. @@ -1495,21 +1502,13 @@ def call() -> JsonDict: self._endpoint, self._prepare_headers(), self._served_name, parsed, timeout=timeout ) + # Sent with no recorded end user and refused for want of one: the account is + # non-shared and its end user can be looked up. Retried once, with it. account_id = self._account_id - without_end_user = account_id is not None and self._recorded_end_user_id() is None - try: - return call() - except StackOneAPIError as exc: - # Sent with no recorded end user and refused for want of one: the account is - # non-shared and its end user can be looked up. Retried once, with it. - if not ( - without_end_user - and account_id is not None - and self._look_up_end_user is not None - and self._look_up_end_user(account_id, exc) - ): - raise - return call() + without_end_user = ( + [account_id] if account_id is not None and self._recorded_end_user_id() is None else [] + ) + return retry_for_end_user(call, without_end_user, self._look_up_end_user) @dataclass(frozen=True) diff --git a/stackone_ai/toolset.py b/stackone_ai/toolset.py index 0780659..011c22a 100644 --- a/stackone_ai/toolset.py +++ b/stackone_ai/toolset.py @@ -35,6 +35,7 @@ is_end_user_refusal, is_rate_limited, is_sdk_owned_header, + retry_for_end_user, ) from stackone_ai.types import ( DEFAULT_BASE_URL, @@ -497,15 +498,12 @@ def _catalog( def _fetch_for_account( account: str | None, ) -> list[_Listing]: - without_end_user = account is not None and self._end_user_id(account) is None - try: - listed = fetch_mcp_tools(endpoint, self._build_mcp_headers(account), timeout=self._timeout) - except StackOneAPIError as exc: - # Refused for want of an end user it was sent without: look it up, and retry - # once with it. - if not (without_end_user and account is not None and self._look_up_end_user(account, exc)): - raise - listed = fetch_mcp_tools(endpoint, self._build_mcp_headers(account), timeout=self._timeout) + without_end_user = [account] if account is not None and self._end_user_id(account) is None else [] + listed = retry_for_end_user( + lambda: fetch_mcp_tools(endpoint, self._build_mcp_headers(account), timeout=self._timeout), + without_end_user, + self._look_up_end_user, + ) return [(tool_def, account, endpoint) for tool_def in listed] def _store(catalog: _Catalog) -> None: @@ -582,13 +580,7 @@ def _list() -> list[_Listing]: return [(tool_def, None, endpoint) for tool_def in listed] without_end_user = [account for account in account_scope if self._end_user_id(account) is None] - try: - listings = _list() - except StackOneAPIError as exc: - refused = next((a for a in without_end_user if is_end_user_refusal(exc, a)), None) - if refused is None or not self._look_up_end_user(refused, exc): - raise - listings = _list() + listings = retry_for_end_user(_list, without_end_user, self._look_up_end_user) with self._cache_lock: if generation == self._cache_generation: From 9b559417d454bb40e2bb1775ea41bc3a1abac486 Mon Sep 17 00:00:00 2001 From: S2D2 Date: Wed, 11 Nov 2026 00:34:25 +0000 Subject: [PATCH 2/6] refactor: drop the comment retry_for_end_user's docstring now states The retry condition is documented once, on retry_for_end_user, as the toolset callers already rely on; the copy above the tool's call site restated it. Co-Authored-By: Claude Opus 5.5 Co-authored-by: Guillaume Lebedel <10488548+glebedel@users.noreply.github.com> --- stackone_ai/tools.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/stackone_ai/tools.py b/stackone_ai/tools.py index 4fccfe2..2e88b1b 100644 --- a/stackone_ai/tools.py +++ b/stackone_ai/tools.py @@ -1502,8 +1502,6 @@ def call() -> JsonDict: self._endpoint, self._prepare_headers(), self._served_name, parsed, timeout=timeout ) - # Sent with no recorded end user and refused for want of one: the account is - # non-shared and its end user can be looked up. Retried once, with it. account_id = self._account_id without_end_user = ( [account_id] if account_id is not None and self._recorded_end_user_id() is None else [] From e53d02b6c3311bc77e786891735e97275b80f2b0 Mon Sep 17 00:00:00 2001 From: S2D2 Date: Wed, 11 Nov 2026 00:46:32 +0000 Subject: [PATCH 3/6] refactor: check the end-user refusal in one place retry_for_end_user already checks is_end_user_refusal before it calls the look-up, and every caller goes through it, so the look-up's own check was a second copy that could drift. Co-Authored-By: Claude Opus 5.5 Co-authored-by: Guillaume Lebedel <10488548+glebedel@users.noreply.github.com> --- stackone_ai/toolset.py | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/stackone_ai/toolset.py b/stackone_ai/toolset.py index 011c22a..2542ac3 100644 --- a/stackone_ai/toolset.py +++ b/stackone_ai/toolset.py @@ -32,7 +32,6 @@ _json_type, build_request_headers, fetch_mcp_tools, - is_end_user_refusal, is_rate_limited, is_sdk_owned_header, retry_for_end_user, @@ -1007,13 +1006,10 @@ def _look_up_end_user(self, account_id: str, refusal: Exception) -> bool: """Given the API's refusal of an account's request for want of its end user, list the accounts and say whether that one now has an end user recorded to retry with. - Only the API's 400 naming this account counts. A GET /accounts already in flight is - joined rather than another made. If it fails, the refusal is raised with that failure - as its cause: a key without the scope to list accounts would otherwise be told only - that the header does not match. + A GET /accounts already in flight is joined rather than another made. If it fails, the + refusal is raised with that failure as its cause: a key without the scope to list + accounts would otherwise be told only that the header does not match. """ - if not is_end_user_refusal(refusal, account_id): - return False try: self._join_accounts_listing() except Exception as exc: From 2494d18f40f79cb8488bc3862525bacf02aa4086 Mon Sep 17 00:00:00 2001 From: S2D2 Date: Wed, 11 Nov 2026 11:46:38 +0000 Subject: [PATCH 4/6] test: assert list_tools pagination params The pagination test only counted calls, so a regression to the old positional cursor argument would still pass. Assert the first call sends params=None and the second carries the next cursor. Co-Authored-By: Claude Opus 5.5 Co-authored-by: Guillaume Lebedel <10488548+glebedel@users.noreply.github.com> --- tests/test_fetch_tools.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/test_fetch_tools.py b/tests/test_fetch_tools.py index e849270..fd59adc 100644 --- a/tests/test_fetch_tools.py +++ b/tests/test_fetch_tools.py @@ -690,7 +690,9 @@ async def mock_streamable_client(endpoint, **_kwargs: object): assert result[0].name == "tool_1" assert result[1].name == "tool_2" assert result[1].input_schema == {} # None should become empty dict - assert mock_session.list_tools.call_count == 2 + first_call, second_call = mock_session.list_tools.call_args_list + assert first_call.kwargs == {"params": None} + assert second_call.kwargs["params"].cursor == "cursor_page_2" class TestCatalogCache: From e11c60fc29fdf6124ee1a4d662a71ef5d366724f Mon Sep 17 00:00:00 2001 From: S2D2 Date: Wed, 11 Nov 2026 15:21:56 +0000 Subject: [PATCH 5/6] feat(deps): support mcp 2 alongside mcp 1 Widen the mcp range to >=1.30.0,<3.0.0 and lock mcp 2.3.0, so installs next to packages that need mcp 2 (fastmcp 4, newer agent frameworks) no longer conflict, while projects pinned to mcp 1 (langchain-mcp-adapters caps mcp<2) keep resolving. mcp 2 changed four things the SDK relied on: - its transport takes an httpx2 client, not an httpx one, and yields two streams instead of three; - model attributes are snake_case only (is_error, structured_content, input_schema, next_cursor), so getattr(result, "isError", False) silently read every failed tool call as a success; - a failed POST becomes a JSON-RPC error with no HTTP status or body, which lost the 400/412/429 status that end-user recovery, rate limiting and error messages read; - ClientRequest is a typing union, so the request is passed directly. The MCP client now uses whichever HTTP library the installed mcp takes, reads fields under either name, and raises a non-404 POST error status itself, as mcp 1 does. GET /accounts keeps using httpx. CI also runs the suite against mcp 1.30.0. Co-Authored-By: Claude Opus 5.5 Co-authored-by: Guillaume Lebedel <10488548+glebedel@users.noreply.github.com> --- .github/workflows/ci.yaml | 4 + pyproject.toml | 2 +- stackone_ai/tools.py | 86 +++++++++------ tests/test_fetch_tools.py | 58 ++++------- tests/test_rate_limit.py | 76 +++++++------- tests/test_shared_vectors.py | 7 +- uv.lock | 195 +++++++++-------------------------- 7 files changed, 174 insertions(+), 254 deletions(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 2317260..97c8647 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -84,6 +84,10 @@ jobs: - name: Run Tests run: uv run pytest + # pyproject allows mcp 1 and 2 and the lockfile pins 2, so the oldest mcp 1 is tested too. + - name: Run Tests against mcp 1 + run: uv run --with "mcp==1.30.0" pytest + # Enforces the wire contract in docs/SDK-UCA-CONTRACT.md. # StackOneHQ/sdk-conformance is private and requires CONFORMANCE_REPO_TOKEN. # Fork PRs and Dependabot runs cannot access this secret and skip this gate; diff --git a/pyproject.toml b/pyproject.toml index ab9154d..cea9226 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -21,7 +21,7 @@ dependencies = [ "httpx>=0.28.0", # fetch_tools() is the only route to a tool and talks MCP, so the client is # not optional: without it the SDK cannot do anything. - "mcp>=1.30.0,<2.0.0", + "mcp>=1.30.0,<3.0.0", ] [project.urls] diff --git a/stackone_ai/tools.py b/stackone_ai/tools.py index 99e3ef9..27bba12 100644 --- a/stackone_ai/tools.py +++ b/stackone_ai/tools.py @@ -27,7 +27,7 @@ from datetime import UTC, datetime, timedelta from decimal import Decimal from importlib import metadata -from typing import Any, NoReturn, TypeVar +from typing import TYPE_CHECKING, Any, NoReturn, TypeVar import anyio import httpx @@ -49,6 +49,13 @@ logger = logging.getLogger("stackone.tools") +# The HTTP library the installed mcp transport takes: httpx before mcp 2, httpx2 (an mcp 2 +# dependency) from then on. GET /accounts always uses httpx. +if TYPE_CHECKING or int(metadata.version("mcp").split(".")[0]) >= 2: + import httpx2 as _mcp_http +else: + _mcp_http = httpx + T = TypeVar("T") try: @@ -345,10 +352,10 @@ def build_auth_header(api_key: str) -> str: return f"Basic {token}" -async def _buffer_error_body(response: httpx.Response) -> None: +async def _buffer_error_body(response: _mcp_http.Response) -> None: """Read an error response's body while its stream is still open. - The ``mcp`` client raises on the status after the streamed response is closed, so + An error status is raised after the streamed response is closed, so reading the body afterwards got nothing and every failure said only "400 Bad Request". The body is where the server explains itself: "Legacy accounts cannot be used with MCP", or a 412 asking for the account to be re-linked. Node already @@ -464,7 +471,7 @@ def _backoff_delay(retry: int, retry_after: float | None, random_value: float | return min(retry_after, RATE_LIMIT_MAX_DELAY_SECONDS) -def _rate_limit_delay(response: httpx.Response, retry: int) -> float: +def _rate_limit_delay(response: httpx.Response | _mcp_http.Response, retry: int) -> float: """How long to wait before retry number ``retry`` (1-based) of this 429.""" return _backoff_delay(retry, _retry_after_seconds(response.headers.get("retry-after"))) @@ -474,7 +481,7 @@ def _waits_for_retry(delay: float, remaining: float) -> bool: return delay < remaining -def _log_rate_limit_retry(request: httpx.Request, attempt: int, delay: float) -> None: +def _log_rate_limit_retry(request: httpx.Request | _mcp_http.Request, attempt: int, delay: float) -> None: logger.warning( "%s %s was rate limited (429) on attempt %d of %d; retrying in %ss", request.method, @@ -485,7 +492,9 @@ def _log_rate_limit_retry(request: httpx.Request, attempt: int, delay: float) -> ) -def _outlasts_deadline(request: httpx.Request, attempt: int, delay: float, remaining: float) -> bool: +def _outlasts_deadline( + request: httpx.Request | _mcp_http.Request, attempt: int, delay: float, remaining: float +) -> bool: """Whether waiting ``delay`` would not end before the deadline, logging when so. Such a wait is not started. Sleeping into the deadline would turn the 429 into a @@ -557,11 +566,11 @@ class _Throttle: GET, say, answered while a ``tools/list`` retry hangs, must not clear that retry's 429. """ - response: httpx.Response | None = None + response: _mcp_http.Response | None = None retrying: int = 0 -class RateLimitRetryingAsyncClient(httpx.AsyncClient): +class RateLimitRetryingAsyncClient(_mcp_http.AsyncClient): """The async counterpart of :class:`RateLimitRetryingClient`, used for every MCP request. The MCP client streams its responses; a discarded 429 is read and closed here, and @@ -579,7 +588,7 @@ def __init__(self, *args: Any, throttle: _Throttle | None = None, **kwargs: Any) super().__init__(*args, **kwargs) self._throttle = throttle - async def send(self, request: httpx.Request, **kwargs: Any) -> httpx.Response: + async def send(self, request: _mcp_http.Request, **kwargs: Any) -> _mcp_http.Response: attempt = 1 retried = False response = await super().send(request, **kwargs) @@ -603,6 +612,13 @@ async def send(self, request: httpx.Request, **kwargs: Any) -> httpx.Response: self._throttle.retrying -= 1 if self._throttle.retrying == 0: self._throttle.response = None + if request.method == "POST" and response.is_error and response.status_code != 404: + # mcp 2 answers a failed POST with a JSON-RPC error that drops the status and the + # body; raised as mcp 1 does, it keeps both. A 404 is left to mcp: a lost session. + await response.aclose() + raise _mcp_http.HTTPStatusError( + f"{response.status_code} {response.reason_phrase}", request=request, response=response + ) return response @@ -623,7 +639,10 @@ def is_rate_limited(exc: BaseException) -> bool: if id(current) in seen: continue seen.add(id(current)) - if isinstance(current, httpx.HTTPStatusError) and current.response.status_code == 429: + if ( + isinstance(current, httpx.HTTPStatusError | _mcp_http.HTTPStatusError) + and current.response.status_code == 429 + ): return True stack.extend(getattr(current, "exceptions", None) or []) stack.extend(e for e in (current.__cause__, current.__context__) if e is not None) @@ -639,7 +658,7 @@ def _ssl_context() -> ssl.SSLContext: @asynccontextmanager async def _mcp_transport( endpoint: str, headers: dict[str, str], timeout: float, throttle: _Throttle | None = None -) -> AsyncGenerator[tuple[Any, Any, Any]]: +) -> AsyncGenerator[tuple[Any, Any]]: """Open the streamable-HTTP transport with the caller's timeout on every leg. The client's own defaults are a 30s connect and a 300s SSE read, and neither was @@ -657,13 +676,14 @@ async def _mcp_transport( async with RateLimitRetryingAsyncClient( throttle=throttle, headers=headers, - timeout=httpx.Timeout(timeout), + timeout=_mcp_http.Timeout(timeout), verify=_ssl_context(), follow_redirects=True, event_hooks={"response": [_buffer_error_body]}, ) as client: async with streamable_http_client(endpoint, http_client=client) as streams: - yield streams + # mcp 1 also yields a session-id getter, which nothing here reads. + yield streams[0], streams[1] def _run_mcp_session( @@ -689,11 +709,7 @@ def _run_mcp_session( async def _run() -> T: with anyio.fail_after(timeout): - async with _mcp_transport(endpoint, headers, timeout, throttle) as ( - read_stream, - write_stream, - _, - ): + async with _mcp_transport(endpoint, headers, timeout, throttle) as (read_stream, write_stream): session = ClientSession( read_stream, write_stream, @@ -711,6 +727,14 @@ async def _run() -> T: _raise_mcp_failure(exc, endpoint, timeout, throttle) +def _mcp_field(model: Any, name: str, wire_name: str, default: Any = None) -> Any: + """A field of an mcp model: mcp 2 names it in snake_case, mcp 1 as the wire does.""" + try: + return getattr(model, name) + except AttributeError: + return getattr(model, wire_name, default) + + def fetch_mcp_tools( endpoint: str, headers: dict[str, str], *, timeout: float = 60.0 ) -> list[McpToolDefinition]: @@ -728,7 +752,7 @@ async def _list(session: Any) -> list[McpToolDefinition]: params = mcp_types.PaginatedRequestParams(cursor=cursor) if cursor is not None else None result = await session.list_tools(params=params) for tool in result.tools: - input_schema = tool.inputSchema or {} + input_schema = _mcp_field(tool, "input_schema", "inputSchema") or {} collected.append( McpToolDefinition( name=tool.name, @@ -736,7 +760,7 @@ async def _list(session: Any) -> list[McpToolDefinition]: input_schema=dict(input_schema), ) ) - cursor = result.nextCursor + cursor = _mcp_field(result, "next_cursor", "nextCursor") if cursor is None: break return collected @@ -744,7 +768,7 @@ async def _list(session: Any) -> list[McpToolDefinition]: return _run_mcp_session(endpoint, headers, timeout, _list) -def _response_body(response: httpx.Response) -> str: +def _response_body(response: _mcp_http.Response) -> str: """Best-effort read of an error body. The MCP transport streams, so `.text` raises until the stream is read, and by @@ -783,7 +807,7 @@ def _describe_mcp_failure(exc: BaseException, endpoint: str, timeout: float) -> # ExceptionGroup because they are raised inside the session's TaskGroup. if isinstance(current, StackOneError): return current - if isinstance(current, httpx.HTTPStatusError): + if isinstance(current, _mcp_http.HTTPStatusError): body = _response_body(current.response) detail = f": {body}" if body else "" status = f"{current.response.status_code} {current.response.reason_phrase}".rstrip() @@ -803,7 +827,7 @@ def _describe_mcp_failure(exc: BaseException, endpoint: str, timeout: float) -> # for the deadline's TimeoutError that is the cancellation, or whatever the # cancelled task happened to be catching. leaf = _leaf_failure(exc) - if isinstance(leaf, TimeoutError | httpx.TimeoutException): + if isinstance(leaf, TimeoutError | _mcp_http.TimeoutException): return ToolsetLoadError(f"MCP request to {endpoint} timed out after {_js_number(timeout)}s") return ToolsetLoadError(f"MCP request to {endpoint} failed: {type(leaf).__name__}: {leaf}") @@ -811,7 +835,7 @@ def _describe_mcp_failure(exc: BaseException, endpoint: str, timeout: float) -> def _leaf_failure(exc: BaseException) -> BaseException: """The innermost cause through group members and ``__cause__``, stopping at a timeout.""" leaf = exc - while not isinstance(leaf, TimeoutError | httpx.TimeoutException): + while not isinstance(leaf, TimeoutError | _mcp_http.TimeoutException): members = getattr(leaf, "exceptions", None) if members: leaf = members[0] @@ -832,8 +856,8 @@ def _raise_mcp_failure(exc: Exception, endpoint: str, timeout: float, throttle: :func:`is_rate_limited` reads it as the HTTP 429 it is. """ throttled = throttle.response - if throttled is not None and isinstance(_leaf_failure(exc), TimeoutError | httpx.TimeoutException): - status = httpx.HTTPStatusError( + if throttled is not None and isinstance(_leaf_failure(exc), TimeoutError | _mcp_http.TimeoutException): + status = _mcp_http.HTTPStatusError( f"429 {throttled.reason_phrase}", request=throttled.request, response=throttled ) status.__cause__ = exc @@ -929,7 +953,7 @@ def parse_tool_result(result: Any, name: str) -> JsonDict: non_text = [_plain_part(part) for part in result.content if not getattr(part, "text", "")] parsed: JsonDict = {} - structured = getattr(result, "structuredContent", None) + structured = _mcp_field(result, "structured_content", "structuredContent") if payload: try: # NaN and Infinity are not JSON; json.loads accepts them, JSON.parse does not, @@ -944,7 +968,7 @@ def parse_tool_result(result: Any, name: str) -> JsonDict: # not write into the caller's result. parsed = dict(structured) - if getattr(result, "isError", False): + if _mcp_field(result, "is_error", "isError", False): # The transport succeeded, so there is no HTTP status here — but the payload # carries the real one, and a caller cannot branch on 0. detail = payload or json.dumps(parsed, ensure_ascii=False, separators=(",", ":"), default=str) @@ -969,10 +993,8 @@ async def _call(session: Any) -> JsonDict: # against the tool's output schema, and on a fresh session that means a # tools/list first — relisting the whole catalog on every call, which the # Node SDK never does. The result is parsed below either way. - request = mcp_types.ClientRequest( - mcp_types.CallToolRequest( - params=mcp_types.CallToolRequestParams(name=name, arguments=arguments), - ) + request = mcp_types.CallToolRequest( + params=mcp_types.CallToolRequestParams(name=name, arguments=arguments) ) result = await session.send_request(request, mcp_types.CallToolResult) return parse_tool_result(result, name) diff --git a/tests/test_fetch_tools.py b/tests/test_fetch_tools.py index 2583c89..5b4aaa4 100644 --- a/tests/test_fetch_tools.py +++ b/tests/test_fetch_tools.py @@ -8,13 +8,14 @@ import time from collections.abc import Iterator from contextlib import asynccontextmanager, contextmanager +from types import SimpleNamespace from typing import Any from unittest.mock import AsyncMock, MagicMock, patch import httpx import pytest -from stackone_ai.tools import McpToolDefinition, StackOneMcpTool, fetch_mcp_tools +from stackone_ai.tools import McpToolDefinition, StackOneMcpTool, _mcp_http, fetch_mcp_tools from stackone_ai.toolset import StackOneToolSet from stackone_ai.types import ( SUBMIT_FEEDBACK_TOOL_NAME, @@ -593,15 +594,13 @@ class TestFetchMcpToolsInternal: def test_fetch_mcp_tools_single_page(self): """Test fetching tools with single page response.""" - # Create mock tool response - mock_tool = MagicMock() - mock_tool.name = "test_tool" - mock_tool.description = "Test description" - mock_tool.inputSchema = {"type": "object", "properties": {"id": {"type": "string"}}} - - mock_result = MagicMock() - mock_result.tools = [mock_tool] - mock_result.nextCursor = None + # Plain objects, not MagicMocks, which would answer any field name either mcp generation reads. + mock_tool = SimpleNamespace( + name="test_tool", + description="Test description", + inputSchema={"type": "object", "properties": {"id": {"type": "string"}}}, + ) + mock_result = SimpleNamespace(tools=[mock_tool], nextCursor=None) # Create mock session mock_session = AsyncMock() @@ -611,7 +610,7 @@ def test_fetch_mcp_tools_single_page(self): mock_session.__aexit__ = AsyncMock(return_value=None) # Create mock streamable client - seen_clients: list[httpx.AsyncClient] = [] + seen_clients: list[_mcp_http.AsyncClient] = [] @asynccontextmanager async def mock_streamable_client(endpoint, *, http_client, **_kwargs: object): @@ -634,7 +633,7 @@ async def mock_streamable_client(endpoint, *, http_client, **_kwargs: object): # The caller's headers and timeout reach the HTTP client, on every leg. [client] = seen_clients assert client.headers["Authorization"] == "Basic test" - assert client.timeout == httpx.Timeout(7) + assert client.timeout == _mcp_http.Timeout(7) assert client.follow_redirects is True assert len(result) == 1 @@ -644,25 +643,14 @@ async def mock_streamable_client(endpoint, *, http_client, **_kwargs: object): def test_fetch_mcp_tools_with_pagination(self): """Test fetching tools with multiple pages.""" - # First page - mock_tool1 = MagicMock() - mock_tool1.name = "tool_1" - mock_tool1.description = "Tool 1" - mock_tool1.inputSchema = {} - - mock_result1 = MagicMock() - mock_result1.tools = [mock_tool1] - mock_result1.nextCursor = "cursor_page_2" - - # Second page - mock_tool2 = MagicMock() - mock_tool2.name = "tool_2" - mock_tool2.description = "Tool 2" - mock_tool2.inputSchema = None # Test None inputSchema - - mock_result2 = MagicMock() - mock_result2.tools = [mock_tool2] - mock_result2.nextCursor = None + mock_result1 = SimpleNamespace( + tools=[SimpleNamespace(name="tool_1", description="Tool 1", inputSchema={})], + nextCursor="cursor_page_2", + ) + mock_result2 = SimpleNamespace( + tools=[SimpleNamespace(name="tool_2", description="Tool 2", inputSchema=None)], + nextCursor=None, + ) # Create mock session with pagination mock_session = AsyncMock() @@ -1220,13 +1208,11 @@ class TestListingFailuresAreDiagnosable: """A failure must name the status, not hide it behind TaskGroup boilerplate.""" def test_http_error_carries_status_and_is_not_taskgroup_noise(self, monkeypatch): - import httpx - from stackone_ai.tools import _describe_mcp_failure - request = httpx.Request("POST", "https://api.example.com/mcp") - response = httpx.Response(412, text='{"message":"re-link the account"}', request=request) - inner = httpx.HTTPStatusError("412", request=request, response=response) + request = _mcp_http.Request("POST", "https://api.example.com/mcp") + response = _mcp_http.Response(412, text='{"message":"re-link the account"}', request=request) + inner = _mcp_http.HTTPStatusError("412", request=request, response=response) # Mirrors reality: the MCP client raises inside a TaskGroup, so the real # error arrives wrapped in an ExceptionGroup. grouped = ExceptionGroup("unhandled errors in a TaskGroup", [inner]) diff --git a/tests/test_rate_limit.py b/tests/test_rate_limit.py index 6302d5e..52cc09e 100644 --- a/tests/test_rate_limit.py +++ b/tests/test_rate_limit.py @@ -19,6 +19,7 @@ RateLimitRetryingAsyncClient, RateLimitRetryingClient, _buffer_error_body, + _mcp_http, _rate_limit_delay, _retry_after_seconds, _Throttle, @@ -54,20 +55,20 @@ async def fake_async_sleep(delay: float) -> None: return recorded -def _responder(*responses: httpx.Response) -> tuple[list[httpx.Request], Any]: +def _responder(*responses: Any) -> tuple[list[Any], Any]: """A handler that answers with ``responses`` in turn, repeating the last, and the requests it saw.""" - seen: list[httpx.Request] = [] + seen: list[Any] = [] - def handler(request: httpx.Request) -> httpx.Response: + def handler(request: Any) -> Any: seen.append(request) return responses[min(len(seen), len(responses)) - 1] return seen, handler -def _429(retry_after: str | None = None) -> httpx.Response: +def _429(retry_after: str | None = None, *, http: Any = httpx) -> Any: headers = {"Retry-After": retry_after} if retry_after is not None else {} - return httpx.Response(429, headers=headers, json={"message": "Too many requests"}) + return http.Response(429, headers=headers, json={"message": "Too many requests"}) def _recorded(base_url: str, account_id: str, method: str) -> list[dict[str, Any]]: @@ -145,20 +146,25 @@ class TestAsyncClient: def _run(self, handler: Any, *, stream: bool) -> tuple[int, bytes]: async def go() -> tuple[int, bytes]: async with RateLimitRetryingAsyncClient( - transport=httpx.MockTransport(handler), + transport=_mcp_http.MockTransport(handler), event_hooks={"response": [_buffer_error_body]}, ) as client: - if not stream: - response = await client.post(URL, json={"jsonrpc": "2.0"}) - return response.status_code, response.content - async with client.stream("POST", URL, json={"jsonrpc": "2.0"}) as response: - return response.status_code, await response.aread() + try: + if not stream: + response = await client.post(URL, json={"jsonrpc": "2.0"}) + return response.status_code, response.content + async with client.stream("POST", URL, json={"jsonrpc": "2.0"}) as response: + return response.status_code, await response.aread() + except _mcp_http.HTTPStatusError as exc: + return exc.response.status_code, exc.response.content return asyncio.run(go()) @pytest.mark.parametrize("stream", [False, True]) def test_a_429_then_success_resends_the_same_body(self, sleeps: list[float], stream: bool): - seen, handler = _responder(_429("1"), _429(), httpx.Response(200, json={"ok": True})) + seen, handler = _responder( + _429("1", http=_mcp_http), _429(http=_mcp_http), _mcp_http.Response(200, json={"ok": True}) + ) assert self._run(handler, stream=stream) == (200, b'{"ok":true}') assert [r.content for r in seen] == [b'{"jsonrpc":"2.0"}'] * 3 assert sleeps[0] == 1.0 @@ -166,14 +172,14 @@ def test_a_429_then_success_resends_the_same_body(self, sleeps: list[float], str @pytest.mark.parametrize("stream", [False, True]) def test_the_last_429_keeps_its_body(self, sleeps: list[float], stream: bool): - seen, handler = _responder(_429("0")) + seen, handler = _responder(_429("0", http=_mcp_http)) assert self._run(handler, stream=stream) == (429, b'{"message":"Too many requests"}') assert len(seen) == 4 assert sleeps == [0.0, 0.0, 0.0] @pytest.mark.parametrize("status", [400, 500]) def test_no_retry_on_any_other_status(self, sleeps: list[float], status: int): - seen, handler = _responder(httpx.Response(status)) + seen, handler = _responder(_mcp_http.Response(status)) assert self._run(handler, stream=True)[0] == status assert len(seen) == 1 assert sleeps == [] @@ -263,19 +269,19 @@ def handler(_self: Any, request: httpx.Request) -> httpx.Response: @staticmethod def _429_then_hang(monkeypatch: pytest.MonkeyPatch, account: str) -> None: """The MCP host answers ``account`` 429 once, then never answers its retry.""" - real = httpx.AsyncHTTPTransport.handle_async_request + real = _mcp_http.AsyncHTTPTransport.handle_async_request attempts: dict[str, int] = {} - async def handler(self: Any, request: httpx.Request) -> httpx.Response: + async def handler(self: Any, request: _mcp_http.Request) -> _mcp_http.Response: if request.headers.get("x-account-id") != account: return await real(self, request) attempts[account] = attempts.get(account, 0) + 1 if attempts[account] == 1: - return _429("0") + return _429("0", http=_mcp_http) await asyncio.sleep(60) raise AssertionError("the exchange's deadline should have cancelled this") - monkeypatch.setattr(httpx.AsyncHTTPTransport, "handle_async_request", handler) + monkeypatch.setattr(_mcp_http.AsyncHTTPTransport, "handle_async_request", handler) def test_listing(self, sleeps: list[float], monkeypatch: pytest.MonkeyPatch): self._429_then_hang(monkeypatch, "throttled") @@ -288,11 +294,11 @@ def test_listing(self, sleeps: list[float], monkeypatch: pytest.MonkeyPatch): assert is_rate_limited(excinfo.value) def test_a_timeout_with_no_429_is_still_a_timeout(self, monkeypatch: pytest.MonkeyPatch): - async def hang(_self: Any, _request: httpx.Request) -> httpx.Response: + async def hang(_self: Any, _request: _mcp_http.Request) -> _mcp_http.Response: await asyncio.sleep(60) raise AssertionError("unreachable") - monkeypatch.setattr(httpx.AsyncHTTPTransport, "handle_async_request", hang) + monkeypatch.setattr(_mcp_http.AsyncHTTPTransport, "handle_async_request", hang) with pytest.raises(ToolsetLoadError, match="timed out after 0.5s"): fetch_mcp_tools(URL, {"x-account-id": "a"}, timeout=0.5) @@ -337,21 +343,21 @@ def test_the_throttle_survives_another_requests_answer(self, sleeps: list[float] list_attempts = 0 retry_started = asyncio.Event() - async def handler(request: httpx.Request) -> httpx.Response: + async def handler(request: _mcp_http.Request) -> _mcp_http.Response: nonlocal list_attempts if request.method == "GET": await retry_started.wait() - return httpx.Response(405) + return _mcp_http.Response(405) list_attempts += 1 if list_attempts == 1: - return _429("0") + return _429("0", http=_mcp_http) retry_started.set() await asyncio.sleep(60) raise AssertionError("cancelled before this") - async def go() -> httpx.Response | None: + async def go() -> _mcp_http.Response | None: async with RateLimitRetryingAsyncClient( - transport=httpx.MockTransport(handler), throttle=throttle + transport=_mcp_http.MockTransport(handler), throttle=throttle ) as client: listing = asyncio.create_task(client.post(URL, json={"method": "tools/list"})) # Bounded, so a change that never retries fails here rather than hanging the run. @@ -375,24 +381,24 @@ class TestAStaleThrottleMarkerDoesNotTaintALaterTimeout: def _429_once_on_initialize_then_hang_on_list(monkeypatch: pytest.MonkeyPatch, account: str) -> None: import json as _json - real = httpx.AsyncHTTPTransport.handle_async_request + real = _mcp_http.AsyncHTTPTransport.handle_async_request attempts: dict[str, int] = {} - async def handler(self: Any, request: httpx.Request) -> httpx.Response: + async def handler(self: Any, request: _mcp_http.Request) -> _mcp_http.Response: if request.headers.get("x-account-id") != account: return await real(self, request) method = _json.loads(request.content or b"{}").get("method") if method == "initialize": attempts["initialize"] = attempts.get("initialize", 0) + 1 if attempts["initialize"] == 1: - return _429("0") + return _429("0", http=_mcp_http) return await real(self, request) if method == "tools/list": await asyncio.sleep(60) raise AssertionError("the exchange's deadline should have cancelled this") return await real(self, request) - monkeypatch.setattr(httpx.AsyncHTTPTransport, "handle_async_request", handler) + monkeypatch.setattr(_mcp_http.AsyncHTTPTransport, "handle_async_request", handler) def test_fetch_mcp_tools_times_out_rather_than_reporting_a_stale_429( self, mcp_mock_server: str, sleeps: list[float], monkeypatch: pytest.MonkeyPatch @@ -424,26 +430,26 @@ class TestA429ThenAStalledStreamIsATimeout: def _429_then_stall_on_list(monkeypatch: pytest.MonkeyPatch, account: str) -> None: import json as _json - real = httpx.AsyncHTTPTransport.handle_async_request + real = _mcp_http.AsyncHTTPTransport.handle_async_request attempts: list[int] = [] - class Stalled(httpx.AsyncByteStream): + class Stalled(_mcp_http.AsyncByteStream): async def __aiter__(self) -> Any: yield b"event: message\n" await asyncio.sleep(60) raise AssertionError("the exchange's deadline should have cancelled this") - async def handler(self: Any, request: httpx.Request) -> httpx.Response: + async def handler(self: Any, request: _mcp_http.Request) -> _mcp_http.Response: if request.headers.get("x-account-id") != account: return await real(self, request) if _json.loads(request.content or b"{}").get("method") != "tools/list": return await real(self, request) attempts.append(1) if len(attempts) == 1: - return _429("0") - return httpx.Response(200, headers={"content-type": "text/event-stream"}, stream=Stalled()) + return _429("0", http=_mcp_http) + return _mcp_http.Response(200, headers={"content-type": "text/event-stream"}, stream=Stalled()) - monkeypatch.setattr(httpx.AsyncHTTPTransport, "handle_async_request", handler) + monkeypatch.setattr(_mcp_http.AsyncHTTPTransport, "handle_async_request", handler) def test_listing(self, mcp_mock_server: str, sleeps: list[float], monkeypatch: pytest.MonkeyPatch): self._429_then_stall_on_list(monkeypatch, "acc1") diff --git a/tests/test_shared_vectors.py b/tests/test_shared_vectors.py index bddc5c7..e2f9357 100644 --- a/tests/test_shared_vectors.py +++ b/tests/test_shared_vectors.py @@ -31,6 +31,7 @@ Tools, _backoff_delay, _describe_mcp_failure, + _mcp_http, _outlasts_deadline, _raise_mcp_failure, _retry_after_seconds, @@ -495,8 +496,8 @@ def _mcp_timeout(mp, log) -> Emitted: def _mcp_http_failure(mp, log) -> Emitted: - response = httpx.Response(503, text=" down ", request=httpx.Request("POST", ENDPOINT)) - failure = httpx.HTTPStatusError("503", request=response.request, response=response) + response = _mcp_http.Response(503, text=" down ", request=_mcp_http.Request("POST", ENDPOINT)) + failure = _mcp_http.HTTPStatusError("503", request=response.request, response=response) values = {"endpoint": ENDPOINT, "status": 503, "reason_phrase": "Service Unavailable", "body": "down"} return _describe_mcp_failure(failure, ENDPOINT, 60), values @@ -508,7 +509,7 @@ def _mcp_failure(mp, log) -> Emitted: def _mcp_rate_limit_timeout(mp, log) -> Emitted: - throttled = httpx.Response(429, request=httpx.Request("POST", ENDPOINT)) + throttled = _mcp_http.Response(429, request=_mcp_http.Request("POST", ENDPOINT)) throttle = _Throttle(response=throttled) error = _raised(StackOneAPIError, lambda: _raise_mcp_failure(TimeoutError(), ENDPOINT, 0.5, throttle)) assert error.status_code == 429 diff --git a/uv.lock b/uv.lock index ff76f2e..66cbb78 100644 --- a/uv.lock +++ b/uv.lock @@ -3,8 +3,8 @@ revision = 5 requires-python = ">=3.11" resolution-markers = [ "python_full_version >= '3.15' and sys_platform == 'win32'", - "python_full_version == '3.14.*' and sys_platform == 'win32'", "python_full_version >= '3.15' and sys_platform != 'win32'", + "python_full_version == '3.14.*' and sys_platform == 'win32'", "python_full_version == '3.14.*' and sys_platform != 'win32'", "python_full_version == '3.13.*' and sys_platform == 'win32'", "python_full_version == '3.13.*' and sys_platform != 'win32'", @@ -97,21 +97,33 @@ wheels = [ ] [[package]] -name = "backports-tarfile" -version = "1.2.0" +name = "beartype" +version = "0.22.9" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/86/72/cd9b395f25e290e633655a100af28cb253e4393396264a98bd5f5951d50f/backports_tarfile-1.2.0.tar.gz", hash = "sha256:d75e02c268746e1b8144c278978b6e98e85de6ad16f8e4b0844a154557eca991", size = 86406, upload-time = "2024-05-28T17:01:54.731Z" } +resolution-markers = [ + "python_full_version == '3.14.*' and sys_platform == 'win32'", + "python_full_version == '3.14.*' and sys_platform != 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'win32'", + "python_full_version == '3.13.*' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'emscripten'", + "python_full_version < '3.12' or (python_full_version == '3.12.*' and sys_platform != 'emscripten')", +] +sdist = { url = "https://files.pythonhosted.org/packages/c7/94/1009e248bbfbab11397abca7193bea6626806be9a327d399810d523a07cb/beartype-0.22.9.tar.gz", hash = "sha256:8f82b54aa723a2848a56008d18875f91c1db02c32ef6a62319a002e3e25a975f", size = 1608866, upload-time = "2025-12-13T06:50:30.72Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/b9/fa/123043af240e49752f1c4bd24da5053b6bd00cad78c2be53c0d1e8b975bc/backports.tarfile-1.2.0-py3-none-any.whl", hash = "sha256:77e284d754527b01fb1e6fa8a1afe577858ebe4e9dad8919e34c862cb399bc34", size = 30181, upload-time = "2024-05-28T17:01:53.112Z" }, + { url = "https://files.pythonhosted.org/packages/71/cc/18245721fa7747065ab478316c7fea7c74777d07f37ae60db2e84f8172e8/beartype-0.22.9-py3-none-any.whl", hash = "sha256:d16c9bbc61ea14637596c5f6fbff2ee99cbe3573e46a716401734ef50c3060c2", size = 1333658, upload-time = "2025-12-13T06:50:28.266Z" }, ] [[package]] name = "beartype" -version = "0.22.9" +version = "0.23.1" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/c7/94/1009e248bbfbab11397abca7193bea6626806be9a327d399810d523a07cb/beartype-0.22.9.tar.gz", hash = "sha256:8f82b54aa723a2848a56008d18875f91c1db02c32ef6a62319a002e3e25a975f", size = 1608866, upload-time = "2025-12-13T06:50:30.72Z" } +resolution-markers = [ + "python_full_version >= '3.15' and sys_platform == 'win32'", + "python_full_version >= '3.15' and sys_platform != 'win32'", +] +sdist = { url = "https://files.pythonhosted.org/packages/79/34/c0cfdaee9c796c8381439fed0fcab62810753b8b0adb1ec88fa7f41eaa5d/beartype-0.23.1.tar.gz", hash = "sha256:8b805f246b32931c74f2b321ea0939fe5bb2ff43c12a3eff19cc4c854b832e1d", size = 1993714, upload-time = "2026-10-11T05:36:55.251Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/71/cc/18245721fa7747065ab478316c7fea7c74777d07f37ae60db2e84f8172e8/beartype-0.22.9-py3-none-any.whl", hash = "sha256:d16c9bbc61ea14637596c5f6fbff2ee99cbe3573e46a716401734ef50c3060c2", size = 1333658, upload-time = "2025-12-13T06:50:28.266Z" }, + { url = "https://files.pythonhosted.org/packages/1c/cb/2f6aa982e2860c1156830db3da7f823b71784ed7d533ca289ea9b6c6347a/beartype-0.23.1-py3-none-any.whl", hash = "sha256:4461b4dc57e3fdd6c8a8464b22cf118002eea107c33e9fef651c69068ab3cce3", size = 1582101, upload-time = "2026-10-11T05:36:52.431Z" }, ] [[package]] @@ -532,9 +544,10 @@ wheels = [ [[package]] name = "fastmcp-slim" -version = "3.4.10" +version = "4.1.4" source = { registry = "https://pypi.org/simple" } dependencies = [ + { name = "mcp-types" }, { name = "platformdirs" }, { name = "pydantic", extra = ["email"] }, { name = "pydantic-settings" }, @@ -542,19 +555,20 @@ dependencies = [ { name = "rich" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/98/3b/28be7f0963fee1c848e78898d801e1232dd2e05b6e37026c400a788caa9a/fastmcp_slim-3.4.10.tar.gz", hash = "sha256:d80ae606ead8dfefa1f21b009929824210ea87eb4b422653a1be8dca61797ccd", size = 610326, upload-time = "2026-10-20T14:49:15.096Z" } +sdist = { url = "https://files.pythonhosted.org/packages/9d/a0/475de742162be2b75b9ac0a7d3e1396f797ca97789a8373ed60581a222ee/fastmcp_slim-4.1.4.tar.gz", hash = "sha256:d1034317e4e2960dd619930c01baabbc77e60825f55c09f93471afa427a68cd7", size = 753435, upload-time = "2026-10-26T06:23:55.282Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/7c/28/1e0681b524191ee170f40e8e800fd3785084e12806fc46675c70d7f8fa43/fastmcp_slim-3.4.10-py3-none-any.whl", hash = "sha256:f388941db8bdf38999e6c9d2536c4cd59a6571908d851cee2d10ee59f4e53532", size = 785895, upload-time = "2026-10-20T14:49:13.466Z" }, + { url = "https://files.pythonhosted.org/packages/4a/d2/bbbf9cb1a92e7f98c34845c8f06f21516fd38efdcd579ecbc0131bb6d4d5/fastmcp_slim-4.1.4-py3-none-any.whl", hash = "sha256:0f611b246504ff0d0ee7ab77123f529b5c9aed68670eaee9c6f960a59bb024da", size = 935728, upload-time = "2026-10-26T06:23:53.486Z" }, ] [package.optional-dependencies] client = [ { name = "authlib" }, + { name = "beartype", version = "0.23.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.15'" }, { name = "exceptiongroup" }, - { name = "httpx" }, + { name = "httpx2" }, { name = "mcp" }, { name = "opentelemetry-api" }, - { name = "py-key-value-aio", extra = ["filetree", "keyring", "memory"] }, + { name = "py-key-value-aio", extra = ["filetree", "memory"] }, { name = "starlette" }, ] @@ -681,15 +695,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/2a/39/e50c7c3a983047577ee07d2a9e53faf5a69493943ec3f6a384bdc792deb2/httpx-0.28.1-py3-none-any.whl", hash = "sha256:d909fcccc110f8c7faf814ca82a9a4d816bc5a6dbfea25d6591d6985b8ba59ad", size = 73517, upload-time = "2024-12-06T15:37:21.509Z" }, ] -[[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 = "httpx2" version = "2.13.1" @@ -818,18 +823,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/58/a2/bb081bab032533a855d44de1d56f8e8426114ff1ba5d1f07a438a0a654f8/idna-3.20-py3-none-any.whl", hash = "sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582c", size = 69583, upload-time = "2026-09-17T14:11:03.168Z" }, ] -[[package]] -name = "importlib-metadata" -version = "8.7.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "zipp" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/f3/49/3b30cad09e7771a4982d9975a8cbf64f00d4a1ececb53297f1d9a7be1b10/importlib_metadata-8.7.1.tar.gz", hash = "sha256:49fef1ae6440c182052f407c8d34a68f72efc36db9ca90dc0113398f2fdde8bb", size = 57107, upload-time = "2025-12-21T10:00:19.278Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/fa/5e/f8e9a1d23b9c20a551a8a02ea3637b4642e22c2626e3a13a9a29cdea99eb/importlib_metadata-8.7.1-py3-none-any.whl", hash = "sha256:5a1f80bf1daa489495071efbb095d75a634cf28a8bc299581244063b53176151", size = 27865, upload-time = "2025-12-21T10:00:18.329Z" }, -] - [[package]] name = "iniconfig" version = "2.3.0" @@ -839,51 +832,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/cb/b1/3846dd7f199d53cb17f49cba7e651e9ce294d8497c8c150530ed11865bb8/iniconfig-2.3.0-py3-none-any.whl", hash = "sha256:f631c04d2c48c52b84d0d0549c99ff3859c98df65b3101406327ecc7d53fbf12", size = 7484, upload-time = "2025-10-18T21:55:41.639Z" }, ] -[[package]] -name = "jaraco-classes" -version = "3.4.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "more-itertools" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/06/c0/ed4a27bc5571b99e3cff68f8a9fa5b56ff7df1c2251cc715a652ddd26402/jaraco.classes-3.4.0.tar.gz", hash = "sha256:47a024b51d0239c0dd8c8540c6c7f484be3b8fcf0b2d85c13825780d3b3f3acd", size = 11780, upload-time = "2024-03-31T07:27:36.643Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/7f/66/b15ce62552d84bbfcec9a4873ab79d993a1dd4edb922cbfccae192bd5b5f/jaraco.classes-3.4.0-py3-none-any.whl", hash = "sha256:f662826b6bed8cace05e7ff873ce0f9283b5c924470fe664fff1c2f00f581790", size = 6777, upload-time = "2024-03-31T07:27:34.792Z" }, -] - -[[package]] -name = "jaraco-context" -version = "6.1.2" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "backports-tarfile", marker = "python_full_version < '3.12'" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/af/50/4763cd07e722bb6285316d390a164bc7e479db9d90daa769f22578f698b4/jaraco_context-6.1.2.tar.gz", hash = "sha256:f1a6c9d391e661cc5b8d39861ff077a7dc24dc23833ccee564b234b81c82dfe3", size = 16801, upload-time = "2026-03-20T22:13:33.922Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/f2/58/bc8954bda5fcda97bd7c19be11b85f91973d67a706ed4a3aec33e7de22db/jaraco_context-6.1.2-py3-none-any.whl", hash = "sha256:bf8150b79a2d5d91ae48629d8b427a8f7ba0e1097dd6202a9059f29a36379535", size = 7871, upload-time = "2026-03-20T22:13:32.808Z" }, -] - -[[package]] -name = "jaraco-functools" -version = "4.4.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "more-itertools" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/0f/27/056e0638a86749374d6f57d0b0db39f29509cce9313cf91bdc0ac4d91084/jaraco_functools-4.4.0.tar.gz", hash = "sha256:da21933b0417b89515562656547a77b4931f98176eb173644c0d35032a33d6bb", size = 19943, upload-time = "2025-12-21T09:29:43.6Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/fd/c4/813bb09f0985cb21e959f21f2464169eca882656849adf727ac7bb7e1767/jaraco_functools-4.4.0-py3-none-any.whl", hash = "sha256:9eec1e36f45c818d9bf307c8948eb03b2b56cd44087b3cdc989abca1f20b9176", size = 10481, upload-time = "2025-12-21T09:29:42.27Z" }, -] - -[[package]] -name = "jeepney" -version = "0.9.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/7b/6f/357efd7602486741aa73ffc0617fb310a29b588ed0fd69c2399acbb85b0c/jeepney-0.9.0.tar.gz", hash = "sha256:cf0e9e845622b81e4a28df94c40345400256ec608d0e55bb8a3feaa9163f5732", size = 106758, upload-time = "2025-02-27T18:51:01.684Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/b2/a3/e137168c9c44d18eff0376253da9f1e9234d0239e0ee230d2fee6cea8e55/jeepney-0.9.0-py3-none-any.whl", hash = "sha256:97e5714520c16fc0a45695e5365a2e11b81ea79bba796e26f9f1d178cb182683", size = 49010, upload-time = "2025-02-27T18:51:00.104Z" }, -] - [[package]] name = "jiter" version = "0.18.0" @@ -1057,24 +1005,6 @@ 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 = "keyring" -version = "25.7.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "importlib-metadata", marker = "python_full_version < '3.12'" }, - { name = "jaraco-classes" }, - { name = "jaraco-context" }, - { name = "jaraco-functools" }, - { name = "jeepney", marker = "sys_platform == 'linux'" }, - { name = "pywin32-ctypes", marker = "sys_platform == 'win32'" }, - { name = "secretstorage", marker = "sys_platform == 'linux'" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/43/4b/674af6ef2f97d56f0ab5153bf0bfa28ccb6c3ed4d1babf4305449668807b/keyring-25.7.0.tar.gz", hash = "sha256:fe01bd85eb3f8fb3dd0405defdeac9a5b4f6f0439edbb3149577f244a2e8245b", size = 63516, upload-time = "2025-11-16T16:26:09.482Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/81/db/e655086b7f3a705df045bf0933bdd9c2f79bb3c97bfef1384598bb79a217/keyring-25.7.0-py3-none-any.whl", hash = "sha256:be4a0b195f149690c166e850609a477c532ddbfbaed96a404d4e43f8d5e2689f", size = 39160, upload-time = "2025-11-16T16:26:08.402Z" }, -] - [[package]] name = "langchain" version = "1.4.9" @@ -1271,15 +1201,15 @@ wheels = [ [[package]] name = "mcp" -version = "1.30.0" +version = "2.3.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "anyio" }, - { name = "httpx" }, - { name = "httpx-sse" }, + { name = "httpx2" }, { name = "jsonschema" }, + { name = "mcp-types" }, + { name = "opentelemetry-api" }, { name = "pydantic" }, - { name = "pydantic-settings" }, { name = "pyjwt", extra = ["crypto"] }, { name = "python-multipart" }, { name = "pywin32", marker = "sys_platform == 'win32'" }, @@ -1289,27 +1219,31 @@ dependencies = [ { 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" } +sdist = { url = "https://files.pythonhosted.org/packages/9d/8d/e0d339616f4810e9051d4aba6887afab289ab1f81875fe908b606cdfd0e3/mcp-2.3.0.tar.gz", hash = "sha256:8b147a50441cf059dc88c684e0aeed3687f0aa0f39c6cde7b90330effd2b34d8", size = 4171955, upload-time = "2026-10-02T22:06:56.091Z" } 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" }, + { url = "https://files.pythonhosted.org/packages/20/d7/4a2878f128df729db3ca04e71bfce26405cc2e0c9ebe19c592feeb4c61b9/mcp-2.3.0-py3-none-any.whl", hash = "sha256:dd0c44c089d16453e8ae31a3877a0054d7a2314caaa81f5e0541b9b1734b2377", size = 368664, upload-time = "2026-10-02T22:06:52.119Z" }, ] [[package]] -name = "mdurl" -version = "0.1.2" +name = "mcp-types" +version = "2.3.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/d6/54/cfe61301667036ec958cb99bd3efefba235e65cdeb9c84d24a8293ba1d90/mdurl-0.1.2.tar.gz", hash = "sha256:bb413d29f5eea38f31dd4754dd7377d4465116fb207585f97bf925588687c1ba", size = 8729, upload-time = "2022-08-14T12:40:10.846Z" } +dependencies = [ + { name = "pydantic" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/9e/2d/7c251e34207f6c51000312fc8839111ac45cfe02023f90b44e7f1051dd8e/mcp_types-2.3.0.tar.gz", hash = "sha256:d1e46549edb35ee19a94940fcee6d1addd7e589ab7ea92dda83f5d84781fc362", size = 65898, upload-time = "2026-10-02T22:06:57.863Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/b3/38/89ba8ad64ae25be8de66a6d463314cf1eb366222074cfda9ee839c56a4b4/mdurl-0.1.2-py3-none-any.whl", hash = "sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8", size = 9979, upload-time = "2022-08-14T12:40:09.779Z" }, + { url = "https://files.pythonhosted.org/packages/ce/48/32583066b155bb5d4507e7887dc88ee23118cc4de8e2a12870c49719e2a8/mcp_types-2.3.0-py3-none-any.whl", hash = "sha256:968efdbdaedfab06adae40d378a34395f1090c5921d4be3c9cde283aaf76d91d", size = 69108, upload-time = "2026-10-02T22:06:54.099Z" }, ] [[package]] -name = "more-itertools" -version = "11.0.2" +name = "mdurl" +version = "0.1.2" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/a2/f7/139d22fef48ac78127d18e01d80cf1be40236ae489769d17f35c3d425293/more_itertools-11.0.2.tar.gz", hash = "sha256:392a9e1e362cbc106a2457d37cabf9b36e5e12efd4ebff1654630e76597df804", size = 144659, upload-time = "2026-04-09T15:01:33.297Z" } +sdist = { url = "https://files.pythonhosted.org/packages/d6/54/cfe61301667036ec958cb99bd3efefba235e65cdeb9c84d24a8293ba1d90/mdurl-0.1.2.tar.gz", hash = "sha256:bb413d29f5eea38f31dd4754dd7377d4465116fb207585f97bf925588687c1ba", size = 8729, upload-time = "2022-08-14T12:40:10.846Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/cb/98/6af411189d9413534c3eb691182bff1f5c6d44ed2f93f2edfe52a1bbceb8/more_itertools-11.0.2-py3-none-any.whl", hash = "sha256:6e35b35f818b01f691643c6c611bc0902f2e92b46c18fffa77ae1e7c46e912e4", size = 71939, upload-time = "2026-04-09T15:01:32.21Z" }, + { url = "https://files.pythonhosted.org/packages/b3/38/89ba8ad64ae25be8de66a6d463314cf1eb366222074cfda9ee839c56a4b4/mdurl-0.1.2-py3-none-any.whl", hash = "sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8", size = 9979, upload-time = "2022-08-14T12:40:09.779Z" }, ] [[package]] @@ -1655,7 +1589,8 @@ name = "py-key-value-aio" version = "0.4.4" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "beartype" }, + { name = "beartype", version = "0.22.9", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.15'" }, + { name = "beartype", version = "0.23.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.15'" }, { name = "typing-extensions" }, ] sdist = { url = "https://files.pythonhosted.org/packages/04/3c/0397c072a38d4bc580994b42e0c90c5f44f679303489e4376289534735e5/py_key_value_aio-0.4.4.tar.gz", hash = "sha256:e3012e6243ed7cc09bb05457bd4d03b1ba5c2b1ca8700096b3927db79ffbbe55", size = 92300, upload-time = "2026-02-16T21:21:43.245Z" } @@ -1668,9 +1603,6 @@ filetree = [ { name = "aiofile" }, { name = "anyio" }, ] -keyring = [ - { name = "keyring" }, -] memory = [ { name = "cachetools" }, ] @@ -2083,15 +2015,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/c0/d2/21af5c535501a7233e734b8af901574572da66fcc254cb35d0609c9080dd/pywin32-311-cp314-cp314-win_arm64.whl", hash = "sha256:a508e2d9025764a8270f93111a970e1d0fbfc33f4153b388bb649b7eec4f9b42", size = 8932540, upload-time = "2025-07-14T20:13:36.379Z" }, ] -[[package]] -name = "pywin32-ctypes" -version = "0.2.3" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/85/9f/01a1a99704853cb63f253eea009390c88e7131c67e66a0a02099a8c917cb/pywin32-ctypes-0.2.3.tar.gz", hash = "sha256:d162dc04946d704503b2edc4d55f3dba5c1d539ead017afa00142c38b9885755", size = 29471, upload-time = "2024-08-14T10:15:34.626Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/de/3d/8161f7711c017e01ac9f008dfddd9410dff3674334c233bde66e7ba65bbf/pywin32_ctypes-0.2.3-py3-none-any.whl", hash = "sha256:8a1513379d709975552d202d942d9837758905c8d01eb82b8bcc30918929e7b8", size = 30756, upload-time = "2024-08-14T10:15:33.187Z" }, -] - [[package]] name = "pyyaml" version = "6.0.3" @@ -2426,19 +2349,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/68/9e/f1dbffcfb8ff25dadbc21f87a8b73c3848abe4abada9d4b08ccef8bec40c/ruff-0.17.4-py3-none-win_arm64.whl", hash = "sha256:181ae38a9a8fb94925bf7d0794327b48d7fd7f4b50cfd84c0e999cc09ef8d131", size = 9889396, upload-time = "2026-11-05T18:52:15.549Z" }, ] -[[package]] -name = "secretstorage" -version = "3.5.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "cryptography" }, - { name = "jeepney" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/1c/03/e834bcd866f2f8a49a85eaff47340affa3bfa391ee9912a952a1faa68c7b/secretstorage-3.5.0.tar.gz", hash = "sha256:f04b8e4689cbce351744d5537bf6b1329c6fc68f91fa666f60a380edddcd11be", size = 19884, upload-time = "2025-11-23T19:02:53.191Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/b7/46/f5af3402b579fd5e11573ce652019a67074317e18c1935cc0b4ba9b35552/secretstorage-3.5.0-py3-none-any.whl", hash = "sha256:0ce65888c0725fcb2c5bc0fdb8e5438eece02c523557ea40ce0703c266248137", size = 15554, upload-time = "2025-11-23T19:02:51.545Z" }, -] - [[package]] name = "sniffio" version = "1.3.1" @@ -2513,7 +2423,7 @@ requires-dist = [ { name = "langchain-core", marker = "extra == 'dev'", specifier = ">=0.3.36" }, { name = "langchain-core", marker = "extra == 'langchain'", specifier = ">=0.3.36" }, { name = "langchain-openai", marker = "extra == 'examples'", specifier = ">=1.1.14" }, - { name = "mcp", specifier = ">=1.30.0,<2.0.0" }, + { name = "mcp", specifier = ">=1.30.0,<3.0.0" }, { name = "openai", marker = "extra == 'examples'", specifier = ">=2.32.0" }, { name = "pydantic", specifier = ">=2.10.6" }, { name = "pydantic-ai", marker = "extra == 'examples'", specifier = ">=1.83.0" }, @@ -2972,15 +2882,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/7b/d9/8d95e906764a386a3d3b596f3c68bb63687dfca806373509f51ce8eea81f/xxhash-3.6.0-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:15e0dac10eb9309508bfc41f7f9deaa7755c69e35af835db9cb10751adebc35d", size = 31565, upload-time = "2025-10-02T14:37:06.966Z" }, ] -[[package]] -name = "zipp" -version = "3.23.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/e3/02/0f2892c661036d50ede074e376733dca2ae7c6eb617489437771209d4180/zipp-3.23.0.tar.gz", hash = "sha256:a07157588a12518c9d4034df3fbbee09c814741a33ff63c05fa29d26a2404166", size = 25547, upload-time = "2025-06-08T17:06:39.4Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/2e/54/647ade08bf0db230bfea292f893923872fd20be6ac6f53b2b936ba839d75/zipp-3.23.0-py3-none-any.whl", hash = "sha256:071652d6115ed432f5ce1d34c336c0adfd6a884660d1e9712a256d3d3bd4b14e", size = 10276, upload-time = "2025-06-08T17:06:38.034Z" }, -] - [[package]] name = "zstandard" version = "0.25.0" From 5429c2bc4da4e14c629972b98b8c9cedb64d3c7c Mon Sep 17 00:00:00 2001 From: S2D2 Date: Wed, 11 Nov 2026 15:27:50 +0000 Subject: [PATCH 6/6] fix(deps): skip mcp 2.0 and 2.1, and test the mcp 2 error path directly mcp 2.0.x and 2.1.x carry four published advisories that 2.2.0 fixes (GHSA-w4fh-qvv9-3v23, GHSA-5h93-6whr-6q8j, GHSA-rwrf-2pqf-9j8j, GHSA-84m7-p3x7-pcfv), so the range excludes them as it already excludes mcp 1 below 1.30.0. The pagination test now builds the installed mcp's own ListToolsResult and Tool models, so it reads the field names that major really uses. The async client tests assert that a failed POST raises with its body readable, and that a 404 POST, a GET and a DELETE are handed back to mcp unchanged. Co-Authored-By: Claude Opus 5.5 Co-authored-by: Guillaume Lebedel <10488548+glebedel@users.noreply.github.com> --- pyproject.toml | 3 ++- tests/test_fetch_tools.py | 16 +++++++++------- tests/test_rate_limit.py | 35 ++++++++++++++++++++++++++--------- uv.lock | 2 +- 4 files changed, 38 insertions(+), 18 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index cea9226..4e47901 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -21,7 +21,8 @@ dependencies = [ "httpx>=0.28.0", # fetch_tools() is the only route to a tool and talks MCP, so the client is # not optional: without it the SDK cannot do anything. - "mcp>=1.30.0,<3.0.0", + # 1.30.0 and 2.2.0 are the first of each major with every published advisory fixed. + "mcp>=1.30.0,!=2.0.*,!=2.1.*,<3.0.0", ] [project.urls] diff --git a/tests/test_fetch_tools.py b/tests/test_fetch_tools.py index 5b4aaa4..079a9be 100644 --- a/tests/test_fetch_tools.py +++ b/tests/test_fetch_tools.py @@ -13,6 +13,7 @@ from unittest.mock import AsyncMock, MagicMock, patch import httpx +import mcp.types as mcp_types import pytest from stackone_ai.tools import McpToolDefinition, StackOneMcpTool, _mcp_http, fetch_mcp_tools @@ -642,14 +643,14 @@ async def mock_streamable_client(endpoint, *, http_client, **_kwargs: object): assert result[0].input_schema == {"type": "object", "properties": {"id": {"type": "string"}}} def test_fetch_mcp_tools_with_pagination(self): - """Test fetching tools with multiple pages.""" - mock_result1 = SimpleNamespace( - tools=[SimpleNamespace(name="tool_1", description="Tool 1", inputSchema={})], + """Test fetching tools with multiple pages, as the installed mcp's own models carry them.""" + schema = {"type": "object", "properties": {"id": {"type": "string"}}} + mock_result1 = mcp_types.ListToolsResult( + tools=[mcp_types.Tool(name="tool_1", description="Tool 1", inputSchema=schema)], nextCursor="cursor_page_2", ) - mock_result2 = SimpleNamespace( - tools=[SimpleNamespace(name="tool_2", description="Tool 2", inputSchema=None)], - nextCursor=None, + mock_result2 = mcp_types.ListToolsResult( + tools=[mcp_types.Tool(name="tool_2", description="Tool 2", inputSchema={"type": "object"})] ) # Create mock session with pagination @@ -676,7 +677,8 @@ async def mock_streamable_client(endpoint, **_kwargs: object): assert len(result) == 2 assert result[0].name == "tool_1" assert result[1].name == "tool_2" - assert result[1].input_schema == {} # None should become empty dict + assert result[0].input_schema == schema + assert result[1].input_schema == {"type": "object"} first_call, second_call = mock_session.list_tools.call_args_list assert first_call.kwargs == {"params": None} assert second_call.kwargs["params"].cursor == "cursor_page_2" diff --git a/tests/test_rate_limit.py b/tests/test_rate_limit.py index 52cc09e..e2a695e 100644 --- a/tests/test_rate_limit.py +++ b/tests/test_rate_limit.py @@ -143,23 +143,27 @@ def test_each_retry_logs_one_warning(self, sleeps: list[float], caplog: pytest.L class TestAsyncClient: - def _run(self, handler: Any, *, stream: bool) -> tuple[int, bytes]: + def _send(self, handler: Any, *, stream: bool, method: str = "POST") -> tuple[int, bytes]: async def go() -> tuple[int, bytes]: async with RateLimitRetryingAsyncClient( transport=_mcp_http.MockTransport(handler), event_hooks={"response": [_buffer_error_body]}, ) as client: - try: - if not stream: - response = await client.post(URL, json={"jsonrpc": "2.0"}) - return response.status_code, response.content - async with client.stream("POST", URL, json={"jsonrpc": "2.0"}) as response: - return response.status_code, await response.aread() - except _mcp_http.HTTPStatusError as exc: - return exc.response.status_code, exc.response.content + if not stream: + response = await client.request(method, URL, json={"jsonrpc": "2.0"}) + return response.status_code, response.content + async with client.stream(method, URL, json={"jsonrpc": "2.0"}) as response: + return response.status_code, await response.aread() return asyncio.run(go()) + def _run(self, handler: Any, *, stream: bool) -> tuple[int, bytes]: + """The status and body the caller sees, whether the response is returned or raised.""" + try: + return self._send(handler, stream=stream) + except _mcp_http.HTTPStatusError as exc: + return exc.response.status_code, exc.response.content + @pytest.mark.parametrize("stream", [False, True]) def test_a_429_then_success_resends_the_same_body(self, sleeps: list[float], stream: bool): seen, handler = _responder( @@ -184,6 +188,19 @@ def test_no_retry_on_any_other_status(self, sleeps: list[float], status: int): assert len(seen) == 1 assert sleeps == [] + @pytest.mark.parametrize("stream", [False, True]) + def test_a_failed_post_raises_with_its_body_readable(self, stream: bool): + _, handler = _responder(_mcp_http.Response(500, json={"message": "boom"})) + with pytest.raises(_mcp_http.HTTPStatusError) as caught: + self._send(handler, stream=stream) + assert caught.value.response.status_code == 500 + assert caught.value.response.content == b'{"message":"boom"}' + + @pytest.mark.parametrize(("method", "status"), [("POST", 404), ("GET", 500), ("DELETE", 500)]) + def test_a_lost_session_and_non_post_failures_are_returned(self, method: str, status: int): + _, handler = _responder(_mcp_http.Response(status)) + assert self._send(handler, stream=True, method=method)[0] == status + class TestFetchAccounts: @pytest.fixture diff --git a/uv.lock b/uv.lock index 66cbb78..dc0dd31 100644 --- a/uv.lock +++ b/uv.lock @@ -2423,7 +2423,7 @@ requires-dist = [ { name = "langchain-core", marker = "extra == 'dev'", specifier = ">=0.3.36" }, { name = "langchain-core", marker = "extra == 'langchain'", specifier = ">=0.3.36" }, { name = "langchain-openai", marker = "extra == 'examples'", specifier = ">=1.1.14" }, - { name = "mcp", specifier = ">=1.30.0,<3.0.0" }, + { name = "mcp", specifier = ">=1.30.0,!=2.0.*,!=2.1.*,<3.0.0" }, { name = "openai", marker = "extra == 'examples'", specifier = ">=2.32.0" }, { name = "pydantic", specifier = ">=2.10.6" }, { name = "pydantic-ai", marker = "extra == 'examples'", specifier = ">=1.83.0" },