mcp: an ended subscriptions/listen stays subscribed when UnsubscribeHandler returns an error

オープン
#1,545 コメント 1 件 リアクション 0 件 担当者 1 名 GitHub で見る

メンテナーはふだん 1 日以内に返信

@nahapetyan-serob がすでに取り組んでいます。

2026年11月25日 から。

  • #1546 @PerryLink による — マージされずにクローズ

評価

この issue はまだ評価されていません。

説明

Checklist
  • I searched the existing issues, and this has not been reported before.
  • This is a real problem that I ran into myself, using the latest release of the SDK.
  • I ran into it in a production system, not in a toy example, a benchmark, or an automated or AI-driven scan of the code.
  • I (a human) examined the relevant SDK code, and wrote or reviewed every line of this report. It is not unreviewed AI output.
  • This report is brief and concise, and sticks to the facts needed to understand the problem.
What happened?

With protocol version 2026-07-28, after Unsubscribe the server keeps an ended subscriptions/listen registered if UnsubscribeHandler returns an error, and ResourceUpdated keeps notifying it. A handler that returns ctx.Err() is enough to trigger this, because the context passed to UnsubscribeHandler at listen teardown is already cancelled.

  • In v1.8.0 (3f3b699b2b67e1ed033a63d6651671dab53c2d32): subscriptionsListen defers s.unsubscribe(ctx, ...) (mcp/server.go:1297), which runs after <-ctx.Done() (:1316). unsubscribe returns on the handler error (:1239-1240) before delete(subscribedSessions, req.Session) (:1246), leaving 1 stale entry for the session.
  • On main (a5f29d0263c94c573654ff4c0279d2095a956c4f): subscriptionsListen defers s.endSubscription(ctx, ..., requestID) (mcp/server.go:1425), which runs after <-ctx.Done() (:1444). endSubscription returns on the handler error (:1326-1327) before removeListen (:1334), and the deferred call discards the error. Because main stores a slice of request IDs per session ([]jsonrpc.ID), entries now accumulate across cycles: over the in-memory transport, 50 subscribe/unsubscribe cycles leave 50 entries registered, and a single ResourceUpdated delivers 50 notifications. Entries are cleared when the session disconnects. Over Streamable HTTP I saw no accumulation (stateless, 2026-07-28; the stateful server negotiated 2025-11-25). stdio was not tested.

By contrast, the list-changed registrations in subscriptionsListen are removed unconditionally on teardown.

Expected: a listen that has ended is no longer registered, whatever UnsubscribeHandler returns. An explicit resources/unsubscribe (!listenID.IsValid() on main) can still be refused by the handler.

Suggested fix (on main): in endSubscription, only return before removeListen when err != nil && !listenID.IsValid(), and return err after removing the ended listenID. I have a patch with tests ready; go test ./... and go vet ./mcp/ pass with it.

Separate question for maintainers: should the teardown call also give UnsubscribeHandler a live context (for example context.WithoutCancel with a bounded timeout), so that its own cleanup can run?

Related, but different: #1359 (closed) is the opposite symptom, an update that is never delivered. #1360 (merged) fixed a teardown removing another listen's entry; here the teardown removes nothing when the handler errors. #1263 (open) is about the server not being able to send notifications/cancelled for a listen.

How to reproduce
package main

import (
	"context"
	"fmt"
	"sync/atomic"
	"time"

	"github.com/modelcontextprotocol/go-sdk/mcp"
)

func main() {
	ctx := context.Background()
	const uri = "file:///r1"

	server := mcp.NewServer(&mcp.Implementation{Name: "server", Version: "v1"}, &mcp.ServerOptions{
		SubscribeHandler: func(context.Context, *mcp.SubscribeRequest) error { return nil },
		// A handler that respects its context.
		UnsubscribeHandler: func(ctx context.Context, _ *mcp.UnsubscribeRequest) error { return ctx.Err() },
	})
	server.AddResource(&mcp.Resource{Name: "r1", URI: uri}, nil)
	ct, st := mcp.NewInMemoryTransports()
	if _, err := server.Connect(ctx, st, nil); err != nil {
		panic(err)
	}

	var updates atomic.Int32
	client := mcp.NewClient(&mcp.Implementation{Name: "client", Version: "v1"}, &mcp.ClientOptions{
		ResourceUpdatedHandler: func(context.Context, *mcp.ResourceUpdatedNotificationRequest) { updates.Add(1) },
	})
	cs, err := client.Connect(ctx, ct, &mcp.ClientSessionOptions{ProtocolVersion: "2026-07-28"})
	if err != nil {
		panic(err)
	}
	defer cs.Close()

	for i := 0; i < 3; i++ {
		if err := cs.Subscribe(ctx, &mcp.SubscribeParams{URI: uri}); err != nil {
			panic(err)
		}
		time.Sleep(200 * time.Millisecond)
		if err := cs.Unsubscribe(ctx, &mcp.UnsubscribeParams{URI: uri}); err != nil {
			panic(err)
		}
		time.Sleep(200 * time.Millisecond)
	}

	if err := server.ResourceUpdated(ctx, &mcp.ResourceUpdatedNotificationParams{URI: uri}); err != nil {
		panic(err)
	}
	time.Sleep(500 * time.Millisecond)
	fmt.Printf("after 3 subscribe/unsubscribe cycles, one ResourceUpdated delivered %d notifications\n", updates.Load())
}

Expected 0:

  • Output on v1.8.0: after 3 subscribe/unsubscribe cycles, one ResourceUpdated delivered 1 notifications (1 stale entry remains because the registry holds one request ID per session).
  • Output on main (a5f29d0263c94c573654ff4c0279d2095a956c4f): after 3 subscribe/unsubscribe cycles, one ResourceUpdated delivered 3 notifications (1 stale entry accumulated per cycle).
Where did you hit this?

Not in production: found during an AI-assisted code review, then reproduced with the program above.

Go MCP SDK version

v1.8.0 and main at a5f29d0263c94c573654ff4c0279d2095a956c4f

Go version

go version go1.27.4 windows/amd64

AI disclosure: I used AI tools to find this, reproduce it and draft the report.

Reported by: René Atencio Roa — Founder, Alekore Systems Inc.

主要言語
Go
スター
5.4k
フォーク
623
平均マージ
22時間 10分
マージ済み PR(30日)
30

環境構築

Codespaces で開く

このプロジェクトの開発コンテナを、あなたの GitHub アカウントでブラウザ上に起動します。

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

modelcontextprotocol/go-sdk のほかの issue

modelcontextprotocol/go-sdk の issue をすべて見る

似ている issue

Go の issue をもっと見る

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。