Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
11 changes: 8 additions & 3 deletions src/mcp/client/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
32 changes: 32 additions & 0 deletions tests/client/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading