Repository navigation
internal/jsonrpc2: cancel notification handlers when the reader stops - #1566
Conversation
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
left a comment
There was a problem hiding this comment.
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),
TestReadErrorCancelsNotificationtimes out at 5s, and both subtests ofTestNotificationHandlerCancelledOnDisconnecttime out. On the head both pass. - On the head,
go vet ./internal/jsonrpc2/ ./mcp/andgo test -race ./...(all packages ok). - Both new tests under
-race:-count=200for the jsonrpc2 test and-count=50for the mcp one. No flakes. - Two throwaway probes in
mcpon 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 callsNotifyProgressback. On the base the handler'sctx.Err()is nil, and on the head it iscontext canceled. The write-back fails withconnection closed: EOFon 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
StreamableHTTPHandlerreceiving 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.
- Half-close over
From reading:
-
The comment at
internal/jsonrpc2/conn.go:597-598still 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 toreadIncoming. -
The write-failure path at
conn.go:829still cancels onlyincomingByID, which means calls only. That seems right, since a notification handler doesn't need to write a response. I mention it only because thePropagateCancellationdoc atconn.go:216-219talks 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 thereadIncomingcomment atconn.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.
When the reader stops (usually because the peer disconnected),
readIncomingcancels every in-flight call so that parked handlers can return. It only looked
at
incomingByID, so a notification handler that was running at that momentkept a live context. Sessions run notification handlers synchronously. If such
a handler waits on
ctx, the connection never goes idle.ServerSession.Waitthen blocks forever once the client is gone, and
ClientSession.Wait/Closeblock 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 theread 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 ascontext.Cause.handleAsyncskips a request whose context is already canceled. That checknow 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
Closewhile the peer is still connected is unchanged: it stillwaits for handlers.
Tests:
internal/jsonrpc2:TestReadErrorCancelsNotificationcovers a parkednotification handler that is canceled with
io.EOFwhileWaitreturns, anda queued notification that is still delivered.
mcp:TestNotificationHandlerCancelledOnDisconnect(server and clientsubtests) covers a
ProgressNotificationHandlerwaiting onctx. When thepeer closes its pipe, the handler is canceled and
Waitreturns.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.