python-sdk icon indicating copy to clipboard operation
python-sdk copied to clipboard

ClientSessionGroup raises KeyError when connecting a server that exposes no components

Open baselarw opened this issue 2 months ago • 2 comments

Initial Checks

  • [x] I confirm that I'm using the newest release of my line (the latest 2.x, or the latest 1.x if I'm still on v1)
  • [ ] I confirm that I searched for my issue in https://github.com/modelcontextprotocol/python-sdk/issues before opening this issue

Release line

2.x (current stable)

Description

What I ran into

ClientSessionGroup._aggregate_components deletes the session from _session_exit_stacks whenever a connected server exposes no prompts, resources, or tools:

if not any((prompts_temp, resources_temp, tools_temp)):
    del self._session_exit_stacks[session]

Via connect_with_session(server_info, session) the caller supplies a session that was never registered in _session_exit_stacks, so this raises KeyError. Via connect_to_server it drops the freshly-registered exit stack, so a later disconnect_from_server can't close that session's transport.

Why it matters

A valid MCP server can legitimately register zero tools/resources/prompts (e.g. one that only does sampling/roots), and list_* failures are swallowed into empty dicts too. In both cases connecting an otherwise-fine server either crashes or leaks a transport until group teardown.

Minimal reproduction

group = ClientSessionGroup()
# server_info + an in-memory session whose list_tools/resources/prompts are empty
await group.connect_with_session(server_info, session)  # -> KeyError

Suggested fix

Remove the empty-server cleanup block so an empty server is aggregated like any other. Happy to open a PR (branch already prepared).

Example Code


Python & MCP Python SDK

Python 3.13.2
MCP Python SDK: main @ f1b6589 (dev build 0.0.1.dev1063)

baselarw avatar Sep 24 '26 05:09 baselarw

Confirmed this reproduces exactly as described — I hit the same KeyError via connect_with_session with an empty-component server (no tools/resources/prompts registered). I've traced it to the cleanup block in _aggregate_components and have a fix ready that removes it and adds regression coverage for both connect_with_session and connect_to_server (the latter silently drops the exit stack instead of raising, which I think is worth covering too). Happy to open a PR once assigned.

baselarw avatar Sep 24 '26 12:09 baselarw

Both reports identify the same empty-component ClientSessionGroup cleanup block, including the KeyError and lost transport exit stack. This is tracked in #3384, so I’m closing this as a duplicate. AI-assisted triage; I reviewed both reports.

Kludex avatar Oct 10 '26 12:10 Kludex