mcp: an ended subscriptions/listen stays subscribed when UnsubscribeHandler returns an error
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):subscriptionsListendeferss.unsubscribe(ctx, ...)(mcp/server.go:1297), which runs after<-ctx.Done()(:1316).unsubscribereturns on the handler error (:1239-1240) beforedelete(subscribedSessions, req.Session)(:1246), leaving 1 stale entry for the session. - On
main(a5f29d0263c94c573654ff4c0279d2095a956c4f):subscriptionsListendeferss.endSubscription(ctx, ..., requestID)(mcp/server.go:1425), which runs after<-ctx.Done()(:1444).endSubscriptionreturns on the handler error (:1326-1327) beforeremoveListen(:1334), and the deferred call discards the error. Becausemainstores 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 singleResourceUpdateddelivers 50 notifications. Entries are cleared when the session disconnects. Over Streamable HTTP I saw no accumulation (stateless,2026-07-28; the stateful server negotiated2025-11-25).stdiowas 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
Inicia el contenedor de desarrollo del proyecto en tu navegador, con tu propia cuenta de GitHub.
- Sin Dockerfile ni archivo de Docker Compose
- Tiene una plantilla de pull request
- Leer la guía de contribución
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Más de modelcontextprotocol/go-sdk
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 82/100
modelcontextprotocol/go-sdk#1557 ·
Los mantenedores suelen responder en 1 día
-
Streamable HTTP (2026-07-28): tools/call with an out-of-range number in arguments fails because extractName decodes Arguments into anyQuizá libre de nuevo @beiryu la tomó hace 10 días y no hay ningún pull request abierto. Abierto
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
modelcontextprotocol/go-sdk#1534 · 1 comentario ·
Los mantenedores suelen responder en 1 día
-
Expose generic `SendNotification` on `ServerSession` for custom protocol extensionsQuizá libre de nuevo Un pull request para esta issue se cerró sin fusionarse. Abiertoneeds investigation
Dificultad 2/5 1-3 horas Aptitud para principiantes 72/100
modelcontextprotocol/go-sdk#745 · 13 comentarios · 1 reacción ·
Los mantenedores suelen responder en 1 día
-
Dificultad 5/5 Más de una semana Aptitud para principiantes 18/100
modelcontextprotocol/go-sdk#1555 ·
Los mantenedores suelen responder en 1 día
-
mcp: 2026-07-28 client runs elicitation and sampling handlers for standalone server requestsQuizá libre de nuevo Un pull request para esta issue se cerró sin fusionarse. Abierto
Dificultad 3/5 1-2 días Aptitud para principiantes 35/100
modelcontextprotocol/go-sdk#1552 ·
Los mantenedores suelen responder en 1 día
Todos los issues de modelcontextprotocol/go-sdk
Issues similares
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
Los mantenedores suelen responder en 1 día
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 76/100
Los mantenedores suelen responder en 1 día
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 86/100
apache/dubbo-admin#1659 ·
Los mantenedores suelen responder en 8 días
-
taskmanager: a failed v1alpha1 backup leaves the partial backup behindPosiblemente ocupada @arshil42 la tomó hoy. Abierto
Dificultad 2/5 1-3 horas Aptitud para principiantes 85/100
Los mantenedores suelen responder en 1 día
-
Packaging: support mise-en-placeAbierto
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100