go-sdk icon indicating copy to clipboard operation
go-sdk copied to clipboard

mcp: Client.Connect succeeds after subscriptions/listen is rejected

Open jstar0 opened this issue 3 months ago • 2 comments

When a v2026-07-28 streamable HTTP client has notification handlers installed, Client.Connect opens subscriptions/listen after server/discover. If the server immediately rejects that subscriptions/listen request with a JSON-RPC error, Connect currently still returns a usable session.

What I did:

I added a regression test with a fake streamable server that returns a successful server/discover response, then returns a JSON-RPC InvalidParams error for subscriptions/listen. The client is configured with ToolListChangedHandler so it attempts the listen call during connect.

What I saw:

On current origin/main at 64e454e35c23, the regression test fails because Connect succeeds even though the listen request was rejected.

What I expected:

Connect should fail and surface the subscriptions/listen error. Otherwise callers believe notification subscriptions are active when the server already rejected them.

Version:

origin/main at 64e454e35c23

Go version:

go version go1.26.5 darwin/arm64

jstar0 avatar Aug 13 '26 22:08 jstar0

Adding another manifestation of this root cause, plus verification results for #1170.

The same defect also affects an explicit ClientSession.Subscribe()

This issue describes Connect succeeding after the auto-opened listen is rejected. The same root cause also makes an explicit Subscribe() call silently succeed on a fully healthy, already-connected session when the server rejects the URI.

I hit this in a downstream server whose SubscribeHandler returns mcp.ResourceNotFoundError for resources the authenticated user is not allowed to watch. The practical consequence is that a client cannot distinguish "subscribed" from "denied" — an authorization decision made by the server is invisible to the caller.

Minimal reproduction against main (b8c53fe), depending only on this SDK:

package main

import (
	"context"
	"fmt"
	"net/http"
	"net/http/httptest"

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

func main() {
	ctx := context.Background()

	srv := mcp.NewServer(&mcp.Implementation{Name: "repro-server", Version: "1.0.0"}, &mcp.ServerOptions{
		// Deny every subscription, exactly as an authorization check would.
		SubscribeHandler: func(_ context.Context, req *mcp.SubscribeRequest) error {
			return mcp.ResourceNotFoundError(req.Params.URI)
		},
		UnsubscribeHandler: func(context.Context, *mcp.UnsubscribeRequest) error { return nil },
	})
	// A resource must exist for the server to advertise resources.subscribe.
	srv.AddResource(
		&mcp.Resource{URI: "repro://resource/1", Name: "r1"},
		func(context.Context, *mcp.ReadResourceRequest) (*mcp.ReadResourceResult, error) {
			return &mcp.ReadResourceResult{Contents: []*mcp.ResourceContents{{URI: "repro://resource/1", Text: "x"}}}, nil
		},
	)

	handler := mcp.NewStreamableHTTPHandler(
		func(*http.Request) *mcp.Server { return srv },
		&mcp.StreamableHTTPOptions{Stateless: true}, // required to negotiate 2026-07-28
	)
	ts := httptest.NewServer(handler)
	defer ts.Close()

	sess, err := mcp.NewClient(&mcp.Implementation{Name: "repro-client", Version: "1.0.0"}, nil).
		Connect(ctx, &mcp.StreamableClientTransport{
			Endpoint:             ts.URL,
			DisableStandaloneSSE: true,
			MaxRetries:           -1,
		}, nil)
	if err != nil {
		panic(err)
	}
	defer sess.Close()

	fmt.Printf("negotiated protocol = %s\n", sess.InitializeResult().ProtocolVersion)
	fmt.Printf("Subscribe() returned: %v\n", sess.Subscribe(ctx, &mcp.SubscribeParams{URI: "repro://watch/denied"}))
}

Output on main, with the HTTP exchange captured by a logging RoundTripper:

wire | server/discover      -> HTTP 200  (text/event-stream)
negotiated protocol = 2026-07-28
wire | subscriptions/listen -> HTTP 400  {"jsonrpc":"2.0","id":2,"error":{"code":-32602,"message":"Resource not found","data":{"uri":"repro://watch/denied"}}}
Subscribe() returned: <nil>

The server answers correctly. Only the client loses the error.

Root cause note

For completeness, since it applies to both entry points: callSubscriptionsListen (mcp/transport.go) has no return value at all, and defaultSendingMethodHandler (mcp/shared.go) therefore returns res, nil unconditionally for this one method while every other method propagates errors.

One detail worth pointing out: the error check at the Connect call site already exists on main (mcp/client.go):

if err := cs.subscriptionsListen(listenCtx, subscribeParams); err != nil {
	cancelListen()
	return nil, fmt.Errorf("opening subscriptions/listen: %w", err)
}

It is simply unreachable, because subscriptionsListen can never return an error. So #1170's shared.go/transport.go change is what makes this pre-existing check live.

Verification of #1170

I checked out a8560a0 and re-ran the reproduction above five times. All five surfaced the rejection:

Subscribe() returned: sending "subscriptions/listen": Resource not found: rejected by transport: Bad Request

So the fix covers the explicit Subscribe() path as well, not just Connect.

I had initially suspected the default: branch would make this racy for HTTP transports (the response not having arrived yet at the moment of the select). That was wrong: the streamable client performs the POST synchronously and retires the call on a non-2xx response, so call.Done() is already closed. The rejected by transport in the message above is that path.

Regression check: go test ./mcp/... on a8560a0 fails only TestServerConformance/resources.txtar, and that test fails identically on main in my environment — the diff is "blob": "Q29udGVudHMK" vs "Q29udGVudHMNCg==", i.e. Contents\n vs Contents\r\n, a CRLF checkout artifact on Windows. Unrelated to this change.

One limitation of #1170

Because the select is non-blocking, it only observes a terminal response that has already arrived. That holds for a go-sdk server, which rejects with a non-2xx status. It does not hold for a peer that answers subscriptions/listen with HTTP 200 and delivers the JSON-RPC error on the stream instead:

case "subscriptions/listen":
	w.Header().Set("Content-Type", "text/event-stream")
	w.WriteHeader(http.StatusOK)
	w.(http.Flusher).Flush()
	time.Sleep(50 * time.Millisecond)
	fmt.Fprintf(w, "event: message\ndata: {\"jsonrpc\":\"2.0\",\"id\":%s,\"error\":{\"code\":-32602,\"message\":\"Resource not found\"}}\n\n", id)

With #1170 applied, Subscribe() still returns <nil> for that server.

I don't know whether that response shape is considered conformant — the spec describes the listen response as an ordinary id-correlated JSON-RPC response and does not constrain the HTTP status — but #1193 suggests real deployments do vary in how they reject this stream. Flagging it in case it belongs in the scope of this fix, or is worth a follow-up.

Environment: go1.27.0 windows/amd64, go-sdk main at b8c53fe and #1170 at a8560a0.

scottlz0310-user avatar Aug 25 '26 06:08 scottlz0310-user

Closing as working as intended. The listen that Connect opens for list-changed notifications is optional: the session stays fully usable if the server rejects it, and some servers do. Failing Connect would break those clients. Seeing that a subscription was rejected or has ended is a fair need. #1284 proposes a handler for it, and we can extend that to the list-changed listen. Closing #1170 for the same reason.

guglielmo-san avatar Oct 05 '26 16:10 guglielmo-san