Skip to content

mcp: retire a listen's subscriptions only while they are its own - #1360

Merged
guglielmo-san merged 2 commits into
modelcontextprotocol:mainfrom
jmrplens:jmrp-retire-a-listens-own-subscriptions
Oct 10, 2026
Merged

guglielmo-san merged 2 commits into
modelcontextprotocol:mainfrom
jmrplens:jmrp-retire-a-listens-own-subscriptions

Conversation

@jmrplens

@jmrplens jmrplens commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

The subscription registries are keyed by session, so a second subscriptions/listen that subscribes to a URI the session already holds, or opts in to a list-changed notification the session already receives, replaces the first listen's entry with its own request ID. The first listen's teardown then deleted that entry by session, and the second listen stayed open with nothing delivered to it.

This SDK's own client reaches it on 2026-07-28 over stdio or any other persistent transport; over streamable HTTP two listens never share a session. ClientSession.Unsubscribe only cancels the listen, so a Subscribe for the same URI right after it can be acknowledged before the server has unwound the first listen, whose deferred unsubscribe then removes what the second listen has just registered. Over the in-memory transport and without -race, Subscribe, Unsubscribe and Subscribe again lost the subscription in 85 to 110 of 200 attempts in each of five runs on main, and in none with this change; under -race the window narrows to 0 to 4 in 200. #1283 guards the client's own table against the same race with a generation number; this is the server's half.

The change follows the guards #1275 added:

  • The teardown of the three list-changed registries deletes an entry only while it still holds this listen's request ID.
  • A listen's deferred resource unsubscribe goes through a new internal endSubscription, which removes resourceSubscriptions[uri][session] only while it holds this listen's request ID. resources/unsubscribe calls it with the zero ID and removes the session's subscription whichever request made it, as before.
  • The UnsubscribeHandler is still called for every URI of every listen that ends, so its calls stay paired with the SubscribeHandler's. Skipping it when a later listen holds the URI would leave a handler that counts listens one unsubscribe short. I kept it this way on purpose; say if you would rather it ran only when the session's entry goes away. The other side of it: a handler that keeps a set of subscribed sessions, as the field's doc reads, now sees an unsubscribe for a URI the session is still subscribed to. If you keep this, I can add a sentence to the UnsubscribeHandler doc saying it is called once for each listen that ends.

There are no exported API changes, and the keying by session stays. What this does not change is two listens held open at once on one URI: the later one receives every update, and if it ends first the earlier one receives nothing, as on main today. That needs the table keyed per listen, and #1359 sets out that shape and one more for you to choose from. This change stands on its own if you keep the keying by session, and the per-listen keying would replace it rather than conflict with it.

Tests, next to the existing TestSubscriptionsListen_* ones and reusing their fixtures:

  • TestSubscriptionsListen_ResubscribeOutlivesEarlierTeardown drives the Go client through Subscribe, Unsubscribe and Subscribe, and holds the first listen's teardown in the UnsubscribeHandler until the client has seen the second listen acknowledged, so the losing order happens every time. It then checks that ResourceUpdated reaches the second listen with that listen's subscription ID, and that unsubscribing the second listen still retires the subscription.
  • TestSubscriptionsListen_ListChangedOutlivesEarlierTeardown opens a second listen next to the auto-listen for each of tools, prompts and resources list-changed, ends the auto-listen, and checks that the change reaches the second listen.

Against main at 8dd5d6a both fail, the second in all three subtests (timed out waiting for "updated", then "tool", "prompt" and "resource"), and with the change they pass. Taking out any one of the four guards fails the test for that registry, making a listen never retire its resource entry fails TestSubscriptionsListen_TeardownKeepsOtherListens, TestSubscriptionsListen_ResubscribeOutlivesEarlierTeardown, TestResourceSubscriptions_InMemory and TestResourceSubscriptions_MultipleURIs, and making resources/unsubscribe keep the entry fails TestEndToEnd. go test ./... on Go 1.25.14 and go test -race ./... on Go 1.26.8 and 1.27.1 pass, the new tests passed 20 runs in a row under -race, gofmt -l and go vet ./... are clean, and so is staticcheck v0.6.1 on Go 1.26.8.

