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

`ClientSessionGroup` attempts to use capabilities that were not advertised

Open mr-brobot opened this issue 6 months ago • 4 comments

Initial Checks

  • [x] I confirm that I'm using the latest version of MCP Python SDK
  • [x] I confirm that I searched for my issue in https://github.com/modelcontextprotocol/python-sdk/issues before opening this issue

Description

ClientSessionGroup calls session.list_tools, session.list_prompts(), and session.list_resources() unconditionally on every connect. It never consults the ServerCapabilities returned by initialize.

For a server that doesn't implement tools, prompts, or resources, the corresponding calls return a JSON-RPC Method not found error. The MCPError is squashed and a WARNING is emitted, e.g.,

WARNING:root:Could not fetch prompts: Method not found

This seems to contradict the MCP lifecycle spec (2025-11-25, Capability Negotiation / Operation):

Both parties MUST: ... Only use capabilities that were successfully negotiated.

ClientSessionGroup should inspect session.initialize_result.capabilities and only interrogate capabilities that the server advertised, e.g.,

caps = session.initialize_result.capabilities if session.initialize_result else None

if caps and caps.prompts is not None:
    prompts = (await session.list_prompts()).prompts
    ...
if caps and caps.resources is not None:
    resources = (await session.list_resources()).resources
    ...
if caps and caps.tools is not None:
    tools = (await session.list_tools()).tools
    ...

Example Code

"""Repro: tools-only server + ClientSessionGroup emits WARNINGs."""

from __future__ import annotations

import anyio

from mcp import Client, types
from mcp.client.session_group import ClientSessionGroup
from mcp.server import Server, ServerRequestContext


async def handle_list_tools(
    ctx: ServerRequestContext, params: types.PaginatedRequestParams | None
) -> types.ListToolsResult:
    return types.ListToolsResult(
        tools=[
            types.Tool(
                name="ping",
                description="Ping",
                input_schema={"type": "object", "properties": {}},
            )
        ]
    )


async def handle_call_tool(
    ctx: ServerRequestContext, params: types.CallToolRequestParams
) -> types.CallToolResult:
    return types.CallToolResult(content=[types.TextContent(type="text", text="pong")])


async def main() -> None:
    server = Server(
        "tools-only-server",
        on_list_tools=handle_list_tools,
        on_call_tool=handle_call_tool,
    )

    async with Client(server) as client:
        # Server omits prompts/resources capabilities:
        assert client.initialize_result.capabilities.prompts is None
        assert client.initialize_result.capabilities.resources is None

        group = ClientSessionGroup()
        await group.connect_with_session(client.initialize_result.server_info, client.session)


if __name__ == "__main__":
    anyio.run(main)

Python & MCP Python SDK

Python: 3.14.4
MCP Python SDK: main @ da4c118 (also reproducible on v1.27.1)
OS: Linux 6.6.87.2-microsoft-standard-WSL2 x86_64

mr-brobot avatar May 26 '26 13:05 mr-brobot

This looks worth fixing at the ClientSessionGroup.connect_with_session boundary rather than only suppressing the warnings.

A clean behavior contract could be:

  • if capabilities.tools is None, skip list_tools() entirely and leave the group's tool collection unchanged for that session
  • do the same for prompts and resources
  • only treat Method not found as recoverable for older/non-conforming servers that advertised the capability but still failed the method
  • add a regression server that advertises tools only, then assert no prompt/resource requests are sent and no warning is emitted

That keeps the client aligned with negotiated capabilities while preserving a fallback path for servers with incorrect capability metadata.

scosemicolon avatar May 26 '26 18:05 scosemicolon

reproduced on main (616476f) and v1.x. ClientSessionGroup._aggregate_components calls list_prompts/list_resources/list_tools without inspecting the session's negotiated ServerCapabilities, so a tools-only server gets two extra requests that come back as Method not found and are swallowed into warnings. spec is unambiguous here — docs/specification/2025-11-25/basic/lifecycle.mdx:220 says clients MUST "Only use capabilities that were successfully negotiated."

the fix in _aggregate_components (src/mcp/client/session_group.py) reads session.initialize_result.capabilities and gates each list_* call on the corresponding capability being non-None; the existing MCPError fallback is preserved for servers that advertise a capability but still fail the method. needs backport to v1.x — block is identical there with the McpError spelling.

repro (in-memory tools-only server, no extra deps)
"""Repro for issue #2689.

ClientSessionGroup._aggregate_components calls list_prompts/list_resources/
list_tools unconditionally on every connect — even when the server's
advertised ServerCapabilities did not include those capabilities.
"""

from __future__ import annotations

import logging

import anyio

from mcp import types
from mcp.client.session import ClientSession
from mcp.client.session_group import ClientSessionGroup
from mcp.server import Server, ServerRequestContext
from mcp.server.lowlevel import NotificationOptions
from mcp.server.models import InitializationOptions
from mcp.server.session import ServerSession
from mcp.shared.memory import create_client_server_memory_streams


async def handle_list_tools(
    ctx: ServerRequestContext, params: types.PaginatedRequestParams | None
) -> types.ListToolsResult:
    return types.ListToolsResult(
        tools=[
            types.Tool(
                name="ping",
                description="Ping",
                input_schema={"type": "object", "properties": {}},
            )
        ]
    )


async def handle_call_tool(
    ctx: ServerRequestContext, params: types.CallToolRequestParams
) -> types.CallToolResult:
    return types.CallToolResult(
        content=[types.TextContent(type="text", text="pong")]
    )


class _CaptureHandler(logging.Handler):
    def __init__(self) -> None:
        super().__init__(level=logging.WARNING)
        self.records: list[logging.LogRecord] = []

    def emit(self, record: logging.LogRecord) -> None:
        self.records.append(record)


async def main() -> None:
    server = Server(
        name="tools-only-server",
        on_list_tools=handle_list_tools,
        on_call_tool=handle_call_tool,
    )

    capture = _CaptureHandler()
    logging.getLogger().addHandler(capture)
    logging.getLogger().setLevel(logging.WARNING)

    async with create_client_server_memory_streams() as (client_streams, server_streams):
        client_read, client_write = client_streams
        server_read, server_write = server_streams

        async def run_server() -> None:
            async with ServerSession(
                server_read,
                server_write,
                InitializationOptions(
                    server_name="tools-only-server",
                    server_version="0.1.0",
                    capabilities=server.get_capabilities(NotificationOptions(), {}),
                ),
            ) as server_session:
                async for message in server_session.incoming_messages:
                    await server._handle_message(message, server_session, {})

        async with (
            anyio.create_task_group() as tg,
            ClientSession(client_read, client_write) as client_session,
        ):
            tg.start_soon(run_server)
            init_result = await client_session.initialize()
            assert init_result.capabilities.tools is not None
            assert init_result.capabilities.prompts is None
            assert init_result.capabilities.resources is None

            group = ClientSessionGroup()
            await group._aggregate_components(init_result.server_info, client_session)

            tg.cancel_scope.cancel()

    warnings = [r.getMessage() for r in capture.records]
    print("warnings:", warnings)
    assert any("Could not fetch prompts" in m for m in warnings)
    assert any("Could not fetch resources" in m for m in warnings)


if __name__ == "__main__":
    anyio.run(main)
run + output (pre-fix)
$ uv run python repro.py
server capabilities:
  tools     = ToolsCapability(list_changed=False)
  prompts   = None
  resources = None

aggregated tools     = ['ping']
aggregated prompts   = []
aggregated resources = []

captured WARNING records:
  - Could not fetch prompts: Method not found
  - Could not fetch resources: Method not found

REPRODUCED: ClientSessionGroup ignores negotiated capabilities.
code path

src/mcp/client/session_group.py:347-376 — three sibling try blocks invoke session.list_prompts() / session.list_resources() / session.list_tools() with no guard. _initialize_result is already stored on ClientSession after initialize() (exposed via the initialize_result property), so the cap dict is reachable; it's just not consulted. v1.x has the identical block (with McpError spelling) at the same location and behaves the same way, so the fix needs a backport.

suggested fix
# src/mcp/client/session_group.py
+        # Per the lifecycle spec, only invoke methods for capabilities the
+        # server advertised during initialization. initialize_result is set
+        # once initialize() has completed; if it is missing, fall back to the
+        # prior unconditional behavior so the existing MCPError handler can
+        # still cope with servers that misbehave.
+        capabilities = session.initialize_result.capabilities if session.initialize_result is not None else None
+
         # Query the server for its prompts and aggregate to list.
-        try:
-            prompts = (await session.list_prompts()).prompts
-            ...
-        except MCPError as err:
-            logging.warning(f"Could not fetch prompts: {err}")
+        if capabilities is None or capabilities.prompts is not None:
+            try:
+                prompts = (await session.list_prompts()).prompts
+                ...
+            except MCPError as err:
+                logging.warning(f"Could not fetch prompts: {err}")
         # (same gate around list_resources and list_tools)

test to verify: a tools-only server (capabilities.prompts is None, capabilities.resources is None, capabilities.tools is set) drives connect_to_server and the test asserts list_prompts/list_resources are never awaited while list_tools is — added as test_client_session_group_skips_unsupported_capabilities in tests/client/test_session_group.py. fails on current main with Expected list_prompts to not have been awaited. Awaited 1 times.; passes with the fix. full suite (1743 tests) stays green.

mcp-claude[bot] avatar Jun 01 '26 11:06 mcp-claude[bot]

This looks worth pinning down as a protocol-level regression rather than only an implementation bug.

For ClientSessionGroup uses unadvertised capabilities, the acceptance test I would want is a minimal client/server fixture that records the exact JSON-RPC or HTTP exchange, then asserts both the wire result and the local lifecycle state after the failure path. In MCP deployments, the dangerous failures are often not just wrong return values; they are pending requests, dropped notifications, mismatched session state, or errors that get translated into a generic response and become impossible to diagnose.

A useful fix boundary would preserve three signals: the protocol error sent to the peer, the local exception or cancellation reason available to application code, and a trace/log field that ties the two together. That makes the behavior debuggable for agent hosts without requiring every host to special-case this SDK detail.

norika1207-lab avatar Jun 02 '26 03:06 norika1207-lab

Implemented the capability negotiation fix for #2689.

ClientSessionGroup now honors server-advertised capabilities and avoids querying prompts, resources, or tools that were not negotiated during initialization.

Added regression tests covering unsupported capability scenarios and verified all CI and conformance checks pass.

Fixes #2689

bobby-nandigam avatar Jun 07 '26 07:06 bobby-nandigam