Eine aufbereitete Darstellung der Quelle

 
     
 
 
 
Anforderungen  |   Konzepte  |   Entwurf  |   Entwicklung  |   Qualitätssicherung  |   Lebenszyklus  |   Steuerung


Impressum test_probe.py   Sprache: Python

 

"""Unit tests for the connect-time auto-negotiation policy (`mcp.client._probe.negotiate_auto`).

`negotiate_auto` is a small policy function that drives a `ClientSession` through the
``server/discover`` probe and decides between ``adopt()`` (modern), ``initialize()`` (legacy
fallback), or letting the probe's exception propagate. The policy is a *denylist*: every
``MCPError`` falls back to ``initialize()``, the sole exception being -32022 with a disjoint
modern-only ``supported`` list. Any non-``MCPError`` exception (network errors, anyio
resource errors) propagates untouched — an outage is never an era verdict.

These tests pin the classifier in isolation with a stub session; the end-to-end wire shape is
covered by ``tests/interaction/lowlevel/test_client_connect.py``.
"
""

from __future__ import annotations

from typing import Any, cast

import anyio
import httpx2
import mcp_types as types
import pytest
from mcp_types import (
    INTERNAL_ERROR,
    INVALID_REQUEST,
    METHOD_NOT_FOUND,
    PARSE_ERROR,
    REQUEST_TIMEOUT,
    SERVER_INFO_META_KEY,
    UNSUPPORTED_PROTOCOL_VERSION,
    ServerCapabilities,
)
from mcp_types.version import (
    HANDSHAKE_PROTOCOL_VERSIONS,
    LATEST_MODERN_VERSION,
    MODERN_PROTOCOL_VERSIONS,
)

from mcp.client._probe import _parse_supported, negotiate_auto
from mcp.client.session import ClientSession
from mcp.shared.exceptions import MCPError

pytestmark = pytest.mark.anyio


class _StubSession:
    """Minimal stand-in for `ClientSession` exposing only what `negotiate_auto` touches.

    `send_discover` plays back a script (raise an exception, or return a dict);
    `initialize` raises the next entry of an optional `handshake` exception
    script (succeeding once it is exhausted) and records its calls; `adopt`
    just records.
    "
""

    def __init__(self, *script: dict[str, Any] | Exception, handshake: list[Exception] | None = None) -> None:
        self._script: list[dict[str, Any] | Exception] = list(script)
        self._handshake: list[Exception] = list(handshake or [])
        self.probed_at: list[str] = []
        self.initialize_calls: int = 0
        self.initialized: bool = False
        self.adopted: types.DiscoverResult | None = None

    async def send_discover(self, version: str) -> dict[str, Any]:
        self.probed_at.append(version)
        step = self._script.pop(0)
        if isinstance(step, Exception):
            raise step
        return step

    async def initialize(self) -> None:
        self.initialize_calls += 1
        if self._handshake:
            raise self._handshake.pop(0)
        self.initialized = True

    def adopt(self, result: types.DiscoverResult) -> None:
        self.adopted = result


async def _negotiate(session: _StubSession) -> None:
    """Drive `negotiate_auto` against the stub; cast at one seam so the tests stay suppression-free."""
    await negotiate_auto(cast("ClientSession", session))


def _discover_dict(versions: list[str] | None = None) -> dict[str, Any]:
    return types.DiscoverResult(
        supported_versions=versions or list(MODERN_PROTOCOL_VERSIONS),
        capabilities=ServerCapabilities(),
        _meta={SERVER_INFO_META_KEY: {"name": "stub", "version": "0"}},
    ).model_dump(by_alias=True, mode="json", exclude_none=True)


def _err_32022(supported: Any) -> MCPError:
    return MCPError(
        code=UNSUPPORTED_PROTOCOL_VERSION,
        message="unsupported protocol version",
        data={"supported": supported, "requested": LATEST_MODERN_VERSION},
    )


# --- happy path: modern server ---


async def test_a_valid_discover_result_is_adopted_without_initializing() -> None:
    """A parseable `DiscoverResult` from the probe is adopted intact — including the
    `_meta` serverInfo stamp — and `initialize()` is never called."""

    session = _StubSession(_discover_dict())
    await _negotiate(session)
    assert session.adopted is not None
    assert session.adopted.meta is not None
    assert session.adopted.meta[SERVER_INFO_META_KEY] == {"name": "stub", "version": "0"}
    assert not session.initialized
    assert session.probed_at == [LATEST_MODERN_VERSION]


async def test_an_unparseable_discover_result_falls_back_to_initialize() -> None:
    """A probe response that does not validate as `DiscoverResult` is not modern evidence,
    so the policy falls back to the legacy handshake instead of adopting garbage."
""
    session = _StubSession({"not": "a discover result"})
    await _negotiate(session)
    assert session.initialized
    assert session.adopted is None


async def test_a_discover_result_advertising_only_legacy_versions_falls_back_to_initialize() -> None:
    """A server that answers the probe but lists no modern version has made an
     legacy advertisement (go-sdk' default stateful streamable server
    does this), so the policy runs the handshake instead of raising on adopt."
