Skip to content

[v2] Let a tool handler answer 401 invalid_token (re-authorization needed), not only a 403 scope challenge #3173

Open

Description

@buptliuhs

What happened?

Summary

A tool handler can discover mid-execution that the user must re-authorize (not merely grant more scopes), and today it has no way to turn that into an HTTP 401 + WWW-Authenticate challenge. The SDK converts the throw into a 200 + isError tool result, so the client doesn't start its re-auth flow until a later request.

This is the 401 invalid_token counterpart of #2957 (mid-handler 403 insufficient_scope), which I raised there in #2957 (comment). Filing separately so it can be tracked whether or not it ends up sharing #2957's mechanism.

Use case

Servers that proxy an upstream API with delegated OAuth: the MCP access token maps to an upstream refresh token stored server-side. The upstream provider can revoke that authorization at any time — a per-user connection cap evicting the oldest connection, or the user disconnecting the app in the upstream provider's settings. The MCP access token stays valid; the connection is unusable until the user re-authorizes.

The server usually only learns this from the upstream call inside a tool (the cached upstream access token still looks valid; the upstream API rejects it; the refresh is then rejected). A pre-dispatch check (requireBearerAuth, scopeChallenge) can't see it without an extra upstream call on every request.

Current behaviour

McpServer's tools/call handler converts any throw into CallToolResult { isError: true } (only UrlElicitationRequired is rethrown, as a JSON-RPC error, on the 2025 era). So the response is HTTP 200 and the model sees an error it can't act on. The client is challenged only on its next request, once the server's pre-dispatch check sees the cleared upstream link.

Observed client behaviour when the server does answer 401 + WWW-Authenticate on that tools/call

With a workaround (below), on the first failing tool call:

Client What the user sees
Claude (web) The tool card shows "Authentication required to use this tool" with a Connect button
Claude Code The server is marked as needing authentication; the user re-authenticates via /mcp
MCP Inspector (v2.13, 2026-07-28 era) Treated as auth_challenge / invalid_token; tries its refresh token, then "Session expired … re-authenticating"

So clients already handle a 401 on a tools/call well — the gap is only that servers can't produce one from inside a tool.

Current workaround

Wrap the handler's fetch face (FetchLikeMcpHandler, accepted by toNodeHandler) for tools/call only, hold the complete Response, and swap in a 401 when the tool recorded a lost upstream link:

function reauthOnLostConnection(handler: FetchLikeMcpHandler, state: { lost: boolean }): FetchLikeMcpHandler {
  return {
    async fetch(request, options) {
      const response = await handler.fetch(request, options);
      const body = await response.arrayBuffer(); // hold the whole response
      if (!state.lost) return new Response(body, response);
      return new Response(JSON.stringify({ error: "invalid_token" }), {
        status: 401,
        headers: { "Content-Type": "application/json", "WWW-Authenticate": challengeHeader },
      });
    },
  };
}

It works on both protocol eras, but only because the server never sends anything mid-request (no progress or other notifications), it discards the SDK's result after the fact, and every server with delegated upstream auth has to rediscover it.

Proposal

A typed error a tool handler can throw, e.g.:

throw new AuthChallengeError({ status: 401, error: "invalid_token", errorDescription: "Upstream session expired, re-authentication required" });
// and, for #2957: { status: 403, error: "insufficient_scope", scopes: [...] }

that tools/call rethrows (like UrlElicitationRequired), and the HTTP entry (createMcpHandler / the transports) answers with that status and a WWW-Authenticate header built the same way as requireBearerAuth's (including resource_metadata), on both protocol eras. If a message has already been sent on the response, fall back to an in-band JSON-RPC error, as discussed in #2957.

Retry safety: the handler should only throw this when the upstream call was rejected before processing (e.g. an upstream 401), so the client can safely retry the tool call after re-authorizing.

Alternatives considered

  • URL-mode elicitation: the spec's tool for "authorize with a third party". It fits when upstream authorization is separate from MCP authorization; it doesn't fit servers where re-running MCP OAuth is the upstream re-link, and it depends on per-client elicitation support, whereas a 401 is handled by every client that supports MCP authorization.
  • Checking upstream before every request: one extra upstream call per request against the upstream's rate limits.

What did you expect?

A typed error a tool handler can throw — e.g. AuthChallengeError({ status: 401, error: "invalid_token", errorDescription }), and for #2957 { status: 403, error: "insufficient_scope", scopes } — that tools/call rethrows (like UrlElicitationRequired), and the HTTP entry (createMcpHandler / the transports) answers with that status and a WWW-Authenticate header built the same way as requireBearerAuth's (including resource_metadata), on both protocol eras. If a message has already been sent on the response, fall back to an in-band JSON-RPC error, as discussed in #2957.

