From ed836e7693392ddf576202a619484a7e38bd9abe Mon Sep 17 00:00:00 2001 From: MIA_Ether Date: Thu, 3 Dec 2026 10:53:47 +0000 Subject: [PATCH 1/4] fix(client): clear session when context exits with an exception Client.__aexit__ cleared _session only after the exit stack returned normally, so an exception leaving 'async with Client(...)' left the session reference in place and later calls (e.g. list_tools) served cached results from a dead client. Clear _session in a finally block so the connection guard rejects later calls on the closed client, while the original exception still propagates. Fixes #3968 --- src/mcp/client/client.py | 11 ++++++++--- tests/client/test_client.py | 26 ++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 3 deletions(-) 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..5877ee73c9 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,31 @@ 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() + 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 From 7addfce69826da06b6db60c2f215074705815ea8 Mon Sep 17 00:00:00 2001 From: MIA_Ether Date: Fri, 4 Dec 2026 12:57:12 +0000 Subject: [PATCH 2/4] test(client): call the echo tool in the exception-exit test MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The tool body ('return "echo"') never executed — the test only listed tools — leaving one line uncovered and tripping the 100% coverage gate on every CI job. Calling the tool also proves it works before the exception exit. --- tests/client/test_client.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/tests/client/test_client.py b/tests/client/test_client.py index 5877ee73c9..08c87c2e4c 100644 --- a/tests/client/test_client.py +++ b/tests/client/test_client.py @@ -311,6 +311,11 @@ def echo() -> str: try: async with client: await client.list_tools() + # Call the tool once so its body executes (the 100% coverage gate + # counts this test file too). + result = await client.call_tool("echo") + assert isinstance(result.content[0], TextContent) + assert result.content[0].text == "echo" raise ApplicationError except* ApplicationError: pass From e2c2638145aaf4dbeb9dd7ef6742a2e6f4ca31b0 Mon Sep 17 00:00:00 2001 From: MIA_Ether Date: Fri, 4 Dec 2026 13:07:27 +0000 Subject: [PATCH 3/4] test(client): call the tool function directly in the exception-exit test Calling it through the client crashed the pytest worker on 3.14/3.15 lowest-direct (the failure traceback carries a tb_lineno=None frame, which pytest's repr formatting cannot handle). The tool body still executes, so the 100% coverage gate stays satisfied. --- tests/client/test_client.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/tests/client/test_client.py b/tests/client/test_client.py index 08c87c2e4c..7719b0562f 100644 --- a/tests/client/test_client.py +++ b/tests/client/test_client.py @@ -311,11 +311,12 @@ def echo() -> str: try: async with client: await client.list_tools() - # Call the tool once so its body executes (the 100% coverage gate - # counts this test file too). - result = await client.call_tool("echo") - assert isinstance(result.content[0], TextContent) - assert result.content[0].text == "echo" + # 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 From c8ae587a16d8c6004fa3b265fa2c2d2188c70790 Mon Sep 17 00:00:00 2001 From: MIA_Ether Date: Fri, 4 Dec 2026 13:21:51 +0000 Subject: [PATCH 4/4] chore(deps): raise coverage floor to 7.13.0 (3.14/3.15 lowest-direct CI) coverage 7.10.7's sys.monitoring tracer crashes with KeyError on Python 3.14/3.15 while tracing 'except*' code (the new test in #3971 is the suite's only 'except*' user), which then crashes the pytest worker while formatting the failure. Locked jobs already use 7.13.0 and are green; lowest-direct installed the 7.10.7 floor and crashed. Raising the floor to the already-locked 7.13.0 fixes lowest-direct with no version change for locked jobs. --- pyproject.toml | 2 +- uv.lock | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) 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/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" },