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

Abierto
#1,545 1 comentario 0 reacciones 1 asignado Ver en GitHub

Los mantenedores suelen responder en 1 día

@nahapetyan-serob ya está trabajando en esto.

Desde el 25/11/2026.

  • #1546 de @PerryLink — cerrado sin fusionar

Evaluación

Este issue todavía no se ha evaluado.

Descripción

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.

Lenguaje dominante
Go
Estrellas
5.4k
Forks
623
Merge medio
22 h 10 min
PR fusionados (30 d)
30

Preparar el entorno

Abrir en Codespaces

Inicia el contenedor de desarrollo del proyecto en tu navegador, con tu propia cuenta de GitHub.

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de modelcontextprotocol/go-sdk

Todos los issues de modelcontextprotocol/go-sdk

Issues similares

Más issues de Go

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.