Skip to content

mcp: a second subscriptions/listen for the same URI silences the first #1489

Closed

Description

@jmrplens

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?

A follow-up to #1359: #1360 applied the first shape set out there, which leaves two listens held open at once on one URI as they were.

On a 2026-07-28 session I open two subscriptions/listen streams for one resource URI. Both are acknowledged and stay open, but Server.ResourceUpdated delivers only on the second, and once the second is cancelled the first, still open, receives nothing.

I expected each listen to get the update with its own subscriptionId: both acknowledgments name the URI in notifications, which "reflects the subset the server agreed to honor" (Acknowledgment).

resourceSubscriptions holds one request ID per URI and session (server.go#L83), so the second listen overwrites the first's (L1300), and the second's teardown then deletes the entry as its own (L1326-L1327). No teardown can bring the first ID back.

The keying by session that #1275 kept can stay: the session's entry would hold every open listen's ID for the URI rather than only the latest, and ResourceUpdated would deliver on each (the second shape in #1359). I can send a PR if that works for you, or a line for the docs if you would rather leave this case unsupported.

How to reproduce

// Two subscriptions/listen streams for one URI on one 2026-07-28 session.
package main

import (
	"context"
	"encoding/json"
	"fmt"
	"sync"
	"time"

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

const uri = "file:///a"

func main() {
	ctx := context.Background()
	unsubscribed := make(chan struct{}, 2)
	server := mcp.NewServer(&mcp.Implementation{Name: "s", Version: "v1"}, &mcp.ServerOptions{
		SubscribeHandler:   func(context.Context, *mcp.SubscribeRequest) error { return nil },
		UnsubscribeHandler: func(context.Context, *mcp.UnsubscribeRequest) error { unsubscribed <- struct{}{}; return nil },
	})
	server.AddResource(&mcp.Resource{URI: uri, Name: "a"}, func(context.Context, *mcp.ReadResourceRequest) (*mcp.ReadResourceResult, error) {
		return &mcp.ReadResourceResult{}, nil
	})
	st, ct := mcp.NewInMemoryTransports()
	if _, err := server.Connect(ctx, st, nil); err != nil {
		panic(err)
	}
	conn, err := ct.Connect(ctx)
	if err != nil {
		panic(err)
	}

	var mu sync.Mutex
	var got []string // subscriptionId of each resources/updated received
	acks := make(chan struct{}, 2)
	go func() {
		for {
			msg, err := conn.Read(ctx)
			if err != nil {
				return
			}
			req, ok := msg.(*jsonrpc.Request)
			if !ok {
				continue
			}
			var p struct {
				Meta          map[string]any  `json:"_meta"`
				Notifications json.RawMessage `json:"notifications"`
			}
			json.Unmarshal(req.Params, &p)
			id := fmt.Sprint(p.Meta[mcp.MetaKeySubscriptionID])
			switch req.Method {
			case "notifications/subscriptions/acknowledged":
				fmt.Printf("listen %s acknowledged with %s\n", id, p.Notifications)
				acks <- struct{}{}
			case "notifications/resources/updated":
				mu.Lock()
				got = append(got, id)
				mu.Unlock()
			}
		}
	}()
	send := func(s string) {
		m, err := jsonrpc.DecodeMessage([]byte(s))
		if err != nil {
			panic(err)
		}
		if err := conn.Write(ctx, m); err != nil {
			panic(err)
		}
	}
	update := func(when string) {
		mu.Lock()
		got = nil
		mu.Unlock()
		server.ResourceUpdated(ctx, &mcp.ResourceUpdatedNotificationParams{URI: uri})
		time.Sleep(200 * time.Millisecond)
		mu.Lock()
		defer mu.Unlock()
		fmt.Printf("%s: update delivered on listens %v\n", when, got)
	}

	listen := `{"jsonrpc":"2.0","id":%d,"method":"subscriptions/listen","params":{"_meta":{` +
		`"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}},` +
		`"notifications":{"resourceSubscriptions":["` + uri + `"]}}}`
	send(fmt.Sprintf(listen, 1))
	<-acks
	send(fmt.Sprintf(listen, 2))
	<-acks
	update("listens 1 and 2 open")

	send(`{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":2}}`)
	<-unsubscribed
	time.Sleep(100 * time.Millisecond)
	update("listen 2 cancelled, listen 1 still open")
}

Where did you hit this?

I hit it in gitlab-mcp-server, an MCP server for GitLab on this SDK, over stdio. With two listens open on the URI of one GitLab issue, each change of the issue reaches only the second; once the second is cancelled, the first stays open and gets nothing while the server keeps polling GitLab for it, and ResourceUpdated logs a subscriber_count of 0.

Go MCP SDK version

v1.8.0 (same output on main at eafb671)

Go version

go version go1.27.3 linux/amd64

Logs

listen 1 acknowledged with {"resourceSubscriptions":["file:///a"]}
listen 2 acknowledged with {"resourceSubscriptions":["file:///a"]}
listens 1 and 2 open: update delivered on listens [2]
listen 2 cancelled, listen 1 still open: update delivered on listens []

Activity

  1. PoisonGodv commented on Nov 2, 2026

    @PoisonGodv

    I'd like to work on this if it can be assigned to me. (Correction to my earlier wording: I have read the issue but have not yet reproduced it locally, and I have not confirmed where in the code the fix belongs.)

    Plan: first write a failing test that opens two subscriptions/listen calls for the same URI and checks the first one stays valid, then fix the subscription bookkeeping so the second call doesn't invalidate the first. I'll report back here with the reproduction before opening a PR.

    Written with AI assistance (Hermes Agent / Claude Sonnet 5.5).

  2. jmrplens commented on Nov 2, 2026

    @jmrplens
    ContributorAuthor

    I have a fix ready: one commit on my fork, jmrplens/go-sdk@e63d737, with a test that fails on main (an update reaches only the second listen) and passes with it; go test -race ./... passes. If you assign this to me I'll open the PR, or feel free to apply the patch below as it is. @PoisonGodv, thanks for offering; this may save you the work.

    Patch
    From e63d737bee4d588755fed2f2ce9ea1db9ea24a23 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jos=C3=A9=20M=2E=20Requena=20Plens?= <[email protected]>
    Date: Mon, 2 Nov 2026 00:40:09 +0100
    Subject: [PATCH] mcp: notify every listen held open on a resource URI
    
    resourceSubscriptions holds one request ID per URI and session, so a
    second subscriptions/listen for a URI the session already holds
    replaced the first listen's ID with its own. Both listens were
    acknowledged with the URI, but ResourceUpdated delivered only on the
    second, and once the second ended its teardown removed the entry and
    the first, still open, received nothing.
    
    The session's entry now holds the ID of every open listen for the URI,
    and ResourceUpdated delivers the update on each of them under its own
    subscription ID. A listen's teardown removes only its own ID, and the
    entry with the last one. resources/subscribe and resources/unsubscribe
    keep one ID per URI and session, as before, and the SubscribeHandler
    and UnsubscribeHandler are still called once for each listen.
    
    Fixes #1489
    ---
     mcp/mcp_test.go    | 193 +++++++++++++++++++++++++++++++++++++++++++++
     mcp/server.go      |  89 ++++++++++++++-------
     mcp/server_test.go |  55 ++++++++++++-
     3 files changed, 307 insertions(+), 30 deletions(-)
    
    diff --git a/mcp/mcp_test.go b/mcp/mcp_test.go
    index a9b825b..0871553 100644
    --- a/mcp/mcp_test.go
    +++ b/mcp/mcp_test.go
    @@ -3808,6 +3808,199 @@ func TestSubscriptionsListen_ResubscribeOutlivesEarlierTeardown(t *testing.T) {
     	})
     }
     
    +// uriListens is a 2026-07-28 session with a server that serves one resource,
    +// for the tests that hold listens open on its URI. The server counts the calls
    +// to its SubscribeHandler and UnsubscribeHandler, and the client reports each
    +// listen's acknowledgment and each update with its subscription ID.
    +type uriListens struct {
    +	t                        *testing.T
    +	ctx                      context.Context
    +	uri                      string
    +	server                   *Server
    +	ss                       *ServerSession
    +	cs                       *ClientSession
    +	events                   chan subListenEvent
    +	subscribes, unsubscribes atomic.Int32
    +}
    +
    +func newURIListens(t *testing.T, uri string) *uriListens {
    +	t.Helper()
    +	f := &uriListens{t: t, uri: uri, events: make(chan subListenEvent, 16)}
    +	f.server = NewServer(testImpl, &ServerOptions{
    +		SubscribeHandler: func(context.Context, *SubscribeRequest) error {
    +			f.subscribes.Add(1)
    +			return nil
    +		},
    +		UnsubscribeHandler: func(context.Context, *UnsubscribeRequest) error {
    +			f.unsubscribes.Add(1)
    +			return nil
    +		},
    +	})
    +	f.server.AddResource(&Resource{Name: "r1", URI: uri}, nil)
    +
    +	ct, st := NewInMemoryTransports()
    +	ss, err := f.server.Connect(context.Background(), st, nil)
    +	if err != nil {
    +		t.Fatalf("server connect: %v", err)
    +	}
    +	t.Cleanup(func() { ss.Close() })
    +	f.ss = ss
    +
    +	c := NewClient(testImpl, &ClientOptions{
    +		ResourceUpdatedHandler: func(_ context.Context, req *ResourceUpdatedNotificationRequest) {
    +			f.events <- subListenEvent{"updated", fmt.Sprint(req.Params.Meta[MetaKeySubscriptionID])}
    +		},
    +	})
    +	c.AddReceivingMiddleware(func(next MethodHandler) MethodHandler {
    +		return func(ctx context.Context, method string, req Request) (Result, error) {
    +			if method == notificationSubscriptionsAck {
    +				if cr, ok := req.(*ClientRequest[*SubscriptionsAcknowledgedParams]); ok && cr.Params != nil {
    +					f.events <- subListenEvent{"ack", fmt.Sprint(cr.Params.Meta[MetaKeySubscriptionID])}
    +				}
    +			}
    +			return next(ctx, method, req)
    +		}
    +	})
    +	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
    +	t.Cleanup(cancel)
    +	f.ctx = ctx
    +	cs, err := c.Connect(ctx, ct, &ClientSessionOptions{ProtocolVersion: protocolVersion20260728})
    +	if err != nil {
    +		t.Fatalf("client connect: %v", err)
    +	}
    +	t.Cleanup(func() { cs.Close() })
    +	f.cs = cs
    +	return f
    +}
    +
    +// listen opens a listen naming uris, and returns its subscription ID and the
    +// function that cancels it.
    +func (f *uriListens) listen(uris ...string) (string, context.CancelFunc) {
    +	f.t.Helper()
    +	listenCtx, cancel := context.WithCancel(f.ctx)
    +	f.t.Cleanup(cancel)
    +	go f.cs.subscriptionsListen(listenCtx, &SubscriptionsListenParams{
    +		Notifications: &NotificationSubscriptions{ResourceSubscriptions: uris},
    +	})
    +	return waitSubListenEvent(f.t, f.events, "ack").id, cancel
    +}
    +
    +// updates returns the subscription IDs of the updates received within d,
    +// returning as soon as there are n.
    +func (f *uriListens) updates(n int, d time.Duration) []string {
    +	f.t.Helper()
    +	var ids []string
    +	timeout := time.After(d)
    +	for len(ids) < n {
    +		select {
    +		case e := <-f.events:
    +			if e.kind != "updated" {
    +				f.t.Fatalf("got event %q, want %q", e.kind, "updated")
    +			}
    +			ids = append(ids, e.id)
    +		case <-timeout:
    +			return ids
    +		}
    +	}
    +	return ids
    +}
    +
    +// wantUpdate calls ResourceUpdated and checks the subscription IDs the update
    +// is delivered under, one delivery for each.
    +func (f *uriListens) wantUpdate(when string, want ...string) {
    +	f.t.Helper()
    +	if err := f.server.ResourceUpdated(f.ctx, &ResourceUpdatedNotificationParams{URI: f.uri}); err != nil {
    +		f.t.Fatalf("ResourceUpdated: %v", err)
    +	}
    +	got := f.updates(len(want), 5*time.Second)
    +	got = append(got, f.updates(1, notificationDelay*10)...)
    +	slices.Sort(got)
    +	slices.Sort(want)
    +	if !slices.Equal(got, want) {
    +		f.t.Errorf("%s: update delivered under subscription IDs %v, want %v", when, got, want)
    +	}
    +}
    +
    +// wantHandlerCalls checks how many times the SubscribeHandler and the
    +// UnsubscribeHandler have been called.
    +func (f *uriListens) wantHandlerCalls(when string, subscribes, unsubscribes int32) {
    +	f.t.Helper()
    +	if s, u := f.subscribes.Load(), f.unsubscribes.Load(); s != subscribes || u != unsubscribes {
    +		f.t.Errorf("%s: SubscribeHandler called %d times and UnsubscribeHandler %d, want %d and %d", when, s, u, subscribes, unsubscribes)
    +	}
    +}
    +
    +// wantUnsubscribed checks that no session is subscribed to the URI.
    +func (f *uriListens) wantUnsubscribed(when string) {
    +	f.t.Helper()
    +	f.server.mu.Lock()
    +	_, subscribed := f.server.resourceSubscriptions[f.uri]
    +	f.server.mu.Unlock()
    +	if subscribed {
    +		f.t.Errorf("%s: the session is still subscribed to %s", when, f.uri)
    +	}
    +}
    +
    +// TestSubscriptionsListen_EveryListenOnAURIIsNotified verifies that two
    +// listens held open at once on one URI each receive every update under their
    +// own subscription ID, whichever of them ends first, and that the
    +// SubscribeHandler and UnsubscribeHandler are still called once for each
    +// listen.
    +func TestSubscriptionsListen_EveryListenOnAURIIsNotified(t *testing.T) {
    +	for _, tc := range []struct {
    +		name           string
    +		laterEndsFirst bool
    +	}{
    +		{"later listen ends first", true},
    +		{"earlier listen ends first", false},
    +	} {
    +		t.Run(tc.name, func(t *testing.T) {
    +			f := newURIListens(t, "file:///r1")
    +			earlier, cancelEarlier := f.listen(f.uri)
    +			later, cancelLater := f.listen(f.uri)
    +			if later == earlier {
    +				t.Fatalf("second listen reused subscription ID %s", earlier)
    +			}
    +			f.wantHandlerCalls("both listens open", 2, 0)
    +			f.wantUpdate("both listens open", earlier, later)
    +
    +			endFirst, endLast, remaining := cancelEarlier, cancelLater, later
    +			if tc.laterEndsFirst {
    +				endFirst, endLast, remaining = cancelLater, cancelEarlier, earlier
    +			}
    +			endFirst()
    +			waitListens(t, f.ss, 1, "the first listen to end to unwind")
    +			// The handlers are told once for each listen, as before, so a
    +			// handler that counts them still holds the session subscribed.
    +			f.wantHandlerCalls("one listen ended", 2, 1)
    +			f.wantUpdate("one listen ended", remaining)
    +
    +			endLast()
    +			waitListens(t, f.ss, 0, "the other listen to unwind")
    +			f.wantHandlerCalls("both listens ended", 2, 2)
    +			f.wantUpdate("both listens ended")
    +			f.wantUnsubscribed("both listens ended")
    +		})
    +	}
    +}
    +
    +// TestSubscriptionsListen_URINamedTwiceIsNotifiedOnce verifies that a listen
    +// naming its URI twice receives each update once, and that the
    +// SubscribeHandler and UnsubscribeHandler are still called once for each time
    +// it names the URI.
    +func TestSubscriptionsListen_URINamedTwiceIsNotifiedOnce(t *testing.T) {
    +	f := newURIListens(t, "file:///r1")
    +	id, cancelListen := f.listen(f.uri, f.uri)
    +	f.wantHandlerCalls("listen open", 2, 0)
    +	f.wantUpdate("listen open", id)
    +
    +	cancelListen()
    +	waitListens(t, f.ss, 0, "the listen to unwind")
    +	f.wantHandlerCalls("listen ended", 2, 2)
    +	f.wantUpdate("listen ended")
    +	f.wantUnsubscribed("listen ended")
    +}
    +
     // TestSubscriptionsListen_ListChangedOutlivesEarlierTeardown verifies that the
     // auto-listen's teardown leaves in place a second listen's registration for
     // the same list-changed notification.
    diff --git a/mcp/server.go b/mcp/server.go
    index 465e4bf..9d86878 100644
    --- a/mcp/server.go
    +++ b/mcp/server.go
    @@ -77,11 +77,11 @@ type Server struct {
     	sessions                    []*ServerSession
     	sendingMethodHandler_       MethodHandler
     	receivingMethodHandler_     MethodHandler
    -	toolChangeSubscriptions     map[*ServerSession]jsonrpc.ID            // session -> requestID for "tools/changed"
    -	promptChangeSubscriptions   map[*ServerSession]jsonrpc.ID            // session -> requestID for "prompts/changed"
    -	resourceChangeSubscriptions map[*ServerSession]jsonrpc.ID            // session -> requestID for "resources/changed"
    -	resourceSubscriptions       map[string]map[*ServerSession]jsonrpc.ID // uri -> session -> requestID
    -	pendingNotifications        map[string]*time.Timer                   // notification name -> timer for pending notification send
    +	toolChangeSubscriptions     map[*ServerSession]jsonrpc.ID              // session -> requestID for "tools/changed"
    +	promptChangeSubscriptions   map[*ServerSession]jsonrpc.ID              // session -> requestID for "prompts/changed"
    +	resourceChangeSubscriptions map[*ServerSession]jsonrpc.ID              // session -> requestID for "resources/changed"
    +	resourceSubscriptions       map[string]map[*ServerSession][]jsonrpc.ID // uri -> session -> requestID of each subscription
    +	pendingNotifications        map[string]*time.Timer                     // notification name -> timer for pending notification send
     	// receiveMethods is the merged map of methods this server may receive
     	// from a client: it always contains the standard server methods (from
     	// serverMethodInfos) plus any custom methods registered via
    @@ -286,7 +286,7 @@ func NewServer(impl *Implementation, options *ServerOptions) *Server {
     		toolChangeSubscriptions:     make(map[*ServerSession]jsonrpc.ID),
     		promptChangeSubscriptions:   make(map[*ServerSession]jsonrpc.ID),
     		resourceChangeSubscriptions: make(map[*ServerSession]jsonrpc.ID),
    -		resourceSubscriptions:       make(map[string]map[*ServerSession]jsonrpc.ID),
    +		resourceSubscriptions:       make(map[string]map[*ServerSession][]jsonrpc.ID),
     		pendingNotifications:        make(map[string]*time.Timer),
     		receiveMethods:              receiveMethods,
     	}
    @@ -834,18 +834,16 @@ func (s *Server) notifySessions(n string) {
     
     	// Notify modern sessions only if they have an active subscription for
     	// this notification type.
    -	s.notifySubscribedSessions(subscribers, n, changeNotificationParams[n])
    +	s.notifySubscribedSessions(maps.All(subscribers), n, changeNotificationParams[n])
     }
     
     // notifySubscribedSessions delivers a list-changed or resource-updated
    -// notification to each session in subscribers, stamping the session's
    -// listen-request ID into the params' _meta so the receiving client can demultiplex
    -// notifications belonging to different concurrent listens.
    -func (s *Server) notifySubscribedSessions(subscribers map[*ServerSession]jsonrpc.ID, method string, makeParams func() Params) {
    -	if len(subscribers) == 0 {
    -		return
    -	}
    -	// One goroutine per session, each with its own deadline, so a session
    +// notification for each session and listen-request ID in subscribers, stamping
    +// the ID into the params' _meta so the receiving client can demultiplex
    +// notifications belonging to different concurrent listens. A session with
    +// several such listens appears once for each.
    +func (s *Server) notifySubscribedSessions(subscribers iter.Seq2[*ServerSession, jsonrpc.ID], method string, makeParams func() Params) {
    +	// One goroutine per notification, each with its own deadline, so a session
     	// whose write stalls neither delays nor fails the others (as in the
     	// notifySessions function in shared.go).
     	var wg sync.WaitGroup
    @@ -1257,30 +1255,49 @@ func (s *Server) ResourceUpdated(ctx context.Context, params *ResourceUpdatedNot
     	subscribedSessions := s.resourceSubscriptions[params.URI]
     	// Only add legacy sessions for the notification, new ones use the new notification mechanism.
     	var legacySessions []*ServerSession
    -	newSessions := make(map[*ServerSession]jsonrpc.ID)
    -	for sess, reqID := range subscribedSessions {
    +	newSessions := make(map[*ServerSession][]jsonrpc.ID)
    +	listens := 0
    +	for sess, reqIDs := range subscribedSessions {
     		if sess.InitializeParams().isNil() || sess.InitializeParams().ProtocolVersion < protocolVersion20260728 {
     			legacySessions = append(legacySessions, sess)
     		} else {
    -			newSessions[sess] = reqID
    +			newSessions[sess] = slices.Clone(reqIDs)
    +			listens += len(reqIDs)
     		}
     	}
     	s.mu.Unlock()
     
     	notifySessions(legacySessions, notificationResourceUpdated, params, s.opts.Logger)
     
    -	// Notify modern sessions, injecting the per-session subscription ID into the notification's metadata.
    -	s.notifySubscribedSessions(newSessions, notificationResourceUpdated, func() Params {
    +	// Notify modern sessions on each of their listens for the URI, injecting
    +	// the listen's subscription ID into the notification's metadata.
    +	s.notifySubscribedSessions(func(yield func(*ServerSession, jsonrpc.ID) bool) {
    +		for sess, reqIDs := range newSessions {
    +			for _, reqID := range reqIDs {
    +				if !yield(sess, reqID) {
    +					return
    +				}
    +			}
    +		}
    +	}, notificationResourceUpdated, func() Params {
     		p := *params
     		return &p
     	})
     	s.opts.Logger.Info("resource updated notification sent",
     		"uri", params.URI,
    -		"subscriber_count", len(legacySessions)+len(newSessions))
    +		"subscriber_count", len(legacySessions)+listens)
     	return nil
     }
     
     func (s *Server) subscribe(ctx context.Context, req *SubscribeRequest) (*emptyResult, error) {
    +	return s.startSubscription(ctx, req, false)
    +}
    +
    +// startSubscription subscribes the session to req.Params.URI under the request
    +// ID in ctx. A listen adds its ID to those of the session's other listens on
    +// the URI, since each listen is a subscription of its own; resources/subscribe
    +// replaces whatever the session held, as before.
    +func (s *Server) startSubscription(ctx context.Context, req *SubscribeRequest, listen bool) (*emptyResult, error) {
     	requestID, ok := ctx.Value(idContextKey{}).(jsonrpc.ID)
     	if !ok || !requestID.IsValid() {
     		return nil, fmt.Errorf("%w: subscribe requires a request ID", jsonrpc2.ErrInvalidRequest)
    @@ -1295,9 +1312,16 @@ func (s *Server) subscribe(ctx context.Context, req *SubscribeRequest) (*emptyRe
     	s.mu.Lock()
     	defer s.mu.Unlock()
     	if s.resourceSubscriptions[req.Params.URI] == nil {
    -		s.resourceSubscriptions[req.Params.URI] = make(map[*ServerSession]jsonrpc.ID)
    +		s.resourceSubscriptions[req.Params.URI] = make(map[*ServerSession][]jsonrpc.ID)
    +	}
    +	reqIDs := s.resourceSubscriptions[req.Params.URI][req.Session]
    +	switch {
    +	case !listen:
    +		reqIDs = []jsonrpc.ID{requestID}
    +	case !slices.Contains(reqIDs, requestID):
    +		reqIDs = append(reqIDs, requestID)
     	}
    -	s.resourceSubscriptions[req.Params.URI][req.Session] = requestID
    +	s.resourceSubscriptions[req.Params.URI][req.Session] = reqIDs
     	s.opts.Logger.Info("resource subscribed", "uri", req.Params.URI, "session_id", req.Session.ID(), "request_id", requestID)
     
     	return &emptyResult{}, nil
    @@ -1308,9 +1332,10 @@ func (s *Server) unsubscribe(ctx context.Context, req *UnsubscribeRequest) (*emp
     }
     
     // endSubscription ends the session's subscription to req.Params.URI. A zero
    -// listenID removes the entry whichever request made it; a valid one removes it
    -// only while the entry still records that listen, since a later listen on the
    -// session may have replaced it. The UnsubscribeHandler is called either way.
    +// listenID removes the session's entry whichever requests made it; a valid one
    +// removes only that listen's ID, and the entry with the last of them, since
    +// other listens on the session may hold the URI too. The UnsubscribeHandler is
    +// called either way.
     func (s *Server) endSubscription(ctx context.Context, req *UnsubscribeRequest, listenID jsonrpc.ID) (*emptyResult, error) {
     	if s.opts.UnsubscribeHandler == nil {
     		return nil, jsonrpc2.ErrMethodNotFound
    @@ -1323,7 +1348,13 @@ func (s *Server) endSubscription(ctx context.Context, req *UnsubscribeRequest, l
     	s.mu.Lock()
     	defer s.mu.Unlock()
     	if subscribedSessions, ok := s.resourceSubscriptions[req.Params.URI]; ok {
    -		if !listenID.IsValid() || subscribedSessions[req.Session] == listenID {
    +		var reqIDs []jsonrpc.ID // what the session still holds once this ends
    +		if listenID.IsValid() {
    +			reqIDs = slices.DeleteFunc(subscribedSessions[req.Session], func(id jsonrpc.ID) bool { return id == listenID })
    +		}
    +		if len(reqIDs) > 0 {
    +			subscribedSessions[req.Session] = reqIDs
    +		} else {
     			delete(subscribedSessions, req.Session)
     		}
     		if len(subscribedSessions) == 0 {
    @@ -1375,13 +1406,13 @@ func (s *Server) subscriptionsListen(ctx context.Context, req *SubscriptionsList
     	}()
     
     	for _, uri := range allowed.ResourceSubscriptions {
    -		_, err := s.subscribe(ctx, &SubscribeRequest{
    +		_, err := s.startSubscription(ctx, &SubscribeRequest{
     			Session: req.Session,
     			Params: &SubscribeParams{
     				URI:  uri,
     				Meta: req.Params.GetMeta(),
     			},
    -		})
    +		}, true)
     		if err != nil {
     			return nil, err
     		}
    diff --git a/mcp/server_test.go b/mcp/server_test.go
    index 02a461c..1ecee46 100644
    --- a/mcp/server_test.go
    +++ b/mcp/server_test.go
    @@ -12,6 +12,7 @@ import (
     	"fmt"
     	"log"
     	"log/slog"
    +	"maps"
     	"slices"
     	"strings"
     	"sync"
    @@ -2420,7 +2421,7 @@ func TestNotifySubscribedSessionsDoesNotShareMeta(t *testing.T) {
     	}
     
     	params := &ResourceUpdatedNotificationParams{URI: "test://r", Meta: Meta{"caller": "set"}}
    -	server.notifySubscribedSessions(subscribers, notificationResourceUpdated, func() Params {
    +	server.notifySubscribedSessions(maps.All(subscribers), notificationResourceUpdated, func() Params {
     		p := *params
     		return &p
     	})
    @@ -2444,6 +2445,58 @@ func TestNotifySubscribedSessionsDoesNotShareMeta(t *testing.T) {
     	}
     }
     
    +// TestServerSubscribe_LegacyResubscribeReplacesID verifies that on a session
    +// before 2026-07-28 a second resources/subscribe for a URI replaces the
    +// request ID the session holds for it rather than adding one, and that
    +// resources/unsubscribe then ends the subscription.
    +func TestServerSubscribe_LegacyResubscribeReplacesID(t *testing.T) {
    +	const uri = "file:///r1"
    +	server := NewServer(testImpl, &ServerOptions{
    +		SubscribeHandler:   func(context.Context, *SubscribeRequest) error { return nil },
    +		UnsubscribeHandler: func(context.Context, *UnsubscribeRequest) error { return nil },
    +	})
    +	server.AddResource(&Resource{Name: "r1", URI: uri}, nil)
    +
    +	ct, st := NewInMemoryTransports()
    +	ss, err := server.Connect(context.Background(), st, nil)
    +	if err != nil {
    +		t.Fatalf("server connect: %v", err)
    +	}
    +	defer ss.Close()
    +	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
    +	defer cancel()
    +	cs, err := NewClient(testImpl, nil).Connect(ctx, ct, &ClientSessionOptions{ProtocolVersion: protocolVersion20251125})
    +	if err != nil {
    +		t.Fatalf("client connect: %v", err)
    +	}
    +	defer cs.Close()
    +
    +	// held returns the request IDs the session holds for uri.
    +	held := func() []jsonrpc.ID {
    +		server.mu.Lock()
    +		defer server.mu.Unlock()
    +		return slices.Clone(server.resourceSubscriptions[uri][ss])
    +	}
    +	if err := cs.Subscribe(ctx, &SubscribeParams{URI: uri}); err != nil {
    +		t.Fatalf("Subscribe: %v", err)
    +	}
    +	first := held()
    +	if err := cs.Subscribe(ctx, &SubscribeParams{URI: uri}); err != nil {
    +		t.Fatalf("second Subscribe: %v", err)
    +	}
    +	second := held()
    +	if len(first) != 1 || len(second) != 1 || second[0] == first[0] {
    +		t.Errorf("the session holds request IDs %v after one resources/subscribe and %v after a second, want the second's ID alone", first, second)
    +	}
    +
    +	if err := cs.Unsubscribe(ctx, &UnsubscribeParams{URI: uri}); err != nil {
    +		t.Fatalf("Unsubscribe: %v", err)
    +	}
    +	if ids := held(); len(ids) != 0 {
    +		t.Errorf("the session holds request IDs %v after resources/unsubscribe, want none", ids)
    +	}
    +}
    +
     // TestServerHandle_LegacyCallBeforeInitialize asserts that a call carrying no
     // new-protocol `_meta` is refused on a session that has not completed
     // 'initialize', whichever branch of the method switch it lands in. The
    -- 
    2.39.5
    
  3. guglielmo-san commented on Nov 2, 2026

    @guglielmo-san
    Contributor

    @jmrplens I assigned the issue to you, feel free to send the PR now

  4. added 4 commits that reference this issue on Nov 2, 2026
    b3cec04
    655fc9f
    a991abe
    5bf666d
  5. added a commit that references this issue on Nov 3, 2026
    5f942ea
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions