Skip to content

mcp: authorize at most once when Connect falls back to initialize - #1564

Open
sks wants to merge 2 commits into
modelcontextprotocol:mainfrom
sks:fix/1423-oauth-authorize-once-per-connect
Open

sks wants to merge 2 commits into
modelcontextprotocol:mainfrom
sks:fix/1423-oauth-authorize-once-per-connect

Conversation

@sks

@sks sks commented Dec 2, 2026 •

Copy link
Copy Markdown

Fixes #1423

When Client.Connect with an OAuthHandler tries server/discover first and falls back to initialize, a server that rejects both requests with 401/403 currently triggers OAuthHandler.Authorize twice in a single Connect call.

This implements the two-case handling described by @guglielmo-san on #1423:

  • OAuthHandler.Authorize returns an error during server/discover (e.g. consent declined or token exchange failed): streamableClientConn.Write wraps the handler error in an unexported authorizeError (preserving Error() and Unwrap() unchanged), and Client.Connect closes the session and returns immediately instead of falling back to initialize.
  • OAuthHandler.Authorize succeeds during server/discover, and the retried request still fails (including with 401/403): streamableClientConn records handshakeAuthorized once Authorize succeeds for a handshake method (server/discover or initialize), so the fallback initialize is still attempted with the newly acquired token in TokenSource without invoking OAuthHandler.Authorize a second time if initialize also returns 401/403.

Also closes the initial 401/403 response body before retrying doRequest() after Authorize succeeds.

Tests: TestStreamableClientOAuth_AuthorizeOncePerConnect verifies that Authorize runs at most once across four cases (Authorize fails, granted token rejected, discover forbidden, initialize allowed, and legacy server). go test -race ./..., go vet ./..., and staticcheck v0.8.2 pass.

AI disclosure: drafted with AI assistance; I reviewed and tested the change locally.

Fixes modelcontextprotocol#1423.

With an OAuthHandler configured, Client.Connect tries server/discover first and
falls back to initialize on any non-modern error. When server/discover stayed
unauthorized, the fallback initialize received 401 and ran OAuthHandler.Authorize
a second time.

Handle the two cases separately:
- If OAuthHandler.Authorize itself returns an error during server/discover
  (e.g. consent declined), wrap it in an unexported authorizeError type (whose
  Error() and Unwrap() preserve the original error unchanged) so Connect can
  return immediately rather than falling back to initialize.
- If OAuthHandler.Authorize succeeds, share an atomic handshake flag across
  Connect's handshake requests via the context so a fallback initialize reuses
  the newly acquired TokenSource credentials without invoking Authorize again.
  Close the initial 401/403 response body before retrying the request.

TestStreamableClientOAuth_AuthorizeOncePerConnect covers Authorize failure,
rejected granted token, method-level 403 on server/discover with 200 on
initialize, and legacy server fallback.

go test ./..., -race on mcp, go vet, and staticcheck v0.8.2 pass.

AI-assisted: implementation and tests drafted with an AI assistant; reviewed and tested locally.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@github-actions github-actions Bot added the missing-issue-link Auto-closed: PR needs a linked issue assigned to its author (see CONTRIBUTING.md) label Dec 2, 2026
@github-actions github-actions Bot closed this Dec 2, 2026
@github-actions github-actions Bot reopened this Dec 2, 2026
@github-actions github-actions Bot removed the missing-issue-link Auto-closed: PR needs a linked issue assigned to its author (see CONTRIBUTING.md) label Dec 2, 2026
Comment thread mcp/streamable.go Resolved
… context

Replace authorizedContextKey on Client.Connect's context with a
handshakeAuthorized boolean on streamableClientConn so Write skips a
second OAuthHandler.Authorize call when a handshake method
(server/discover or initialize) has already authorized.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Comment thread mcp/streamable.go
if (resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden) && c.oauthHandler != nil {
isHandshake := requestMethod == methodDiscover || requestMethod == methodInitialize
if (resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden) && c.oauthHandler != nil &&
(!isHandshake || !c.handshakeAuthorized.Load()) {

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.

Suggested change
(!isHandshake || !c.handshakeAuthorized.Load()) {
!(requestMethod == methodInitialize && c.discoverAuthorized.Load()) {

Comment thread mcp/streamable.go
Comment on lines +2640 to 2642
if isHandshake {
c.handshakeAuthorized.Store(true)
}

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.

Suggested change
if isHandshake {
c.handshakeAuthorized.Store(true)
}
if requestMethod == methodDiscover {
c.discoverAuthorized.Store(true)
}

This branch has not been deployed

No deployments
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.

mcp: Client.Connect falls back to initialize after a 401 on server/discover, running the authorization flow twice

2 participants