Client serves cached tools after its context exits with an exception

Aberta Para iniciantes
#3,968 1 comentário 0 reações 0 responsáveis Ver no GitHub

Mantenedores costumam responder em até 1 dia

@jonxsong já está trabalhando nisso.

Desde 3/12/2026.

  • #3970 de @jonxsong — aberto
  • #3971 de @mia03ther — aberto

Avaliação

Dificuldade
2/5
Tempo estimado
1-3 horas
Facilidade para iniciantes
65/100
Tipo de issue
Bug
Clareza
Claramente especificada
Status de atividade
Ativa
Stack de tecnologia
python

Direção de pesquisa

A issue aponta para src/mcp/client/client.py, especificamente para Client.__aexit__ nas linhas 480–496. Leia esse método e a verificação de conexão existente; em seguida, reproduza o exemplo com uma resposta tools/list em cache e uma exceção dentro do contexto. O trabalho estará concluído quando chamadas após uma saída normal ou excepcional rejeitarem o cliente fechado e a exceção original continuar sendo propagada.

Escrita pelo modelo de indexação a partir do texto da issue.

Descrição

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.

Linguagem predominante
Python
Estrelas
25k
Forks
4.2k
Merge médio
10min
PRs com merge (30d)
1

Preparar o ambiente

Primeiros passos

  1. Leia a issue inteira e depois o guia de contribuição do projeto.
  2. Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
  3. Faça um fork do repositório e trabalhe em uma branch.
  4. Abra um pull request que referencie o número da issue.

Mais de modelcontextprotocol/python-sdk

Todas as issues de modelcontextprotocol/python-sdk

Issues semelhantes

Mais issues de Python

Receba novas issues na sua caixa de entrada

Um resumo curto de issues do GitHub para quem está começando.