Client serves cached tools after its context exits with an exception

未关闭 适合新手
#3,968 1 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

维护者通常 1 天内回复

@jonxsong 已经在做这个了。

开始于 2026年12月3日。

  • #3970 来自 @jonxsong —— 未关闭
  • #3971 来自 @mia03ther —— 未关闭

评估

难度
2/5
预计耗时
1-3 小时
新手友好度
65/100
Issue 类型
缺陷
描述清晰度
描述清楚
活跃度
活跃
技术栈
python

调研方向

Issue 指向 src/mcp/client/client.py,具体是第 480–496 行的 Client.__aexit__。阅读该方法和现有的连接检查,然后用缓存的 tools/list 响应以及 context 内部发生的异常重现示例。正常退出或因异常退出后,如果后续调用会拒绝已关闭的客户端,同时原始异常仍会继续传播,则表示完成。

由索引模型根据 Issue 内容生成。

描述

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.

主要语言
Python
星标
25k
派生
4.2k
平均合并
10 分钟
30 天内合并 PR
1

环境准备

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

modelcontextprotocol/python-sdk 的其他 Issue

查看 modelcontextprotocol/python-sdk 的全部 Issue

相似的 Issue

更多 Python Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。