Skip to content

fix: Refuse a request whose id is in flight, and answer no cancelled request - #390

Merged
jeanmatthieu merged 4 commits into
rel/1.0.0from
fix/server-duplicate-request-ids
Nov 28, 2026
Merged

jeanmatthieu merged 4 commits into
rel/1.0.0from
fix/server-duplicate-request-ids

Conversation

@jeanmatthieu

Copy link
Copy Markdown
Contributor

Summary

Takes two fixes from #270 by darius.codes, credited with Co-authored-by. The rest of that PR is already on rel/1.0.0, and the PR conflicts with it. Independent of #375, which also edits the server's receive loop: it merges with this PR without conflict (see Evidence).

1. A request whose id is in flight gets -32600. A second request with the id of one still in flight, alone or in a batch, overwrote the first's startingRequests and pendingRequestTasks entries. notifications/cancelled then stopped the wrong handler, the first could no longer be cancelled, and both were answered with the same id. An id must not be reused while its request is in flight: "MUST NOT match the ID of any other request the sender has issued and not yet received a response for" (2026-07-28 basic). 2025-11-25 is stricter ("MUST NOT have been previously used by the requestor within the same session"); the server enforces only the in-flight rule, under both revisions, so no ProtocolProfile flag is needed. An id is free again once its response is sent.

 receive loop
   batch:
-    startingRequests[id] = false for each request
+    admittingRequests(of: batch)   // a refused item becomes .invalid -> -32600 in the reply
   single request:
-    startingRequests[id] = false
+    guard admit(id) else { send -32600 "A request with id <id> is already in progress"
+                           (a failed send is logged); continue }

 admit(id): refuse if id is in startingRequests, pendingRequestTasks or listenRequests

 handleRequest
-  defer: remove startingRequests / pendingRequestTasks entry   // after send(response)
-  send(response)
+  release(): remove this request's entries                     // pendingRequestTasks only if still this handler's task
+  send(response)                                                // the client may reuse the id now
  • The identity check in release() covers a client that reuses the id of a request it cancelled while that handler still runs.
  • Tracking used to stop only after send(response) returned. The actor is reentrant across send, so a client that read the response and at once reused the id could get -32600. Tracking now stops right before the response goes out: for handler responses, errors sent without a handler, and listen requests. Exception: a listen stream the server closes keeps its id until its teardown notifications/cancelled, which names the id.
  • Before its handler task is registered, each return of handleRequest untracks the request explicitly. A shared defer that captures the mutable flag is rejected by Swift 6 region isolation.

2. A cancelled request gets no response. A handler that caught CancellationError and returned had its result sent. The receiver of notifications/cancelled SHOULD NOT send a response (2025-11-25 basic/utilities/cancellation):

   let response = try await handlerTask.value
   (cancel a task the cancelled tools/call created; unchanged)
   guard generation == connectionGeneration else { return nil }
+  if handlerTask.isCancelled { return nil }   // also no batch reply item
  • Wire behavior change: a duplicate in-flight id gets -32600 instead of a second handler run, and a cancelled request that returns gets no response. Only clients that already break the spec see it, so it isn't listed under "Behavior that can break working code".
  • No public API change.
  • Docs: CHANGELOG.md (1.0.0 Fixes), design/design.md dispatch table, docs/src/protocol.src.md and the woven docs/protocol.md. The sentence "If it throws CancellationError, the server sends nothing; any other error is sent as a response" became stale and is corrected.

Not covered:

  • StatefulHTTPServerTransport keys its per-request streams by the client's id, so two POSTs with one id in a session may still mix up routing there. That is transport-level, a separate change.
  • A listen request still being authorized when stop() runs keeps its listenRequests entry until its handler ends, so the id is refused on a new connection until then.
  • A request cancelled before its handler task registers keeps its pendingRequestTasks entry until the handler ends, so reusing that id is refused until then.

Evidence

Eight new tests in CancellationTests. A private ControlledSendTransport can fail chosen sends, or hold one inside send until the test releases it, which makes the reuse race deterministic. Each source hunk was removed on its own and the tests re-run:

Hunk removed Before: failing tests After
duplicate check single duplicate at both revisions (one answered "second" for id x); cancel after a refused duplicate; batch duplicates (got ["x 0","y 0","y 0"]) pass
cancelled-response drop swallowed cancellation, single; swallowed cancellation in a batch (got ["a","b"]); reused id pass
cleanup identity check reused id of a cancelled request: the second request couldn't be cancelled pass
logged refusal (back to try?) a failed refusal is logged: no "Failed to send error response" pass
release before send an id is free once its response is sent: ping, unknown method, and a listen request refused before its stream opens all got -32600 pass
  • swift test: 1412 tests in 142 suites pass. CancellationTests passes 20 of 20 runs.
  • swift scripts/weave.swift --check, swift scripts/doc-coverage.swift, and DocC --warnings-as-errors all pass.
  • scripts/run-conformance.sh --spec-version 2025-11-25 and --spec-version 2026-07-28: both pass against the baseline.
  • With fix: Distinguish invalid JSON-RPC messages from JSON parse errors #375:
    • This branch's changes apply cleanly on pull/375/head; no hunk touches the lines that PR changes in Server.swift.
    • Before the review fixes: on rel/1.0.0 merged with pull/375/head and then this PR, the build succeeded and 1413 MCPTests plus 115 SnippetTests passed. That merge has one conflict of its own, in RequestLifecycleTests.swift, which this PR doesn't touch.
  • The branch also merges cleanly into the current upstream rel/1.0.0 (5702c80a).

