Skip to content

Client serves cached tools after its context exits with an exception #3968

Backlog

Description

@jonxsong

Initial Checks

  • Reproduced on the latest 2.x release.
  • Searched existing issues and pull requests for this behavior.

Release line

2.x (current stable)

Description

After an exception leaves an async with Client(...) block, client.list_tools() can still return a cached tool list even though the connection has closed. The same call after a normal exit raises RuntimeError: Client must be used within an async context manager. Both exits should make subsequent calls reject the closed client.

Client.aexit clears _session after awaiting the exit stack. If the stack propagates an exception, the assignment is skipped and the cache's connection check still passes.

The example prints ['echo'] on both versions below. Remove the line that raises ApplicationError and the final call raises RuntimeError as expected.

Example Code

import anyio
from mcp import Client
from mcp.server import CacheHint, MCPServer


class ApplicationError(Exception):
    pass


async def main() -> None:
    server = MCPServer("repro", 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

    print([tool.name for tool in (await client.list_tools()).tools])


anyio.run(main)

Python & MCP Python SDK

Windows, CPython 3.12.4, MCP 2.3.0 and main at 77001c96.

I'd like to work on the fix if maintainers are open to an outside PR. Clearing the session reference even when the exit stack raises would preserve the original exception and let the existing connection guard reject later calls.

Codex helped with implementation. Report written and reviewed by Jon Zhang.

Activity

  1. mia03ther commented on Dec 3, 2026

    @mia03ther

    Reproduced on main at 77001c9: after the exception leaves the async with, list_tools() returns the cached ['echo'] instead of raising, exactly as described — the await self._exit_stack.__aexit__(...) in Client.__aexit__ propagates the exception, so self._session = None never runs.

    The fix I have ready clears _session in a finally block, so the existing connection guard rejects later calls while the original exception still propagates unchanged, plus a regression test (fails without the fix, passes with it). It's on my fork at mia03ther/python-sdk branch fix/3968-cached-tools-after-exit (commit ed836e7) — happy to open the PR if a maintainer wants it. (I tried opening one, but the API returns a permissions error for PR creation from my account, so the branch is here for now.)

    Noting the reporter @jonxsong already offered to fix this and has first call — deferring to them if they'd like to take it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions