René's URL Explorer Experiment


Title: `handle_get_stream` reconnects indefinitely when the server ends the GET stream normally (`attempt = 0` defeats `MAX_RECONNECTION_ATTEMPTS`) · Issue #3257 · modelcontextprotocol/python-sdk · GitHub

Open Graph Title: `handle_get_stream` reconnects indefinitely when the server ends the GET stream normally (`attempt = 0` defeats `MAX_RECONNECTION_ATTEMPTS`) · Issue #3257 · modelcontextprotocol/python-sdk

X Title: `handle_get_stream` reconnects indefinitely when the server ends the GET stream normally (`attempt = 0` defeats `MAX_RECONNECTION_ATTEMPTS`) · Issue #3257 · modelcontextprotocol/python-sdk

Description: Initial Checks I confirm that I'm using the newest release of my line (the latest 2.x, or the latest 1.x if I'm still on v1) I confirm that I searched for my issue in https://github.com/modelcontextprotocol/python-sdk/issues before openi...

Open Graph Description: Initial Checks I confirm that I'm using the newest release of my line (the latest 2.x, or the latest 1.x if I'm still on v1) I confirm that I searched for my issue in https://github.com/modelcontex...

X Description: Initial Checks I confirm that I'm using the newest release of my line (the latest 2.x, or the latest 1.x if I'm still on v1) I confirm that I searched for my issue in https://github.com/mod...

Opengraph URL: https://github.com/modelcontextprotocol/python-sdk/issues/3257

X: @github

direct link

Domain: github.com


