The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(mcp): complete the handshake when a stateless server names a modern protocolVersion and lacks server/discover
teknium19bd8257c0274
diff --git a/tests/tools/test_mcp_protocol_negotiation.py b/tests/tools/test_mcp_protocol_negotiation.pyindex aff171bac32..b1cdc6c0a65 100644--- a/tests/tools/test_mcp_protocol_negotiation.py+++ b/tests/tools/test_mcp_protocol_negotiation.py@@ -139,3 +139,49 @@ class TestModernRejectionClassifier:assert _handshake_rejected_as_modern(Exception("Unsupported protocol version"))assert _handshake_rejected_as_modern(Exception("Unknown method: initialize"))assert not _handshake_rejected_as_modern(Exception("connection reset by peer"))+++class _EchoingStatelessSession(_Session):+ """A stateless server that answers the legacy ``initialize`` 200 but names a protocolVersion+ outside the SDK's handshake set (#113359): the SDK raises RuntimeError AFTER the wire exchange+ succeeded, and the server has no ``server/discover``. Exposes the SDK's manual-handshake+ surface (``send_request`` / ``adopt`` / ``send_notification``)."""++ def __init__(self, disc):+ super().__init__(init=RuntimeError("Unsupported protocol version from the server: 2026-07-28"), disc=disc)+ self.adopted = None++ async def send_request(self, request, result_type):+ self.calls.append(("send_request", request.method))+ import mcp.types as types+ return types.InitializeResult(+ protocolVersion="2026-07-28", capabilities=types.ServerCapabilities(tools=types.ToolsCapability()),+ serverInfo=types.Implementation(name="StatelessServer", version="ESF"))++ def adopt(self, result):+ self.calls.append("adopt")+ self.adopted = result++ async def send_notification(self, notification):+ self.calls.append(("notify", notification.method))+++class TestModernVersionEchoedToLegacyHandshake:+ """#113359: a stateless server that accepts ``initialize`` but reports 2026-07-28 and 400s+ ``server/discover`` must still connect — the handshake succeeded on the wire."""++ def test_auto_completes_the_handshake_at_the_offered_version_when_discover_fails(self):+ from tools import mcp_tool as _core+ s = _EchoingStatelessSession(disc=_Err(-32603, "Server returned an error response"))+ out = _run(_task()._negotiate_session(s, 5))+ assert out.capabilities.tools is not None+ assert s.calls == ["initialize", "discover", ("send_request", "initialize"), "adopt",+ ("notify", "notifications/initialized")]+ assert s.adopted.protocol_version == _core.LATEST_HANDSHAKE_VERSION # later requests stay legacy-shaped++ def test_genuine_unsupported_version_error_never_re_handshakes(self):+ s = _Session(init=_Err(_JSONRPC_UNSUPPORTED_PROTOCOL_VERSION, "unsupported protocol version"),+ disc=_Err(-32603, "Server returned an error response"))+ with pytest.raises(_Err, match="Server returned an error response"):+ _run(_task()._negotiate_session(s, 5))+ assert s.calls == ["initialize", "discover"]diff --git a/tools/mcp_tool_errors.py b/tools/mcp_tool_errors.pyindex 2052d99afd7..2227ea8d917 100644--- a/tools/mcp_tool_errors.py+++ b/tools/mcp_tool_errors.py@@ -34,6 +34,13 @@ def _handshake_rejected_as_modern(exc: BaseException) -> bool:code=getattr(exc, "code", None)) or _is_method_not_found_error(exc)+def _handshake_answered_with_unsupported_version(exc: BaseException) -> bool:+ """True when ``initialize`` SUCCEEDED on the wire (HTTP 200, a valid InitializeResult) but the SDK+ refused the ``protocolVersion`` the server named — its ``RuntimeError("Unsupported protocol version+ from the server: ...")``. Distinct from a JSON-RPC -32022 rejection, where the server refused us."""+ return "unsupported protocol version from the server" in str(_unwrap_exception_group(exc)).lower()++def _is_method_not_found_error(exc: BaseException) -> bool:"""True if *exc* is a JSON-RPC ``method not found`` (-32601; ``ping`` is optional in MCP). Thesubstring fallback includes "Unknown method: <name>" — without it the ping→list_tools keepalivediff --git a/tools/mcp_tool_transport.py b/tools/mcp_tool_transport.pyindex 835a2bfe65b..b042ebad0a8 100644--- a/tools/mcp_tool_transport.py+++ b/tools/mcp_tool_transport.py@@ -12,7 +12,7 @@ from typing import Dict, Optional, Setfrom utils import normalize_proxy_urlfrom agent.proxy_bypass import is_loopback_host, should_bypass_proxyfrom agent import runtime_cwd as _runtime_cwd-from tools.mcp_tool_errors import NonMcpEndpointError, _apply_identity_header, _describe_http_failure, _handshake_rejected_as_modern, _is_streamable_http_rejection, _make_http_rejection_recorder, _make_mcp_body_cap_transport, _make_redirect_header_stripper, _resolve_client_cert, _unwrap_exception_group+from tools.mcp_tool_errors import NonMcpEndpointError, _apply_identity_header, _describe_http_failure, _handshake_answered_with_unsupported_version, _handshake_rejected_as_modern, _is_streamable_http_rejection, _make_http_rejection_recorder, _make_mcp_body_cap_transport, _make_redirect_header_stripper, _resolve_client_cert, _unwrap_exception_groupfrom tools.mcp_tool_lifecycle import _filter_mcp_children, _orphan_stdio_pid_servers, _orphan_stdio_pids, _stdio_pgids, _stdio_pidsfrom tools.mcp_tool_common import _corefrom tools import mcp_tool_config as _config@@ -131,7 +131,20 @@ class MCPServerTransportMixin:if isinstance(exc, asyncio.TimeoutError) or not should_fallback(exc):raiselogger.info(log_fmt, self.name, exc, *log_extra)- return await call(fallback)+ try:+ return await call(fallback)+ except Exception as fallback_exc:+ # #113359: the server ANSWERED ``initialize`` (200, valid result) but named a version the+ # SDK's handshake refuses (e.g. 2026-07-28 echoed to a 2025-11-25 offer), and it has no+ # ``server/discover`` either. The wire handshake succeeded, so complete it ourselves.+ if (isinstance(fallback_exc, asyncio.TimeoutError) or primary != "initialize"+ or not _handshake_answered_with_unsupported_version(exc)):+ raise+ logger.info("MCP server '%s': server/discover also failed (%s) — completing the handshake "+ "at %s, the version this client offered", self.name, fallback_exc,+ _core.LATEST_HANDSHAKE_VERSION)+ return await asyncio.wait_for(self._complete_handshake_at_offered_version(session),+ timeout=connect_timeout)mode = str((self._config or {}).get("protocol", "auto")).lower().strip()if mode in ("stateless", "modern", "2026-07-28"):return await attempt("discover", "initialize", lambda exc: True,@@ -147,6 +160,28 @@ class MCPServerTransportMixin:"initialize", "discover", lambda exc: _handshake_rejected_as_modern(exc) and hasattr(session, "discover"),"MCP server '%s': legacy handshake rejected (%s) — retrying via server/discover (2026-07-28 stateless server)")+ async def _complete_handshake_at_offered_version(self, session):+ """Re-run the legacy ``initialize`` exchange the SDK already proved works against this server and+ adopt its result pinned to the version WE offered (#113359). ``ClientSession.initialize()`` raises+ on a ``protocolVersion`` outside its handshake set even though the server answered 200, and a+ stateless server that echoes 2026-07-28 to every offer has no ``server/discover`` — so this is the+ only way to reach ``notifications/initialized`` and ``tools/list``. Pinning to the offered version+ keeps later requests legacy-shaped (envelope and MCP-Protocol-Version header), the form the+ handshake itself just proved the server accepts. The returned result keeps the server's own+ version for logging/diagnostics."""+ import mcp.types as types # late: keeps the SDK import lazy+ offered = _core.LATEST_HANDSHAKE_VERSION+ build_caps = getattr(session, "_build_capabilities", None)+ capabilities = build_caps(offered) if callable(build_caps) else types.ClientCapabilities()+ client_info = getattr(session, "_client_info", None) or types.Implementation(name="hermes-agent", version="0")+ result = await session.send_request(+ types.InitializeRequest(params=types.InitializeRequestParams(+ protocolVersion=offered, capabilities=capabilities, clientInfo=client_info)),+ types.InitializeResult)+ session.adopt(result.model_copy(update={"protocol_version": offered}))+ await session.send_notification(types.InitializedNotification())+ return result+async def _serve_session(self, session, connect_timeout: float,label: str = "", mark_lifecycle: bool = False) -> str:"""Handshake, discover, publish readiness, then serve until a lifecycle event. Clears stale