Skip to content

Commit 45da779

Browse files
shigechikaclaude
andauthored
fix(relay): do not treat a notification-only SSE reply as answered (#476)
* fix(relay): do not treat a notification-only SSE reply as answered A request-scoped SSE reply that carried only notifications and then ended passed for a successful request, so the stdio client never got an answer for its id. Track whether the request's own response was emitted: a stream that ends without it now gets one error, and a read error after the response no longer adds a second answer for the same id. Fixes #475 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(relay): keep tracking answers under the tools/list hook; note why not era-gated Only an MRTR hook (which comes with input_required_abort) owns the answer for its transaction. The tools/list header hook never swallows, so its requests are tracked like plain ones. Record in the code why the fix applies to the legacy era too, as #444 and #416 do. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(relay): track answers under MRTR too and stop at the response Address the code review on #476: track the answer after an MRTR hook's rewrite and route the one error through input_required_abort; skip ids the client cancelled; leave null ids untracked; stop reading once the response is out so a repeated one never reaches the client; word the error like #444; do not log a failed attempt for an answered request; skip the parse for payloads without an id. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(relay): recognise the response by parsing, not by a literal "id" Address ai-review R3F1: an escaped key such as "id" is a valid id, so drop the substring prefilter and always parse. Address R2F1: state the no-difference claim for intact streams only. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(relay): answer directly when no MRTR transaction owns the request The abort funnel does nothing when no transaction is live, so an MRTR-eligible request whose SSE stream carried only progress and ended before any round opened was still left unanswered. The callback now returns whether it answered, and the relay writes the error itself when it did not. Adds an end-to-end test through run(). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(relay): keep reading after the response and centralise the owed error Address the second code review on #476: instead of stopping at the response, keep reading so later frames (list_changed) arrive and the connection returns to the pool, and drop only a repeated response. Route every "this id is owed one error" outcome through one helper that tries the MRTR funnel first. Drop the unreachable cancel-tracker check and update the docstring to the new contract. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(relay): keep the cancel-tracker check in the owed-error helper Address ai-review R6F1: REVIEW.md §3 asks every synthesized response to skip ids the client has cancelled, so the helper consults the tracker before the plain write, as #444's path does. R6F2: the repeated-response test's docstring now says the stream is still read to its end. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 40b99d7 commit 45da779

2 files changed

Lines changed: 438 additions & 41 deletions

File tree

‎src/mcp_stdio/relay.py‎

Lines changed: 109 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -4004,7 +4004,7 @@ def _post_and_stream(
40044004
capture_init: bool = False,
40054005
has_id: bool = True,
40064006
input_required_hook: Callable[[str], str | None] | None = None,
4007-
input_required_abort: Callable[[str], None] | None = None,
4007+
input_required_abort: Callable[[str], bool] | None = None,
40084008
abort: "threading.Event | None" = None,
40094009
publish_response: Callable[["httpx.Response | None"], None] | None = None,
40104010
capture_error: bool = False,
@@ -4029,8 +4029,9 @@ def _post_and_stream(
40294029

40304030
``has_id`` mirrors the run() loop's notification policy one frame
40314031
deeper: a notification (no JSON-RPC id) must never receive a
4032-
synthesized error response, so the retry-exhausted / stream-interrupted
4033-
error writes below are suppressed when ``has_id`` is False (the failure
4032+
synthesized error response, so the retry-exhausted / stream-interrupted /
4033+
unanswered-stream (#475) error writes below are suppressed when ``has_id``
4034+
is False (the failure
40344035
is still logged to stderr), matching the ``req_has_id`` gating in run().
40354036

40364037
``input_required_hook`` is the MRTR interception point (#270 Phase 2 PR
@@ -4066,7 +4067,8 @@ def _post_and_stream(
40664067
original body while a transaction it opened is still alive.
40674068

40684069
``input_required_abort`` (#356 review R1F1) is the failure counterpart,
4069-
passed by exactly the same two call sites and never alone. When the
4070+
passed by exactly the same two call sites and never alone. It returns
4071+
whether it answered: ``False`` when no transaction is live. When the
40704072
stream breaks AFTER a swallow, writing the ordinary
40714073
"upstream stream interrupted" error under ``req_id`` would answer the
40724074
client while the transaction stays alive and its minted requests stay on
@@ -4076,12 +4078,15 @@ def _post_and_stream(
40764078
callback is invoked INSTEAD of the generic write; it funnels through
40774079
``_mrtr_abort``, which purges the transaction, cancels the outstanding
40784080
minted requests downstream and writes exactly one error under the
4079-
client's id. (Only the SWALLOWED case is special. A retry whose re-keyed
4080-
final result was already emitted and is then interrupted still gets a
4081-
result plus an interrupted error under one id — that is the generic
4082-
partial-delivery behavior of this function on both eras, unchanged by
4083-
and pre-dating the bridge; ``_mrtr_run_retry`` merely purges afterwards
4084-
so no THIRD response follows.)
4081+
client's id. Every other "this id is owed one error" outcome — an empty
4082+
reply, a stream that ended without the response (#475), an interruption
4083+
after a non-response payload — goes through the same ``_owe_error``
4084+
helper: the funnel first, and the plain write only when the funnel did
4085+
not answer and nothing was swallowed. Once the request's own response
4086+
(re-keyed or not) has been emitted, nothing more is written for its id:
4087+
a later interruption is ignored and a repeated response is dropped
4088+
(#475; this replaced the older "result plus an interrupted error under
4089+
one id" outcome).
40854090

40864091
A non-compliant server can also make a payload LOOK swallowed when
40874092
nothing is actually pending: a duplicate of an already-emitted terminal
@@ -4164,6 +4169,39 @@ def _post_and_stream(
41644169
# written), so both the empty-response synthesis and the
41654170
# mid-stream replay must treat it exactly like a partial delivery.
41664171
swallowed = False
4172+
4173+
def _owe_error(reason: str, swallowed: bool) -> None:
4174+
"""Write the one error a request with an id is still owed (#475).
4175+
4176+
A live MRTR transaction answers through its own funnel; when it
4177+
does not (no transaction), the error is written here unless a
4178+
swallowed payload means the hook already answered, or the client
4179+
has cancelled the id (the non-consuming tracker check REVIEW.md
4180+
§3 asks of every synthesized response, as in #444's path).
4181+
"""
4182+
if input_required_abort is not None and input_required_abort(reason):
4183+
return
4184+
if swallowed:
4185+
return
4186+
if tracker is not None and tracker.contains(req_id):
4187+
return
4188+
_write_line(_error_response(reason, req_id))
4189+
4190+
# Whether the request's own JSON-RPC response has reached stdout on
4191+
# this attempt (#475). ``emitted`` alone is not enough: a server may
4192+
# send notifications (progress, logging) on a request-scoped SSE
4193+
# stream before the response, and a stream that then ends without
4194+
# it must not pass for an answered request. The check runs on what
4195+
# reached stdout, i.e. after an MRTR hook rewrote the payload to the
4196+
# client's id. A request with a null id cannot be matched (a pure
4197+
# response needs a non-null id), so it is not tracked.
4198+
# Deliberately NOT era-gated, like #444 and #416: both outcomes it
4199+
# changes (an id left unanswered forever, and two answers for one id)
4200+
# are JSON-RPC violations to fix, not legacy wire behavior to freeze.
4201+
# A server that answers its requests over a stream that stays intact
4202+
# sees no difference.
4203+
answered = False
4204+
tracked = has_id and req_id is not None
41674205
try:
41684206
with client.stream("POST", url, content=content, headers=headers) as resp:
41694207
if publish_response is not None:
@@ -4268,8 +4306,21 @@ def _post_and_stream(
42684306
swallowed = True
42694307
continue
42704308
payload = replacement
4309+
if answered and _is_pure_response_for(payload, req_id):
4310+
# A misbehaving server repeated the response: one
4311+
# answer per id. Reading continues, so frames that
4312+
# follow (e.g. list_changed) still arrive and the
4313+
# connection can return to the pool.
4314+
log(f"request {req_id!r}: repeated response dropped")
4315+
continue
42714316
_emit(payload, tracker)
42724317
emitted = True
4318+
if (
4319+
tracked
4320+
and not answered
4321+
and _is_pure_response_for(payload, req_id)
4322+
):
4323+
answered = True
42734324
else:
42744325
_read_bounded(resp, client)
42754326
text = resp.text.strip()
@@ -4291,6 +4342,10 @@ def _post_and_stream(
42914342
if text:
42924343
_emit(text, tracker)
42934344
emitted = True
4345+
# A single JSON body is the whole reply, passed
4346+
# through as-is even when malformed; only the SSE
4347+
# branch can carry notifications ahead of it.
4348+
answered = True
42944349

42954350
if _abort_requested(abort):
42964351
# Required changes 2 and 4, the FALSE-NORMAL arm. A
@@ -4311,7 +4366,18 @@ def _post_and_stream(
43114366
# waiting forever. Synthesize an error so the client is not
43124367
# left hanging, mirroring the >=400 fall-through in run().
43134368
# Notifications (has_id False) stay silent.
4314-
_write_line(_error_response("empty response from server", req_id))
4369+
_owe_error("empty response from server", False)
4370+
elif emitted and tracked and not answered and not swallowed:
4371+
# #475: the stream delivered only notifications and ended
4372+
# without the response. Same reasoning as above: without
4373+
# this the client waits forever for an id nobody answers.
4374+
# Worded like #444: the server may have run the request.
4375+
log(f"request {req_id!r}: stream ended without a response")
4376+
_owe_error(
4377+
"upstream stream ended without a response; "
4378+
"the request may have executed",
4379+
False,
4380+
)
43154381
# pv is intentionally None here: no InitializeResult was
43164382
# delivered, so an empty-200 to an `initialize` request leaves
43174383
# the relay's protocol_version unset rather than guessing a
@@ -4346,6 +4412,13 @@ def _post_and_stream(
43464412
# funnel — required changes 4 and 10.
43474413
log(f"request {req_id!r} cancelled by the client: {e}")
43484414
return _aborted_result()
4415+
if answered:
4416+
# #475: the response already reached the client; a read
4417+
# failure after it (a trailing frame, the close) must not
4418+
# produce a second answer for the same id, nor count as a
4419+
# failed attempt.
4420+
log(f"request {req_id!r}: transport error after the response; ignored")
4421+
return _StreamResult(session, 200, protocol_version=pv)
43494422
last_error = e
43504423
log(f"attempt {attempt}/{MAX_RETRIES} failed: {e}")
43514424
if emitted or swallowed:
@@ -4356,23 +4429,20 @@ def _post_and_stream(
43564429
# requests on the client's stdin and the server-side work may
43574430
# already have run, so a replay would duplicate both.
43584431
log("upstream stream interrupted after partial delivery; not retrying")
4359-
if swallowed and input_required_abort is not None:
4360-
# #356 review R1F1: the swallowed payload opened (or
4361-
# extended) an MRTR transaction that is STILL alive, with
4362-
# minted requests already on the client's stdin. A plain
4363-
# error under req_id would answer the client now and the
4364-
# completed retry would answer it again later. Route
4365-
# through the transaction's own abort funnel instead —
4366-
# exactly one error under this id, plus the downstream
4367-
# cancels that retire the dialogs nobody will collect.
4368-
# The callback is a no-op when the hook ALREADY aborted
4369-
# (an unbridgeable round answers and purges from inside
4370-
# the swallow), so this path can never write twice.
4371-
input_required_abort(f"upstream stream interrupted: {e}")
4372-
elif has_id:
4373-
_write_line(
4374-
_error_response(f"upstream stream interrupted: {e}", req_id)
4375-
)
4432+
if has_id:
4433+
# #356 review R1F1: when an MRTR transaction is STILL
4434+
# alive (minted requests already on the client's stdin), a
4435+
# plain error under req_id would answer the client now and
4436+
# the completed retry would answer it again later, so
4437+
# ``_owe_error`` routes through the transaction's own abort
4438+
# funnel first — exactly one error under this id, plus the
4439+
# downstream cancels that retire the dialogs nobody will
4440+
# collect. When the funnel finds no live transaction after
4441+
# a swallow, the hook ALREADY answered (an unbridgeable
4442+
# round answers and purges from inside the swallow), so
4443+
# nothing more is written; without a swallow the plain
4444+
# error is written.
4445+
_owe_error(f"upstream stream interrupted: {e}", swallowed)
43764446
# Return a 200 result carrying any captured protocol_version instead of None: the InitializeResult was already
43774447
# delivered, so the client considers init complete. Returning None
43784448
# would discard the negotiated version, leaving the relay's
@@ -9239,7 +9309,7 @@ def hook(payload: str) -> str | None:
92399309

92409310
return hook
92419311

9242-
def _make_input_required_abort(client_id: Any) -> Callable[[str], None]:
9312+
def _make_input_required_abort(client_id: Any) -> Callable[[str], bool]:
92439313
"""Build the failure counterpart of the interception hook (R1F1).
92449314

92459315
Handed to ``_post_and_stream`` alongside every hook and invoked on
@@ -9266,16 +9336,22 @@ def _make_input_required_abort(client_id: Any) -> Callable[[str], None]:
92669336
server, and the same code already covers the other "the exchange
92679337
could not be completed" outcomes (cap breaches, a client error on a
92689338
minted id).
9339+
9340+
Returns whether it answered: ``False`` when no transaction is live,
9341+
which is also the case for an initial request whose stream ended
9342+
before any round opened (#475). The caller then owes the client
9343+
the error itself.
92699344
"""
92709345

9271-
def abort(reason: str) -> None:
9346+
def abort(reason: str) -> bool:
92729347
if client_id not in mrtr_txns:
92739348
log(
9274-
f"MRTR POST for id {client_id!r} failed after the "
9275-
f"transaction was already answered: {reason}"
9349+
f"MRTR POST for id {client_id!r} failed with no live "
9350+
f"transaction: {reason}"
92769351
)
9277-
return
9352+
return False
92789353
_mrtr_abort(client_id, reason, code=-32000)
9354+
return True
92799355

92809356
return abort
92819357

0 commit comments

Comments
 (0)