@cgair named this case in the Known limitations of #1275 and showed it there with failing tests; this takes the part of it that the Go client reaches.

Updates #1359

The subscription registries are keyed by session, so a second listen
that subscribes to a URI the session already holds, or opts in to a
list-changed notification it already receives, replaces the first
listen's entry with its own request ID. The first listen's teardown then
deleted that entry by session, and the second listen stayed open with
nothing delivered to it.

The Go client reaches this on 2026-07-28 over stdio or any other
persistent transport, without meaning to hold two listens.
ClientSession.Unsubscribe only cancels the listen, so a Subscribe for
the same URI right after it can be acknowledged before the server has
unwound the first listen, whose deferred unsubscribe then removes the
subscription the second listen has just made.

A listen's teardown now removes an entry only while it still records
that listen's request ID. resources/unsubscribe still removes the
session's subscription whichever request made it, and the
UnsubscribeHandler is still called for every URI of every listen that
ends, so its calls stay paired with the SubscribeHandler's.
@guglielmo-san
guglielmo-san merged commit 218aedd into modelcontextprotocol:main Oct 10, 2026
9 checks passed
guglielmo-san pushed a commit that referenced this pull request Nov 3, 2026
`resourceSubscriptions` holds one request ID per URI and session, so on
a 2026-07-28 session a second `subscriptions/listen` for a URI the
session already holds replaced the first listen's ID with its own. Both
listens are acknowledged with the URI, but `ResourceUpdated` delivered
only on the second, and once the second ended the first, still open,
received nothing. The three list-changed registries did the same to two
listens asking for one list-changed notification.

This is the second shape from #1359, keeping the keying by session that
#1275 kept:

- Each of the four registries holds the ID of every open listen of the
session (per URI for `resourceSubscriptions`), through `addListen` and
`removeListen`, and `notifySubscribedSessions` delivers on each with its
own `subscriptionId`.
- A listen holds its ID once even if it names the URI twice; its
teardown removes only that ID, and the session's entry with the last
one.
- `resources/subscribe` and `resources/unsubscribe` keep one ID per URI
and session, as before.
- `SubscribeHandler` and `UnsubscribeHandler` are still called once for
each listen, as #1360 left them, so a handler that counts them still
holds the session subscribed while one listen remains.

There are no exported API changes.

`TestSubscriptionsListen_EveryListenOnAURIIsNotified` holds two listens
open on one URI and checks, as it ends them one at a time (later first
in one subtest, earlier in the other), which IDs each update reaches,
the handler counts, and that the session ends unsubscribed. On `main` at
ae26252 both subtests fail with `both listens open: update delivered
under subscription IDs [3], want [2 3]`.
`TestSubscriptionsListen_EveryListenIsNotifiedOfListChanges` does the
same for a tools, a prompts and a resources list change, and fails the
same way for each on `main`.
`TestSubscriptionsListen_URINamedTwiceIsNotifiedOnce` and
`TestServerSubscribe_LegacyResubscribeReplacesID` keep what `main` did
for a listen naming its URI twice and for a second
`resources/subscribe`, and each fails if its path always appends.

`gofmt -l`, `go vet ./...` and `staticcheck` v0.6.1 are clean, `go test
-race ./...` passes on Go 1.26.10 and `go test ./...` on Go 1.25.14 and
1.26.10, and the listen and subscribe tests pass 20 runs in a row under
`-race`.

Three existing tests are flaky under load, on `main` as well as with
this change: in batches of 50 on Go 1.25.14
`TestStreamableStateful_DiscoverDoesNotLeakSession` failed 0 to 13 times
on `main` and 0 to 8 with the change, and in batches of 160 under
`-race` `TestResourceSubscriptions_InMemory` and
`TestResourceSubscriptions_MultipleURIs` failed 1 to 25 times on `main`
and 1 to 29 with the change. Those two call `ResourceUpdated` as soon as
the `SubscribeHandler` runs, before the listen is registered.

