Skip to content

mcp/transport.go call() attempts to call Notify() on a failed connection #882

Closed

Description

@smlx

Describe the bug
I am using mcp.StreamableClientTransport with an OAuthHandler. As documented, this handler will automatically be invoked by go-sdk on e.g. a 401 from the MCP endpoint.

My client implement an interactive OAuth2 authorization flow using the newly exposed APIs in v1.5.0-pre.

The behaviour I am seeing that I believe to be a bug is this:

  1. I configure a new MCP server endpoint in my client config.
  2. My client tries to use the MCP server via the StreamableClientTransport.
  3. It receives a 401 and calls Authorize() on my OAuthHandler.
  4. The context passed to Authorize() times out.
  5. In the switch statement in call(), the execution flow enters the case where ctx.Err() != nil. Here, conn.Notify is called. This Notify call, of course, receives a 401 which then calls Authorize() on my handler again.

In the case of my client, this prompts the user for interactive authorization again, even though the timeout has already cancelled the authorization request.

Relevant code is here:

go-sdk/mcp/transport.go

Lines 213 to 223 in 862d78a

call := conn.Call(ctx, method, params)
err := call.Await(ctx, result)
switch {
case errors.Is(err, jsonrpc2.ErrClientClosing), errors.Is(err, jsonrpc2.ErrServerClosing):
return fmt.Errorf("%w: calling %q: %v", ErrConnectionClosed, method, err)
case ctx.Err() != nil:
// Notify the peer of cancellation.
err := conn.Notify(xcontext.Detach(ctx), notificationCancelled, &CancelledParams{
Reason: ctx.Err().Error(),
RequestID: call.ID().Raw(),
})

To Reproduce
Steps to reproduce the behavior:

  1. Set up a StreamableClientTransport with an OAuthHandler.
  2. Use the transport without setting up authorization.
  3. Pass a context with a short timeout to Authorize(), and wait for it to expire before returning.

Expected behavior
I would expect cancelling the context passed to Authorize() to indicate that the connection should be abandoned and not to use it for any further communication.

Logs
n/a

Additional context
n/a

Activity

  1. added theissue type on Apr 7, 2026
  2. added
    needs investigation
    P2
    on Apr 7, 2026
  3. ravyg commented on Apr 8, 2026

    @ravyg
    Contributor

    I tracked through this and the bug needs a fix in two layers. Posting here for visibility before I open a PR.

    Root cause

    The Notify(notificationCancelled) in mcp/transport.go:call() is unconditional. When the original Await fails because the user's OAuthHandler.Authorize() returned a cancelled context, the SDK still tries to send a "cancelled" notification back to the peer — but that notification has to travel through the same auth.HTTPTransport, which has no TokenSource stored, gets a fresh 401, and re-invokes Authorize(). The user sees a second prompt for the request they just abandoned.

    Proposed fix (two parts, defense-in-depth)

    Part 1 — mcp/transport.go call()

    Bound the cancellation Notify with a fresh context.Background()-derived context so it can never block the caller's return path on a degraded connection.

    case ctx.Err() != nil:
        // Best-effort notify; bounded so a degraded connection (e.g. expired
        // OAuth flow) cannot re-trigger expensive recovery on the caller's
        // path. See #882.
        notifyCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
        defer cancel()
        notifyErr := conn.Notify(notifyCtx, notificationCancelled, &CancelledParams{
            Reason:    ctx.Err().Error(),
            RequestID: call.ID().Raw(),
        })
        conn.Retire(call, ctx.Err())
        return errors.Join(ctx.Err(), notifyErr)

    Part 2 — auth/client.go HTTPTransport

    Track the last handler error. When Authorize() returns a context-cancelled error, store it. Subsequent RoundTrip calls short-circuit instead of re-invoking the handler — directly enforcing the expectation in the bug report that "cancelling Authorize should indicate the connection should be abandoned."

    type HTTPTransport struct {
        handler     OAuthHandler
        mu          sync.Mutex
        opts        HTTPTransportOptions
        lastAuthErr error // sticky after a cancelled handler
    }
    
    func (t *HTTPTransport) RoundTrip(req *http.Request) (*http.Response, error) {
        t.mu.Lock()
        if t.lastAuthErr != nil {
            err := t.lastAuthErr
            t.mu.Unlock()
            return nil, err
        }
        t.mu.Unlock()
        // ... existing flow ...
        // On 401 path, after ts, err := t.handler(req, resp):
        //   if err != nil {
        //       if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
        //           t.lastAuthErr = err  // make it sticky
        //       }
        //       return nil, err
        //   }
    }

    Why both parts

    Part 1 only Part 2 only Both
    Caller doesn't hang on doomed Notify ✅ ❌ ✅
    User isn't re-prompted to authorize ❌ (background notify still triggers handler) ✅ ✅
    Matches reporter's stated expectation ❌ ✅ ✅

    Part 1 prevents the hang, Part 2 prevents the re-prompt. They're independent.

    Behavioral impact

    • Healthy connections and successful Authorize: unchanged
    • Cancelled Authorize: the transport is cleanly dead — caller gets the cancellation error immediately, no re-prompts. The user must construct a new client/transport to retry. This matches the reporter's mental model.

    Test plan

    • Fake OAuthHandler that records invocation count and returns ctx.Err()
    • Regression test: Initialize with a tight deadline → assert handler invoked exactly once, caller returns within bounded time
    • Test that a fresh HTTPTransport after the failed one works normally

    Will open a PR shortly.

  4. added a commit that references this issue on Apr 8, 2026
    88305e8
  5. added a commit that references this issue on Apr 9, 2026
    ed376d5
  6. added 2 commits that reference this issue on Apr 16, 2026
    10a5638
    ee7d07d
  7. added a commit that references this issue on Apr 24, 2026
    0f5ca92
  8. added a commit that references this issue on Apr 24, 2026
    db50910
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    P2needs investigation

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions