Repository navigation
Conversation
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
Contributor
There was a problem hiding this comment.
🟡 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_tokenauthentication 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 | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.

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 withWWW-Authenticateinstead, 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. AnisError: trueinside 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
WithInvalidTokenChallengemiddleware (pkg/http/middleware/auth_challenge.go): ontools/call, probes token validity and responds with a 401 +WWW-Authenticatewhen GitHub returns 401. Classic PATs reuse the scopes already fetched byWithPATScopes;ghu_/gho_/fine-grained tokens get a lightweightHEADprobe. Wired into the chain inpkg/http/handler.goright afterWithPATScopes.sendInvalidTokenChallengehelper (pkg/http/middleware/token.go): sibling of the existingsendAuthChallenge, addingerror="invalid_token"(RFC 6750 §3.1) so clients refresh a stale token rather than re-authorizing from scratch.scopes.ErrInvalidToken(pkg/scopes/fetcher.go):FetchTokenScopesnow returns it on 401 so callers can detect credential failure viaerrors.Is, distinct from network/5xx errors.MCP impact
Prompts tested (tool changes only)
Security / limits
scopes.ErrInvalidToken). Rate-limit 403/429, validation 422, and all other errors continue to returnisError: trueunchanged, consistent with Failed API calls should not be failures, not errors #420. Non-PAT tokens incur one extra lightweightHEADpertools/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
Lint & tests
./script/lint(0 issues)./script/test(pass)Docs