Fixes #1489
@jmrplens
jmrplens deleted the jmrp-retire-a-listens-own-subscriptions branch November 8, 2026 00:04
jmrplens added a commit to jmrplens/gitlab-mcp-server that referenced this pull request Dec 4, 2026
Moves `github.com/modelcontextprotocol/go-sdk` from v1.8.0 to v1.9.0
(released 2026-11-30, no new protocol revision) and takes in everything
the release changes for this server: the pins that fail on it, the
workarounds it makes unnecessary, and the pages that describe the old
behaviour. The dependency sweep in #1985 held go-sdk at v1.8.0 for this
change.

## What v1.9.0 changes, and what changed here

| go-sdk change | Here |
| --- | --- |
| A handler or middleware error with no JSON-RPC code goes out as
`-32603` with its text, no longer as code 0
([#1407](modelcontextprotocol/go-sdk#1407)) |
Correct per JSON-RPC, adopted. The carried-channel tests in
`internal/tenancy` expect `-32603` (plain error and load shedding at
2025-11-25); the Refusal channels section of the tenant policy spec,
`Validate`'s "no code" reason, the `CodedError` comment and the
subscriptions page (EN and ES) say so |
| `-32022` (unsupported protocol version) is answered with HTTP 400 in
both eras | Correct per the transport spec, adopted. `sdkStatus` maps it
in both eras; the spec says which statuses an in-band error takes. No
register row emits `-32022` |
| A typed nil result from a middleware is answered `null` at 2026-07-28
instead of ending the process | The test is renamed
`TestTypedNilResult_FromAMiddleware_IsAnsweredNullInBothEras` and still
runs each era in a child process; the spec keeps "a refusal is always an
error" with the new reason |
| Results a middleware returns are labeled with `resultType` like the
dispatcher's
([#1226](modelcontextprotocol/go-sdk#1226), for
[#1225](modelcontextprotocol/go-sdk#1225)) |
Workaround retired: `internal/toolutil/result_type.go` and its tests are
deleted, and the rate limiter, `heldRequestsRefusal` (its `req`
parameter dropped) and both toolvisibility middlewares return their
refusals as built. RTC-001, AUT-007, AUT-008 and the F-20 paragraph say
the SDK labels them. `test/e2e/http/result_type_test.go` and the
fine-grained e2e case still hold the label on the wire, and pass |
| The client's `Ping` fails locally on a 2026-07-28 session, which
removed ping
([#1378](modelcontextprotocol/go-sdk#1378)) |
Test-only: `pingWithin` in `cmd/server` asks `server/discover` on such a
session. The server's keepalive stays off; nothing in production changes
|
| The client passes the input requests of a multi round-trip result
through its own receiving middleware as `elicitation/create`
([#1479](modelcontextprotocol/go-sdk#1479)) |
Test-only: `callAs` in `language_test.go` counts the
`elicitation/create` requests the server sends at the transport |
| The multi round-trip interaction is chosen by the negotiated version,
and input requests answered on a session negotiated below 2026-07-28 are
fulfilled by the SDK with `elicitation/create`
([#1266](modelcontextprotocol/go-sdk#1266), for
[#1258](modelcontextprotocol/go-sdk#1258)) |
`internal/elicitation.FlowFromRequest` keeps reading the version the
request states (the SDK exposes no negotiated one per request, and
reconciles the two), with its comment rewritten.
`test/e2e/stdio/elicitation_declared_version_test.go` is no longer a pin
of an SDK defect: it asserts the legacy flow, a first question sent as
`elicitation/create`, and a result with no `resultType` or
`inputRequests`, and a second case accepts the title and the description
and checks that the third question asks for the labels, so the SDK's
fulfillment carries every answer and the signed state. The elicitation
page (EN and ES) says the negotiated version decides |
| Streamed POST responses are kept alive by the SDK, committing the
headers after an interval of silence
([#1477](modelcontextprotocol/go-sdk#1477), for
[#1262](modelcontextprotocol/go-sdk#1262)) |
`streamableHTTPOptions` passes `StreamKeepAlive: sseKeepAliveInterval`
(25 s), and `sseAwareWriter` no longer heartbeats a POST response, so a
stream never carries two; it still clears the write deadline and keeps
the standalone GET alive. A silent tool call now gets bytes on the wire
before its result. The unit and e2e keep-alive tests assert that; the
HTTP server, remote deployment and troubleshooting pages (EN and ES)
drop the "a silent tool call gets no keep-alive" advice, and the spec
notes that a keep-alive committed POST takes a protocol error as an
event at 200 |
| `MCPGODEBUG` switches removed, among them `customresnotfounderrcode`
and `noprotocolerrorbody` | `subscriptions.isResourceNotFound` compares
against `jsonrpc.CodeInvalidParams` (no deprecated variable, no
`nolint`, and `internal/subscriptions` no longer imports `mcp`); the
dead `noprotocolerrorbody` skip in `session_not_found_test.go` is gone |
| `mcp.HasParams`
([#1269](modelcontextprotocol/go-sdk#1269), for
[#1261](modelcontextprotocol/go-sdk#1261)) |
Adopted: `mcpotel.paramsOf` and the e2e harness drop their reflect
checks |
| Notifications go to each session on a goroutine of their own
([#1228](modelcontextprotocol/go-sdk#1228)) and
`_meta` is cloned per session
([#1490](modelcontextprotocol/go-sdk#1490)) |
Already allowed for by `sessionOwners.sendingMiddleware`; its comments,
ADR-0020 (whose "what in the go-sdk this rests on" section is
re-verified against v1.9.0) and the resource hot spots page say it is
released |
| A second listen on a URI no longer clobbers the first
([#1360](modelcontextprotocol/go-sdk#1360), for
[#1359](modelcontextprotocol/go-sdk#1359));
`Subscribe` awaits the listen in the background and clears its entry
when it ends
([#1283](modelcontextprotocol/go-sdk#1283), for
[#1169](modelcontextprotocol/go-sdk#1169)) |
The resubscribe caveat in the e2e harness (on `TrySubscribe`,
`Subscription.Close` and the subscription's cleanup) is retired; the
subscriptions and troubleshooting pages (EN and ES) describe the v1.9.0
client. A resubscribe during the earlier listen's teardown is now
something a client does, and it exposed a race in `sessionBridge`: the
unsubscribe released the last hold and stopped the watch with nothing
held between the two, so a resubscribe joining in that gap was
acknowledged on a stopped watch. The subscribes and unsubscribes of one
watch now run under a lock per session and URI (a waiting subscribe
gives up with its request), pinned by
`TestSessionBridge_ResubscribeDuringTeardown_KeepsTheWatch`, which fails
without it |
| The cancellation reason reaches the handler as the context's cause
([#1255](modelcontextprotocol/go-sdk#1255), for
[#1254](modelcontextprotocol/go-sdk#1254)) |
Not logged: it is text the client writes. The `wasCancelled` comment
says so instead of saying it cannot be read |

Version mentions move to v1.9.0 in CLAUDE.md, the Copilot and agent
instructions, the architecture, HTTP server, subscriptions and
troubleshooting pages (EN and ES), the tenancy package, ADR-0020 and
ADR-0027. `docs/development/upstream-bugs.md` records every go-sdk row
that shipped in v1.9.0 and what it retired; the rows still open upstream
(malformed messages, `notifications/cancelled` for a listen, the client
after a 404) keep their pins, which pass. CLAUDE.md and
`test/e2e/README.md` now name two go-sdk pins, `listen_end_test.go` and
`session_not_found_test.go`.

## Upstream changes this release ships

Ours: [#1266](modelcontextprotocol/go-sdk#1266),
[#1267](modelcontextprotocol/go-sdk#1267) (stdio
at 2026-07-28; HTTP still answers a cancelled call),
[#1255](modelcontextprotocol/go-sdk#1255),
[#1268](modelcontextprotocol/go-sdk#1268),
[#1269](modelcontextprotocol/go-sdk#1269),
[#1360](modelcontextprotocol/go-sdk#1360),
[#1490](modelcontextprotocol/go-sdk#1490),
[#1273](modelcontextprotocol/go-sdk#1273),
[#1274](modelcontextprotocol/go-sdk#1274).

Others' that this server tracked:
[#1477](modelcontextprotocol/go-sdk#1477),
[#1242](modelcontextprotocol/go-sdk#1242),
[#1464](modelcontextprotocol/go-sdk#1464),
[#1524](modelcontextprotocol/go-sdk#1524),
[#1226](modelcontextprotocol/go-sdk#1226),
[#1283](modelcontextprotocol/go-sdk#1283).

## Left for a decision

- **Request id on spans**
([#1464](modelcontextprotocol/go-sdk#1464)):
`Request.GetID` makes `jsonrpc.request.id` recordable, but the id is the
client's own value and the telemetry page and the collector privacy
suite promise no client-controlled value on a span. Not adopted.
- **Per-session resource updates**
([#1524](modelcontextprotocol/go-sdk#1524)):
`ServerSession.NotifyResourceUpdated` could deliver to an owner's
2026-07-28 sessions directly; legacy `resources/subscribe` sessions
still need the sending middleware, so this is an optimisation, not a
retirement.
- **`OnRequestSummary`** and the opt-in
`MCPGODEBUG=demotesessionlifecyclelog=1` are not used.

## Verification

Run on the branch, through the remote runner unless noted:

- `go build ./...`, `go vet -tags e2e,stdioe2e,httpe2e ./...`
- `go test ./internal/... ./cmd/... -count=1`: green except
`cmd/orbit_fixtures`, which reads git and fails only because the remote
copy is not a repository (it passes in CI)
- stdio and HTTP transport e2e modules against a binary built from the
branch: both green
- `golangci-lint`, `govulncheck`, `check-tenancy`, `check-supply-chain`,
the 1:1 audit scopes (`sdk`, `paths`, `grants`, `required`, `params`,
`routes`, `enums`), `check-audit-1to1-baseline`, `check-testing-docs`,
`check-md-tables`, `check-doc-links`, `check-doc-tool-names`,
`check-e2e-static` and the test-shape, i18n, escaping, action-id, godoc
and surface-quality gates
- locally: `check-file-headers`, `check-em-dash`, `check-dco`,
`check-pr-description`, the site's `i18n:check`, `build` and `lint`,
markdownlint on the changed Markdown
- The branch is rebased on main after #1985 landed, with client-go
v3.60.0 and the rest of that sweep, and again after #1987 (R-ROUTE wave
4, 38 new actions) landed. Wave 4 uses none of the helpers this bump
retires, and only the testing reference needed regenerating. On the tree
rebased onto #1987: `go build`, `go vet` with every e2e tag, the unit
suite (with the request inventory recorded from it, which comes out
unchanged), both transport e2e modules, `golangci-lint`, `govulncheck`,
the seven 1:1 scopes, the baseline, `check-supply-chain`,
`check-tenancy`, the generated-artifact gates CI runs, the local gates
and the site gates. All pass
- `go test -race` over `cmd/server` and `internal/subscriptions`
- The release rehearsal (`release.yml` dispatched on dc520bb, before
the rebase onto #1987) passed every job. That includes the Docker GitLab
e2e gate, which drives the real binary through the go-sdk
`ClientSession` this bump changes, the race gates, the reproducible
build and every publisher's dry run. Dispatched again on the rebased
head 6f9fcfd, it passed all 20 jobs.

---------

Signed-off-by: José M. Requena Plens <mail@jmrp.io>
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