Retry safety: a handler should only throw this when the upstream call was rejected before processing (e.g. an upstream 401), so the client can safely retry the tool call after re-authorizing.

Code to reproduce

// Today: a tool that finds the user's upstream authorization revoked can only fail the call.
server.registerTool("list_items", { description: "…" }, async () => {
  const res = await fetch(upstreamUrl, { headers: { Authorization: `Bearer ${upstreamToken}` } });
  if (res.status === 401 && !(await refreshUpstream())) {
    // Upstream revoked the user's authorization. The best we can do is throw,
    // which the SDK turns into HTTP 200 + { isError: true } — not a 401 challenge.
    throw new Error("Upstream authorization revoked; re-authorization required");
  }
  return { content: [{ type: "text", text: await res.text() }] };
});

// Workaround: wrap the handler's fetch face for tools/call, hold the whole response,
// and swap in a 401 when the tool recorded a lost upstream link.
function reauthOnLostConnection(handler: FetchLikeMcpHandler, state: { lost: boolean }): FetchLikeMcpHandler {
  return {
    async fetch(request, options) {
      const response = await handler.fetch(request, options);
      const body = await response.arrayBuffer();
      if (!state.lost) return new Response(body, response);
      return new Response(JSON.stringify({ error: "invalid_token" }), {
        status: 401,
        headers: { "Content-Type": "application/json", "WWW-Authenticate": challengeHeader },
      });
    },
  };
}

SDK version

@modelcontextprotocol/server 2.3.1 (still present in 2.4.0), @modelcontextprotocol/node 2.1.1

Area

Auth

Activity

  1. added
    v2Ideas, requests and plans for v2 of the SDK which will incorporate major changes and fixes
    on Nov 11, 2026
  2. media-ctrl commented on Nov 11, 2026

    @media-ctrl
  3. 0xamlab commented on Nov 11, 2026

    @0xamlab

    Confirmed on main@919bb8e with a live upstream-401/failed-refresh reproduction. Both protocol eras returned HTTP 200, CallToolResult.isError: true, and no WWW-Authenticate. The 2026 path did so before commit (JSON) and after a progress notification (SSE); the 2025 fallback was already SSE in both cases. A pre-dispatch invalid-token control returned 401 correctly. The handler throw is consumed at packages/server/src/server/mcp.ts:316-321, so packages/server/src/server/middleware/bearerAuth.ts:203-221 is not reached. Could I be assigned to help align the typed auth/public API and #2957’s committed-response behavior before opening a PR?

  4. buptliuhs commented on Nov 11, 2026

    @buptliuhs
    Author

    @media-ctrl

    Thanks, agreed: 403 widens an existing grant, while 401 here means the grant is gone.

    On your open question, the server can tell the two cases apart, and only the second ever reaches the client:

    • Upstream token no longer valid, refresh succeeds: this shouldn't come up normally. The server tracks the upstream token's expires_in and refreshes it before it expires, so calls don't fail on expiry. It only happens when the token stops working before its expiry, for example because it was refreshed out of band or for a reason specific to that OAuth service. In that case the upstream API returns 401, and the server makes one extra call to the upstream OAuth server's token endpoint, refreshes, and retries once. The client never sees it.
    • Upstream grant revoked (refresh rejected with invalid_grant): the server answers 401 + WWW-Authenticate with its own error_description. It never forwards the upstream's text, which in our case echoes the rejected token.

    Transient upstream failures (5xx, timeouts) stay ordinary tool errors and never trigger a challenge. A rejected refresh is never retried, and re-authorization always goes through the upstream's sign-in again, so there's no loop.

    Today we get the 401 out of a tool call by buffering the whole response and swapping the isError result for the challenge. That only works because we're stateless and never stream mid-request. A second error class on the branch that already re-throws UrlElicitationRequired, sharing the WWW-Authenticate mapping with #2957, would remove the need for that.

  5. buptliuhs commented on Nov 11, 2026

    @buptliuhs
    Author

    @0xamlab Thanks for reproducing this on current main. Happy for you to take it, if the maintainers agree.

    One thing to settle first: what happens once the response is already committed (streaming has started)? Before that, an opt-in error class re-thrown next to UrlElicitationRequired could produce the 401. After it, the status can't change, so that case probably needs to be decided together with #2957.

    We work around this today by buffering the response and swapping the isError result for a 401, which only works because we never stream mid-request. Happy to test a branch against it.

  6. media-ctrl commented on Nov 11, 2026

    @media-ctrl
  7. 0xamlab commented on Nov 11, 2026

    @0xamlab

    Agreed. I’ll align with #2957 on one AuthChallengeError carrying status, RFC 6750 error, optional scopes, and a sanitized optional description. resource_metadata should come from the verified auth context, not arbitrary handler input. Before commitment, reuse bearerAuthChallengeResponse to send 401/403 + WWW-Authenticate: 401/invalid_token means re-authorize; 403/insufficient_scope means widen the grant. After commitment, emit an in-band JSON-RPC error with the same discriminator and metadata in data; never rewrite the HTTP status or imply automatic retry. I’ll wait for maintainer alignment on that committed-path contract before opening a PR.

  8. media-ctrl commented on Nov 11, 2026

    @media-ctrl
  9. A7mdMe commented on Nov 15, 2026

    @A7mdMe

    The consensus articulated above by @media-ctrl and @0xamlab regarding the strict separation between 401 invalid_token (grant revoked -> re-authorize; scopes prohibited) and 403 insufficient_scope (incremental consent -> widen grant; scopes required) matches our production findings with delegated-OAuth MCP servers.

    When a tool proxies an upstream provider (GitHub, Google, Jira, Slack, databases), swallowing mid-execution revocations into { isError: true } with HTTP 200 leaves the LLM client blind, unable to trigger re-authorization or render a "Connect" card.

    Here is the typed implementation pattern we landed in production to enforce this contract across both pre-commit HTTP and committed / stdio transports:

    1. Invariant-Enforcing Error Class with Upstream Sanitization

    Enforce at construction time that a 401 never carries scopes (preventing clients from entering infinite retry/widen loops), while sanitizing provider messages to prevent token leaks:

    export type AuthChallengeStatus = 401 | 403;
    export type AuthChallengeErrorCode = 'invalid_token' | 'insufficient_scope';
    
    export class AuthChallengeError extends Error {
      public readonly status: AuthChallengeStatus;
      public readonly authError: AuthChallengeErrorCode;
      public readonly errorDescription?: string;
      public readonly scopes?: string[];
      public readonly resourceMetadata?: string;
    
      constructor(options: {
        status: AuthChallengeStatus;
        errorDescription?: string;
        scopes?: string[];
        resourceMetadata?: string;
      }) {
        // Protocol Invariant: 401 means the grant is gone; scopes MUST NOT be present
        if (options.status === 401 && options.scopes && options.scopes.length > 0) {
          throw new Error("Scopes must not be specified on an invalid_token (401) challenge: the grant is revoked, not expandable");
        }
        // Protocol Invariant: 403 requires explicit missing scopes
        if (options.status === 403 && (!options.scopes || options.scopes.length === 0)) {
          throw new Error("AuthChallengeError with status 403 must specify missing required scopes");
        }
    
        const sanitized = options.errorDescription
          ? options.errorDescription
              .replace(/(sk-[a-zA-Z0-9_-]{15,}|ghp_[a-zA-Z0-9]{36}|whsec_[a-zA-Z0-9_-]{15,})/g, '[REDACTED_SECRET]')
              .replace(/(Bearer\s+)[A-Za-z0-9-_=]+\.[A-Za-z0-9-_=]+\.?[A-Za-z0-9-_.+/=]*/gi, '$1[REDACTED_TOKEN]')
          : (options.status === 401 ? 'Session revoked; re-authentication required' : 'Insufficient scope for requested tool');
    
        super(sanitized);
        this.name = 'AuthChallengeError';
        this.status = options.status;
        this.authError = options.status === 401 ? 'invalid_token' : 'insufficient_scope';
        this.errorDescription = sanitized;
        this.scopes = options.scopes;
        this.resourceMetadata = options.resourceMetadata;
      }
    }

    2. Dual-Mode Emission: Pre-Commit RFC 6750 vs Committed JSON-RPC

    • Pre-commitment (HTTP Headers Open): Emit HTTP 401 or 403 with RFC 6750 WWW-Authenticate:
      HTTP/1.1 401 Unauthorized
      WWW-Authenticate: Bearer error="invalid_token", error_description="Session revoked; re-authentication required", resource_metadata="https://auth.example.com/.well-known/oauth-protected-resource"
    • Post-commitment (SSE Streaming Started / Stdio Transports): Emit standard JSON-RPC 2.0 error with explicit machine-readable fields under data:
      {
        "jsonrpc": "2.0",
        "id": 1,
        "error": {
          "code": -32001,
          "message": "Session revoked; re-authentication required",
          "data": {
            "status": 401,
            "error": "invalid_token",
            "reauthorize": true,
            "resourceMetadata": "https://auth.example.com/.well-known/oauth-protected-resource"
          }
        }
      }
      Setting reauthorize: true on -32001 and reauthorize: false on -32003 gives client SDKs an unequivocal boolean discriminator so they never misinterpret a revoked grant as an expandable one.

    Disclosure: Maintainer of mcp-production-kit (open-source TypeScript kit for MCP servers featuring mid-execution auth challenges, DNS rebinding guards, secret redaction, and stdio stream isolation).

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

    v2Ideas, requests and plans for v2 of the SDK which will incorporate major changes and fixes

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions