π The fast, Pythonic way to build MCP servers and clients.
fix(client): preserve a caller-provided OAuth httpx client factory when verify is set (#5849)
εεΊη±³b7c6568552d2
diff --git a/fastmcp_slim/fastmcp/client/client.py b/fastmcp_slim/fastmcp/client/client.pyindex 8ed1e187d..7472aa64f 100644--- a/fastmcp_slim/fastmcp/client/client.py+++ b/fastmcp_slim/fastmcp/client/client.py@@ -109,7 +109,7 @@ from .transports import (StreamableHttpTransport,infer_transport,)-from .transports.base import TransportOptions+from .transports.base import TransportOptions, _is_verify_replaceable_factory__all__ = ["Client",@@ -480,12 +480,16 @@ class Client(if isinstance(self.transport, StreamableHttpTransport | SSETransport):self.transport.verify = verify# Re-sync existing OAuth auth with the new verify setting,- # but only if the transport doesn't have a custom factory- # (which takes precedence and was already applied to OAuth).+ # but only if neither the transport nor the auth provider has+ # a custom factory (which takes precedence and was already+ # applied to OAuth).if (isinstance(self.transport.auth, OAuth)and auth is Noneand self.transport.httpx_client_factory is None+ and _is_verify_replaceable_factory(+ self.transport.auth.httpx_client_factory+ )):verify_factory = self.transport._make_verify_factory()if verify_factory is not None:diff --git a/fastmcp_slim/fastmcp/client/transports/base.py b/fastmcp_slim/fastmcp/client/transports/base.pyindex 5080e571e..4324eda8e 100644--- a/fastmcp_slim/fastmcp/client/transports/base.py+++ b/fastmcp_slim/fastmcp/client/transports/base.py@@ -15,11 +15,38 @@ from mcp.client.session import (MessageHandlerFnT,SamplingFnT,)+from mcp.shared._httpx_utils import McpHttpClientFactoryfrom typing_extensions import TypedDict, Unpack# TypeVar for preserving specific ClientTransport subclass typesClientTransportT = TypeVar("ClientTransportT", bound="ClientTransport")+#: Attribute set on factories generated from a transport's ``verify`` setting.+#: A non-default factory without this marker was supplied by the caller (for+#: proxies, mTLS, custom headers, ...) and takes precedence over ``verify``.+#: The value is exactly ``True``; dynamic attribute lookup (proxies, mocks)+#: must not be mistaken for the marker.+_VERIFY_FACTORY_MARKER = "_fastmcp_verify_factory"+++def _mark_verify_factory(factory: McpHttpClientFactory) -> McpHttpClientFactory:+ """Tag a factory generated from ``verify`` so it can be told apart from a+ caller-supplied factory."""+ setattr(factory, _VERIFY_FACTORY_MARKER, True)+ return factory+++def _is_verify_replaceable_factory(factory: object) -> bool:+ """Whether a Client-level ``verify`` may replace this OAuth factory.++ Only the bare ``httpx2.AsyncClient`` default and factories generated from+ a transport's own ``verify`` setting are replaceable. A caller-supplied+ factory must be preserved.+ """+ if factory is httpx2.AsyncClient:+ return True+ return getattr(factory, _VERIFY_FACTORY_MARKER, False) is True+class ClientSessionKwargs(TypedDict, total=False):"""Keyword arguments for the MCP ClientSession constructor."""diff --git a/fastmcp_slim/fastmcp/client/transports/http.py b/fastmcp_slim/fastmcp/client/transports/http.pyindex 10a698339..50b03b3b9 100644--- a/fastmcp_slim/fastmcp/client/transports/http.py+++ b/fastmcp_slim/fastmcp/client/transports/http.py@@ -25,6 +25,7 @@ from fastmcp.client.transports.base import (ClientTransport,SessionKwargs,TransportOptions,+ _mark_verify_factory,)@@ -160,7 +161,7 @@ class StreamableHttpTransport(ClientTransport):kwargs["auth"] = authreturn httpx2.AsyncClient(**kwargs)- return cast(McpHttpClientFactory, factory)+ return _mark_verify_factory(cast(McpHttpClientFactory, factory))@contextlib.asynccontextmanagerasync def connect_session(diff --git a/fastmcp_slim/fastmcp/client/transports/sse.py b/fastmcp_slim/fastmcp/client/transports/sse.pyindex 4571e87c8..2f9618f71 100644--- a/fastmcp_slim/fastmcp/client/transports/sse.py+++ b/fastmcp_slim/fastmcp/client/transports/sse.py@@ -26,6 +26,7 @@ from fastmcp.client.transports.base import (ClientTransport,SessionKwargs,TransportOptions,+ _mark_verify_factory,)from fastmcp.utilities.timeout import normalize_timeout_to_timedelta@@ -126,7 +127,7 @@ class SSETransport(ClientTransport):kwargs["auth"] = authreturn httpx2.AsyncClient(**kwargs)- return cast(McpHttpClientFactory, factory)+ return _mark_verify_factory(cast(McpHttpClientFactory, factory))@contextlib.asynccontextmanagerasync def connect_session(diff --git a/tests/client/transports/test_transports.py b/tests/client/transports/test_transports.pyindex 36b209543..cebe8a4eb 100644--- a/tests/client/transports/test_transports.py+++ b/tests/client/transports/test_transports.py@@ -3,6 +3,7 @@ import sslfrom collections.abc import AsyncGeneratorfrom ssl import VerifyModefrom typing import Any, cast+from unittest.mock import Mockimport httpx2import pytest@@ -274,6 +275,120 @@ class TestSSLVerify:assert isinstance(transport.auth, OAuth)assert transport.auth.httpx_client_factory is custom_factory+ @pytest.mark.parametrize(+ ("transport_cls", "url"),+ [+ (StreamableHttpTransport, "https://example.com/mcp"),+ (SSETransport, "https://example.com/sse"),+ ],+ )+ async def test_client_verify_preserves_custom_oauth_factory(+ self,+ transport_cls: type[StreamableHttpTransport] | type[SSETransport],+ url: str,+ ):+ custom_factory = cast(+ McpHttpClientFactory,+ lambda **kwargs: httpx2.AsyncClient(verify=False, **kwargs),+ )+ transport = transport_cls(url, auth=OAuth(httpx_client_factory=custom_factory))+ assert isinstance(transport.auth, OAuth)+ assert transport.auth.httpx_client_factory is custom_factory++ # Wrapping the transport must not replace the caller's factory with a+ # verify-only one; the custom factory (proxy/mTLS/headers) still wins.+ client = Client(transport, verify=True)+ assert isinstance(client.transport, StreamableHttpTransport | SSETransport)+ assert isinstance(client.transport.auth, OAuth)+ assert client.transport.auth.httpx_client_factory is custom_factory+ async with client.transport.auth.httpx_client_factory() as httpx_client:+ assert (+ httpx_client._transport._pool._ssl_context.verify_mode # type: ignore[attr-defined] # ty:ignore[unresolved-attribute]+ == VerifyMode.CERT_NONE+ )++ @pytest.mark.parametrize(+ ("transport_cls", "url"),+ [+ (StreamableHttpTransport, "https://example.com/mcp"),+ (SSETransport, "https://example.com/sse"),+ ],+ )+ def test_client_verify_preserves_factory_with_dynamic_attributes(+ self,+ transport_cls: type[StreamableHttpTransport] | type[SSETransport],+ url: str,+ ):+ # Mock-style callables fabricate every attribute lookup, including the+ # private marker. Those dynamic values must not be mistaken for the+ # exact marker set on transport-generated factories.+ mock_factory = Mock(+ side_effect=lambda **kwargs: httpx2.AsyncClient(verify=False, **kwargs)+ )+ assert mock_factory._fastmcp_verify_factory++ transport = transport_cls(+ url,+ auth=OAuth(httpx_client_factory=cast(McpHttpClientFactory, mock_factory)),+ )+ assert isinstance(transport.auth, OAuth)+ assert transport.auth.httpx_client_factory is mock_factory++ client = Client(transport, verify=True)+ assert isinstance(client.transport, StreamableHttpTransport | SSETransport)+ assert isinstance(client.transport.auth, OAuth)+ assert client.transport.auth.httpx_client_factory is mock_factory++ @pytest.mark.parametrize(+ ("transport_cls", "url"),+ [+ (StreamableHttpTransport, "https://example.com/mcp"),+ (SSETransport, "https://example.com/sse"),+ ],+ )+ async def test_client_verify_resyncs_default_oauth_factory(+ self,+ transport_cls: type[StreamableHttpTransport] | type[SSETransport],+ url: str,+ ):+ transport = transport_cls(url, auth="oauth")+ assert isinstance(transport.auth, OAuth)+ assert transport.auth.httpx_client_factory is httpx2.AsyncClient++ client = Client(transport, verify=False)+ assert isinstance(client.transport, StreamableHttpTransport | SSETransport)+ assert isinstance(client.transport.auth, OAuth)+ assert client.transport.auth.httpx_client_factory is not httpx2.AsyncClient+ async with client.transport.auth.httpx_client_factory() as httpx_client:+ assert (+ httpx_client._transport._pool._ssl_context.verify_mode # type: ignore[attr-defined] # ty:ignore[unresolved-attribute]+ == VerifyMode.CERT_NONE+ )++ @pytest.mark.parametrize(+ ("transport_cls", "url"),+ [+ (StreamableHttpTransport, "https://example.com/mcp"),+ (SSETransport, "https://example.com/sse"),+ ],+ )+ def test_client_verify_leaves_no_auth_transport_unchanged(+ self,+ transport_cls: type[StreamableHttpTransport] | type[SSETransport],+ url: str,+ ):+ custom_factory = cast(+ McpHttpClientFactory,+ lambda **kwargs: httpx2.AsyncClient(verify=False, **kwargs),+ )+ transport = transport_cls(url, httpx_client_factory=custom_factory)++ client = Client(transport, verify=True)+ assert isinstance(client.transport, StreamableHttpTransport | SSETransport)+ assert client.transport.verify is True+ assert client.transport.httpx_client_factory is custom_factory+ assert client.transport.auth is None+def test_warns_when_both_factory_and_verify_provided_streamable(self):factory = cast(McpHttpClientFactory, httpx2.AsyncClient)with pytest.warns(UserWarning, match="httpx_client_factory.*takes precedence"):