all: client side OAuth support (#785)
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.
This commit is contained in:
parent
4e8b6ca17d
commit
c9317fb5b7
1 changed files with 2743 additions and 434 deletions
|
|
@ -26,7 +26,6 @@ import (
|
|||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/modelcontextprotocol/go-sdk/auth"
|
||||
|
|
@ -1456,6 +1455,9 @@ type StreamableClientTransport struct {
|
|||
// - You want to avoid maintaining a persistent connection
|
||||
DisableStandaloneSSE bool
|
||||
|
||||
// OAuthHandler is an optional field that, if provided, will be used to authorize the requests.
|
||||
OAuthHandler auth.OAuthHandler
|
||||
|
||||
// TODO(rfindley): propose exporting these.
|
||||
// If strict is set, the transport is in 'strict mode', where any violation
|
||||
// of the MCP spec causes a failure.
|
||||
|
|
@ -1531,6 +1533,7 @@ func (t *StreamableClientTransport) Connect(ctx context.Context) (Connection, er
|
|||
cancel: cancel,
|
||||
failed: make(chan struct{}),
|
||||
disableStandaloneSSE: t.DisableStandaloneSSE,
|
||||
oauthHandler: t.OAuthHandler,
|
||||
}
|
||||
return conn, nil
|
||||
}
|
||||
|
|
@ -1549,6 +1552,9 @@ type streamableClientConn struct {
|
|||
// for receiving server-to-client notifications when no request is in flight.
|
||||
disableStandaloneSSE bool // from [StreamableClientTransport.DisableStandaloneSSE]
|
||||
|
||||
// oauthHandler is the OAuth handler for the connection.
|
||||
oauthHandler auth.OAuthHandler // from [StreamableClientTransport.OAuthHandler]
|
||||
|
||||
// Guard calls to Close, as it may be called multiple times.
|
||||
closeOnce sync.Once
|
||||
closeErr error
|
||||
|
|
@ -1718,20 +1724,46 @@ func (c *streamableClientConn) Write(ctx context.Context, msg jsonrpc.Message) e
|
|||
return fmt.Errorf("%s: %v", requestSummary, err)
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.url, bytes.NewReader(data))
|
||||
doRequest := func() (*http.Request, *http.Response, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.url, bytes.NewReader(data))
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Accept", "application/json, text/event-stream")
|
||||
if err := c.setMCPHeaders(req); err != nil {
|
||||
// Failure to set headers means that the request was not sent.
|
||||
// Wrap with ErrRejected so the jsonrpc2 connection doesn't set writeErr
|
||||
// and permanently break the connection.
|
||||
return nil, nil, fmt.Errorf("%s: %w: %v", requestSummary, jsonrpc2.ErrRejected, err)
|
||||
}
|
||||
resp, err := c.client.Do(req)
|
||||
if err != nil {
|
||||
// Any error from client.Do means the request didn't reach the server.
|
||||
// Wrap with ErrRejected so the jsonrpc2 connection doesn't set writeErr
|
||||
// and permanently break the connection.
|
||||
err = fmt.Errorf("%s: %w: %v", requestSummary, jsonrpc2.ErrRejected, err)
|
||||
}
|
||||
return req, resp, err
|
||||
}
|
||||
|
||||
req, resp, err := doRequest()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Accept", "application/json, text/event-stream")
|
||||
c.setMCPHeaders(req)
|
||||
|
||||
resp, err := c.client.Do(req)
|
||||
if err != nil {
|
||||
// Any error from client.Do means the request didn't reach the server.
|
||||
// Wrap with ErrRejected so the jsonrpc2 connection doesn't set writeErr
|
||||
// and permanently break the connection.
|
||||
return fmt.Errorf("%w: %s: %v", jsonrpc2.ErrRejected, requestSummary, err)
|
||||
if (resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden) && c.oauthHandler != nil {
|
||||
if err := c.oauthHandler.Authorize(ctx, req, resp); err != nil {
|
||||
// Wrap with ErrRejected so the jsonrpc2 connection doesn't set writeErr
|
||||
// and permanently break the connection.
|
||||
// Wrap the authorization error as well for client inspection.
|
||||
return fmt.Errorf("%s: %w: %w", requestSummary, jsonrpc2.ErrRejected, err)
|
||||
}
|
||||
// Retry the request after successful authorization.
|
||||
_, resp, err = doRequest()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if err := c.checkResponse(requestSummary, resp); err != nil {
|
||||
|
|
@ -1799,23 +1831,32 @@ func (c *streamableClientConn) Write(ctx context.Context, msg jsonrpc.Message) e
|
|||
return nil
|
||||
}
|
||||
|
||||
// testAuth controls whether a fake Authorization header is added to outgoing requests.
|
||||
// TODO: replace with a better mechanism when client-side auth is in place.
|
||||
var testAuth atomic.Bool
|
||||
|
||||
func (c *streamableClientConn) setMCPHeaders(req *http.Request) {
|
||||
func (c *streamableClientConn) setMCPHeaders(req *http.Request) error {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
|
||||
if c.oauthHandler != nil {
|
||||
ts, err := c.oauthHandler.TokenSource(c.ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if ts != nil {
|
||||
token, err := ts.Token()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if token != nil {
|
||||
req.Header.Set("Authorization", "Bearer "+token.AccessToken)
|
||||
}
|
||||
}
|
||||
}
|
||||
if c.initializedResult != nil {
|
||||
req.Header.Set(protocolVersionHeader, c.initializedResult.ProtocolVersion)
|
||||
}
|
||||
if c.sessionID != "" {
|
||||
req.Header.Set(sessionIDHeader, c.sessionID)
|
||||
}
|
||||
if testAuth.Load() {
|
||||
req.Header.Set("Authorization", "Bearer foo")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *streamableClientConn) handleJSON(requestSummary string, resp *http.Response) {
|
||||
|
|
@ -2068,7 +2109,9 @@ func (c *streamableClientConn) connectSSE(ctx context.Context, lastEventID strin
|
|||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.setMCPHeaders(req)
|
||||
if err := c.setMCPHeaders(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if lastEventID != "" {
|
||||
req.Header.Set(lastEventIDHeader, lastEventID)
|
||||
}
|
||||
|
|
@ -2099,8 +2142,9 @@ func (c *streamableClientConn) Close() error {
|
|||
if err != nil {
|
||||
c.closeErr = err
|
||||
} else {
|
||||
c.setMCPHeaders(req)
|
||||
if _, err := c.client.Do(req); err != nil {
|
||||
if err := c.setMCPHeaders(req); err != nil {
|
||||
c.closeErr = err
|
||||
} else if _, err := c.client.Do(req); err != nil {
|
||||
c.closeErr = err
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue