Skip to content

mcp: reject Subscribe on a closed session and roll back failed registrations - #1198

Open
GerardGao wants to merge 1 commit into
modelcontextprotocol:mainfrom
GerardGao:fix/issue-1171-subscribe-rollback-on-close
Open

mcp: reject Subscribe on a closed session and roll back failed registrations#1198
GerardGao wants to merge 1 commit into
modelcontextprotocol:mainfrom
GerardGao:fix/issue-1171-subscribe-rollback-on-close

Conversation

@GerardGao

Copy link
Copy Markdown

What

ClientSession.Subscribe (SEP-2575 path) starts a subscriptions/listen stream
without awaiting the send result, so on a session that is closing — or when the
listen send fails for any other reason — it can return nil even though the
stream never started. The local resourceSubs map also keeps an entry whose
cancel func is then never called, leaking the registration and misreporting the
URI as subscribed. Fixes #1171.

How

  • Add a closed flag to ClientSession, set at the top of Close.
  • Subscribe checks the flag under resourceSubsMu before registering, so a
    call after Close has started returns ErrConnectionClosed and registers
    nothing. Because the check and the registration share the mutex with the
    Close cleanup sweep, a racing registration is either swept by Close or
    refused outright — no interleaving leaks.
  • If subscriptionsListen reports an error, the registration is rolled back
    (entry removed and cancel func called), so a later Subscribe retries the
    listen instead of treating the URI as already subscribed.

Unsubscribe and idempotent double-Subscribe behavior are unchanged.

Tests

  • TestResourceSubscriptions_SubscribeClosedSession: Subscribe after Close
    returns ErrConnectionClosed and leaves no resourceSubs entry.
  • TestResourceSubscriptions_SubscribeListenFailureRollsBack: a failed listen
    send (injected via AddSendingMiddleware) rolls back the registration and a
    retry re-attempts the listen.
  • TestResourceSubscriptions_SubscribeCloseRace: 50 rounds of racing Close
    and Subscribe asserting that a failed Subscribe never leaves an entry.

go test -race ./mcp/ and go test ./... pass; gofmt, go vet, and
staticcheck are clean.

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.

ClientSession.Subscribe can silently succeed while the session is closing

1 participant