Skip to content

πŸš€ The fast, Pythonic way to build MCP servers and clients.

Merge remote-tracking branch 'origin/main' into feature/client-auto-default

Jeremiah Lowin1a788cf34950
diff --cc docs/clients/auth/bearer.mdx
index 3385eda3b,3385eda3b..109f54df6
--- a/docs/clients/auth/bearer.mdx
+++ b/docs/clients/auth/bearer.mdx
@@@ -37,7 -37,7 +37,7 @@@ async with Client
"https://your-server.fastmcp.app/mcp",
auth="<your-token>",
) as client:
-- await client.ping()
++ await client.list_tools()
```
You can also supply a Bearer token to a transport instance, such as `StreamableHttpTransport` or `SSETransport`:
@@@ -52,7 -52,7 +52,7 @@@ transport = StreamableHttpTransport
)
async with Client(transport) as client:
-- await client.ping()
++ await client.list_tools()
```
## `BearerAuth` Helper
@@@ -67,7 -67,7 +67,7 @@@ async with Client
"https://your-server.fastmcp.app/mcp",
auth=BearerAuth(token="<your-token>"),
) as client:
-- await client.ping()
++ await client.list_tools()
```
## Custom Headers
@@@ -84,5 -84,5 +84,5 @@@ async with Client
headers={"X-API-Key": "<your-token>"},
),
) as client:
-- await client.ping()
++ await client.list_tools()
```
diff --cc docs/clients/auth/cimd.mdx
index c1f92d1c4,c1f92d1c4..5b1a6b934
--- a/docs/clients/auth/cimd.mdx
+++ b/docs/clients/auth/cimd.mdx
@@@ -32,7 -32,7 +32,7 @@@ async with Client
client_metadata_url="https://myapp.example.com/oauth/client.json",
),
) as client:
-- await client.ping()
++ await client.list_tools()
```
When the server supports CIMD, the client uses your metadata URL as its `client_id` instead of performing Dynamic Client Registration. The server fetches your document, validates it, and proceeds with the standard OAuth authorization flow.
diff --cc docs/clients/auth/oauth.mdx
index 3a237ef00,3a237ef00..21236406d
--- a/docs/clients/auth/oauth.mdx
+++ b/docs/clients/auth/oauth.mdx
@@@ -29,7 -29,7 +29,7 @@@ from fastmcp import Clien
# Uses default OAuth settings
async with Client("https://your-server.fastmcp.app/mcp", auth="oauth") as client:
-- await client.ping()
++ await client.list_tools()
```
@@@ -44,7 -44,7 +44,7 @@@ from fastmcp.client.auth import OAut
oauth = OAuth(scopes=["user"])
async with Client("https://your-server.fastmcp.app/mcp", auth=oauth) as client:
-- await client.ping()
++ await client.list_tools()
```
<Note>
@@@ -125,7 -125,7 +125,7 @@@ encrypted_storage = FernetEncryptionWra
oauth = OAuth(token_storage=encrypted_storage)
async with Client("https://your-server.fastmcp.app/mcp", auth=oauth) as client:
-- await client.ping()
++ await client.list_tools()
```
You can use any `AsyncKeyValue`-compatible backend from the [key-value library](https://github.com/strawgate/py-key-value) including Redis, DynamoDB, and more. Wrap your storage in `FernetEncryptionWrapper` for encryption.
@@@ -150,7 -150,7 +150,7 @@@ async with Client
client_metadata_url="https://myapp.example.com/oauth/client.json",
),
) as client:
-- await client.ping()
++ await client.list_tools()
```
See the [CIMD Authentication](/clients/auth/cimd) page for complete documentation on creating, hosting, and validating CIMD documents.
@@@ -172,7 -172,7 +172,7 @@@ async with Client
client_secret="my-client-secret",
),
) as client:
-- await client.ping()
++ await client.list_tools()
```
Public clients that rely on PKCE for security can omit `client_secret`:
diff --cc docs/clients/client.mdx
index 0f008355a,3d93b13ec..1024984c7
--- a/docs/clients/client.mdx
+++ b/docs/clients/client.mdx
@@@ -37,9 -37,9 +37,6 @@@ client = Client("my_mcp_server.py"
async def main():
async with client:
-- # Basic server interaction
-- await client.ping()
--
# List available operations
tools = await client.list_tools()
resources = await client.list_resources()
@@@ -176,16 -176,16 +173,26 @@@ By default, `mode="auto"`. The client p
```python
from fastmcp import Client
-# Legacy handshake (the default)
-client = Client("https://example.com/mcp", mode="legacy")
+# Negotiate the newest era the server supports (the default)
+client = Client("https://example.com/mcp", mode="auto")
```
-Set `mode="auto"` to negotiate the newest era the server supports. The client probes `server/discover` and adopts the modern protocol when the server responds; for any server that is not positive evidence of modern support, it falls back to the legacy handshake. This makes `"auto"` safe to use against a mixed fleet of legacy and modern servers.
+Set `mode="legacy"` to force the initialize handshake. This behaves identically to earlier FastMCP versions and is the opt-out if a server misbehaves under discovery or you need the legacy `initialize` result object.
```python
-client = Client("https://example.com/mcp", mode="auto")
+client = Client("https://example.com/mcp", mode="legacy")
```
++Legacy mode is also what you need for the capabilities that depend on a live session between client and server. The handshake opens a persistent back-channel the server can push requests down, and the modern era removed it. Pin `mode="legacy"` when your code relies on any of these:
++
++- **[Sampling](/clients/sampling)** β€” server-initiated LLM completion requests
++- **[Roots](/clients/roots)** β€” server-initiated requests for the client's roots
++- **[Elicitation](/clients/elicitation)** β€” server-initiated requests for user input, which modern connections replace with [input-required rounds](/clients/elicitation#input-required-rounds)
++- **[Background tasks](/clients/tasks)** β€” submitting an operation with `task=True`
++- `client.ping()` and `transport.get_session_id()`
++
++A FastMCP server serves both eras, so a default client negotiates the modern one and these raise an era-specific error. Pinning the handshake restores them.
++
You can also pin a specific modern protocol version to adopt it directly, without a discovery probe:
```python
@@@ -328,6 -301,6 +335,8 @@@ See [Prompts](/clients/prompts) for det
The client supports callback handlers for advanced server interactions. These let you respond to server-initiated requests and receive notifications.
++Sampling, elicitation, and roots are all server-initiated, so they belong to the handshake era described under [protocol negotiation](#protocol-negotiation). A default client negotiates the newest era both peers share, where the server has no back-channel to push those requests down, so an example that exercises them pins `mode="legacy"`. Logging and progress arrive as notifications on the response stream and work in either era.
++
```python
from fastmcp import Client
from fastmcp.client.logging import LogMessage
@@@ -344,6 -317,6 +353,7 @@@ async def sampling_handler(messages, pa
client = Client(
"my_mcp_server.py",
++ mode="legacy",
log_handler=log_handler,
progress_handler=progress_handler,
sampling_handler=sampling_handler,
diff --cc docs/clients/elicitation.mdx
index e4286f206,e4286f206..cb5c1431e
--- a/docs/clients/elicitation.mdx
+++ b/docs/clients/elicitation.mdx
@@@ -13,6 -13,6 +13,10 @@@ Use this when you need to respond to se
Elicitation allows MCP servers to request structured input from users during operations. Instead of requiring all inputs upfront, servers can interactively ask for missing parameters, request clarification, or gather additional context.
++Two routes reach that outcome, and the protocol era the client negotiates decides which one applies. Handshake-era connections let the server push an elicitation request down the back-channel the handshake opens, which is the flow the next few sections describe. Modern-era connections work through [input-required rounds](#input-required-rounds) instead, where the server returns a description of what it needs and the client answers with a fresh call. You write the same `elicitation_handler` either way β€” FastMCP routes it to whichever mechanism the connection supports.
++
++A client left at its default `mode="auto"` negotiates the newest era it shares with the server, so the examples below pin `mode="legacy"` to exercise the server-initiated flow. See [protocol negotiation](/clients/client#protocol-negotiation) for the full picture.
++
## Handler Template
```python
@@@ -54,6 -54,6 +58,7 @@@ async def elicitation_handler
client = Client(
"my_mcp_server.py",
++ mode="legacy",
elicitation_handler=elicitation_handler,
)
```
@@@ -138,6 -138,6 +143,7 @@@ async def elicitation_handler(message,
client = Client(
"my_mcp_server.py",
++ mode="legacy",
elicitation_handler=elicitation_handler
)
```
diff --cc docs/clients/roots.mdx
index 0370c119a,0370c119a..90adfeb1b
--- a/docs/clients/roots.mdx
+++ b/docs/clients/roots.mdx
@@@ -13,6 -13,6 +13,8 @@@ Use this when you need to tell servers
Roots inform servers about resources the client can provide. Servers can use this information to adjust behavior or provide more relevant responses.
++A server reads roots by asking the client for them, which requires the back-channel that only the handshake era of the MCP protocol provides. A client left at its default `mode="auto"` negotiates the newest era it shares with the server, so against a FastMCP server it lands on the modern era and the server's request for roots fails. Both examples below pin `mode="legacy"` for that reason. See [protocol negotiation](/clients/client#protocol-negotiation) for the full picture.
++
## Static Roots
Provide a list of roots when creating the client:
@@@ -22,6 -22,6 +24,7 @@@ from fastmcp import Clien
client = Client(
"my_mcp_server.py",
++ mode="legacy",
roots=["/path/to/root1", "/path/to/root2"]
)
```
@@@ -40,6 -40,6 +43,7 @@@ async def roots_callback(context: Reque
client = Client(
"my_mcp_server.py",
++ mode="legacy",
roots=roots_callback
)
```
diff --cc docs/clients/sampling.mdx
index b0655989b,458135b63..6181129b6
--- a/docs/clients/sampling.mdx
+++ b/docs/clients/sampling.mdx
@@@ -13,6 -13,6 +13,8 @@@ Use this when you need to respond to se
MCP servers can request LLM completions from clients during tool execution. This enables servers to delegate AI reasoning to the client, which controls which LLM is used and how requests are made.
++Sampling belongs to the handshake era of the MCP protocol, which is the only era that gives a server a back-channel to push requests down. A client left at its default `mode="auto"` negotiates the newest era it shares with the server, so against a FastMCP server it lands on the modern era and sampling requests fail. Every example on this page pins `mode="legacy"` for that reason. See [protocol negotiation](/clients/client#protocol-negotiation) for the full picture.
++
## Handler Template
```python
@@@ -49,6 -49,6 +51,7 @@@ async def sampling_handler
client = Client(
"my_mcp_server.py",
++ mode="legacy",
sampling_handler=sampling_handler,
)
```
@@@ -109,6 -109,6 +112,7 @@@ from fastmcp.client.sampling.handlers.o
client = Client(
"my_mcp_server.py",
++ mode="legacy",
sampling_handler=OpenAISamplingHandler(default_model="gpt-4o"),
)
```
@@@ -120,6 -120,6 +124,7 @@@ from openai import AsyncOpenA
client = Client(
"my_mcp_server.py",
++ mode="legacy",
sampling_handler=OpenAISamplingHandler(
default_model="llama-3.1-70b",
client=AsyncOpenAI(base_url="http://localhost:8000/v1"),
@@@ -141,6 -141,6 +146,7 @@@ from fastmcp.client.sampling.handlers.a
client = Client(
"my_mcp_server.py",
++ mode="legacy",
sampling_handler=AnthropicSamplingHandler(default_model="claude-sonnet-4-5"),
)
```
@@@ -159,6 -159,6 +165,7 @@@ from fastmcp.client.sampling.handlers.g
client = Client(
"my_mcp_server.py",
++ mode="legacy",
sampling_handler=GoogleGenaiSamplingHandler(default_model="gemini-2.0-flash"),
)
```
@@@ -176,6 -176,6 +183,7 @@@ from fastmcp.types import SamplingCapab
client = Client(
"my_mcp_server.py",
++ mode="legacy",
sampling_handler=basic_handler,
sampling_capabilities=SamplingCapability(), # No tool support
)
diff --cc docs/clients/tasks.mdx
index 630323167,630323167..b294ce653
--- a/docs/clients/tasks.mdx
+++ b/docs/clients/tasks.mdx
@@@ -14,6 -14,6 +14,8 @@@ Use this when you need to run long oper
The MCP task protocol lets you request operations to run in the background. The call returns a Task object immediately, letting you track progress, cancel operations, or await results.
++FastMCP submits a task over the session that the `initialize` handshake opens, which makes background execution a handshake-era capability. A client left at its default `mode="auto"` negotiates the newest era it shares with the server, so against a FastMCP server it lands on the modern era where task submission is unavailable. The examples on this page pin `mode="legacy"` for that reason. See [protocol negotiation](/clients/client#protocol-negotiation) for the full picture.
++
## Requesting Background Execution
Pass `task=True` to run an operation as a background task:
@@@ -21,7 -21,7 +23,7 @@@
```python
from fastmcp import Client
--async with Client(server) as client:
++async with Client(server, mode="legacy") as client:
# Start a background task
task = await client.call_tool("slow_computation", {"duration": 10}, task=True)
@@@ -154,7 -154,7 +156,7 @@@ import asynci
from fastmcp import Client
async def main():
-- async with Client(server) as client:
++ async with Client(server, mode="legacy") as client:
# Start background task
task = await client.call_tool(
"slow_computation",
diff --cc docs/clients/transports.mdx
index 2c8d20caa,2c8d20caa..23acab535
--- a/docs/clients/transports.mdx
+++ b/docs/clients/transports.mdx
@@@ -86,7 -86,7 +86,7 @@@ client = Client(transport
async def efficient_multiple_operations():
async with client:
-- await client.ping()
++ await client.list_tools()
async with client: # Reuses the same subprocess
await client.call_tool("process_data", {"file": "data.csv"})
diff --cc docs/development/tests.mdx
index 79131802c,bbdbd972a..11e61f1aa
--- a/docs/development/tests.mdx
+++ b/docs/development/tests.mdx
@@@ -323,26 -320,84 +320,89 @@@ def create_test_server() -> FastMCP
return server
- @pytest.fixture
- async def http_server() -> str:
- """Start server in-process for testing."""
- server = create_test_server()
- async with run_server_async(server) as url:
- yield url
+ async def test_greet_over_http():
+ async with asgi_client(create_test_server()) as client:
+ greeting = await client.call_tool("greet", {"name": "World"})
+ assert greeting.data == "Hello, World!"
+ ```
- async def test_http_transport(http_server: str):
- """Test actual HTTP transport behavior."""
- async with Client(
- transport=StreamableHttpTransport(http_server)
+ Pass `transport="sse"` to exercise the SSE app instead of streamable HTTP, `path=` to serve on a custom path, `headers=` and `auth=` to configure the client's requests, and any other keyword argument to configure the `Client` itself.
+
+ ```python
+ async def test_tenant_header_is_visible_to_tools():
+ async with asgi_client(
+ create_test_server(),
+ headers={"X-Tenant-ID": "acme"},
+ timeout=5,
) as client:
- result = await client.ping()
- assert result is True
- await client.ping()
++ await client.list_tools()
+ ```
+
+ #### Sharing One Server Across Tests
+
+ When several tests share a server but each needs its own client, use `asgi_server` in a fixture. It yields an `ASGIServer`, whose `client()` method produces a fresh client β€” with its own session β€” on demand.
+
+ ```python
+ import pytest
+ from fastmcp import FastMCP
+ from fastmcp.utilities.tests import ASGIServer, asgi_server
+
+ @pytest.fixture
+ async def http_server():
+ server = FastMCP("TestServer")
+ @server.tool
+ def greet(name: str) -> str:
+ return f"Hello, {name}!"
+
+ async with asgi_server(server) as running_server:
+ yield running_server
+
+ async def test_greet(http_server: ASGIServer):
+ async with http_server.client() as client:
greeting = await client.call_tool("greet", {"name": "World"})
assert greeting.data == "Hello, World!"
+
+ async def test_sessions_are_isolated(http_server: ASGIServer):
- async with http_server.client() as first, http_server.client() as second:
++ async with (
++ http_server.client(mode="legacy") as first,
++ http_server.client(mode="legacy") as second,
++ ):
+ assert await first.ping() is True
+ assert await second.ping() is True
```
- The `run_server_async` context manager automatically handles server lifecycle and cleanup. This approach is faster than subprocess-based testing and provides better error messages.
++Sessions belong to the handshake era of the MCP protocol, and so does `ping`, so a test that is about session behavior pins `mode="legacy"`. Every keyword argument `client()` doesn't consume itself is passed straight to `Client`. See [protocol negotiation](/clients/client#protocol-negotiation).
++
+ For assertions about raw HTTP β€” status codes, response headers, metadata endpoints β€” `http_client()` returns an `httpx.AsyncClient` bound to the same app. Because nothing is listening on the network, this is the only way to make raw requests; a plain `httpx.AsyncClient()` cannot reach the server.
+
+ ```python
+ async def test_unauthenticated_request_is_rejected(http_server: ASGIServer):
+ async with http_server.http_client() as http:
+ response = await http.post(http_server.url, json={"jsonrpc": "2.0", "id": 1})
+ assert response.status_code in (400, 401)
+ ```
+
+ If you need to build the client transport yourself, `transport()` returns a `StreamableHttpTransport` or `SSETransport` already wired to the in-process app.
+
+ #### Testing on a Real Port
+
+ <VersionBadge version="2.13.0" />
+
+ `run_server_async` starts a real uvicorn server on a real TCP port as a task in the current process and yields its URL. Reach for it only when the subject of the test is the network itself β€” real sockets, TLS, or a server that must be reachable by something other than an in-process client.
+
+ ```python
+ from fastmcp import FastMCP, Client
+ from fastmcp.utilities.tests import run_server_async
+
+ async def test_server_binds_a_real_port():
+ server = FastMCP("TestServer")
+
+ async with run_server_async(server) as url:
+ assert url.startswith("http://127.0.0.1:")
+ async with Client(url) as client:
- assert await client.ping() is True
++ assert await client.list_tools() == []
+ ```
#### Subprocess Testing (Special Cases)
@@@ -375,8 -430,8 +435,8 @@@ async def test_http_transport(http_serv
async with Client(
transport=StreamableHttpTransport(http_server)
) as client:
-- result = await client.ping()
-- assert result is True
++ tools = await client.list_tools()
++ assert "greet" in [tool.name for tool in tools]
```
The `run_server_in_process` utility handles server lifecycle, port allocation, and cleanup automatically. Use this only when subprocess isolation is truly necessary, as it's slower and harder to debug than in-process testing. FastMCP uses the `client_process` marker to isolate these tests in CI.
diff --cc docs/integrations/authkit.mdx
index c77175201,c77175201..05c6e5d7b
--- a/docs/integrations/authkit.mdx
+++ b/docs/integrations/authkit.mdx
@@@ -81,7 -81,7 +81,8 @@@ auth = OAuth(additional_client_metadata
async def main():
async with Client("http://127.0.0.1:8000/mcp", auth=auth) as client:
-- assert await client.ping()
++ tools = await client.list_tools()
++ print(f"Authenticated. Server exposes {len(tools)} tools.")
if __name__ == "__main__":
asyncio.run(main())
diff --cc docs/integrations/descope.mdx
index 7b00cd3e1,7b00cd3e1..f0357f333
--- a/docs/integrations/descope.mdx
+++ b/docs/integrations/descope.mdx
@@@ -116,7 -116,7 +116,8 @@@ import asynci
async def main():
async with Client("http://localhost:8000/mcp", auth="oauth") as client:
-- assert await client.ping()
++ tools = await client.list_tools()
++ print(f"Authenticated. Server exposes {len(tools)} tools.")
if __name__ == "__main__":
asyncio.run(main())
diff --cc docs/integrations/propelauth.mdx
index 7f21d2010,7f21d2010..7875a1ce2
--- a/docs/integrations/propelauth.mdx
+++ b/docs/integrations/propelauth.mdx
@@@ -101,7 -101,7 +101,8 @@@ import asynci
async def main():
async with Client("http://localhost:8000/mcp", auth="oauth") as client:
-- assert await client.ping()
++ tools = await client.list_tools()
++ print(f"Authenticated. Server exposes {len(tools)} tools.")
if __name__ == "__main__":
asyncio.run(main())
diff --cc fastmcp_slim/fastmcp/client/client.py
index e3e019536,ba657560b..07f631ee9
--- a/fastmcp_slim/fastmcp/client/client.py
+++ b/fastmcp_slim/fastmcp/client/client.py
@@@ -8,7 -8,7 +8,7 @@@ import secret
import ssl
import uuid
import weakref
- from collections.abc import Callable, Coroutine, Mapping, Sequence
-from collections.abc import Callable, Coroutine
++from collections.abc import AsyncIterator, Callable, Coroutine, Mapping, Sequence
from contextlib import AsyncExitStack, asynccontextmanager, suppress
from dataclasses import dataclass, field
from pathlib import Path
@@@ -43,8 -38,8 +43,9 @@@ from mcp_types import
TaskStatusNotification,
TaskStatusNotificationParams,
)
++from mcp_types.methods import validate_server_result
from mcp_types.version import HANDSHAKE_PROTOCOL_VERSIONS, MODERN_PROTOCOL_VERSIONS
--from pydantic import AnyUrl
++from pydantic import AnyUrl, ValidationError
import fastmcp as fastmcp
from fastmcp.client.auth.oauth import OAuth
@@@ -154,92 -149,6 +155,154 @@@ def _synthesize_discover(protocol_versi
)
++@asynccontextmanager
++async def _conformant_discover_only(
++ session: ClientSession,
++) -> AsyncIterator[None]:
++ """Hold ``session.send_discover`` to the same wire schema every later reply must meet.
++
++ ``negotiate_auto`` accepts a probe that parses as the version-free
++ ``DiscoverResult``, whose ``resultType``/``ttlMs``/``cacheScope`` all carry
++ SDK-side defaults. Every request *after* adoption is instead checked against
++ the strict per-version surface (``validate_server_result``), where those same
++ three fields are required. A server that answers ``server/discover`` without
++ them therefore passes the probe and then fails every subsequent call β€” the
++ connection is adopted into an era the peer cannot actually serve.
++
++ Closing that gap means judging the probe by the rule that will govern the rest
++ of the connection. A result that would be rejected later is not positive
++ evidence of a modern peer, so it is reported as an ordinary probe failure and
++ ``negotiate_auto`` falls back to the initialize handshake, exactly as it does
++ for a server with no ``server/discover`` at all.
++ """
++ send_discover = session.send_discover
++
++ async def _checked_send_discover(version: str) -> dict[str, Any]:
++ raw = await send_discover(version)
++ try:
++ validate_server_result("server/discover", version, raw)
++ except ValidationError as e:
++ # Ordered before the ValueError arm below: pydantic's ValidationError
++ # subclasses ValueError, so a broader clause first would swallow it.
++ logger.debug(
++ "server/discover at %s is not %s-conformant (%s); "
++ "falling back to the initialize handshake",
++ version,
++ version,
++ e,
++ )
++ raise MCPError(
++ code=mcp_types.INVALID_PARAMS,
++ message=(
++ f"server/discover result is not conformant with {version}; "
++ "treating the server as handshake-era"
++ ),
++ ) from e
++ except (KeyError, ValueError):
++ # No schema on file for this method/version pair, so there is nothing to
++ # judge the probe against; leave the verdict to negotiate_auto's parse.
++ return raw
++ return raw
++
++ # A transport may itself have installed a `send_discover` override, so restore
++ # whatever was there rather than assuming the class attribute.
++ had_own = "send_discover" in vars(session)
++ session.send_discover = _checked_send_discover # ty: ignore[invalid-assignment]
++ try:
++ yield
++ finally:
++ if had_own:
++ session.send_discover = send_discover # ty: ignore[invalid-assignment]
++ else:
++ del session.send_discover
++
++
+@dataclass
+class _FoldedExtensions:
+ """`Client(extensions=...)` folded into the shapes `ClientSession` consumes.
+
+ `ad` maps each extension identifier to its advertised settings (the SEP-2133
+ capability ad), `claims` maps each identifier to its `ResultClaim`s, `bindings`
+ is the flat list of `NotificationBinding`s the extensions observe, and `by_model`
+ indexes every claim by its result model so a claimed `tools/call` result can be
+ routed back to the owning resolver.
+ """
+
+ ad: dict[str, dict[str, Any]]
+ claims: dict[str, tuple[ResultClaim[Any], ...]]
+ bindings: list[NotificationBinding[Any]]
+ by_model: dict[type[mcp_types.Result], ResultClaim[Any]]
+
+
+def _fold_extensions(
+ extensions: Sequence[ClientExtension] | None,
+) -> _FoldedExtensions:
+ """Decompose `ClientExtension` instances into `ClientSession` kwargs.
+
+ Mirrors the SDK Client's own folding, using only the public `ClientExtension`
+ surface (`settings()`, `claims()`, `notifications()`). Duplicate identifiers,
+ result-type tags, or notification methods across extensions raise here rather
+ than at session construction, naming both owners. `by_model` is the model→claim
+ index the resolution path uses to finish a claimed result.
+ """
+ folded = _FoldedExtensions(ad={}, claims={}, bindings=[], by_model={})
+ if not extensions:
+ return folded
+ if isinstance(extensions, Mapping):
+ raise TypeError(
+ "extensions= takes a sequence of ClientExtension instances; use "
+ "mcp.client.advertise(identifier, settings) for an advertise-only entry"
+ )
+ claim_owners: dict[str, str] = {}
+ binding_owners: dict[str, str] = {}
+ for extension in extensions:
+ identifier = getattr(extension, "identifier", None)
+ if identifier is None:
+ raise ValueError(
+ f"{type(extension).__name__} has no `identifier`; a ClientExtension "
+ "must set the `identifier` class attribute (or assign one in "
+ "`__init__`) before it can be used"
+ )
+ if identifier in folded.ad:
+ raise ValueError(
+ f"extension identifier {identifier!r} is passed more than once"
+ )
+ folded.ad[identifier] = extension.settings()
+ extension_claims = tuple(extension.claims())
+ for claim in extension_claims:
+ tag = claim.result_type
+ if tag in claim_owners:
+ owner = claim_owners[tag]
+ both = (
+ f"extension {identifier!r} claims"
+ if owner == identifier
+ else f"extensions {owner!r} and {identifier!r} both claim"
+ )
+ raise ValueError(
+ f"{both} resultType {tag!r}; a wire tag can have only one resolver"
+ )
+ claim_owners[tag] = identifier
+ # Each model pins its result_type Literal to one tag, so this cannot collide.
+ folded.by_model[claim.model] = claim
+ if extension_claims:
+ folded.claims[identifier] = extension_claims
+ for binding in extension.notifications():
+ if binding.method in binding_owners:
+ owner = binding_owners[binding.method]
+ both = (
+ f"extension {identifier!r} binds"
+ if owner == identifier
+ else f"extensions {owner!r} and {identifier!r} both bind"
+ )
+ raise ValueError(
+ f"{both} notification method {binding.method!r}; a method can "
+ "have only one observer"
+ )
+ binding_owners[binding.method] = identifier
+ folded.bindings.append(binding)
+ return folded
+
+
def _evicting_message_handler(
cache: ClientResponseCache, user_handler: MessageHandlerFnT | None
) -> MessageHandlerFnT:
@@@ -870,8 -751,8 +933,9 @@@ class Client
self._session_state.initialize_result = (
await self.session.initialize()
)
- elif self.mode == "auto":
- await negotiate_auto(self.session)
+ elif effective_mode == "auto":
- await negotiate_auto(self.session)
++ async with _conformant_discover_only(self.session):
++ await negotiate_auto(self.session)
# auto may have fallen back to the legacy handshake; surface its
# InitializeResult through the existing public property when so.
self._session_state.initialize_result = (
diff --cc tests/client/client/test_mode_negotiation.py
index 13aaca7e3,fc0b14f62..37eb96075
--- a/tests/client/client/test_mode_negotiation.py
+++ b/tests/client/client/test_mode_negotiation.py
@@@ -100,62 -91,7 +100,147 @@@ class TestAutoMode
async with Client(mcp, mode="auto") as client:
assert client.protocol_version == LATEST_MODERN_VERSION
+ async def test_auto_falls_back_cleanly_when_discover_is_rejected(
+ self, fastmcp_server
+ ):
+ """A server that rejects the server/discover probe with a JSON-RPC error
+ (e.g. a non-FastMCP legacy server that doesn't implement discover) makes
+ auto fall back to the initialize handshake, cleanly β€” no error surfaces
+ and the legacy InitializeResult is populated.
+
+ This characterizes the FastMCP-observable outcome of the SDK's
+ denylist fallback (`negotiate_auto`): every RPC error except a
+ disjoint modern-only -32022 falls back to `initialize()`.
+ """
+
+ class _DiscoverRejectingTransport(FastMCPTransport):
+ """Wraps the in-memory transport but rejects server/discover."""
+
+ @contextlib.asynccontextmanager
+ async def connect_session(
+ self, **session_kwargs: Unpack[SessionKwargs]
+ ) -> AsyncIterator[ClientSession]:
+ async with super().connect_session(**session_kwargs) as session:
+
+ async def _reject_discover(version: str) -> dict[str, Any]:
+ raise MCPError(
+ code=METHOD_NOT_FOUND, message="Method not found"
+ )
+
+ session.send_discover = _reject_discover # ty: ignore[invalid-assignment]
+ yield session
+
+ transport = _DiscoverRejectingTransport(fastmcp_server)
+ async with Client(transport, mode="auto") as client:
+ # Fell back to the handshake: legacy version + populated InitializeResult.
+ assert client.protocol_version == LATEST_HANDSHAKE_VERSION
+ assert client.initialize_result is not None
+ result = await client.call_tool("add", {"a": 1, "b": 2})
+ assert result.data == 3
+
+ async def test_auto_uses_legacy_on_legacy_only_transport(self, fastmcp_server):
+ """A `legacy_only` transport (e.g. SSE) negotiates the handshake under auto.
+
+ SSE cannot serve the sessionless modern era, so a client with the default
+ `mode="auto"` must run the initialize handshake directly rather than
+ probing server/discover (which the FastMCP server answers even over SSE
+ but then cannot serve).
+ """
+
+ class _LegacyOnlyTransport(FastMCPTransport):
+ legacy_only = True
+
+ transport = _LegacyOnlyTransport(fastmcp_server)
+ async with Client(transport, mode="auto") as client:
+ assert client.protocol_version == LATEST_HANDSHAKE_VERSION
+ assert client.initialize_result is not None
+
+
++class TestNonConformantModernPeer:
++ """A peer that answers ``server/discover`` but cannot actually serve the era.
++
++ ``negotiate_auto`` accepts a probe that parses as the version-free
++ ``DiscoverResult``, where ``resultType``/``ttlMs``/``cacheScope`` all carry
++ SDK-side defaults. Every request after adoption is checked against the strict
++ per-version surface, where those three fields are required. Left alone, a
++ server that omits them on ``server/discover`` passes the probe and then fails
++ every subsequent call, so ``auto`` would adopt an era the peer cannot serve.
++
++ GitHub's remote MCP server is a live example: it has adopted the SEP-2549
++ cache fields but not result tagging, so it answers ``server/discover``
++ with ``ttlMs``/``cacheScope`` and no ``resultType``.
++ """
++
++ @staticmethod
++ def _discover_body(**envelope: Any) -> dict[str, Any]:
++ return {
++ "supportedVersions": [LATEST_MODERN_VERSION],
++ "capabilities": {"tools": {}, "resources": {}, "prompts": {}},
++ "serverInfo": {"name": "TestServer", "version": "1.0"},
++ **envelope,
++ }
++
++ @staticmethod
++ def _transport_answering(body: dict[str, Any], server) -> FastMCPTransport:
++ """An in-memory transport whose ``server/discover`` returns ``body`` verbatim."""
++
++ class _FixedDiscoverTransport(FastMCPTransport):
++ @contextlib.asynccontextmanager
++ async def connect_session(
++ self, **session_kwargs: Unpack[SessionKwargs]
++ ) -> AsyncIterator[ClientSession]:
++ async with super().connect_session(**session_kwargs) as session:
++
++ async def _fixed_discover(version: str) -> dict[str, Any]:
++ return body
++
++ session.send_discover = _fixed_discover # ty: ignore[invalid-assignment]
++ yield session
++
++ return _FixedDiscoverTransport(server)
++
++ @pytest.mark.parametrize(
++ "envelope",
++ [
++ pytest.param({}, id="no-envelope-fields"),
++ pytest.param(
++ {"ttlMs": 0, "cacheScope": "private"}, id="github-shape-no-resultType"
++ ),
++ pytest.param({"resultType": "complete"}, id="no-cache-fields"),
++ ],
++ )
++ async def test_non_conformant_discover_falls_back_to_handshake(
++ self, fastmcp_server, envelope
++ ):
++ """A discover result missing required 2026-07-28 fields is not modern evidence.
++
++ Rather than adopting an era the peer cannot serve, auto degrades to the
++ initialize handshake and the connection stays fully usable.
++ """
++ transport = self._transport_answering(
++ self._discover_body(**envelope), fastmcp_server
++ )
++ async with Client(transport, mode="auto") as client:
++ assert client.protocol_version == LATEST_HANDSHAKE_VERSION
++ assert client.initialize_result is not None
++ # The connection works, which is the whole point of degrading.
++ assert await client.list_tools()
++ result = await client.call_tool("add", {"a": 1, "b": 2})
++ assert result.data == 3
++
++ async def test_conformant_discover_still_adopts_modern(self, fastmcp_server):
++ """The conformance check must not reject a well-formed modern peer."""
++ transport = self._transport_answering(
++ self._discover_body(resultType="complete", ttlMs=0, cacheScope="private"),
++ fastmcp_server,
++ )
++ async with Client(transport, mode="auto") as client:
++ assert client.protocol_version == LATEST_MODERN_VERSION
++ assert client.initialize_result is None
++ result = await client.call_tool("add", {"a": 1, "b": 2})
++ assert result.data == 3
++
+
class TestPinnedMode:
async def test_pinned_modern_adopts_without_probe(self, fastmcp_server):
"""Pinning the modern version adopts it directly; a synthesized
diff --cc tests/client/telemetry/test_client_task_tracing.py
index 9d96985f7,f910b6cc8..6af938d40
--- a/tests/client/telemetry/test_client_task_tracing.py
+++ b/tests/client/telemetry/test_client_task_tracing.py
@@@ -71,10 -71,12 +71,12 @@@ async def test_task_id_operations_creat
@server.tool(task=True)
async def slow_tool() -> str:
started.set()
- await asyncio.sleep(10)
+ # Never completes on its own - the test cancels this task well
+ # before any real-time completion would matter.
+ await asyncio.Event().wait()
return "done"
- async with Client(server) as client:
+ async with Client(server, mode="legacy") as client:
completed_task = await client.call_tool("quick_tool", task=True)
await completed_task.wait(timeout=2)
trace_exporter.clear()
diff --cc tests/client/test_client_extensions.py
index 87c29b994,000000000..6ad8b26f3
mode 100644,000000..100644
--- a/tests/client/test_client_extensions.py
+++ b/tests/client/test_client_extensions.py
@@@ -1,331 -1,0 +1,332 @@@
+"""Tests for surfacing SEP-2133 client extensions on ``fastmcp.Client``.
+
+Covers that ``extensions=`` / ``result_claims=`` are folded into the underlying
+``ClientSession`` kwargs on construction, that user-supplied notification
+bindings *compose* with FastMCP's internal task-status binding rather than
+clobbering it, that both bindings actually fire against a live server, and that
+a claimed ``tools/call`` result is resolved end-to-end through the owning
+extension's resolver.
+"""
+
+import asyncio
+from typing import Any, Literal
+
+import pytest
+from mcp.client.extension import (
+ ClaimContext,
+ ClientExtension,
+ NotificationBinding,
+ ResultClaim,
+ UnexpectedClaimedResult,
+)
+from mcp.server.context import CallNext, HandlerResult, ServerRequestContext
+from mcp.server.extension import Extension
+from mcp.server.mcpserver import MCPServer as SDKServer
+from mcp_types import CallToolRequestParams, CallToolResult, Result, TextContent
+from mcp_types.version import LATEST_MODERN_VERSION
+from pydantic import BaseModel
+
+from fastmcp import FastMCP
+from fastmcp.client import Client
+from fastmcp.server.dependencies import get_context
+
+CUSTOM_METHOD = "notifications/x-test/ping"
+TASK_STATUS_METHOD = "notifications/tasks/status"
+EXTENSION_ID = "test.example.com/demo"
+CLAIMED_TYPE = "x-test/claimed"
+
+
+class PingParams(BaseModel):
+ value: int = 0
+
+
+class ClaimedResult(Result):
+ result_type: Literal["x-test/claimed"]
+ payload: str = ""
+
+
+async def _resolve_claimed(result: ClaimedResult, ctx: ClaimContext) -> CallToolResult:
+ """Finish a claimed result into an ordinary CallToolResult.
+
+ Echoes the claimed payload so a test can prove the resolver ran on the
+ server-emitted value rather than a placeholder.
+ """
+ return CallToolResult(
+ content=[TextContent(type="text", text=f"resolved:{result.payload}")]
+ )
+
+
+def _make_claim() -> ResultClaim[ClaimedResult]:
+ return ResultClaim(
+ result_type=CLAIMED_TYPE,
+ model=ClaimedResult,
+ resolve=_resolve_claimed,
+ )
+
+
+class _DemoExtension(ClientExtension):
+ """Extension contributing a settings ad, a result claim, and a binding."""
+
+ identifier = EXTENSION_ID
+
+ def __init__(self, received: list[PingParams] | None = None) -> None:
+ self._received = received if received is not None else []
+
+ def settings(self) -> dict[str, Any]:
+ return {"enabled": True}
+
+ def claims(self):
+ return (_make_claim(),)
+
+ def notifications(self):
+ async def _handler(params: PingParams) -> None:
+ self._received.append(params)
+
+ return (
+ NotificationBinding(
+ method=CUSTOM_METHOD,
+ params_type=PingParams,
+ handler=_handler,
+ ),
+ )
+
+
+class _ServerClaimExtension(Extension):
+ """Server-side extension that answers a specific tool with a claimed shape."""
+
+ identifier = EXTENSION_ID
+
+ async def intercept_tool_call(
+ self,
+ params: CallToolRequestParams,
+ ctx: ServerRequestContext[Any, Any],
+ call_next: CallNext,
+ ) -> HandlerResult:
+ if params.name == "claimed_tool":
+ return ClaimedResult(result_type=CLAIMED_TYPE, payload="from-server")
+ return await call_next(ctx)
+
+
+def _claiming_server() -> SDKServer:
+ """An SDK MCPServer whose `claimed_tool` returns a claimed extension result."""
+ server = SDKServer("claim-server", extensions=[_ServerClaimExtension()])
+
+ # No return annotation β†’ no output schema, so the resolved CallToolResult
+ # (plain text, no structured content) passes revalidation.
+ @server.tool()
+ def claimed_tool():
+ return None
+
+ return server
+
+
+def _binding_methods(client: Client) -> list[str]:
+ bindings = client._session_kwargs.get("notification_bindings") or []
+ return [b.method for b in bindings]
+
+
+def test_extension_folds_into_session_kwargs():
+ """A ClientExtension's ad, claim, and binding reach the session kwargs."""
+ client = Client(FastMCP("srv"), extensions=[_DemoExtension()])
+
+ assert client._session_kwargs.get("extensions") == {EXTENSION_ID: {"enabled": True}}
+ result_claims = client._session_kwargs.get("result_claims")
+ assert result_claims is not None
+ assert [c.result_type for c in result_claims[EXTENSION_ID]] == [CLAIMED_TYPE]
+
+
+def test_extension_populates_claim_by_model_index():
+ """The claim is indexed by its model so the resolution path can find it."""
+ client = Client(FastMCP("srv"), extensions=[_DemoExtension()])
+
+ assert client._claim_by_model[ClaimedResult].result_type == CLAIMED_TYPE
+
+
+def test_binding_composes_with_internal_task_binding():
+ """User binding is appended to (not replacing) the task-status binding."""
+ client = Client(FastMCP("srv"), extensions=[_DemoExtension()])
+
+ methods = _binding_methods(client)
+ assert TASK_STATUS_METHOD in methods
+ assert CUSTOM_METHOD in methods
+ # The internal task binding must lead so user bindings extend it.
+ assert methods[0] == TASK_STATUS_METHOD
+
+
+def test_no_extensions_leaves_only_task_binding():
+ """Without extensions, only the internal task-status binding is registered."""
+ client = Client(FastMCP("srv"))
+
+ assert _binding_methods(client) == [TASK_STATUS_METHOD]
+ assert "extensions" not in client._session_kwargs
+ assert "result_claims" not in client._session_kwargs
+ assert client._claim_by_model == {}
+
+
+def test_new_preserves_extension_composition():
+ """new() rebuilds the clone with both the task binding and user bindings."""
+ client = Client(FastMCP("srv"), extensions=[_DemoExtension()])
+ clone = client.new()
+
+ methods = _binding_methods(clone)
+ assert methods[0] == TASK_STATUS_METHOD
+ assert CUSTOM_METHOD in methods
+ assert clone._session_kwargs.get("extensions") == {EXTENSION_ID: {"enabled": True}}
+ assert clone._claim_by_model[ClaimedResult].result_type == CLAIMED_TYPE
+
+
+def test_result_claims_merge_with_extension_claims():
+ """Explicit result_claims merge with an advertised extension's own claims."""
+
+ class ExtraClaimed(Result):
+ result_type: Literal["x-test/extra"]
+
+ async def _resolve_extra(result: ExtraClaimed, ctx: ClaimContext) -> CallToolResult:
+ return CallToolResult(content=[])
+
+ extra_claim = ResultClaim(
+ result_type="x-test/extra",
+ model=ExtraClaimed,
+ resolve=_resolve_extra,
+ )
+
+ client = Client(
+ FastMCP("srv"),
+ extensions=[_DemoExtension()],
+ result_claims={EXTENSION_ID: [extra_claim]},
+ )
+
+ result_claims = client._session_kwargs.get("result_claims")
+ assert result_claims is not None
+ tags = {c.result_type for c in result_claims[EXTENSION_ID]}
+ assert tags == {CLAIMED_TYPE, "x-test/extra"}
+ # Both the extension claim and the explicit extra claim are resolvable.
+ assert set(client._claim_by_model) == {ClaimedResult, ExtraClaimed}
+
+
+async def test_user_binding_clobbering_task_method_is_rejected():
+ """A user extension binding the task-status method cannot silently replace it.
+
+ Composition means the internal task binding always leads; a user extension
+ that binds the same method collides with it, and the SDK session rejects the
+ duplicate at connect time rather than letting one silently win.
+ """
+
+ class TaskClobberExtension(ClientExtension):
+ identifier = "test.example.com/clobber"
+
+ def notifications(self):
- async def _handler(params: PingParams) -> None: ...
++ async def _handler(params: PingParams) -> None:
++ return None
+
+ return (
+ NotificationBinding(
+ method=TASK_STATUS_METHOD,
+ params_type=PingParams,
+ handler=_handler,
+ ),
+ )
+
+ client = Client(FastMCP("srv"), extensions=[TaskClobberExtension()])
+ with pytest.raises(RuntimeError, match="duplicate notification binding"):
+ async with client:
+ pass
+
+
+async def test_both_bindings_fire_against_live_server():
+ """The internal task binding and a user extension binding both fire.
+
+ A ``task=True`` tool drives ``notifications/tasks/status`` (the internal
+ binding) while a second tool emits a custom notification the user extension
+ observes, proving the two coexist on one live connection. Pinned to
+ ``mode="legacy"`` because FastMCP task submission is a legacy-era feature.
+ """
+ received: list[PingParams] = []
+ mcp = FastMCP("compose-server")
+
+ @mcp.tool
+ async def emit(value: int) -> int:
+ ctx = get_context()
+ # Emit a custom (non-core) notification straight onto the outbound
+ # channel; unknown methods route to the client's notification bindings.
+ await ctx.session._connection.notify(CUSTOM_METHOD, {"value": value})
+ return value
+
+ @mcp.tool(task=True)
+ async def background(value: int) -> int:
+ await asyncio.sleep(0.02)
+ return value * 2
+
+ client = Client(mcp, extensions=[_DemoExtension(received)], mode="legacy")
+
+ async with client:
+ # The user extension binding fires on the custom notification.
+ await client.call_tool("emit", {"value": 21})
+ # The internal task binding fires on the task-status notification.
+ task = await client.call_tool("background", {"value": 5}, task=True)
+ status = await task.wait(timeout=2.0)
+ # Give the custom-notification queue a moment to drain.
+ await asyncio.sleep(0.1)
+
+ # Internal task binding fired: the task completed via a status notification.
+ assert status.status == "completed"
+ # User extension binding fired: it observed the custom notification.
+ assert [p.value for p in received] == [21]
+
+
+class TestClaimedResultResolution:
+ """End-to-end resolution of a server-emitted claimed `tools/call` result."""
+
+ @pytest.mark.parametrize("mode", ["auto", LATEST_MODERN_VERSION])
+ async def test_call_tool_mcp_resolves_claimed_result(self, mode):
+ """`call_tool_mcp` resolves a claimed result through the extension resolver.
+
+ The server emits a claimed shape; the client's registered extension
+ parses it and its resolver finishes it into an ordinary CallToolResult.
+ Both the negotiated (`auto`) and pinned modern eras admit the claim.
+ """
+ client = Client(_claiming_server(), extensions=[_DemoExtension()], mode=mode)
+ async with client:
+ assert client.protocol_version == LATEST_MODERN_VERSION
+ result = await client.call_tool_mcp("claimed_tool", {})
+
+ block = result.content[0]
+ assert isinstance(block, TextContent)
+ assert block.text == "resolved:from-server"
+
+ async def test_call_tool_resolves_claimed_result(self):
+ """The high-level `call_tool` also returns the resolver's CallToolResult."""
+ client = Client(
+ _claiming_server(),
+ extensions=[_DemoExtension()],
+ mode=LATEST_MODERN_VERSION,
+ )
+ async with client:
+ parsed = await client.call_tool("claimed_tool", {})
+
+ block = parsed.content[0]
+ assert isinstance(block, TextContent)
+ assert block.text == "resolved:from-server"
+
+ async def test_unwired_session_call_raises_unexpected_claimed(self):
+ """Regression guard for the half-wired bug: the raw session path raises.
+
+ With the claim registered, calling `session.call_tool` directly (FastMCP's
+ old tool path, which omitted `allow_claimed=True`) surfaces the claimed
+ result as `UnexpectedClaimedResult` β€” the exact failure the wired
+ `call_tool_mcp` path now avoids by resolving instead.
+ """
+ client = Client(
+ _claiming_server(),
+ extensions=[_DemoExtension()],
+ mode=LATEST_MODERN_VERSION,
+ )
+ async with client:
+ with pytest.raises(UnexpectedClaimedResult):
+ await client.session.call_tool("claimed_tool", {})
+
+ # The wired path resolves the very same claimed result.
+ resolved = await client.call_tool_mcp("claimed_tool", {})
+ block = resolved.content[0]
+ assert isinstance(block, TextContent)
+ assert block.text == "resolved:from-server"
diff --cc tests/client/test_streamable_http.py
index 81f8371b2,e50fcfdba..6ff47ed62
--- a/tests/client/test_streamable_http.py
+++ b/tests/client/test_streamable_http.py
@@@ -147,25 -147,18 +147,22 @@@ async def nested_server()
await asyncio.wait_for(server_task, timeout=2.0)
- async def test_ping(streamable_http_server: str):
+ async def test_ping(streamable_http_server: ASGIServer):
"""Test pinging the server."""
- async with Client(
- transport=StreamableHttpTransport(streamable_http_server), mode="legacy"
- ) as client:
- async with streamable_http_server.client() as client:
++ # `ping` is a handshake-era method, so this pins the legacy era.
++ async with streamable_http_server.client(mode="legacy") as client:
result = await client.ping()
assert result is True
async def test_ping_with_streamable_http_alias(
- streamable_http_server_with_streamable_http_alias: str,
+ streamable_http_server_with_streamable_http_alias: ASGIServer,
):
"""Test pinging the server."""
- async with Client(
- transport=StreamableHttpTransport(
- streamable_http_server_with_streamable_http_alias
- ),
- mode="legacy",
- async with streamable_http_server_with_streamable_http_alias.client() as client:
++ # `ping` is a handshake-era method, so this pins the legacy era.
++ async with streamable_http_server_with_streamable_http_alias.client(
++ mode="legacy"
+ ) as client:
result = await client.ping()
assert result is True
@@@ -184,11 -175,11 +179,11 @@@ async def test_http_headers(streamable_
assert json_result["x-demo-header"] == "ABC"
- async def test_session_id_callback(streamable_http_server: str):
+ async def test_session_id_callback(streamable_http_server: ASGIServer):
"""Test getting mcp-session-id from the transport."""
- transport = StreamableHttpTransport(streamable_http_server)
+ transport = streamable_http_server.transport()
assert transport.get_session_id() is None
- async with Client(transport=transport):
+ async with Client(transport=transport, mode="legacy"):
session_id = transport.get_session_id()
assert session_id is not None
@@@ -224,10 -214,8 +218,9 @@@ async def test_elicitation_tool(streama
if stateless_http:
pytest.xfail("Elicitation is not supported in stateless HTTP mode")
- async with Client(
- transport=StreamableHttpTransport(streamable_http_server),
- elicitation_handler=elicitation_handler,
- mode="legacy",
++ # Server-initiated elicitation is handshake-era only.
+ async with streamable_http_server.client(
- elicitation_handler=elicitation_handler
++ elicitation_handler=elicitation_handler, mode="legacy"
) as client:
result = await client.call_tool("elicit")
assert result.data == "You said your name was: Alice!"
@@@ -267,23 -251,15 +258,19 @@@ async def test_nested_streamable_http_s
reason="Timeout tests are flaky on Windows. Timeouts *are* supported but the tests are unreliable.",
)
class TestTimeout:
- async def test_timeout(self, streamable_http_server: str):
+ async def test_timeout(self, streamable_http_server: ASGIServer):
# note this transport behaves differently than others and raises
- # MCPError from the *client* context
+ # MCPError from the *client* context. Pinned to legacy: on a modern
+ # (server/discover) connection a connect-time timeout surfaces as a raw
+ # httpx.ReadTimeout from the probe rather than a wrapped MCPError.
with pytest.raises(MCPError, match="timed out"):
- async with Client(
- transport=StreamableHttpTransport(streamable_http_server),
- timeout=0.02,
- mode="legacy",
- async with streamable_http_server.client(timeout=0.02) as client:
++ async with streamable_http_server.client(
++ timeout=0.02, mode="legacy"
+ ) as client:
await client.call_tool("sleep", {"seconds": 0.05})
- async def test_timeout_tool_call(self, streamable_http_server: str):
- async with Client(
- transport=StreamableHttpTransport(streamable_http_server),
- ) as client:
+ async def test_timeout_tool_call(self, streamable_http_server: ASGIServer):
+ async with streamable_http_server.client() as client:
with pytest.raises(MCPError):
await client.call_tool("sleep", {"seconds": 0.2}, timeout=0.1)
diff --cc tests/integration_tests/auth/test_github_provider_integration.py
index af7863746,af7863746..0079072f5
--- a/tests/integration_tests/auth/test_github_provider_integration.py
+++ b/tests/integration_tests/auth/test_github_provider_integration.py
@@@ -359,8 -359,8 +359,10 @@@ async def test_github_oauth_with_mock(g
"""Test complete GitHub OAuth flow with mocked callback."""
async with github_client_with_mock:
-- # Test that we can ping the server (requires successful OAuth)
-- assert await github_client_with_mock.ping()
++ # Reaching the server at all requires successful OAuth. `list_tools` stands
++ # in for `ping` here because it works in either protocol era, and a default
++ # client negotiates the modern one, which has no `ping` method.
++ assert await github_client_with_mock.list_tools()
# Test that we can call protected tools
result = await github_client_with_mock.call_tool("get_protected_data", {})
diff --cc tests/integration_tests/test_github_mcp_remote.py
index b6190afc7,b6190afc7..9ec9776a3
--- a/tests/integration_tests/test_github_mcp_remote.py
+++ b/tests/integration_tests/test_github_mcp_remote.py
@@@ -24,6 -24,6 +24,13 @@@ pytestmark = pytest.mark.xfail
@pytest.fixture(name="streamable_http_client")
def fixture_streamable_http_client() -> Client[StreamableHttpTransport]:
++ """A default client, so this suite exercises `mode="auto"` against a real peer.
++
++ GitHub answers `server/discover` but has not adopted result tagging, so its
++ result envelope is not conformant with the modern version it advertises. The
++ client's conformance check catches that at connect time and degrades to the
++ initialize handshake, which is why these tests behave as they always have.
++ """
assert FASTMCP_GITHUB_TOKEN is not None
return Client(
@@@ -34,6 -34,6 +41,20 @@@
)
[email protected](name="legacy_client")
++def fixture_legacy_client() -> Client[StreamableHttpTransport]:
++ """A handshake-pinned client, for capabilities that exist only in that era."""
++ assert FASTMCP_GITHUB_TOKEN is not None
++
++ return Client(
++ StreamableHttpTransport(
++ url=GITHUB_REMOTE_MCP_URL,
++ auth=BearerAuth(FASTMCP_GITHUB_TOKEN),
++ ),
++ mode="legacy",
++ )
++
++
class TestGithubMCPRemote:
async def test_connect_disconnect(
self,
@@@ -44,11 -44,11 +65,16 @@@
await streamable_http_client._disconnect() # pylint: disable=W0212 (protected-access)
assert streamable_http_client.is_connected() is False
-- async def test_ping(self, streamable_http_client: Client[StreamableHttpTransport]):
-- """Test pinging the server."""
-- async with streamable_http_client:
-- assert streamable_http_client.is_connected() is True
-- result = await streamable_http_client.ping()
++ async def test_ping(self, legacy_client: Client[StreamableHttpTransport]):
++ """Test pinging the server.
++
++ `ping` is defined only in the handshake era β€” the modern protocol version
++ does not carry the method at all β€” so this pins `mode="legacy"` rather
++ than relying on the default negotiation landing there.
++ """
++ async with legacy_client:
++ assert legacy_client.is_connected() is True
++ result = await legacy_client.ping()
assert result is True
async def test_list_tools(
@@@ -106,6 -106,6 +132,10 @@@
"""Test calling a list_commit tool"""
async with streamable_http_client:
assert streamable_http_client.is_connected()
++ # On a modern connection the client derives `Mcp-Param-*` headers from
++ # the tool's schema, which it only holds once the tool has been listed
++ # in this session. Listing first keeps the call correct in either era.
++ await streamable_http_client.list_tools()
result = await streamable_http_client.call_tool(
"list_commits", {"owner": "prefecthq", "repo": "fastmcp"}
)
diff --cc tests/server/middleware/test_initialization_middleware.py
index a05727d04,d65a72c24..fb3d4fcf0
--- a/tests/server/middleware/test_initialization_middleware.py
+++ b/tests/server/middleware/test_initialization_middleware.py
@@@ -402,8 -401,7 +401,8 @@@ async def test_state_isolation_between_
import json
# Client 1 stores its value
- transport1 = StreamableHttpTransport(url=url)
- async with Client(transport=transport1, mode="legacy") as client1:
- async with running_server.client() as client1:
++ # Session ids belong to the handshake era, so these pin the legacy era.
++ async with running_server.client(mode="legacy") as client1:
result1 = await client1.call_tool(
"store_and_read", {"value": "client1-value"}
)
@@@ -413,8 -411,7 +412,7 @@@
session_id_1 = data1["session_id"]
# Client 2 should have completely isolated state
- transport2 = StreamableHttpTransport(url=url)
- async with Client(transport=transport2, mode="legacy") as client2:
- async with running_server.client() as client2:
++ async with running_server.client(mode="legacy") as client2:
result2 = await client2.call_tool(
"store_and_read", {"value": "client2-value"}
)
diff --cc tests/server/tasks/test_concurrent_dependencies.py
index edc3b6a6a,7f6f79563..19f977a5c
--- a/tests/server/tasks/test_concurrent_dependencies.py
+++ b/tests/server/tasks/test_concurrent_dependencies.py
@@@ -77,10 -77,10 +77,10 @@@ async def test_concurrent_background_ta
@mcp.tool(task=True)
async def bg_tool(name: str, ctx: Context) -> str:
- await asyncio.sleep(0.05)
+ await asyncio.sleep(0.01)
return f"bg:{name}"
- async with Client(mcp) as client:
+ async with Client(mcp, mode="legacy") as client:
task_handles = [
await client.call_tool("bg_tool", {"name": f"bg-{i}"}, task=True)
for i in range(4)
diff --cc tests/server/tasks/test_task_mount.py
index 218ef1a47,bc82c7188..e984f4969
--- a/tests/server/tasks/test_task_mount.py
+++ b/tests/server/tasks/test_task_mount.py
@@@ -138,9 -139,9 +139,9 @@@ class TestMountedToolTasks
async def test_mounted_tool_task_status(self, parent_server):
"""Can poll task status for mounted tool."""
- async with Client(parent_server) as client:
+ async with Client(parent_server, mode="legacy") as client:
task = await client.call_tool(
- "child_slow_child_tool", {"duration": 0.5}, task=True
+ "child_slow_child_tool", {"duration": 0.05}, task=True
)
# Check status while running
diff --cc tests/server/tasks/test_task_status_notifications.py
index 1b292bc73,5fb4cec7d..1b1629d74
--- a/tests/server/tasks/test_task_status_notifications.py
+++ b/tests/server/tasks/test_task_status_notifications.py
@@@ -132,8 -135,8 +135,9 @@@ async def test_subscriptions_cleanup_on
):
"""Subscriptions are cleaned up when session disconnects."""
# Start session and create task
- async with Client(notification_server) as client:
++ # Task submission is a handshake-era capability, so this pins the legacy era.
+ async with Client(notification_server, mode="legacy") as client:
- task = await client.call_tool("slow_task", {"duration": 1.0}, task=True)
+ task = await client.call_tool("slow_task", {}, task=True)
task_id = task.task_id
# Disconnect before task completes (session __aexit__ cancels subscriptions)
diff --cc tests/utilities/test_asgi_transport.py
index 000000000,8260defb6..5a473b5c1
mode 000000,100644..100644
--- a/tests/utilities/test_asgi_transport.py
+++ b/tests/utilities/test_asgi_transport.py
@@@ -1,0 -1,250 +1,255 @@@
+ """Tests for the in-process ASGI bridge and `asgi_server`."""
+
+ from typing import Literal
+
+ import httpx2
+ import pytest
+ from starlette.applications import Starlette
+ from starlette.requests import Request
+ from starlette.responses import Response, StreamingResponse
+ from starlette.routing import Route
+ from starlette.types import Receive, Scope, Send
+
+ from fastmcp import Context, FastMCP
+ from fastmcp.server.auth.providers.jwt import JWTVerifier, RSAKeyPair
+ from fastmcp.utilities.asgi_transport import StreamingASGITransport, run_asgi_lifespan
+ from fastmcp.utilities.tests import ASGIServer, asgi_server
+
+
+ def build_server() -> FastMCP:
+ server = FastMCP("BridgeTestServer")
+
+ @server.tool
+ def greet(name: str) -> str:
+ return f"Hello, {name}!"
+
+ @server.tool
+ async def elicit_name(ctx: Context) -> str:
+ """Round-trips a server-initiated request while the response is still open."""
+ result = await ctx.elicit("What is your name?", response_type=str)
+ if result.action == "accept":
+ return f"You said {result.data}"
+ return "declined"
+
+ return server
+
+
+ class TestStreamingASGITransport:
+ async def test_forwards_chunks_as_the_app_produces_them(self):
+ """The bridge must stream, not buffer: chunks arrive before the app finishes."""
+
+ async def stream(request: Request) -> StreamingResponse:
+ async def body():
+ yield b"first"
+ yield b"second"
+
+ return StreamingResponse(body(), media_type="text/plain")
+
+ app = Starlette(routes=[Route("/stream", stream)])
+ async with httpx2.AsyncClient(
+ transport=StreamingASGITransport(app), base_url="http://testserver"
+ ) as client:
+ chunks: list[bytes] = []
+ async with client.stream("GET", "/stream") as response:
+ async for chunk in response.aiter_bytes():
+ chunks.append(chunk)
+
+ assert b"".join(chunks) == b"firstsecond"
+
+ async def test_request_body_and_headers_reach_the_app(self):
+ async def echo(request: Request) -> Response:
+ body = await request.body()
+ return Response(
+ content=body,
+ headers={"x-seen-header": request.headers.get("x-demo", "missing")},
+ )
+
+ app = Starlette(routes=[Route("/echo", echo, methods=["POST"])])
+ async with httpx2.AsyncClient(
+ transport=StreamingASGITransport(app), base_url="http://testserver"
+ ) as client:
+ response = await client.post(
+ "/echo", content=b"payload", headers={"x-demo": "abc"}
+ )
+
+ assert response.content == b"payload"
+ assert response.headers["x-seen-header"] == "abc"
+
+ async def test_query_string_reaches_the_app(self):
+ async def show(request: Request) -> Response:
+ return Response(content=request.query_params["q"])
+
+ app = Starlette(routes=[Route("/search", show)])
+ async with httpx2.AsyncClient(
+ transport=StreamingASGITransport(app), base_url="http://testserver"
+ ) as client:
+ response = await client.get("/search", params={"q": "hello"})
+
+ assert response.text == "hello"
+
+ async def test_error_before_response_start_propagates_to_caller(self):
+ async def boom(scope: Scope, receive: Receive, send: Send) -> None:
+ raise ValueError("app exploded")
+
+ async with httpx2.AsyncClient(
+ transport=StreamingASGITransport(boom), base_url="http://testserver"
+ ) as client:
+ with pytest.raises(ValueError, match="app exploded"):
+ await client.get("/anything")
+
+ async def test_error_after_response_start_truncates_the_body(self):
+ """Post-start failures look like a dropped socket, not a raised exception."""
+
+ async def boom(scope: Scope, receive: Receive, send: Send) -> None:
+ await send(
+ {
+ "type": "http.response.start",
+ "status": 200,
+ "headers": [(b"content-type", b"text/plain")],
+ }
+ )
+ # Raise with no checkpoint in between, so the error is guaranteed to be
+ # recorded before the transport's waiter resumes β€” the scheduling order
+ # that used to surface the failure as a raised exception.
+ raise ValueError("app exploded mid-response")
+
+ async with httpx2.AsyncClient(
+ transport=StreamingASGITransport(boom), base_url="http://testserver"
+ ) as client:
+ response = await client.get("/anything")
+
+ assert response.status_code == 200
+ assert response.content == b""
+
+
+ class TestRunAsgiLifespan:
+ async def test_startup_and_shutdown_run_once(self):
+ events: list[str] = []
+
+ async def app(scope: Scope, receive: Receive, send: Send) -> None:
+ assert scope["type"] == "lifespan"
+ while True:
+ message = await receive()
+ if message["type"] == "lifespan.startup":
+ events.append("startup")
+ await send({"type": "lifespan.startup.complete"})
+ elif message["type"] == "lifespan.shutdown":
+ events.append("shutdown")
+ await send({"type": "lifespan.shutdown.complete"})
+ return
+
+ async with run_asgi_lifespan(app):
+ assert events == ["startup"]
+
+ assert events == ["startup", "shutdown"]
+
+ async def test_startup_failure_raises(self):
+ async def app(scope: Scope, receive: Receive, send: Send) -> None:
+ await receive()
+ await send({"type": "lifespan.startup.failed", "message": "nope"})
+
+ with pytest.raises(RuntimeError, match="startup failed"):
+ async with run_asgi_lifespan(app):
+ pass
+
+ async def test_shutdown_failure_raises(self):
+ async def app(scope: Scope, receive: Receive, send: Send) -> None:
+ await receive()
+ await send({"type": "lifespan.startup.complete"})
+ await receive()
+ await send({"type": "lifespan.shutdown.failed", "message": "teardown nope"})
+
+ with pytest.raises(RuntimeError, match="shutdown failed"):
+ async with run_asgi_lifespan(app):
+ pass
+
+ async def test_shutdown_failure_does_not_mask_body_error(self):
+ """A broken teardown must never hide the failure the caller actually cares about."""
+
+ async def app(scope: Scope, receive: Receive, send: Send) -> None:
+ await receive()
+ await send({"type": "lifespan.startup.complete"})
+ await receive()
+ await send({"type": "lifespan.shutdown.failed", "message": "teardown nope"})
+
+ with pytest.raises(ValueError, match="body exploded"):
+ async with run_asgi_lifespan(app):
+ raise ValueError("body exploded")
+
+
+ class TestRunServerInMemory:
+ @pytest.mark.parametrize("transport", ["http", "streamable-http", "sse"])
+ async def test_client_round_trip(
+ self, transport: Literal["http", "streamable-http", "sse"]
+ ):
+ async with asgi_server(build_server(), transport=transport) as server:
+ async with server.client() as client:
+ result = await client.call_tool("greet", {"name": "World"})
+
+ assert result.data == "Hello, World!"
+
+ async def test_default_path_matches_transport(self):
+ async with asgi_server(build_server(), transport="sse") as server:
+ assert server.url.endswith("/sse")
+ async with asgi_server(build_server(), transport="http") as server:
+ assert server.url.endswith("/mcp")
+
+ async def test_custom_path_is_used(self):
+ async with asgi_server(build_server(), path="/custom") as server:
+ assert server.url.endswith("/custom")
- async with server.client() as client:
++ # `ping` exists only in the handshake era, so this pins that era.
++ async with server.client(mode="legacy") as client:
+ assert await client.ping() is True
+
+ async def test_server_initiated_request_mid_stream(self):
+ """Elicitation needs a server->client request while the POST is still open.
+
+ This is the capability a buffering ASGI transport cannot provide, and the
+ reason the bridge streams responses.
+ """
+
+ async def elicitation_handler(message, response_type, params, ctx):
+ return {"value": "Alice"}
+
+ async with asgi_server(build_server()) as server:
- async with server.client(elicitation_handler=elicitation_handler) as client:
++ # Server-initiated elicitation is handshake-era only, and it is the
++ # mid-stream request this test exists to exercise, so pin that era.
++ async with server.client(
++ elicitation_handler=elicitation_handler, mode="legacy"
++ ) as client:
+ result = await client.call_tool("elicit_name", {})
+
+ assert result.data == "You said Alice"
+
+ async def test_http_client_reaches_the_app(self):
+ async with asgi_server(build_server()) as server:
+ async with server.http_client() as http:
+ # A GET on the streamable HTTP endpoint without a session is rejected;
+ # the point is that the request reaches the real app at all.
+ response = await http.get(server.url)
+
+ assert response.status_code in {400, 405}
+
+ async def test_auth_middleware_runs(self):
+ """A migrated test must not pass by bypassing the real middleware stack."""
+ key_pair = RSAKeyPair.generate()
+ server = build_server()
+ server.auth = JWTVerifier(
+ public_key=key_pair.public_key,
+ issuer="https://issuer.example.com",
+ audience="test-audience",
+ )
+
+ async with asgi_server(server) as running_server:
+ async with running_server.http_client() as http:
+ unauthenticated = await http.post(
+ running_server.url,
+ json={"jsonrpc": "2.0", "id": 1, "method": "initialize"},
+ )
+
+ assert unauthenticated.status_code == 401
+
+ async def test_yields_in_memory_server(self):
+ async with asgi_server(build_server()) as server:
+ assert isinstance(server, ASGIServer)
+ assert server.transport_type == "http"