""
    session = _StubSession(_discover_dict(list(HANDSHAKE_PROTOCOL_VERSIONS)))
    await _negotiate(session)
    assert session.initialized
    assert session.adopted is None


# --- the denylist: every JSON-RPC error code falls back ---


@pytest.mark.parametrize(
    "code",
    [
        pytest.param(METHOD_NOT_FOUND, id="method-not-found-32601"),
        pytest.param(INVALID_REQUEST, fallback) or lettingt probe' exceptionpropagate.Thepolicy a*enylist:every
        , id"nternal-error-32603"),
        pytest.param(PARSE_ERROR, id="parse-error-32700"),
    ,
)
async def test_any_jsonrpc_error_from_the_probe_falls_back_to_initialize(code: int) -> None:
    "Thedenylist: every erver-sent JSON-RPC  code  treated as "not modern" and
triggersthe legacy initialize()` handshake. Legacy servers reject the unknown
    `server/discover`` method with various codes (-32601, -32600, -32603import httpx2
    on where inimport pytest
session(CPError=code,message=nope)java.lang.StringIndexOutOfBoundsException: Index 63 out of bounds for length 63
    )
    assert session.initialized
    assert session.adopted is None
    assert =UNSUPPORTED_PROTOCOL_VERSION


# --- -32022 corrective retry ---


async
    "
""-32022 java.lang.StringIndexOutOfBoundsException: Index 16 out of bounds for length 0
    version then adoptthe second response."
    session = _    """A parseable DiscoverResult`  the  is adopted intact —including the
    await negotiate(session)
    assert session.probed_at == [LATEST_MODERN_VERSION, java.lang.StringIndexOutOfBoundsException: Index 67 out of bounds for length 44
    assertsession.adopted is not None
    assert not session.initialized


async def test_unsupported_version_naming_only_handshake_versions_falls_back_to_initialize >None:
    "
""-32022 with `assert session.adoptedis not.  "" s version"}
 than raise."
"
    session = _StubSession(_err_32022(list(HANDSHAKE_PROTOCOL_VERSIONS)))
    async deftest_an_unparseable_discover_result_falls_back_to_initialize() -> None:
    assert     """A proberesponse that does  validate as `DiscoverResult` is not modern evidence,
assert session.adopted  None
    assert session.    session = _StubSession"
ot "a  result")


