Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions src/mcp/client/streamable_http.py
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,7 @@ async def handle_get_stream(self, client: httpx2.AsyncClient, read_stream_writer
last_event_id: str | None = None
retry_interval_ms: int | None = None
attempt: int = 0
last_exc: Exception | None = None

while attempt < MAX_RECONNECTION_ATTEMPTS: # pragma: no branch
try:
Expand Down Expand Up @@ -227,13 +228,16 @@ async def handle_get_stream(self, client: httpx2.AsyncClient, read_stream_writer
# Stream ended normally (server closed) - reset attempt counter
attempt = 0

except Exception:
except Exception as exc:
Comment thread
wukath marked this conversation as resolved.
Outdated
logger.debug("GET stream error", exc_info=True)
attempt += 1
last_exc = exc

if attempt >= MAX_RECONNECTION_ATTEMPTS: # pragma: no cover
if attempt >= MAX_RECONNECTION_ATTEMPTS:
logger.debug(f"GET stream max reconnection attempts ({MAX_RECONNECTION_ATTEMPTS}) exceeded")
return
raise StreamableHTTPError(
Comment thread
wukath marked this conversation as resolved.
f"Failed to connect to GET stream after {MAX_RECONNECTION_ATTEMPTS} attempts"
) from last_exc

# Wait before reconnecting
delay_ms = retry_interval_ms if retry_interval_ms is not None else DEFAULT_RECONNECTION_DELAY_MS
Expand Down
37 changes: 35 additions & 2 deletions tests/shared/test_streamable_http.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from contextlib import asynccontextmanager
from dataclasses import dataclass, field
from typing import Any
from unittest.mock import MagicMock
from unittest.mock import AsyncMock, MagicMock, patch
from urllib.parse import urlparse

import anyio
Expand Down Expand Up @@ -45,7 +45,11 @@
from mcp import MCPError
from mcp.client import ClientRequestContext
from mcp.client.session import ClientSession
from mcp.client.streamable_http import StreamableHTTPTransport, streamable_http_client
from mcp.client.streamable_http import (
StreamableHTTPError,
StreamableHTTPTransport,
streamable_http_client,
)
from mcp.server import Server, ServerRequestContext
from mcp.server.streamable_http import (
GET_STREAM_KEY,
Expand Down Expand Up @@ -2283,3 +2287,32 @@ async def asgi_receive() -> Message:
assert body_chunks[-1] == {"type": "http.response.body", "body": b"", "more_body": False}
assert "Error in standalone SSE writer" not in caplog.text
assert "Error in standalone SSE response" not in caplog.text


@pytest.mark.anyio
async def test_reconnect_failure_propagates_error() -> None:
"""Client should raise StreamableHTTPError when reconnection fails completely."""
transport = StreamableHTTPTransport(url="http://localhost:8000/mcp")
transport.session_id = "test-session"
client = AsyncMock(spec=httpx2.AsyncClient)

# Create a context-aware stream writer (matches StreamWriter type alias)
write_stream, read_stream = create_context_streams[SessionMessage | Exception](1)

# Mock client.sse to raise an exception
client.sse.side_effect = Exception("Connection refused")

# Patch anyio.sleep to avoid waiting
with patch("mcp.client.streamable_http.anyio.sleep", new_callable=AsyncMock) as mock_sleep:
with pytest.raises(StreamableHTTPError) as exc_info:
await transport.handle_get_stream(client, write_stream)
assert "Failed to connect to GET stream" in str(exc_info.value)
# Should have attempted MAX_RECONNECTION_ATTEMPTS times (default is 2)
assert client.sse.call_count == 2
# Should have slept between attempts (attempts - 1 times)
assert mock_sleep.call_count == 1
# Verify it slept with the default delay (1000ms / 1000.0 = 1.0s)
mock_sleep.assert_called_once_with(1.0)

await write_stream.aclose()
await read_stream.aclose()
Loading