Hey, it has json ld scripts:
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"`handle_get_stream` reconnects indefinitely when the server ends the GET stream normally (`attempt = 0` defeats `MAX_RECONNECTION_ATTEMPTS`)","articleBody":"### Initial Checks\n\n- [x] I confirm that I'm using the newest release of my line (the latest 2.x, or the latest 1.x if I'm still on v1)\n- [x] I confirm that I searched for my issue in https://github.com/modelcontextprotocol/python-sdk/issues before opening this issue\n\n### Release line\n\n1.x (maintenance line, v1.x branch)\n\n### Description\n\n### Summary\n\n`StreamableHTTPTransport.handle_get_stream` reconnects forever — once per second,\nfor the lifetime of the session — when the server accepts the standalone GET and\nthen ends the SSE stream without error. `MAX_RECONNECTION_ATTEMPTS` is meant to\nbound the retry loop, but a clean stream close resets the attempt counter, so the\nbound is never reached.\n\nThe server that triggers this is **spec-conformant, not misbehaving**: terminating\nthe stream immediately is an explicit permission — *\"The server **MAY** close the SSE\nstream at any time\"* ([2025-11-25\n§Transports](https://modelcontextprotocol.io/specification/2025-11-25/basic/transports),\nthe last revision defining this mechanism). The spec section below shows that the\nrevision distinguishes *closing the connection* from *terminating the stream*, and\nthat the loop cannot tell them apart.\n\nMinimal reproduction (single stdlib file + the `mcp` client, public API only):\nhttps://github.com/luiz00martins/mcp-get-stream-reconnect-loop\n\nIt is a **single self-contained file** — stdlib stub server plus the `mcp` client,\nno external server and no reach into transport internals. Inlined below so it can\nbe run without leaving this page:\n\n```bash\nuv run --no-project --with 'mcp==2.0.0' python repro.py            # bug\nuv run --no-project --with 'mcp==2.0.0' python repro.py --mode 405 # control\n```\n\n\u003cdetails>\n\u003csummary>\u003ccode>repro.py\u003c/code> (single file, stdlib + \u003ccode>mcp\u003c/code>)\u003c/summary>\n\n\u003c/details>\n\n### Affected versions\n\nReproduced via `streamable_http_client` + `ClientSession.initialize()`, 5s window:\n\n| `mcp` | GET requests | Verdict |\n|---|---|---|\n| 1.22.0 | 1 | clean (no retry loop in this release) |\n| 1.23.0 | 5 | unbounded |\n| 1.24.0 | 5 | unbounded |\n| 1.28.1 | 5 | unbounded |\n| 1.29.0 | 5 | unbounded |\n| 2.0.0 | 5 | unbounded |\n\nIntroduced in 1.23.0 with the auto-reconnect loop; still present in 2.0.0. The\ncount scales linearly with the observation window — it never terminates.\n\n### Environment\n\n- Python 3.13.14 (CPython), Linux x86_64 (Ubuntu 24.04)\n- `anyio` 4.14.2\n- On 2.0.0 the HTTP stack is `httpx2` / `httpcore2` 2.9.1; on the 1.2x line it is\n  `httpx` 0.28.1 with `httpx-sse` 0.4.3\n\nNothing in the reproduction is platform-specific — the loop is paced by\n`anyio.sleep` against a localhost stub server.\n\n### Root cause\n\n`src/mcp/client/streamable_http.py`, `StreamableHTTPTransport.handle_get_stream`\n(quoted from 2.0.0):\n\n```python\nwhile attempt \u003c MAX_RECONNECTION_ATTEMPTS:              # pragma: no branch\n    try:\n        if not self.session_id:\n            return\n        async with client.sse(self.url, headers=headers) as event_source:\n            event_source.response.raise_for_status()\n            async for sse in event_source:\n                ...\n            # Stream ended normally (server closed) - reset attempt counter\n            attempt = 0                                 # \u003c-- defeats the loop bound\n    except Exception:\n        attempt += 1\n\n    if attempt >= MAX_RECONNECTION_ATTEMPTS:            # pragma: no cover\n        return\n\n    await anyio.sleep(delay_ms / 1000.0)\n```\n\nThe 1.2x line is the same logic with different plumbing\n(`aconnect_sse(client, \"GET\", ...)` and `event_source.aiter_sse()`).\n\nA server returning `200` + `Content-Type: text/event-stream` and then closing\nmakes the event iterator complete without raising. That's treated as \"ended\nnormally\", so `attempt` resets to `0` and neither the `while` condition nor the\nguard is ever satisfied.\n\nThe two coverage pragmas are themselves evidence: `# pragma: no branch` on the\n`while` and `# pragma: no cover` on the termination guard assert that the test\nsuite never sees this loop exit. Both have been present in every affected\nrelease, 1.23.0 through 2.0.0.\n\nThe reset is sensible in isolation — a stream that ran a while shouldn't be\npenalised for earlier failures. The bug is that a stream yielding **zero events\nand closing immediately** is indistinguishable from a productive one.\n\n### Expected vs actual\n\n**Expected:** at most `MAX_RECONNECTION_ATTEMPTS` (2) GETs, then the background\ntask gives up.\n**Actual:** one GET per second, indefinitely.\n\n### Which terminations trigger it — and which don't\n\nWhether the loop terminates depends entirely on how the response body ended —\nnot on whether the server is healthy. `termination_modes.py` in the repo measures\nall five cases (identical on 1.28.1 and 2.0.0, 5-second window):\n\n| GET response ends by | Client sees | `Last-Event-ID` sent on reconnects | Loop |\n|---|---|---|---|\n| event with an `id`, then connection close | clean EOF | **yes** (4 of 4) | unbounded — *but correctly polling* |\n| connection close, no `Content-Length`, no events | clean EOF | no | **unbounded (the bug)** |\n| chunked, terminating `0\\r\\n\\r\\n`, no events | clean EOF | no | **unbounded (the bug)** |\n| chunked, RST with no terminating chunk | truncation error | no | terminates (2 GETs) |\n| `405 Method Not Allowed` | HTTP error | no | terminates (2 GETs) |\n\nThe first three rows are **behaviourally identical** — 5 GETs, one per second — yet\nonly the first is a conformant resumption, and the sole thing distinguishing it is a\nvalue the SDK already tracks. That is the defect in one line: `last_event_id` holds\nthe answer and the retry logic never consults it.\n\n**The retry bound itself works** — both error rows increment `attempt` and stop\ncorrectly after 2 tries. That isolates the defect to the `attempt = 0` reset\nrather than to retrying.\n\n**Worth flagging for reproduction:** an intermediary that kills a connection\n*abruptly* produces the benign truncation path. So \"a proxy timed out my SSE\nstream\" is not by itself enough to see the bug — the body has to end in a\nwell-formed way, which is what a server *deliberately* ending an idle stream\ndoes.\n\nThe client also cannot distinguish the two clean-EOF rows from a productive\nstream at the protocol layer: SSE responses carry no `Content-Length`, so \"ended\nafter zero events\" and \"ended after a thousand\" are the same shape of completion.\nThe only per-response signal available is malformedness, and that case is already\nhandled correctly.\n\n### The spec defines three server signals; the loop collapses two of them\n\n**Which revision applies.** The standalone GET stream exists in protocol revisions\n`2025-03-26` through `2025-11-25`, and was *removed* in the current revision\n`2026-07-28` ([\"Removal of the GET stream\nendpoint\"](https://modelcontextprotocol.io/specification/2026-07-28/basic/transports/streamable-http)).\nThat scopes the bug but does not shrink it: the SDK's handshake path still\nnegotiates `2025-11-25` — `ClientSession.initialize()` sends\n`LATEST_HANDSHAKE_VERSION`, which is `2025-11-25` on 2.0.0, confirmed on the wire —\nso `handle_get_stream` runs for every session against a server of that era. Quotes\nbelow are therefore from [2025-11-25\n§Transports](https://modelcontextprotocol.io/specification/2025-11-25/basic/transports),\nthe last revision that defines this mechanism.\n\n*Listening for Messages from the Server*:\n\n> 3. The server **MUST** either return `Content-Type: text/event-stream` in response\n>    to this HTTP GET, or else return HTTP 405 Method Not Allowed, indicating that\n>    the server does not offer an SSE stream at this endpoint.\n>\n> 4. If the server initiates an SSE stream:\n>    * […]\n>    * The server **MAY** close the SSE stream at any time.\n>    * If the server closes the *connection* without terminating the *stream*, it\n>      **SHOULD** follow the same polling behavior as described for POST requests:\n>      sending a `retry` field and allowing the client to reconnect.\n\nAnd the POST rules that clause 4 defers to, which define the priming mechanism:\n\n> * The server **SHOULD** immediately send an SSE event consisting of an event ID\n>   and an empty `data` field in order to prime the client to reconnect (using that\n>   event ID as `Last-Event-ID`).\n> * After the server has sent an SSE event with an event ID to the client, the\n>   server **MAY** close the *connection* (without terminating the *SSE stream*) at\n>   any time in order to avoid holding a long-lived connection. The client\n>   **SHOULD** then \"poll\" the SSE stream by attempting to reconnect.\n\nThe spec therefore gives a server **three** distinct things to say:\n\n| Server intent | Spec signal | Correct client response |\n|---|---|---|\n| \"I offer no stream at this endpoint\" | `405` | never ask again |\n| \"Come back — I closed the *connection*, the *stream* is alive\" | an event carrying an `id` (plus `retry`), then close the connection | reconnect, sending `Last-Event-ID` |\n| \"Done — I *terminated* the stream\" | end the response with the stream terminated | do not reconnect |\n\nRows 2 and 3 are both \"`200`, then a closed connection.\" What distinguishes them is\n**whether an event carrying an `id` was ever sent** — exactly the priming mechanism\nthe POST clause describes. `handle_get_stream` already tracks that (`last_event_id`),\nbut does not condition reconnection on it. So it treats row 3 as if it were row 2,\nforever.\n\nTwo consequences worth noting:\n\n- The reconnect it issues is not a conformant resumption. Clause 2 of *Resumability\n  and Redelivery* pairs resumption with `Last-Event-ID`; with zero events received,\n  `last_event_id` is `None`, so no such header is sent. It is the resumption request\n  minus the thing that makes it a resumption.\n- `405` is a statement about the *endpoint*, not about *right now*. A server with\n  intermittent server-initiated traffic cannot use it to decline a single GET without\n  misreporting its capabilities. Its conformant way to say \"nothing for you, don't\n  wait on me\" is row 3 — precisely the case that gets punished.\n\n**Steelmanning the current behaviour**, since it isn't baseless: reconnecting after a\nserver-initiated closure *is* explicitly contemplated — 2025-11-25 broadened\nresumption to cover \"a disconnection (whether due to network failure or\nserver-initiated closure)\". Row 2 is real and the loop serves it correctly. Browser\n`EventSource` likewise reconnects indefinitely. But `EventSource` uses exponential\nbackoff where this uses a flat 1 s; it reconnects a channel the page explicitly\nopened, whereas this GET is opened unconditionally on `notifications/initialized`\n(clause 1 makes it only a **MAY**); and decisively, **the code declares a bound it\ndoes not honour.** `MAX_RECONNECTION_ATTEMPTS = 2` and the two guards enforcing it\ncannot be reconciled with never stopping. Either the bound is broken or it is dead\ncode — and the `# pragma: no cover` on the exit says the test suite has never\nestablished which.\n\n### Upgrading the SDK is not an escape\n\nSince `2026-07-28` deletes the GET stream, the natural assumption is that this ages\nout on its own. It does not, because the deciding factor is the **server's**\nrevision, not the client's version.\n\n`mcp` 2.x ships a high-level `Client` oriented at the new revision. Run against a\nlegacy-era server it probes with `server/discover`, takes a plain `400`, and falls\nback to `initialize` + `notifications/initialized` — which is precisely what calls\n`start_get_stream()`. Measured with `modern_client_probe.py` on 2.0.0:\n\n```\nPOST  server/discover\nPOST  initialize\nPOST  notifications/initialized\nGET   None\nPOST  tools/list\nGET   None\nGET   None\nGET   None          \u003c- 4 GETs in 4s, no Last-Event-ID, still climbing\n```\n\nSo the loop is reachable from **both** client APIs in the current release, and stays\nreachable for as long as pre-2026 servers exist. Given that the 2024-11-05 transport\nis still only *deprecated* and hosted for compatibility, that is likely to be a long\ntime.\n\n### Impact\n\n`handle_get_stream` runs as a background task in the transport's task group, so\nnothing surfaces the loop — no exception, and above `DEBUG` only a recurring\n`GET stream disconnected, reconnecting in 1000ms...` at `INFO`.\n\nA long-lived process holding many sessions accumulates a permanent 1 req/s of\nbackground traffic per affected session, plus a task that can't be reaped without\ntearing the session down. Load grows linearly with sessions opened and is\ninvisible unless outbound request volume is correlated against session count.\n\nServers that behave this way aren't exotic, in rough order of how reliably they\ntrigger it:\n\n- **A POST-oriented server that accepts the GET and immediately ends the stream**\n  instead of refusing it with `405` — up, routing correctly, with nothing to\n  push, forever and identically. The unambiguous trigger.\n- **A server that closes idle streams by design**, expecting reconnection on\n  demand.\n- **An intermediary (nginx, Cloudflare, an ALB) timing out an idle SSE\n  response** — but only when it terminates the response gracefully; an abrupt\n  severance lands on the benign path above.\n\nIn the intermediary case the origin never learns the stream ended and never needs\nto: the proxy ended the response toward the client while the origin may still\nconsider its stream open. Nothing is coordinating.\n\n### Suggested fix\n\nReset only when the stream actually delivered something:\n\n```python\nsaw_event = False\nasync for sse in event_source:\n    saw_event = True\n    ...\nif saw_event:\n    attempt = 0\nelse:\n    attempt += 1\n```\n\nThat keeps the intent while restoring `MAX_RECONNECTION_ATTEMPTS` as a real bound.\n\n**This is not an arbitrary heuristic — it is the spec's own reconnect signal.** Per\nthe priming clause quoted above, a server that intends to be polled again\n**SHOULD** first send an event carrying an `id`. \"An event was seen\" is therefore\nvery close to \"the server primed me to reconnect,\" and the tighter variant needs no\nnew state at all, because the loop already tracks it:\n\n```python\nif last_event_id is not None:\n    attempt = 0        # server primed a reconnect (row 2)\nelse:\n    attempt += 1       # nothing was ever delivered (row 3)\n```\n\n`saw_event` is the looser form, and is the safer default of the two: it also resets\nfor a server that delivered real events without ids — productive, though not\nresumable.\n\nThe underlying conflation: `attempt` is meant to count consecutive *failures*, but\nit is updated from *protocol* outcomes. A request that returns `200` and delivers\nnothing is a protocol success and a functional failure, and the current code can\nonly see the former.\n\n**It doesn't break healthy idle streams.** A server holding a stream open for\nhours without sending anything never reaches the reset line — it blocks inside the\n`async for`, holding the response open, for as long as the server keeps it open.\nOnly a *terminated* stream falls through to `attempt = 0`. So \"terminated AND\ndelivered nothing\" has no false positives against the case people would worry\nabout.\n\n**The trade-off, stated honestly:** `saw_event` would make the client give up on a\nserver that legitimately cycles short empty streams and expects reconnection. If\nthat pattern should stay supported, an overall reconnect cap with exponential\nbackoff is the better fix — it bounds the runaway case without abandoning such a\nserver, and softens the fixed 1s interval as well.\n\n### Possibly related\n\n- **#1941** (closed as *not planned*) — the mirror image of this report, in the same\n  eight lines. There the bound is too *aggressive*: a POST-only server answers the\n  GET with `405`, the loop correctly gives up after 2 attempts, and the now-dead\n  background task leaves later POST/SSE responses unable to arrive. Here the bound is\n  *unreachable*.\n\n  Both symptoms being real at once is itself the diagnosis: the retry policy keys off\n  the **protocol** outcome of each attempt rather than whether the channel is\n  functioning. That makes it simultaneously too quick to abandon a stream that\n  matters and unable to abandon one that never will. A fix aimed only at the retry\n  *count* will shuttle the problem between these two reports instead of resolving\n  either.\n\n  The one maintainer comment on #1941 asked for \"a single self-contained script that\n  reproduces this locally… A minimal server + client in one file… rather than an\n  external repo.\" That is exactly what the inlined `repro.py` above is.\n\n- **modelcontextprotocol/typescript-sdk#2098** (open) — the sibling symptom in the TS\n  transport: same 2-retry ceiling, same dead-channel outcome as #1941. Worth reading\n  alongside this one because its two remedies diverge sharply here:\n  - its **Bug 1** proposal — `maxRetries: 10` with the existing 1.5× backoff capped at\n    30 s, so ~5 minutes of retries and then stop — would address that report *and*\n    leave this case bounded;\n  - its **Bug 3 option (C)** — \"keep retrying SSE indefinitely with the existing\n    exponential backoff\" — would entrench this case instead. Backoff lowers the\n    request rate but not the non-termination, and against a server that will never\n    send anything, unbounded is unbounded at any interval.\n\n  So for both reports the decisive question is whether an overall cap exists, not the\n  shape of the delay curve.\n\n  Its trigger also corroborates the termination table above: a CloudFlare Tunnel idle\n  timeout severing the stream surfaced there as `Failed to open SSE stream` — the\n  *error* path. That is why that report sees premature give-up where this one sees no\n  give-up at all.\n\n### Example Code\n\n```Python\nhttps://github.com/luiz00martins/mcp-get-stream-reconnect-loop\n\n\n#!/usr/bin/env python3\n\"\"\"Minimal reproduction: StreamableHTTPTransport.handle_get_stream never terminates.\n\nThe standalone GET/SSE stream reconnects forever when the server accepts the GET\nand then ends the stream normally, because `attempt = 0` on a clean stream close\ndefeats the `MAX_RECONNECTION_ATTEMPTS` bound that guards the retry loop.\n\nEverything is driven through the public API (`streamablehttp_client` +\n`ClientSession.initialize`). The only stdlib-served pieces are a stub MCP\nendpoint, so the behaviour observed is entirely the SDK client's.\n\nUsage:\n    uv run repro.py                # bug:     server accepts GET, ends stream\n    uv run repro.py --mode 405     # control: server rejects GET (correct)\n\"\"\"\n\nfrom __future__ import annotations\n\nimport argparse\nimport asyncio\nimport json\nimport threading\nimport time\nfrom http.server import BaseHTTPRequestHandler, ThreadingHTTPServer\nfrom importlib.metadata import version\n\nfrom mcp import ClientSession\nfrom mcp.types import LATEST_PROTOCOL_VERSION\n\n# The transport factory is spelled both ways across releases\n# (`streamablehttp_client` in the 1.2x line, `streamable_http_client` in 2.x),\n# so accept either and one file reproduces across the whole range.\ntry:\n    from mcp.client.streamable_http import streamable_http_client as http_client\nexcept ImportError:  # pragma: no cover\n    from mcp.client.streamable_http import streamablehttp_client as http_client\n\nSESSION_ID = \"repro-session-0001\"\n\n_lock = threading.Lock()\nGET_TIMES: list[float] = []\nMODE = \"close\"\n\n\nclass StubMCP(BaseHTTPRequestHandler):\n    \"\"\"Speaks just enough Streamable HTTP for the client to finish initialising.\"\"\"\n\n    protocol_version = \"HTTP/1.1\"\n\n    def log_message(self, *_args) -> None:  # keep stdout clean\n        pass\n\n    # -- POST: initialize handshake -----------------------------------------\n    def do_POST(self) -> None:\n        raw = self.rfile.read(int(self.headers.get(\"Content-Length\") or 0))\n        try:\n            msg = json.loads(raw or b\"{}\")\n        except ValueError:\n            msg = {}\n        method = msg.get(\"method\", \"\")\n\n        # `notifications/initialized` is what makes the client open the GET\n        # stream (streamable_http.py, post_writer: `start_get_stream()`).\n        if method.startswith(\"notifications/\"):\n            self.send_response(202)\n            self.send_header(\"Content-Length\", \"0\")\n            self.end_headers()\n            return\n\n        if method == \"initialize\":\n            # Echo back whatever version the client asked for. A real server\n            # negotiates, and echoing keeps this file working across releases\n            # whose supported-version tables differ.\n            requested = (msg.get(\"params\") or {}).get(\n                \"protocolVersion\", LATEST_PROTOCOL_VERSION\n            )\n            body = json.dumps(\n                {\n                    \"jsonrpc\": \"2.0\",\n                    \"id\": msg.get(\"id\", 1),\n                    \"result\": {\n                        \"protocolVersion\": requested,\n                        \"capabilities\": {},\n                        \"serverInfo\": {\"name\": \"stub\", \"version\": \"0.0.0\"},\n                    },\n                }\n            ).encode()\n            self.send_response(200)\n            self.send_header(\"Content-Type\", \"application/json\")\n            # Without a session id the client returns from handle_get_stream\n            # immediately, so a real session is required to see the bug.\n            self.send_header(\"mcp-session-id\", SESSION_ID)\n            self.send_header(\"Content-Length\", str(len(body)))\n            self.end_headers()\n            self.wfile.write(body)\n            return\n\n        self.send_response(202)\n        self.send_header(\"Content-Length\", \"0\")\n        self.end_headers()\n\n    # -- GET: the standalone server-initiated stream ------------------------\n    def do_GET(self) -> None:\n        with _lock:\n            GET_TIMES.append(time.perf_counter())\n\n        if MODE == \"405\":\n            # Spec-legal for a server that offers no GET stream. The client\n            # treats this as an error, so the attempt counter is NOT reset and\n            # the loop correctly stops after MAX_RECONNECTION_ATTEMPTS.\n            self.send_response(405)\n            self.send_header(\"Content-Length\", \"0\")\n            self.end_headers()\n            return\n\n        # A valid but empty SSE stream, closed immediately. This is what an\n        # intermediary (nginx / Cloudflare / ALB) or a POST-oriented server\n        # does. `aiter_sse()` completes without error => \"ended normally\".\n        self.send_response(200)\n        self.send_header(\"Content-Type\", \"text/event-stream\")\n        self.send_header(\"Connection\", \"close\")\n        self.end_headers()\n        self.close_connection = True\n\n    def do_DELETE(self) -> None:\n        self.send_response(200)\n        self.send_header(\"Content-Length\", \"0\")\n        self.end_headers()\n\n\nasync def drive(url: str, seconds: float) -> None:\n    \"\"\"Initialise a session over the public API, then idle.\"\"\"\n    # 1.x yields (read, write, get_session_id); 2.x yields (read, write).\n    async with http_client(url) as streams:\n        read, write = streams[0], streams[1]\n        async with ClientSession(read, write) as session:\n            await session.initialize()\n            await asyncio.sleep(seconds)\n\n\nasync def main() -> int:\n    global MODE\n    ap = argparse.ArgumentParser()\n    ap.add_argument(\"--mode\", choices=(\"close\", \"405\"), default=\"close\")\n    ap.add_argument(\"--seconds\", type=float, default=8.0)\n    args = ap.parse_args()\n    MODE = args.mode\n\n    server = ThreadingHTTPServer((\"127.0.0.1\", 0), StubMCP)\n    server.daemon_threads = True\n    threading.Thread(target=server.serve_forever, daemon=True).start()\n    url = f\"http://127.0.0.1:{server.server_port}/mcp\"\n\n    print(f\"mcp version : {version('mcp')}\")\n    print(f\"server mode : {args.mode}\")\n    print(f\"observing   : {args.seconds:.0f}s after initialize()\\n\")\n\n    try:\n        await asyncio.wait_for(drive(url, args.seconds), timeout=args.seconds + 20)\n    except asyncio.TimeoutError:\n        print(\"client did not shut down within the grace period\")\n    finally:\n        server.shutdown()\n\n    with _lock:\n        times = list(GET_TIMES)\n\n    print(f\"GET /mcp requests observed: {len(times)}\")\n    if len(times) > 1:\n        gaps = [times[i + 1] - times[i] for i in range(len(times) - 1)]\n        gaps.sort()\n        print(f\"inter-request gap (median): {gaps[len(gaps) // 2] * 1000:.0f}ms\")\n\n    print()\n    if args.mode == \"405\":\n        ok = len(times) \u003c= 2\n        print(\n            f\"EXPECTED: at most 2 (MAX_RECONNECTION_ATTEMPTS)\\n\"\n            f\"RESULT  : {len(times)} -> {'correct' if ok else 'UNEXPECTED'}\"\n        )\n        return 0 if ok else 1\n\n    bug = len(times) > 2\n    print(\n        f\"EXPECTED: at most 2 (MAX_RECONNECTION_ATTEMPTS)\\n\"\n        f\"RESULT  : {len(times)} -> {'BUG REPRODUCED (unbounded)' if bug else 'no bug seen'}\"\n    )\n    return 0 if bug else 1\n\n\nif __name__ == \"__main__\":\n    raise SystemExit(asyncio.run(main()))\n```\n\n### Python & MCP Python SDK\n\n```Text\nProduction Environment — Python 3.13.14, mcp 1.28.1, httpx 0.28.1, httpx-sse 0.4.3, anyio 4.11.0.\n\nReproduction env — Python 3.13.14 (CPython), Linux x86_64 / Ubuntu 24.04, anyio 4.14.2. HTTP stack varies across the range: httpx2/httpcore2 2.9.1 on mcp 2.0.0, httpx 0.28.1 + httpx-sse 0.4.3 on the 1.2x line. Bug present either way.\n```","author":{"url":"https://github.com/luiz00martins","@type":"Person","name":"luiz00martins"},"datePublished":"2026-08-05T21:38:20Z","url":"https://github.com/modelcontextprotocol/python-sdk/issues/3257"}

react-profiling0
react-import-mapreact,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322
route-pattern/_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format)
route-controllervoltron_issues_fragments
route-actionissue_layout
fetch-noncev2:90c10424-36ea-6a7d-e967-4c23a97102dc
current-catalog-service-hash81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114
request-idA846:19114D:3A7AE5:4CE75C:6B00C51C
html-safe-nonce61ee224c5a61f7f023c2af3ebab36be69f9b3e2ef482b20472f00ef64d800a7a
visitor-payloadeyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJBODQ2OjE5MTE0RDozQTdBRTU6NENFNzVDOjZCMDBDNTFDIiwidmlzaXRvcl9pZCI6IjQ4MTA1NjUyMjM4OTMyMjI2ODQiLCJyZWdpb25fZWRnZSI6ImlhZCIsInJlZ2lvbl9yZW5kZXIiOiJpYWQifQ==
visitor-hmac603c00aa8ae624d5e455d81d5467ce22fc2fcfc28f7dc0cbdc0e44aad9e91c39
hovercard-subject-tagissue:5075442058
github-keyboard-shortcutsrepository,issues,copilot
google-site-verificationApib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I
octolytics-urlhttps://collector.github.com/github/collect
analytics-location///voltron/issues_fragments/issue_layout
fb:app_id1401488693436528
apple-itunes-appapp-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/modelcontextprotocol/python-sdk/3257/issue_layout
twitter:imagehttps://opengraph.githubassets.com/c4fe711ea2a42ac354f93a959d2f41ace49c6c52747c9ed9c11805bf30c821f2/modelcontextprotocol/python-sdk/issues/3257
twitter:cardsummary_large_image
og:imagehttps://opengraph.githubassets.com/c4fe711ea2a42ac354f93a959d2f41ace49c6c52747c9ed9c11805bf30c821f2/modelcontextprotocol/python-sdk/issues/3257
og:image:altInitial Checks I confirm that I'm using the newest release of my line (the latest 2.x, or the latest 1.x if I'm still on v1) I confirm that I searched for my issue in https://github.com/modelcontex...
og:image:width1200
og:image:height600
og:site_nameGitHub
og:typeobject
og:author:usernameluiz00martins
hostnamegithub.com
expected-hostnamegithub.com
None93edd3bebc4afb7ce711ee74cb5d2a95927850b082a4d43e212222389cb1c415
turbo-cache-controlno-preview
go-importgithub.com/modelcontextprotocol/python-sdk git https://github.com/modelcontextprotocol/python-sdk.git
octolytics-dimension-user_id182288589
octolytics-dimension-user_loginmodelcontextprotocol
octolytics-dimension-repository_id862584018
octolytics-dimension-repository_nwomodelcontextprotocol/python-sdk
octolytics-dimension-repository_publictrue
octolytics-dimension-repository_is_forkfalse
octolytics-dimension-repository_network_root_id862584018
octolytics-dimension-repository_network_root_nwomodelcontextprotocol/python-sdk
turbo-body-classeslogged-out env-production page-responsive
disable-turbofalse
browser-stats-urlhttps://api.github.com/_private/browser/stats
browser-errors-urlhttps://api.github.com/_private/browser/errors
release1fee81a280ea86312b69448e261b418189bfd5b5
ui-targetfull
theme-color#1e2327
color-schemelight dark
react-app-nameissues

