diff --git a/docs/client/index.md b/docs/client/index.md index c4c392bf5c..467086703c 100644 --- a/docs/client/index.md +++ b/docs/client/index.md @@ -23,7 +23,7 @@ That serves it at `http://localhost:8000/mcp`. The client is its own program. Sa ``` * `Client("http://localhost:8000/mcp")` is given a **URL**, so it connects over Streamable HTTP to the server you just started. -* `async with` is the **lifecycle**. Entering it connects and negotiates; leaving it disconnects. There is no `connect()` / `close()` pair, and a `Client` cannot be reused after the block ends. +* `async with` is the **lifecycle**. Entering the block connects and negotiates. Leaving it disconnects, including when an exception escapes the block. Create a new `Client` for another connection. * Inside the block the connection facts are already there as plain properties. ### What you can pass to `Client` diff --git a/src/mcp/client/client.py b/src/mcp/client/client.py index 099dcbb874..34669dee9c 100644 --- a/src/mcp/client/client.py +++ b/src/mcp/client/client.py @@ -479,9 +479,11 @@ async def __aenter__(self) -> Client: async def __aexit__(self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: Any) -> None: """Exit the async context manager.""" - if self._exit_stack: # pragma: no branch - await self._exit_stack.__aexit__(exc_type, exc_val, exc_tb) - self._session = None + try: + if self._exit_stack: # pragma: no branch + await self._exit_stack.__aexit__(exc_type, exc_val, exc_tb) + finally: + self._session = None @property def session(self) -> ClientSession: diff --git a/tests/client/test_client_caching.py b/tests/client/test_client_caching.py index 30f752eb6c..6528d558af 100644 --- a/tests/client/test_client_caching.py +++ b/tests/client/test_client_caching.py @@ -1572,3 +1572,24 @@ async def read(ctx: ServerRequestContext, params: types.ReadResourceRequestParam await client.read_resource("memo://a") assert len(fetched) == 5 # nothing was served from the cache and nothing reached the server + + +async def test_a_client_that_exits_with_an_exception_no_longer_serves_cached_tools() -> None: + """SDK-defined: an exceptional exit propagates the error and ends cache access.""" + server, fetches = _varying_tools_server() + client = Client(server, cache=CacheConfig(clock=_ManualClock())) + failure = RuntimeError("application error") + + with pytest.RaisesGroup( + pytest.RaisesExc(RuntimeError, check=lambda exc: exc is failure), flatten_subgroups=True, allow_unwrapped=True + ): + async with client: + assert _tool_names(await client.list_tools()) == ["t0"] + assert _tool_names(await client.list_tools()) == ["t0"] + assert fetches == [None] + raise failure + + with pytest.raises(RuntimeError) as exc_info: + await client.list_tools() + assert str(exc_info.value) == snapshot("Client must be used within an async context manager") + assert fetches == [None]