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

Đang mở
#1,545 1 bình luận 0 reaction 1 người được giao Xem trên GitHub

Maintainer thường phản hồi trong vòng 1 ngày

@nahapetyan-serob đang làm issue này rồi.

Từ ngày 25/11/2026.

  • #1546 của @PerryLink — đã đóng, không merge

Đánh giá

Issue này chưa được đánh giá.

Mô tả

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.

Ngôn ngữ chính
Go
Star
5.4k
Fork
623
Merge trung bình
22 giờ 10 phút
Pull request đã merge (30 ngày)
30

Chuẩn bị môi trường

Mở trong Codespaces

Khởi chạy dev container của dự án ngay trên trình duyệt, bằng tài khoản GitHub của bạn.

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Issue khác của modelcontextprotocol/go-sdk

Tất cả issue của modelcontextprotocol/go-sdk

Issue tương tự

Thêm issue về Go

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.