diff --git a/pyproject.toml b/pyproject.toml index 6d7626d79b..0a9e49053d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -71,7 +71,7 @@ dev = [ "pytest-pretty>=1.2.0", "inline-snapshot>=0.23.0", "dirty-equals>=0.9.0", - "coverage[toml]>=7.10.7,<=7.13", + "coverage[toml]>=7.13.0,<=7.13", "pillow>=12.3; python_version >= '3.15'", "pillow>=12.0; python_version < '3.15'", "strict-no-cover", diff --git a/src/mcp/client/client.py b/src/mcp/client/client.py index 099dcbb874..95556bb546 100644 --- a/src/mcp/client/client.py +++ b/src/mcp/client/client.py @@ -479,9 +479,14 @@ 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: + # Clear the session even when the exit stack propagates an exception: + # otherwise the response cache's connection check still passes and + # later calls (e.g. list_tools) serve cached results from a dead client. + self._session = None @property def session(self) -> ClientSession: diff --git a/tests/client/test_client.py b/tests/client/test_client.py index c63248798e..7719b0562f 100644 --- a/tests/client/test_client.py +++ b/tests/client/test_client.py @@ -43,6 +43,7 @@ from mcp.client.session import ClientRequestContext from mcp.client.streamable_http import streamable_http_client from mcp.server import Server, ServerRequestContext +from mcp.server.caching import CacheHint from mcp.server.mcpserver import Context, MCPServer from mcp.shared.memory import MessageStream, create_client_server_memory_streams from mcp.shared.message import SessionMessage @@ -293,6 +294,37 @@ async def test_client_reentry_raises_runtime_error(app: MCPServer): await client.__aenter__() +async def test_list_tools_after_exception_exit_rejects_cached_tools(): + """After an exception leaves the `async with Client(...)` block, `list_tools` + raises `RuntimeError` instead of serving the cached listing (issue #3968).""" + + class ApplicationError(Exception): + pass + + server = MCPServer("test", cache_hints={"tools/list": CacheHint(ttl_ms=60_000)}) + + @server.tool() + def echo() -> str: + return "echo" + + client = Client(server, mode="2026-07-28") + try: + async with client: + await client.list_tools() + # Execute the tool body directly: the 100% coverage gate counts + # this test file, and calling it through the client crashes the + # pytest worker on 3.14/3.15 lowest-direct (the failure's + # traceback carries a tb_lineno=None frame, which pytest's repr + # formatting cannot handle). + assert echo() == "echo" + raise ApplicationError + except* ApplicationError: + pass + + with pytest.raises(RuntimeError, match="Client must be used within an async context manager"): + await client.list_tools() + + async def test_client_send_progress_notification(): """Test sending progress notification.""" received_from_client = None diff --git a/uv.lock b/uv.lock index 3b718ff868..1f6a3e956d 100644 --- a/uv.lock +++ b/uv.lock @@ -1070,7 +1070,7 @@ codegen = [{ name = "datamodel-code-generator", specifier = "==0.81.0" }] dev = [ { name = "blockbuster", marker = "python_full_version < '3.15'", specifier = ">=1.5.27" }, { name = "blockbuster", marker = "python_full_version >= '3.15'", specifier = ">=1.5.29" }, - { name = "coverage", extras = ["toml"], specifier = ">=7.10.7,<=7.13" }, + { name = "coverage", extras = ["toml"], specifier = ">=7.13.0,<=7.13" }, { name = "dirty-equals", specifier = ">=0.9.0" }, { name = "inline-snapshot", specifier = ">=0.23.0" }, { name = "logfire", specifier = ">=3.0.0" },