Skip to content

Emit HTTP 401 for invalid/expired tokens so OAuth clients can refresh - #3879

Closed
Anika-Sol wants to merge 1 commit into
github:mainfrom
Anika-Sol:fix/http-401-invalid-token-challenge
Closed

Anika-Sol wants to merge 1 commit into
github:mainfrom
Anika-Sol:fix/http-401-invalid-token-challenge

Conversation

@Anika-Sol

Copy link
Copy Markdown
Contributor

Summary

When GitHub rejects a credential with HTTP 401, tool calls currently return HTTP 200 with isError: true. This adds a pre-dispatch middleware that surfaces a transport-level HTTP 401 with WWW-Authenticate instead, so OAuth clients recognize the expired token and refresh.

Why

Hosts that front this server with an OAuth flow (e.g. GitHub Enterprise Server with short-lived GitHub App user-to-server ghu_ tokens) see tokens expire mid-session. The MCP authorization spec says an invalid/expired token MUST receive an HTTP 401 — that is the signal clients use to refresh. An isError: true inside an HTTP 200 never triggers a refresh, so the session silently breaks and every subsequent GitHub call fails with no prompt to re-auth.

Because this server streams tool responses as SSE, the HTTP 200 + stream headers are flushed before the tool handler runs and cannot be rewritten afterward — so the 401 has to be emitted before dispatch, which is what this middleware does.

Fixes #3677

What changed

  • New WithInvalidTokenChallenge middleware (pkg/http/middleware/auth_challenge.go): on tools/call, probes token validity and responds with a 401 + WWW-Authenticate when GitHub returns 401. Classic PATs reuse the scopes already fetched by WithPATScopes; ghu_/gho_/fine-grained tokens get a lightweight HEAD probe. Wired into the chain in pkg/http/handler.go right after WithPATScopes.
  • sendInvalidTokenChallenge helper (pkg/http/middleware/token.go): sibling of the existing sendAuthChallenge, adding error="invalid_token" (RFC 6750 §3.1) so clients refresh a stale token rather than re-authorizing from scratch.
  • Typed sentinel scopes.ErrInvalidToken (pkg/scopes/fetcher.go): FetchTokenScopes now returns it on 401 so callers can detect credential failure via errors.Is, distinct from network/5xx errors.

MCP impact

  • No tool or API changes — only the HTTP status/headers for credential-rejection responses change. No tool schemas or behavior are affected.

Prompts tested (tool changes only)

  • N/A — no tool changes.

Security / limits

  • Auth / permissions considered — the challenge fires only on a GitHub 401 (scopes.ErrInvalidToken). Rate-limit 403/429, validation 422, and all other errors continue to return isError: true unchanged, consistent with Failed API calls should not be failures, not errors #420. Non-PAT tokens incur one extra lightweight HEAD per tools/call; classic PATs reuse the existing probe. Known limitation: a pre-dispatch probe catches an already-expired token (the common case) but not a token that expires mid-call — that case cannot produce a spec-compliant transport 401 on an SSE response.

Tool renaming

  • I am not renaming tools as part of this PR

Lint & tests

  • Linted locally with ./script/lint (0 issues)
  • Tested locally with ./script/test (pass)

Docs

  • Not needed

When GitHub rejects a credential with 401, tool calls currently return
HTTP 200 with isError: true, which OAuth clients never treat as a signal
to refresh — so sessions silently break once a short-lived token expires.

Add a pre-dispatch middleware that probes token validity on tools/call and
responds with a transport-level 401 + WWW-Authenticate (error="invalid_token",
RFC 6750) when GitHub returns 401. It must run before dispatch because tool
responses stream as SSE: the status is flushed before the handler runs and
cannot be rewritten afterward.

The check is deliberately narrow — only a 401 challenges. All other errors
(404, 409, 422, rate limits, business logic) keep returning isError: true
per the project's error model (github#420). Classic PATs reuse the existing
WithPATScopes probe; ghu_/gho_/fine-grained tokens get a lightweight HEAD.

Fixes github#3677
@Anika-Sol
Anika-Sol requested a review from a team as a code owner November 18, 2026 07:15
Copilot AI adaptive review requested due to automatic review settings November 18, 2026 07:15

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The authentication guard can miss expired credentials by treating existing scopes as proof of validation and skipping GitHub-backed methods, preventing the HTTP 401 needed for token refresh.

3 open issues
What changed in this PR

Adds pre-dispatch credential checks to the GitHub MCP server’s HTTP transport so OAuth clients can refresh invalid or expired tokens before streaming begins.

Changes:

  • Registers token-validation middleware after PAT scope fetching.
  • Returns HTTP 401 with an invalid_token authentication challenge when GitHub rejects a credential.
  • Adds a recognizable credential-error sentinel and tests for the new handling.
File Description
pkg/​scopes/​fetcher.go Returns ErrInvalidToken for GitHub 401 responses.
pkg/​scopes/​fetcher_test.go Verifies invalid-token error identity.
pkg/​http/​middleware/​token.go Adds the invalid-token authentication challenge helper.
pkg/​http/​middleware/​auth_challenge.go Checks tool-call credentials before dispatch.
pkg/​http/​middleware/​auth_challenge_test.go Tests challenges, successful validation, and bypass paths.
pkg/​http/​handler.go Registers the middleware after PAT scope fetching.

Review effort: Max (adaptive)

// Only tools/call needs a valid credential; discovery methods
// (tools/list, initialize) must stay reachable pre-auth.
methodInfo, ok := ghcontext.MCPMethod(ctx)
if !ok || methodInfo == nil || methodInfo.Method != "tools/call" {

// Classic PATs were already probed by WithPATScopes; scopes in
// context mean the token authenticated, so skip a second call.
if _, ok := ghcontext.GetTokenScopes(ctx); ok {
Comment on lines +55 to +59
_, err := scopeFetcher.FetchTokenScopes(ctx, tokenInfo.Token)
if errors.Is(err, scopes.ErrInvalidToken) {
sendInvalidTokenChallenge(w, r, oauthCfg)
return
}
@Anika-Sol Anika-Sol closed this Nov 18, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Return HTTP 401 for credential/authorization failures instead of isError: true, so OAuth clients can refresh

2 participants