This PR introduces client-side OAuth support. # Overall design philosophy The main new interface introduced to support client-side OAuth is the `OAuthHandler`. Contrary to its counter-parts in some other SDKs, it is intentionally small and generic so that it can support most of the OAuth authorization flow variants. The main `mcp` package purposefully delegates almost all auth handling to `OAuthHandler` implementations. This way, the `mcp` package continues to be largely OAuth agnostic. The `auth` package comes with a default `OAuthHandler` implementation – `AuthorizationCodeHandler`, which implements the authorization flow for the `authorization_code` grant type, as defined in the [MCP specification](https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization). It is expected that the `OAuthHandler` implementation granularity will be roughly per grant type, as this parameter influences the authorization flow the most. # Detailed design ## `OAuthHandler` (auth/client.go) The main interface for the integration consists of two methods: ```go type OAuthHandler interface { // TokenSource returns a token source to be used for outgoing requests. // Returned token source might be nil. In that case, the transport will not // add any authorization headers to the request. TokenSource(context.Context) (oauth2.TokenSource, error) // Authorize is called when an HTTP request results in an error that may // be addressed by the authorization flow (currently 401 Unauthorized and 403 Forbidden). // It is responsible for performing the OAuth flow to obtain an access token. // The arguments are the request that failed and the response that was received for it. // The headers of the request are available, but the body will have already been consumed // when Authorize is called. // If the returned error is nil, TokenSource is expected to return a non-nil token source. // After a successful call to Authorize, the HTTP request will be retried by the transport. // The function is responsible for closing the response body. Authorize(context.Context, *http.Request, *http.Response) error } ``` `StreamableClientTransport` accepts this interface as a field and uses the `TokenSource` method to add an `Authorization: Bearer` header to outgoing requests to the MCP server. If the request fails with `401: Unauthorized` or `403: Forbidden`, the transport calls `Authorize` to perform the authorization flow. If `Authorize` returns a non-nil error, the request is retried once. `Authorize` errors do not result in termination of the client session (unless they happen during connection initialization), as some OAuth flows are multi-legged and it should be acceptable to retry for example when the authorization grant was received. *Note:* There was already an `OAuthHandler` type defined as part of a previous iteration of OAuth support. It was renamed to `OAuthHandlerLegacy`. This is the only backwards incompatible API change in the experimental client `auth` part (protected by the `mcp_go_client_oauth` Go build tag). The cost of replacing previous usages is deemed worthwhile to maintain clear naming, under the assumption that the experimental client `auth` part was not widely used. ## `AuthorizationCodeHandler` (auth/authorization_code.go) This is the `OAuthHandler` implementation that fulfills the [MCP specification](https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization). In particular, in supports: - Protected Resource Metadata discovery and fetching - Authorization Server Metadata discovery and fetching - Client registration - OpenID Connect metadata document - Pre-registration - Dynamic Client Registration - PKCE - `client_secret_post`, `client_secret_basic` token endpoint auth methods - Automatic refresh of tokens ### Authorization Server redirect As part of the flow for the `authorization_code` grant type, the client needs to point the user to the authorization URL, so that they confirm the access request. This design proposes that it will be supported via a pluggable dependency that will initiate this process in an application-specific way: ```go type AuthorizationCodeHandler struct { ... // AuthorizationCodeFetcher is a required function called to initiate the authorization flow. // It is responsible for opening the URL in a browser for the user to start the authorization process. // It should return the authorization code and state once the Authorization Server // redirects back to the RedirectURL. AuthorizationCodeFetcher func(ctx context.Context, args *AuthorizationArgs) (*AuthorizationResult, error) ... } ``` The function is supposed perform any application specific logic to handle the redirect from the Authorization Server and return the resulting code and state. ## `oauthex` changes Some additional/adjusted building blocks that may be useful when creating `OAuthHandler` implementations are present in the `oauthex` package: - `auth_meta.go`: Authorization Server Metadata utilities: - `GetAuthServerMeta`: get Authorization Server Metadata from a URL - `dcr.go`: Dynamic Client Registration utilities (unchanged) - `resource_meta.go`: Protected Resource Metadata utilities: - `GetProtectedResourceMetadata`: get Protected Resource Metadata from a URL - `ParseWWWAuthenticate` – as per name (unchanged) - [deprecated] `GetProtectedResourceMetadataFromID` and `GetProtectedResourceMetadataFromHeader` in favor of more generic `GetProtectedResourceMetadata`. They will be kept under the Go build tag and removed one version of the SDK in the future.
135 lines
4.2 KiB
Go
135 lines
4.2 KiB
Go
// Copyright 2025 The Go MCP SDK Authors. All rights reserved.
|
|
// Use of this source code is governed by an MIT-style
|
|
// license that can be found in the LICENSE file.
|
|
|
|
//go:build mcp_go_client_oauth
|
|
|
|
package auth
|
|
|
|
import (
|
|
"bytes"
|
|
"errors"
|
|
"io"
|
|
"net/http"
|
|
"sync"
|
|
|
|
"golang.org/x/oauth2"
|
|
)
|
|
|
|
// An OAuthHandlerLegacy conducts an OAuth flow and returns a [oauth2.TokenSource] if the authorization
|
|
// is approved, or an error if not.
|
|
// The handler receives the HTTP request and response that triggered the authentication flow.
|
|
// To obtain the protected resource metadata, call [oauthex.GetProtectedResourceMetadataFromHeader].
|
|
//
|
|
// Deprecated: Please use the new [OAuthHandler] abstraction that is built
|
|
// into the streamable transport. This struct will be removed in v1.5.0.
|
|
type OAuthHandlerLegacy func(req *http.Request, res *http.Response) (oauth2.TokenSource, error)
|
|
|
|
// HTTPTransport is an [http.RoundTripper] that follows the MCP
|
|
// OAuth protocol when it encounters a 401 Unauthorized response.
|
|
//
|
|
// Deprecated: Please use the new [OAuthHandler] abstraction that is built
|
|
// into the streamable transport. This struct will be removed in v1.5.0.
|
|
type HTTPTransport struct {
|
|
handler OAuthHandlerLegacy
|
|
mu sync.Mutex // protects opts.Base
|
|
opts HTTPTransportOptions
|
|
}
|
|
|
|
// NewHTTPTransport returns a new [*HTTPTransport].
|
|
// The handler is invoked when an HTTP request results in a 401 Unauthorized status.
|
|
// It is called only once per transport. Once a TokenSource is obtained, it is used
|
|
// for the lifetime of the transport; subsequent 401s are not processed.
|
|
//
|
|
// Deprecated: Please use the new [OAuthHandler] abstraction that is built
|
|
// into the streamable transport. This struct will be removed in v1.5.0.
|
|
func NewHTTPTransport(handler OAuthHandlerLegacy, opts *HTTPTransportOptions) (*HTTPTransport, error) {
|
|
if handler == nil {
|
|
return nil, errors.New("handler cannot be nil")
|
|
}
|
|
t := &HTTPTransport{
|
|
handler: handler,
|
|
}
|
|
if opts != nil {
|
|
t.opts = *opts
|
|
}
|
|
if t.opts.Base == nil {
|
|
t.opts.Base = http.DefaultTransport
|
|
}
|
|
return t, nil
|
|
}
|
|
|
|
// HTTPTransportOptions are options to [NewHTTPTransport].
|
|
//
|
|
// Deprecated: Please use the new [OAuthHandler] abstraction that is built
|
|
// into the streamable transport. This struct will be removed in v1.5.0.
|
|
type HTTPTransportOptions struct {
|
|
// Base is the [http.RoundTripper] to use.
|
|
// If nil, [http.DefaultTransport] is used.
|
|
Base http.RoundTripper
|
|
}
|
|
|
|
func (t *HTTPTransport) RoundTrip(req *http.Request) (*http.Response, error) {
|
|
t.mu.Lock()
|
|
base := t.opts.Base
|
|
t.mu.Unlock()
|
|
|
|
var (
|
|
// If haveBody is set, the request has a nontrivial body, and we need avoid
|
|
// reading (or closing) it multiple times. In that case, bodyBytes is its
|
|
// content.
|
|
haveBody bool
|
|
bodyBytes []byte
|
|
)
|
|
if req.Body != nil && req.Body != http.NoBody {
|
|
// if we're setting Body, we must mutate first.
|
|
req = req.Clone(req.Context())
|
|
haveBody = true
|
|
var err error
|
|
bodyBytes, err = io.ReadAll(req.Body)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
// Now that we've read the request body, http.RoundTripper requires that we
|
|
// close it.
|
|
req.Body.Close() // ignore error
|
|
req.Body = io.NopCloser(bytes.NewReader(bodyBytes))
|
|
}
|
|
|
|
resp, err := base.RoundTrip(req)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if resp.StatusCode != http.StatusUnauthorized {
|
|
return resp, nil
|
|
}
|
|
if _, ok := base.(*oauth2.Transport); ok {
|
|
// We failed to authorize even with a token source; give up.
|
|
return resp, nil
|
|
}
|
|
|
|
resp.Body.Close()
|
|
// Try to authorize.
|
|
t.mu.Lock()
|
|
defer t.mu.Unlock()
|
|
// If we don't have a token source, get one by following the OAuth flow.
|
|
// (We may have obtained one while t.mu was not held above.)
|
|
// TODO: We hold the lock for the entire OAuth flow. This could be a long
|
|
// time. Is there a better way?
|
|
if _, ok := t.opts.Base.(*oauth2.Transport); !ok {
|
|
ts, err := t.handler(req, resp)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
t.opts.Base = &oauth2.Transport{Base: t.opts.Base, Source: ts}
|
|
}
|
|
|
|
// If we don't have a body, the request is reusable, though it will be cloned
|
|
// by the base. However, if we've had to read the body, we must clone.
|
|
if haveBody {
|
|
req = req.Clone(req.Context())
|
|
req.Body = io.NopCloser(bytes.NewReader(bodyBytes))
|
|
}
|
|
|
|
return t.opts.Base.RoundTrip(req)
|
|
}
|