Client serves cached tools after its context exits with an exception

Aperta Adatta ai principianti
#3,968 1 commento 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

@jonxsong ci sta già lavorando.

Dal 3/12/2026.

  • #3970 di @jonxsong — aperta
  • #3971 di @mia03ther — aperta

Valutazione

Difficoltà
2/5
Tempo stimato
1-3 ore
Idoneità per principianti
65/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
python

Direzione di ricerca

La issue rimanda a src/mcp/client/client.py, in particolare a Client.__aexit__ alle righe 480–496. Leggi quel metodo e il controllo della connessione esistente, quindi riproduci l’esempio con una risposta tools/list memorizzata nella cache e un’eccezione all’interno del context. Il lavoro è completato quando le chiamate successive a un’uscita normale o eccezionale rifiutano il client chiuso e l’eccezione originale continua a propagarsi.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

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.

Lingua principale
Python
Stelle
25k
Fork
4.2k
Merge medio
10m
PR unite (30g)
1

Preparare l'ambiente

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di modelcontextprotocol/python-sdk

Tutte le issue di modelcontextprotocol/python-sdk

Issue simili

Altre issue su Python

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.