Links:

Skip to contenthttps://github.com/modelcontextprotocol/python-sdk/issues/3257#start-of-content
https://github.com/
Sign inhttps://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fmodelcontextprotocol%2Fpython-sdk%2Fissues%2F3257
GitHubRepository hosting, code review, and collaborationhttps://github.com/platform
CopilotAI coding agent for tasks, projects, and automated workhttps://github.com/features/copilot
ActionsCI/CD and automationhttps://github.com/features/actions
Code QualityQuality analysis, fixes, and enforcementhttps://github.com/features/code-quality
CodespacesCloud development environmentshttps://github.com/features/codespaces
Code SecurityVulnerability detection and remediationhttps://github.com/security/advanced-security/code-security
Secret ProtectionSecret scanning and leak preventionhttps://github.com/security/advanced-security/secret-protection
All Featureshttps://github.com/features
Documentationhttps://docs.github.com/en
Traininghttps://learn.github.com/skills
Certificationshttps://learn.github.com/credentials
Build with Copilothttps://github.com/features/ai
Customize Copilothttps://docs.github.com/en/copilot/how-tos/copilot-on-github/customize-copilot/customize-copilot-overview
Integrationshttps://github.com/marketplace
Trending reposhttps://github.com/trending
GitHub Sponsorshttps://github.com/open-source/sponsors
Developer articleshttps://github.com/resources/articles
ChangelogYour source for the latest features, improvements, and fixes across GitHub products, all in one place.https://github.blog/changelog/
Enterpriseshttps://github.com/enterprise
Teamhttps://github.com/team
Startupshttps://github.com/enterprise/startups
Nonprofitshttps://github.com/solutions/industry/nonprofits
Healthcarehttps://github.com/solutions/industry/healthcare
Financial serviceshttps://github.com/solutions/industry/financial-services
Manufacturinghttps://github.com/solutions/industry/manufacturing
Governmenthttps://github.com/solutions/industry/government
See all industrieshttps://github.com/solutions/industry
Why GitHubhttps://github.com/why-github
Customer Storieshttps://github.com/customer-stories
Business insightshttps://github.com/solutions/executive-insights
Trust Centerhttps://github.com/trust-center
GitHub Advanced SecurityEnterprise-grade code securityhttps://github.com/security/advanced-security
Copilot for businessEnterprise-grade AI featureshttps://github.com/features/copilot/copilot-business
Premium SupportEnterprise-grade 24/7 supporthttps://github.com/enterprise/premium-support
Documentationhttps://docs.github.com/en
Resource centerhttps://github.com/resources
Bloghttps://github.blog/
Events & webinarshttps://github.com/resources/events
Community Forumhttps://github.com/orgs/community/discussions
Customer Storieshttps://github.com/customer-stories
Integrationshttps://github.com/marketplace
Customer supporthttps://help.github.com/
Traininghttps://learn.github.com/skills
GitHub Statushttps://www.githubstatus.com/
Abouthttps://github.com/about
Partnershttps://github.com/partners
Changeloghttps://github.blog/changelog/
GitHub UniverseThe event for developers, by developers — talks, workshops, and what’s next for GitHub.https://githubuniverse.com/
Pricinghttps://github.com/pricing
Sign inhttps://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fmodelcontextprotocol%2Fpython-sdk%2Fissues%2F3257
Sign uphttps://github.com/signup?ref_cta=Sign+up&ref_loc=header+logged+out&ref_page=%2F%3Cuser-name%3E%2F%3Crepo-name%3E%2Fvoltron%2Fissues_fragments%2Fissue_layout&source=header-repo&source_repo=modelcontextprotocol%2Fpython-sdk
Reloadhttps://github.com/modelcontextprotocol/python-sdk/issues/3257
Reloadhttps://github.com/modelcontextprotocol/python-sdk/issues/3257
Reloadhttps://github.com/modelcontextprotocol/python-sdk/issues/3257
modelcontextprotocolhttps://github.com/modelcontextprotocol
python-sdkhttps://github.com/modelcontextprotocol/python-sdk
Codehttps://github.com/modelcontextprotocol/python-sdk
Issues308 (308)https://github.com/modelcontextprotocol/python-sdk/issues
Pull requests112 (112)https://github.com/modelcontextprotocol/python-sdk/pulls
Actionshttps://github.com/modelcontextprotocol/python-sdk/actions
Projectshttps://github.com/modelcontextprotocol/python-sdk/projects
Security and quality12 (12)https://github.com/modelcontextprotocol/python-sdk/security
Insightshttps://github.com/modelcontextprotocol/python-sdk/insights
https://github.com/modelcontextprotocol/python-sdk
New issuehttps://github.com/login?return_to=https://github.com/modelcontextprotocol/python-sdk/issues/3257
New issuehttps://github.com/login?return_to=https://github.com/modelcontextprotocol/python-sdk/issues/3257
handle_get_stream reconnects indefinitely when the server ends the GET stream normally (attempt = 0 defeats MAX_RECONNECTION_ATTEMPTS)https://github.com/modelcontextprotocol/python-sdk/issues/3257#top
P2Moderate issues affecting some users, edge cases, potentially valuable featurehttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22P2%22
bugSomething isn't workinghttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22bug%22
v1Affects the v1.x maintenance linehttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22v1%22
v2Affects the v2 line (2.x on main)https://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22v2%22
https://github.com/luiz00martins
luiz00martinshttps://github.com/luiz00martins
on Aug 5, 2026https://github.com/modelcontextprotocol/python-sdk/issues/3257#issue-5075442058
https://github.com/modelcontextprotocol/python-sdk/issueshttps://github.com/modelcontextprotocol/python-sdk/issues
2025-11-25 §Transportshttps://modelcontextprotocol.io/specification/2025-11-25/basic/transports
https://github.com/luiz00martins/mcp-get-stream-reconnect-loophttps://github.com/luiz00martins/mcp-get-stream-reconnect-loop
"Removal of the GET stream endpoint"https://modelcontextprotocol.io/specification/2026-07-28/basic/transports/streamable-http
2025-11-25 §Transportshttps://modelcontextprotocol.io/specification/2025-11-25/basic/transports
streamable_http client hangs indefinitely when connecting to POST-only MCP servers (ex: GitHub MCP) #1941https://github.com/modelcontextprotocol/python-sdk/issues/1941
streamable_http client hangs indefinitely when connecting to POST-only MCP servers (ex: GitHub MCP) #1941https://github.com/modelcontextprotocol/python-sdk/issues/1941
StreamableHTTPClientTransport: 2-retry SSE reconnect ceiling + silent-success after exhaustion typescript-sdk#2098https://github.com/modelcontextprotocol/typescript-sdk/issues/2098
streamable_http client hangs indefinitely when connecting to POST-only MCP servers (ex: GitHub MCP) #1941https://github.com/modelcontextprotocol/python-sdk/issues/1941
https://github.com/luiz00martins
luiz00martinshttps://github.com/luiz00martins
on Aug 5, 2026https://github.com/modelcontextprotocol/python-sdk/issues/3257#issuecomment-5197695527
https://github.com/Ben-Home
Ben-Homehttps://github.com/Ben-Home
on Aug 10, 2026https://github.com/modelcontextprotocol/python-sdk/issues/3257#issuecomment-5247028279
maxisbeyhttps://github.com/maxisbey
P2Moderate issues affecting some users, edge cases, potentially valuable featurehttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22P2%22
v1Affects the v1.x maintenance linehttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22v1%22
v2Affects the v2 line (2.x on main)https://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22v2%22
on Aug 12, 2026https://github.com/modelcontextprotocol/python-sdk/issues/3257#event-29354927463
claudehttps://github.com/apps/claude
bugSomething isn't workinghttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22bug%22
on Oct 8, 2026https://github.com/modelcontextprotocol/python-sdk/issues/3257#event-32781079081
Sign up for freehttps://github.com/signup?return_to=https://github.com/modelcontextprotocol/python-sdk/issues/3257
Sign in to commenthttps://github.com/login?return_to=https://github.com/modelcontextprotocol/python-sdk/issues/3257
P2Moderate issues affecting some users, edge cases, potentially valuable featurehttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22P2%22
bugSomething isn't workinghttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22bug%22
v1Affects the v1.x maintenance linehttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22v1%22
v2Affects the v2 line (2.x on main)https://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22v2%22
https://github.com
Termshttps://docs.github.com/site-policy/github-terms/github-terms-of-service
Privacyhttps://docs.github.com/site-policy/privacy-policies/github-privacy-statement
Securityhttps://github.com/security
Statushttps://www.githubstatus.com/
Communityhttps://github.community/
Docshttps://docs.github.com/
Contacthttps://support.github.com?tags=dotcom-footer

Viewport: width=device-width


URLs of crawlers that visited me.