Skip to content

internal/jsonrpc2: cancel notification handlers when the reader stops - #1566

Merged
guglielmo-san merged 1 commit into
modelcontextprotocol:mainfrom
RealAdhi:fix/cancel-notification-ctx-on-disconnect
Dec 4, 2026
Merged

guglielmo-san merged 1 commit into
modelcontextprotocol:mainfrom
RealAdhi:fix/cancel-notification-ctx-on-disconnect

Conversation

@RealAdhi

@RealAdhi RealAdhi commented Dec 3, 2026

Copy link
Copy Markdown
Contributor

When the reader stops (usually because the peer disconnected), readIncoming
cancels every in-flight call so that parked handlers can return. It only looked
at incomingByID, so a notification handler that was running at that moment
kept a live context. Sessions run notification handlers synchronously. If such
a handler waits on ctx, the connection never goes idle. ServerSession.Wait
then blocks forever once the client is gone, and ClientSession.Wait/Close
block forever once the server is gone.

This change derives every incoming request context, notifications included,
from a context scoped to readIncoming. That context is canceled with the
read error when the reader exits, replacing the loop over incomingByID.
Calls behave as before, with the same cause. Notification handlers now see
ctx.Done() with the read error as context.Cause.

handleAsync skips a request whose context is already canceled. That check
now applies only to calls. A notification that was read before the reader
stopped, but was still queued, is still delivered (with a canceled context)
instead of being silently dropped, which matches the previous behavior.
A local Close while the peer is still connected is unchanged: it still
waits for handlers.

Tests:

  • internal/jsonrpc2: TestReadErrorCancelsNotification covers a parked
    notification handler that is canceled with io.EOF while Wait returns, and
    a queued notification that is still delivered.
  • mcp: TestNotificationHandlerCancelledOnDisconnect (server and client
    subtests) covers a ProgressNotificationHandler waiting on ctx. When the
    peer closes its pipe, the handler is canceled and Wait returns.

Both tests time out after 5s and fail without the fix.

Fixes #1565

AI disclosure: I used an AI coding assistant to help write this change; I reviewed and tested it, and can explain it.

When the reader stopped, readIncoming cancelled only the calls in
incomingByID, so a notification handler running at that moment kept a
live context. Sessions run notification handlers synchronously, so a
handler waiting on its context kept the connection from going idle, and
ServerSession.Wait (or ClientSession.Wait and Close) blocked forever
after the peer went away.

Derive every incoming request context from one scoped to readIncoming
and cancel it with the read error when the reader exits. Calls are
cancelled as before. A notification read before the reader stopped is
still delivered, with its cancelled context, rather than dropped.

TestReadErrorCancelsNotification and
TestNotificationHandlerCancelledOnDisconnect fail without the change.

Fixes modelcontextprotocol#1565

@1AbdullahButt 1AbdullahButt left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The fix looks correct and small. I found no regressions, and I have two minor notes.

What I ran, in Docker (golang:1.26), on the head (11da698) and the merge base (723d70e):

  • The two new tests on both trees. On the base (with the test files copied in), TestReadErrorCancelsNotification times out at 5s, and both subtests of TestNotificationHandlerCancelledOnDisconnect time out. On the head both pass.
  • On the head, go vet ./internal/jsonrpc2/ ./mcp/ and go test -race ./... (all packages ok).
  • Both new tests under -race: -count=200 for the jsonrpc2 test and -count=50 for the mcp one. No flakes.
  • Two throwaway probes in mcp on both trees, to look for behaviour changes outside the reported hang:
    • Half-close over IOTransport. The client sends a progress notification and then closes only its write pipe. The server handler sleeps 200ms and then calls NotifyProgress back. On the base the handler's ctx.Err() is nil, and on the head it is context canceled. The write-back fails with connection closed: EOF on both, and the client receives nothing on either. So the only visible difference is the context, which is the point of the change.
    • A stateless StreamableHTTPHandler receiving a POST that contains only a notification. The result was the same on both trees (202, and the handler was not invoked in my setup), so this path doesn't show a difference either.

From reading:

  1. The comment at internal/jsonrpc2/conn.go:597-598 still says "In theory notifications cannot be cancelled, but we build them a cancel context anyway." After this change their context is cancelled when the reader stops, so the comment could say that and point to readIncoming.

  2. The write-failure path at conn.go:829 still cancels only incomingByID, which means calls only. That seems right, since a notification handler doesn't need to write a response. I mention it only because the PropagateCancellation doc at conn.go:216-219 talks about "a transport read/write failure cancelling every in-flight request". With this change, that is true for read failures (notifications included) but only for calls on write failures. It might be worth one sentence there, or in the readIncoming comment at conn.go:585-589, so the asymmetry is clearly intentional.

Deriving the request contexts from one reqCtx also keeps cleanup bounded: finishIncoming (conn.go:788) still calls req.cancel(nil), so finished requests unregister from the parent, and a long-lived connection doesn't accumulate children.

I used Claude Code to help with this review, and I checked the results myself.

@guglielmo-san
guglielmo-san merged commit d90aee8 into modelcontextprotocol:main Dec 4, 2026
9 checks passed
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.

mcp: a notification handler's context is not canceled when the peer disconnects

3 participants