[v2] Let a tool handler answer 401 invalid_token (re-authorization needed), not only a 403 scope challenge
Maintainer antworten meist innerhalb von 1 Tag
@0xamlab arbeitet bereits daran.
Seit 11.11.2026.
Bewertung
- Schwierigkeit
- 4/5
- Geschätzter Aufwand
- 3-5 Tage
- Anfängerfreundlichkeit
- 44/100
- Issue-Typ
- Feature
- Klarheit
- Klar beschrieben
- Aktivitätsstatus
- Aktiv
- Tech-Stack
- typescript
- Bereich
- authentication, backend-api-design
Rechercherichtung
Start by reading the tools/call handler and the HTTP entry points (createMcpHandler and the transports), then compare their error handling with UrlElicitationRequired and requireBearerAuth. Trace how responses are sent across both protocol eras, including the case where a message has already been sent. Done means a typed auth challenge from a tool handler can produce a 401 with the expected WWW-Authenticate header, with an in-band fallback when needed.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Beschreibung
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 https://github.com/modelcontextprotocol/typescript-sdk/issues/2957#issuecomment-6785575041. 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
- Vorherrschende Sprache
- TypeScript
- Sterne
- 13.8k
- Forks
- 2.5k
- Ø Merge
- 6 T. 23 Std.
- Gemergte PRs (30 T.)
- 2
Entwicklungsumgebung
- Kein Dockerfile und keine Docker-Compose-Datei
- Keine Pull-Request-Vorlage
- Beitragsleitfaden lesen
Erste Schritte
- Lesen Sie das ganze Issue und danach den Beitragsleitfaden des Projekts.
- Schreiben Sie ins Issue, dass Sie es übernehmen — das erspart doppelte Arbeit.
- Forken Sie das Repository und arbeiten Sie in einem Branch.
- Öffnen Sie einen Pull Request, der die Issue-Nummer nennt.
Mehr aus modelcontextprotocol/typescript-sdk
-
v2
Schwierigkeit 1/5 Unter einer Stunde Anfängerfreundlichkeit 72/100
modelcontextprotocol/typescript-sdk#3270 · 1 Kommentar ·
Maintainer antworten meist innerhalb von 1 Tag
-
`callTool` with `allowInputRequired: true` throws on an `input_required` result when the tool declares an `outputSchema`Evtl. vergeben @mgoldsborough hat das vor 6 Tagen übernommen. Offenv2
Schwierigkeit 2/5 1-3 Stunden Anfängerfreundlichkeit 78/100
modelcontextprotocol/typescript-sdk#3249 ·
Maintainer antworten meist innerhalb von 1 Tag
-
v2
Schwierigkeit 2/5 1-3 Stunden Anfängerfreundlichkeit 68/100
modelcontextprotocol/typescript-sdk#3243 · 3 Kommentare ·
Maintainer antworten meist innerhalb von 1 Tag
-
TypeScript client accepts an unknown `resultType` in the first `server/discover` replyEvtl. vergeben @Tidehyc hat das vor 7 Tagen übernommen. Offenv2
Schwierigkeit 2/5 1-3 Stunden Anfängerfreundlichkeit 72/100
modelcontextprotocol/typescript-sdk#3235 · 3 Kommentare ·
Maintainer antworten meist innerhalb von 1 Tag
-
UriTemplate.match() throws a TypeError on an empty expression it acceptsEvtl. vergeben @yunusemrejs hat das vor 12 Tagen übernommen. Offenv1 v2
Schwierigkeit 2/5 1-3 Stunden Anfängerfreundlichkeit 80/100
modelcontextprotocol/typescript-sdk#3221 · 3 Kommentare ·
Maintainer antworten meist innerhalb von 1 Tag
Alle Issues in modelcontextprotocol/typescript-sdk
Ähnliche Issues
-
bug
Schwierigkeit 2/5 1-3 Stunden Anfängerfreundlichkeit 72/100
-
Schwierigkeit 2/5 1-3 Stunden Anfängerfreundlichkeit 68/100
Vessel9817/onion-site-template#512 ·
Maintainer antworten meist innerhalb von 1 Tag
-
nightly-tests
Schwierigkeit 2/5 1-3 Stunden Anfängerfreundlichkeit 68/100
BlackBeltTechnology/pi-agent-dashboard#1256 ·
Maintainer antworten meist innerhalb von 1 Tag
-
approved
Schwierigkeit 2/5 1-3 Stunden Anfängerfreundlichkeit 85/100
fritzprix/libr-agent#3266 ·
Maintainer antworten meist innerhalb von 1 Tag
-
Schwierigkeit 1/5 Unter einer Stunde Anfängerfreundlichkeit 88/100
better-auth/better-auth#13101 · 1 Kommentar · 1 Reaktion ·
Maintainer antworten meist innerhalb von 1 Tag