mcp: prune completed listen request IDs from the session (#1190)

### Problem

`ServerSession` tracks the request IDs of in-flight
`subscriptions/listen` streams so `Close` can cancel the parked handlers
and avoid the jsonrpc2 drain deadlock. The ID is appended when the
listen starts, but it is never removed when the listen handler returns.

Every completed listen stream (peer cancel, unsubscribe, stream break)
therefore leaves one stale entry in the session for its entire lifetime.
On a long-lived session where a client repeatedly subscribes and
unsubscribes, the slice grows without bound: one leaked entry per cycle.

`Close` calls `jsonrpc2.Connection.Cancel` on each recorded ID, and a
stale ID is a no-op there today, but the bookkeeping is meant to hold
only in-flight listens and currently never shrinks.

### Change

Drop the request ID from the session's bookkeeping when the listen
handler returns, matching the lifecycle of the in-flight handler that
owns it.

### Tests

Three tests reproduce the leak, failing on `main` and passing here:

- `TestListenPrunedAfterSingleCompletion`
- `TestListenIDsDoNotAccumulate`
- `TestListenIDsLeakViaPublicSubscribeUnsubscribe`

The third exercises the leak through the public
`Subscribe`/`Unsubscribe` API. `go test ./mcp/` passes.

---------

Co-authored-by: Guglielmo Colombo <guglielmoc@google.com>
This commit is contained in:
Recoordinate 2026-08-26 03:15:09 +12:00 • committed by GitHub
commit 2732839dba
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -1962,6 +1962,19 @@ func (ss *ServerSession) handle(ctx context.Context, req *jsonrpc.Request) (any,
ss.mu.Lock()
ss.listenIDs = append(ss.listenIDs, req.ID)
ss.mu.Unlock()
// The listen completes when the handler returns (peer cancellation,
// stream break, or error); drop the ID so completed listens don't
// accumulate in the slice indefinitely.
defer func() {
ss.mu.Lock()
for i, id := range ss.listenIDs {
if id == req.ID {
ss.listenIDs = append(ss.listenIDs[:i], ss.listenIDs[i+1:]...)
break
}
}
ss.mu.Unlock()
}()
}
res, err := handleReceive(ctx, ss, req)