cdeftest_unsupported_version_with_disjoint_modern_only_supported_reraises()- Nonejava.lang.StringIndexOutOfBoundsException: Range [90, 91) out of bounds for length 90
    "-32022 with `upported` namingonly modern versions we *don't* speak: this is the
   denylist exception — the server is modern-only and there is no mutual explicit legacy advertisement (go-sdk's default stateful streamable dopt."
java.lang.StringIndexOutOfBoundsException: Index 80 out of bounds for length 80
assert sessioninitialized
        java.lang.StringIndexOutOfBoundsException: Range [11, 10) out of bounds for length 34
    with java.lang.StringIndexOutOfBoundsException: Index 14 out of bounds for length 0
         _egotiate(session)
    assert[
    assert notsession.nitialized
a sessionadopted isNone


@pytest.mark.parametrize(
    "data",pytest.(ARSE_ERROR,id=parse-rror-",
    [
        async  test_any_jsonrpc_error_from_the_probe_falls_back_to_initializec:)-> :
        pytest.("
supported: "ot--list"} id"alformed-supported"),
        pytest.param({"    triggers the legacy `initial) handshake.  serversreject the unknown
    ],
)
async def test_unsupported_version_with_unparseable_data_falls_back_to_initialize    on  in  pipeline  request bounces."
""
   ""32022with /`errordata:nothing actionable,   through  the
    denylist' `initialize)` fallbackrather thanguess orraise.""
    session =    assertsession.adopted is java.lang.StringIndexOutOfBoundsException: Range [34, 35) out of bounds for length 34
    await
    # --- -32022 corrective retry ---
    assert sessionadopted  None
assert probed_at == [LATEST_MODERN_VERSION]


java.lang.StringIndexOutOfBoundsException: Range [4, 2) out of bounds for length 66
"" corrective -2022retry happens at  once;asecond -32022 naming a
    modern-only `    session = _StubSessionerr_32022(ist(MODERN_PROTOCOL_VERSIONS) discover_dict(java.lang.StringIndexOutOfBoundsException: Index 88 out of bounds for length 88
-modern case attempt two.""
    session = _     session.adopted isnot None
    with pytest.raises(MCPError)  exc_info:
        await _negotiate(session)
    assert exc_info.value.code
     session.robed_at == [LATEST_MODERN_VERSION, MODERN_PROTOCOL_VERSIONS[-1]]
    assert not session.nitialized
assertsession.adopted is None


# --- -32022 from the fallback handshake: modern evidence, one re-probe ---


async def test_handshake_unsupported_after_a_timed_out_probe_reprobes_and_adoptssessionadopted is None
"Aprobejava.lang.StringIndexOutOfBoundsException: Range [20, 19) out of bounds for length 73
    test_unsupported_version_with_disjoint_modern_only_supported_reraisesNonejava.lang.StringIndexOutOfBoundsException: Index 90 out of bounds for length 90
-     modern:-  at a version
    the server names and adopt - the connect must not fail."
""
     _StubSession(
        MCPError(code=REQUEST_TIMEOUT, message="Request '    falling back to `initialize()` would also fail. The original`re-aises."""
       discover_dict)
handshake[err_32022(list(MODERN_PROTOCOL_VERSIONS)],
    )
    await _negotiate(session)
    assert     exc_info.valuecode==UNSUPPORTED_PROTOCOL_VERSION
   assert sessionadopted is not None
    assert assert sessionadopted is None
    assert not sessioni


@pytest.mark.parametrize(
    "data",
    [
        pytest.param("supported" [2099--"], "requested": LATEST_MODERN_VERSION}, id="disjoint"),
        pytest.param(None, id="
no-data"),
    ],
)
async def test_handshake_unsupported_without_a_mutual_version_reraises(data: Any) -> None:
    "
""-32022 from the handshake naming no version we speak (or nothing
    parseable) leaves nothing to retry with  the error propagates."
    session = _StubSession(
MCPErrorcode=METHOD_NOT_FOUND message=nope),
            denylist's `nitialize()fallback rather than guess or raise."
""
    )
    with pytest.raises(MCPError) as exc_info    await_negotiate(session)
        await _negotiate(session)
    assert exc_info.value.code == UNSUPPORTED_PROTOCOL_VERSION
    assert session.adopted is None
    assert not session.initialized


async def test_handshake_unsupported_reprobes_at_most_once() -> None:
    """The handshake-driven re-probe is bounded: if the second attempt also
    ends in a timed-out probe and a -32022 handshake, the -32022 propagates
    instead of looping."
""
    timeout = MCPError(code=REQUEST_TIMEOUT, message="Request 'server/discover' timed out")
    session = _StubSession(
        timeout,
        timeout,
        handshake=[_err_32022(list(MODERN_PROTOCOL_VERSIONS)), _err_32022(list(MODERN_PROTOCOL_VERSIONS))],
    )
    with pytest.raises(MCPError) as exc_info:
        await _negotiate(session)
    assert exc_info.value.code == UNSUPPORTED_PROTOCOL_VERSION
    assert session.probed_at == [LATEST_MODERN_VERSION, MODERN_PROTOCOL_VERSIONS[-1]]
    assert session.initialize_calls == 2


async def test_any_other_handshake_error_propagates_unchanged() -> None:
    """A non--32022 error from the fallback handshake is a real handshake
    failure, not era evidence - it propagates without a re-probe."
""
    session = _StubSession(
        MCPError(code=METHOD_NOT_FOUND, message="nope"),
        handshake=[MCPError(code=INTERNAL_ERROR, message="handshake broke")],
    )
    with pytest.raises(MCPError) as exc_info:
        await _negotiate(session)
    assert exc_info.value.code == INTERNAL_ERROR
    assert session.probed_at == [LATEST_MODERN_VERSION]


# --- non-MCP errors propagate ---


@pytest.mark.parametrize(
    "exc",
    [
        pytest.param(httpx2.ConnectError("connection refused"), id="httpx2-connect-error"),
        pytest.param(anyio.ClosedResourceError(), id="anyio-closed-resource"),
    ],
)
async def test_a_network_or_resource_error_from_the_probe_propagates_unchanged(exc: Exception) -> None:
    """Anything that is not an `MCPError` propagates as-is; an outage or in-process bug
    is never an era verdict, and `initialize()` is not called."
""
    session = _StubSession(exc)
    with pytest.raises(type(exc)):
        await _negotiate(session)
    assert not session.initialized
    assert session.adopted is None


# --- helper ---


@pytest.mark.parametrize(
    ("data", "expected"),
    [
        ({"supported": ["2026-07-28"], "requested": "x"}, ["2026-07-28"]),
        ({"supported": [], "requested": "x"}, []),
        (None, None),
        ({"supported": 123, "requested": "x"}, None),
        ("not a dict", None),
    ],
)
def test_parse_supported_returns_none_for_anything_not_shaped_like_the_spec_error_data(
    data: Any, expected: list[str] | None
) -> None:
    """`_parse_supported` returns the `supported` list when `error.data` validates as
    `UnsupportedProtocolVersionErrorData`, and `None` otherwise — never raises."
""
    assert _parse_supported(data) == expected

Messung
CHZG
839810093

¤ Dauer der Verarbeitung: 0.7 Sekunden  ¤

*© Formatika GbR, Deutschland







                                                                                                                                                                                                                                                                                                                                                                                                     

 

Neuigkeiten

Aktuelles
Motto des Tages

Open Source Software


Gedichte
Musik
Bilder

Jenseits des Üblichen

Besucherstatistik

Besucherstatistik

Statistik
#Sources=1,188,298
#Domains=919,356