Merge Danger

Door: two-way until 1.0.0 is tagged: revert the commits. After the tag, the wire behavior is part of 1.0.

Blast Radius: servers

Every Server. A client that reuses an in-flight id now gets -32600 for the second request. A handler that ignores cancellation and returns no longer has its answer delivered.

AI assistance: written and opened by Claude at the author's request, for human review before merge.

jeanmatthieu and others added 3 commits November 26, 2026 18:34
…request

Server tracked each received request by its JSON-RPC id, in
startingRequests until its handler task was registered and in
pendingRequestTasks while it ran. A second request with the id of one
still in flight, alone or as a batch item, overwrote both entries: a
notifications/cancelled for the id then cancelled the second handler
and left the first running with no way to cancel it, and the first
handler's cleanup removed the second's entry. Both requests ran and
were answered with the same id. The id of a request MUST NOT be reused
while it is in flight: "MUST NOT have been previously used by the
requestor within the same session" (2025-11-25 basic, Requests), and
"MUST NOT match the ID of any other request the sender has issued and
not yet received a response for" (2026-07-28 basic).

The receive loop now admits each request before it records it
(admit(_:)): an id that is starting, running or open as a listen stream
is answered with -32600 "A request with id <id> is already in
progress", and no handler runs. In a batch such an item, or a later
item with the id of an earlier one, becomes an invalid item and gets
its -32600 in the batch reply. The first request's entries are left as
they are, so it is answered and can still be cancelled. The check runs
before the request's revision is known and applies to both: both
revisions forbid the reuse. StatelessHTTPServerTransport gives each
request its own internal id, so clients behind it never collide.

A request may reuse the id of one it cancelled while that handler still
runs: the cancellation already removed the entry. The cancelled
request's cleanup now removes the entry only if it is still its own.

A handler that caught the CancellationError and returned had its
result, or the error it returned, sent anyway: handleRequest dropped
the response only when the handler task threw CancellationError. The
receiver of notifications/cancelled SHOULD NOT send a response for the
cancelled request (2025-11-25 basic/utilities/cancellation, Behavior
Requirements 4). A response of a cancelled handler task is now dropped,
and a batched one adds no reply to its batch, as when the handler
throws. A cancelled tools/call that created a task still cancels it.

Taken from #270, without its other changes, which rel/1.0.0 already has.

Co-authored-by: darius.codes <commits@darius.codes>
Assisted-by: Claude
The receive loop sent the -32600 for a request whose id is in flight
with try?, so a transport failure was dropped without a trace. It is now
sent in a do/catch and a failure is logged as "Failed to send error
response" with the id and the error, as sendUnattributedError does. The
loop still goes on to the next message.

The comment in admit(_:) cited the 2025-11-25 rule that a request ID
"MUST NOT have been previously used by the requestor within the same
session", which the server does not enforce: it refuses only an id that
is still in flight. It now cites what is enforced, the 2026-07-28 rule
(basic, Requests: "MUST NOT match the ID of any other request the sender
has issued and not yet received a response for"), notes that 2025-11-25
is stricter, and the SeeAlso links the 2026-07-28 section.

Assisted-by: Claude
admit(_:) refuses an id that startingRequests, pendingRequestTasks or
listenRequests holds. handleRequest removed those entries only after
it returned: after send(response), and for a listen stream in the
receive loop's task after that. The actor is reentrant across send, so
a client that read the response and at once sent a new request with the
same id, which 2026-07-28 allows ("MUST NOT match the ID of any other
request the sender has issued and not yet received a response for",
basic, Requests), could get -32600 "already in progress". This held for
a handler's response, for an error sent without running a handler
(unknown method, wrong revision, ...), and for a listen request refused
before its stream opened.

handleRequest now stops tracking the request right before it sends its
response. Before the handler task is registered, every return calls
untrackStarting(), which removes the startingRequests entry and the
listen entry; after it, release() removes the pendingRequestTasks entry,
only if it is still this handler's, and the listen entry, once, before
the send or on return. The receive loop no longer clears listenRequests
itself: clearing it after handleRequest returned could remove the entry
of a later listen request that reused the id. A batched request is
untracked when its handler finishes, as before.

A listen stream the server closes keeps its id until its teardown is
sent: the notifications/cancelled that follows the result names the id
(2026-07-28 basic/utilities/cancellation), and a client such as this
SDK's fails its own pending request of that id when it gets one. A
notifications/cancelled that arrives while the result is sent still
cancels the handler task and skips the teardown, as before. A request
cancelled while its handler runs, the task-manager cancellation of a
cancelled tools/call and the stop() generation guard do not change.

The new test holds the server's send of the first reply in a transport
whose send waits until released, then sends a request with the same id:
it fails with -32600 without this change, for a ping, an unknown method
and a refused listen request.

Assisted-by: Claude
@jeanmatthieu
jeanmatthieu requested a review from a team as a code owner November 27, 2026 14:08
varun06
varun06 previously approved these changes Nov 28, 2026
@jeanmatthieu
jeanmatthieu merged commit b48b18a into rel/1.0.0 Nov 28, 2026
14 checks passed
@jeanmatthieu
jeanmatthieu deleted the fix/server-duplicate-request-ids branch November 28, 2026 16:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants