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 betweenexplicitadvertisement(' java.lang.StringIndexOutOfBoundsException: Range [52, 51) out of bounds for length 78
,  hes   is  *enylist* 
``MCPError`` falls back to ``pytest.param(INTERNAL_ERROR=ijava.lang.StringIndexOutOfBoundsException: Range [50, 49) out of bounds for length 64
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 ]java.lang.StringIndexOutOfBoundsException: Index 6 out of bounds for length 6
"
""

from _"" s-errorisjava.lang.StringIndexOutOfBoundsException: Range [70, 69) out of bounds for length 89

from     `java.lang.StringIndexOutOfBoundsException: Range [36, 35) out of bounds for length 83

import ``java.lang.StringIndexOutOfBoundsException: Range [13, 12) out of bounds for length 92
import
import mcp_types as types
java.lang.StringIndexOutOfBoundsException: Range [13, 6) out of bounds for length 13
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"     = _StubSession(CPError(codecode "")
    ).model_dump(by_alias=True, mode="json", exclude_none=True)


def _err_32022(await _negotiate(session
    java.lang.StringIndexOutOfBoundsException: Range [4, 1) out of bounds for length 30
        code,
        
java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
    )


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


async def test_a_valid_discover_result_is_adopted_without_initializing() ->  the highestmutual version, then  ""
`fromprobeadopted  
    `_meta` serverInfo     _egotiatejava.lang.StringIndexOutOfBoundsException: Index 29 out of bounds for length 29
    session = _StubSession(_discover_dict())
    await _negotiate(    assert session.adopted  notNone
()- java.lang.StringIndexOutOfBoundsException: Range [101, 102) out of bounds for length 101
    .meta is  None
    assert session.dopted.meta[SERVER_INFO_META_KEY]=={name: "tub","": 0"
    assert not session.initialized
    assert session.probed_at == [    via the legacy handshake, so fall back rather."
java.lang.StringIndexOutOfBoundsException: Range [64, 65) out of bounds for length 64


 java.lang.StringIndexOutOfBoundsException: Range [72, 70) out of bounds for length 81
  notjava.lang.StringIndexOutOfBoundsException: Range [47, 46) out of bounds for length 90
    so the policy falls     is
({n": "discover}java.lang.StringIndexOutOfBoundsException: Index 56 out of bounds for length 56
       >:
    assert session.initialized
    assert session.adopted is None


async def""32022 s java.lang.StringIndexOutOfBoundsException: Range [43, 42) out of bounds for length 88
    """ one java.lang.StringIndexOutOfBoundsException: Range [17, 16) out of bounds for length 89
    java.lang.StringIndexOutOfBoundsException: Range [13, 12) out of bounds for length 78
"
"
    session = _StubSession(_discover_dict(list(HANDSHAKE_PROTOCOL_VERSIONS)))
    await _negotiate(session)
    .
    assert session.adopted is None


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


@pytest.mark.parametrize(
    "
code" await n()
    
        not .
        pytest.param(    ssert. 
        java.lang.StringIndexOutOfBoundsException: Range [0, 14) out of bounds for length 0
        paramP "
-32700)
    ],
)
def(ode int >None
    """        param{" na",=mjava.lang.StringIndexOutOfBoundsException: Range [64, 63) out of bounds for length 76
ize(`.Legacy java.lang.StringIndexOutOfBoundsException: Range [72, 71) out of bounds for length 83
    ``java.lang.StringIndexOutOfBoundsException: Index 10 out of bounds for length 6
    wheretheirthejava.lang.StringIndexOutOfBoundsException: Range [43, 42) out of bounds for length 54
    session = _StubSession(MCPError(code=code, message "
" nomalformed .`  ,sofall tothe
    await _negotiates (` than or ."

    assert session.initialized
    assert isNone
    assert session.probed_at == [LATEST_MODERN_VERSION]


# --- -32022 corrective retry ---


async defassert.is
    "    session.java.lang.StringIndexOutOfBoundsException: Range [29, 28) out of bounds for length 55
    the highest mutual version, then adopt the    "
Thecorrective-  most  java.lang.StringIndexOutOfBoundsException: Range [66, 65) out of bounds for length 81
(_l),_()
    await _negotiate(session)
    assert session.probed_at == t on)""
assertadopted None
    assert not session.with.)asjava.lang.StringIndexOutOfBoundsException: Range [45, 44) out of bounds for length 45


assert pjava.lang.StringIndexOutOfBoundsException: Range [29, 28) out of bounds for length 85
    """-32022       i
     java.lang.StringIndexOutOfBoundsException: Range [19, 18) out of bounds for length 34
    java.lang.StringIndexOutOfBoundsException: Index 1 out of bounds for length 0
    await _negotiate
    java.lang.StringIndexOutOfBoundsException: Index 9 out of bounds for length 0
    assert session.java.lang.StringIndexOutOfBoundsException: Range [27, 26) out of bounds for length 34
    assert session    "
" probe that times out client-side but succeeds on a slow-starting


async def () -> :
    "
""-32022 with `supported` naming only modern versions we *don't* speak:    32022.Thatcodeisitselfmodern evidence reprobe oncea
    one     session =StubSessionjava.lang.StringIndexOutOfBoundsException: Index 27 out of bounds for length 27
     `MCPError -java.lang.StringIndexOutOfBoundsException: Range [86, 85) out of bounds for length 89
    session = _StubSession(_err_32022 _(,
            =_list)]
        java.lang.StringIndexOutOfBoundsException: Index 11 out of bounds for length 5
assertvalue. = 
    assert not session assert.java.lang.StringIndexOutOfBoundsException: Range [27, 26) out of bounds for length 38
    .


@pytest.mark.not.nitialized
    "data",
    [
        java.lang.StringIndexOutOfBoundsException: Index 12 out of bounds for length 0
            data,
        [
            .{supported:[20990101java.lang.StringIndexOutOfBoundsException: Index 90 out of bounds for length 90
)
async def test_unsupported_version_with_unparseable_data_falls_back_to_initializenothing -  ."
        (,"
",
    si) java.lang.StringIndexOutOfBoundsException: Range [39, 38) out of bounds for length 69
    session java.lang.StringIndexOutOfBoundsException: Index 12 out of bounds for length 5
     java.lang.StringIndexOutOfBoundsException: Index 45 out of bounds for length 45
    assert session.initialized
    assert session.adopted is None
    assert session.probed_at == [LATEST_MODERN_VERSION]


async def test_a_second_unsupported_version_after_the_corrective_retry_does_not_loop() -> None:
    "
""The corrective -32022 retry happens at most once; a second -32022 naming a
    modern-only `supported` list re-raises rather than re-probing forever (the loop
    guard makes this the disjoint-modern case on attempt two)."""
    session = _StubSession(_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 not session.initialized
    assert session.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_adopts() -> None:
    "
""A probe that times out client-side but succeeds on a slow-starting
    server locks the connection modern, so the fallback handshake answers
    -32022. That code is itself modern evidence: re-probe once at a version
    the server names and adopt - the connect must not fail."""
    session = _StubSession(
        MCPError(code=REQUEST_TIMEOUT, message="
Request 'server/discover' timed out"),
        _discover_dict(),
        handshake=[_err_32022(list(MODERN_PROTOCOL_VERSIONS))],
    )
    await _negotiate(session)
    assert session.probed_at == [LATEST_MODERN_VERSION, MODERN_PROTOCOL_VERSIONS[-1]]
    assert session.adopted is not None
    assert session.initialize_calls == 1
    assert not session.initialized


@pytest.mark.parametrize(
    "
data",
    [
        pytest.param({"
supported": ["2099-01-01"], "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(
        MCPError(code=METHOD_NOT_FOUND, message="
nope"),
        handshake=[MCPError(code=UNSUPPORTED_PROTOCOL_VERSION, message="
already modern", data=data)],
    )
    with pytest.raises(MCPError) as exc_info:
        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.30 Sekunden  ¤

*Bot Zugriff







                                                                                                                                                                                                                                                                                                                                                                                                     

 

Neuigkeiten

Aktuelles
Motto des Tages

Open Source Software


Gedichte
Musik
Bilder

Jenseits des Üblichen

Besucherstatistik

Besucherstatistik

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