|
| 1 | +// Copyright 2025 The Go MCP SDK Authors. All rights reserved. |
| 2 | +// Use of this source code is governed by an MIT-style |
| 3 | +// license that can be found in the LICENSE file. |
| 4 | + |
| 5 | +package auth |
| 6 | + |
| 7 | +import ( |
| 8 | + "context" |
| 9 | + "log" |
| 10 | + "net/http" |
| 11 | + "sync" |
| 12 | + |
| 13 | + "github.com/modelcontextprotocol/go-sdk/internal/oauthex" |
| 14 | + "golang.org/x/oauth2" |
| 15 | +) |
| 16 | + |
| 17 | +// An OAuthHandler conducts an OAuth flow and returns a [oauth2.TokenSource] if the authorization |
| 18 | +// is approved, or an error if not. |
| 19 | +type OAuthHandler func(context.Context, OAuthHandlerArgs) (oauth2.TokenSource, error) |
| 20 | + |
| 21 | +// OAuthHandlerArgs are arguments to an [OAuthHandler]. |
| 22 | +type OAuthHandlerArgs struct { |
| 23 | + // The URL to fetch protected resource metadata, extracted from the WWW-Authenticate header. |
| 24 | + // Empty if not present or there was an error obtaining it. |
| 25 | + ResourceMetadataURL string |
| 26 | +} |
| 27 | + |
| 28 | +// HTTPTransport is an [http.RoundTripper] that follows the MCP |
| 29 | +// OAuth protocol when it encounters a 401 Unauthorized response. |
| 30 | +type HTTPTransport struct { |
| 31 | + handler OAuthHandler |
| 32 | + mu sync.Mutex // protects opts.Base |
| 33 | + opts HTTPTransportOptions |
| 34 | +} |
| 35 | + |
| 36 | +// NewHTTPTransport returns a new [*HTTPTransport]. |
| 37 | +// The handler is invoked when an HTTP request results in a 401 Unauthorized status. |
| 38 | +// It is called only once per transport. Once a TokenSource is obtained, it is used |
| 39 | +// for the lifetime of the transport; subsequent 401s are not processed. |
| 40 | +func NewHTTPTransport(handler OAuthHandler, opts *HTTPTransportOptions) (*HTTPTransport, error) { |
| 41 | + t := &HTTPTransport{} |
| 42 | + if opts != nil { |
| 43 | + t.opts = *opts |
| 44 | + } |
| 45 | + if t.opts.Base == nil { |
| 46 | + t.opts.Base = http.DefaultTransport |
| 47 | + } |
| 48 | + return t, nil |
| 49 | +} |
| 50 | + |
| 51 | +// HTTPTransportOptions are options to [NewHTTPTransport]. |
| 52 | +type HTTPTransportOptions struct { |
| 53 | + // Base is the [http.RoundTripper] to use. |
| 54 | + // If nil, [http.DefaultTransport] is used. |
| 55 | + Base http.RoundTripper |
| 56 | +} |
| 57 | + |
| 58 | +func (t *HTTPTransport) RoundTrip(req *http.Request) (*http.Response, error) { |
| 59 | + t.mu.Lock() |
| 60 | + base := t.opts.Base |
| 61 | + _, haveTokenSource := base.(*oauth2.Transport) |
| 62 | + t.mu.Unlock() |
| 63 | + |
| 64 | + resp, err := base.RoundTrip(req) |
| 65 | + if err != nil { |
| 66 | + return nil, err |
| 67 | + } |
| 68 | + if resp.StatusCode != http.StatusUnauthorized { |
| 69 | + return resp, nil |
| 70 | + } |
| 71 | + if haveTokenSource { |
| 72 | + // We failed to authorize even with a token source; give up. |
| 73 | + return resp, nil |
| 74 | + } |
| 75 | + // Try to authorize. |
| 76 | + t.mu.Lock() |
| 77 | + // If we don't have a token source, get one by following the OAuth flow. |
| 78 | + // (We may have obtained one while t.mu was not held above.) |
| 79 | + if _, ok := t.opts.Base.(*oauth2.Transport); !ok { |
| 80 | + authHeaders := resp.Header[http.CanonicalHeaderKey("WWW-Authenticate")] |
| 81 | + ts, err := t.handler(req.Context(), OAuthHandlerArgs{ |
| 82 | + ResourceMetadataURL: extractResourceMetadataURL(authHeaders), |
| 83 | + }) |
| 84 | + if err != nil { |
| 85 | + t.mu.Unlock() |
| 86 | + return nil, err |
| 87 | + } |
| 88 | + t.opts.Base = &oauth2.Transport{Base: t.opts.Base, Source: ts} |
| 89 | + } |
| 90 | + t.mu.Unlock() |
| 91 | + // Only one level of recursion, because we now have a token source. |
| 92 | + return t.RoundTrip(req) |
| 93 | +} |
| 94 | + |
| 95 | +func extractResourceMetadataURL(authHeaders []string) string { |
| 96 | + cs, err := oauthex.ParseWWWAuthenticate(authHeaders) |
| 97 | + if err != nil { |
| 98 | + log.Printf("parsing auth headers %q: %v", authHeaders, err) |
| 99 | + return "" |
| 100 | + } |
| 101 | + return oauthex.ResourceMetadataURL(cs) |
| 102 | +} |
0 commit comments