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
3 changed files with 2743 additions and 434 deletions
|
|
@ -1,20 +1,2 @@
|
|||
server: [] # All tests pass!
|
||||
client:
|
||||
- auth/basic-cimd
|
||||
- auth/metadata-default
|
||||
- auth/metadata-var1
|
||||
- auth/metadata-var2
|
||||
- auth/metadata-var3
|
||||
- auth/2025-03-26-oauth-metadata-backcompat
|
||||
- auth/2025-03-26-oauth-endpoint-fallback
|
||||
- auth/scope-from-www-authenticate
|
||||
- auth/scope-from-scopes-supported
|
||||
- auth/scope-omitted-when-undefined
|
||||
- auth/scope-step-up
|
||||
- auth/scope-retry-limit
|
||||
- auth/token-endpoint-auth-basic
|
||||
- auth/token-endpoint-auth-post
|
||||
- auth/token-endpoint-auth-none
|
||||
- auth/client-credentials-jwt
|
||||
- auth/client-credentials-basic
|
||||
- auth/pre-registration
|
||||
client: [] # All tests pass!
|
||||
|
|
|
|||
139
conformance/everything-client/client_private.go
Normal file
139
conformance/everything-client/client_private.go
Normal file
|
|
@ -0,0 +1,139 @@
|
|||
// 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.
|
||||
|
||||
// The conformance client implements features required for MCP conformance testing.
|
||||
// It mirrors the functionality of the TypeScript conformance client at
|
||||
// https://github.com/modelcontextprotocol/typescript-sdk/blob/main/src/conformance/everything-client.ts
|
||||
|
||||
//go:build mcp_go_client_oauth
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
|
||||
"github.com/modelcontextprotocol/go-sdk/auth"
|
||||
"github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
"github.com/modelcontextprotocol/go-sdk/oauthex"
|
||||
)
|
||||
|
||||
func init() {
|
||||
authScenarios := []string{
|
||||
"auth/2025-03-26-oauth-metadata-backcompat",
|
||||
"auth/2025-03-26-oauth-endpoint-fallback",
|
||||
"auth/basic-cimd",
|
||||
"auth/metadata-default",
|
||||
"auth/metadata-var1",
|
||||
"auth/metadata-var2",
|
||||
"auth/metadata-var3",
|
||||
"auth/pre-registration",
|
||||
"auth/resource-mismatch",
|
||||
"auth/scope-from-www-authenticate",
|
||||
"auth/scope-from-scopes-supported",
|
||||
"auth/scope-omitted-when-undefined",
|
||||
"auth/scope-step-up",
|
||||
"auth/scope-retry-limit",
|
||||
"auth/token-endpoint-auth-basic",
|
||||
"auth/token-endpoint-auth-post",
|
||||
"auth/token-endpoint-auth-none",
|
||||
}
|
||||
for _, scenario := range authScenarios {
|
||||
registerScenario(scenario, runAuthClient)
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Auth scenarios
|
||||
// ============================================================================
|
||||
|
||||
func fetchAuthorizationCodeAndState(ctx context.Context, args *auth.AuthorizationArgs) (*auth.AuthorizationResult, error) {
|
||||
client := &http.Client{
|
||||
CheckRedirect: func(req *http.Request, via []*http.Request) error {
|
||||
return http.ErrUseLastResponse
|
||||
},
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, "GET", args.URL, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
// In conformance tests the authorization server immediately redirects
|
||||
// to the callback URL with the authorization code and state.
|
||||
locURL, err := url.Parse(resp.Header.Get("Location"))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse location: %v", err)
|
||||
}
|
||||
|
||||
return &auth.AuthorizationResult{
|
||||
Code: locURL.Query().Get("code"),
|
||||
State: locURL.Query().Get("state"),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func runAuthClient(ctx context.Context, serverURL string, configCtx map[string]any) error {
|
||||
authConfig := &auth.AuthorizationCodeHandlerConfig{
|
||||
RedirectURL: "http://localhost:3000/callback",
|
||||
AuthorizationCodeFetcher: fetchAuthorizationCodeAndState,
|
||||
// Try client ID metadata document based registration.
|
||||
ClientIDMetadataDocumentConfig: &auth.ClientIDMetadataDocumentConfig{
|
||||
URL: "https://conformance-test.local/client-metadata.json",
|
||||
},
|
||||
// Try dynamic client registration.
|
||||
DynamicClientRegistrationConfig: &auth.DynamicClientRegistrationConfig{
|
||||
Metadata: &oauthex.ClientRegistrationMetadata{
|
||||
RedirectURIs: []string{"http://localhost:3000/callback"},
|
||||
},
|
||||
},
|
||||
}
|
||||
// Try pre-registered client information if provided in the context.
|
||||
if clientID, ok := configCtx["client_id"].(string); ok {
|
||||
if clientSecret, ok := configCtx["client_secret"].(string); ok {
|
||||
authConfig.PreregisteredClientConfig = &auth.PreregisteredClientConfig{
|
||||
ClientSecretAuthConfig: &auth.ClientSecretAuthConfig{
|
||||
ClientID: clientID,
|
||||
ClientSecret: clientSecret,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
authHandler, err := auth.NewAuthorizationCodeHandler(authConfig)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create auth handler: %w", err)
|
||||
}
|
||||
|
||||
session, err := connectToServer(ctx, serverURL, withOAuthHandler(authHandler))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer session.Close()
|
||||
|
||||
if _, err := session.ListTools(ctx, nil); err != nil {
|
||||
return fmt.Errorf("session.ListTools(): %v", err)
|
||||
}
|
||||
|
||||
if _, err := session.CallTool(ctx, &mcp.CallToolParams{
|
||||
Name: "test-tool",
|
||||
Arguments: map[string]any{},
|
||||
}); err != nil {
|
||||
return fmt.Errorf("session.CallTool('test-tool'): %v", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func withOAuthHandler(handler auth.OAuthHandler) connectOption {
|
||||
return func(c *connectConfig) {
|
||||
c.oauthHandler = handler
|
||||
}
|
||||
}
|
||||
|
|
@ -9,6 +9,7 @@ package main
|
|||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
|
|
@ -16,12 +17,13 @@ import (
|
|||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/modelcontextprotocol/go-sdk/auth"
|
||||
"github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
)
|
||||
|
||||
// scenarioHandler is the function signature for all conformance test scenarios.
|
||||
// It takes a context and the server URL to connect to.
|
||||
type scenarioHandler func(ctx context.Context, serverURL string) error
|
||||
type scenarioHandler func(ctx context.Context, serverURL string, configCtx map[string]any) error
|
||||
|
||||
var (
|
||||
// registry stores all registered scenario handlers.
|
||||
|
|
@ -48,7 +50,7 @@ func init() {
|
|||
// Basic scenarios
|
||||
// ============================================================================
|
||||
|
||||
func runBasicClient(ctx context.Context, serverURL string) error {
|
||||
func runBasicClient(ctx context.Context, serverURL string, _ map[string]any) error {
|
||||
session, err := connectToServer(ctx, serverURL)
|
||||
if err != nil {
|
||||
return err
|
||||
|
|
@ -63,7 +65,7 @@ func runBasicClient(ctx context.Context, serverURL string) error {
|
|||
return nil
|
||||
}
|
||||
|
||||
func runToolsCallClient(ctx context.Context, serverURL string) error {
|
||||
func runToolsCallClient(ctx context.Context, serverURL string, _ map[string]any) error {
|
||||
session, err := connectToServer(ctx, serverURL)
|
||||
if err != nil {
|
||||
return err
|
||||
|
|
@ -97,7 +99,7 @@ func runToolsCallClient(ctx context.Context, serverURL string) error {
|
|||
// Elicitation scenarios
|
||||
// ============================================================================
|
||||
|
||||
func runElicitationDefaultsClient(ctx context.Context, serverURL string) error {
|
||||
func runElicitationDefaultsClient(ctx context.Context, serverURL string, _ map[string]any) error {
|
||||
elicitationHandler := func(ctx context.Context, req *mcp.ElicitRequest) (*mcp.ElicitResult, error) {
|
||||
return &mcp.ElicitResult{
|
||||
Action: "accept",
|
||||
|
|
@ -141,8 +143,7 @@ func runElicitationDefaultsClient(ctx context.Context, serverURL string) error {
|
|||
// SSE retry scenario
|
||||
// ============================================================================
|
||||
|
||||
func runSSERetryClient(ctx context.Context, serverURL string) error {
|
||||
// TODO: this scenario is not passing yet. It requires a fix in the client SSE handling.
|
||||
func runSSERetryClient(ctx context.Context, serverURL string, _ map[string]any) error {
|
||||
session, err := connectToServer(ctx, serverURL)
|
||||
if err != nil {
|
||||
return err
|
||||
|
|
@ -185,6 +186,7 @@ func main() {
|
|||
|
||||
serverURL := os.Args[1]
|
||||
scenarioName := os.Getenv("MCP_CONFORMANCE_SCENARIO")
|
||||
configCtx := getConformanceContext()
|
||||
|
||||
if scenarioName == "" {
|
||||
printUsageAndExit("MCP_CONFORMANCE_SCENARIO not set")
|
||||
|
|
@ -196,11 +198,21 @@ func main() {
|
|||
}
|
||||
|
||||
ctx := context.Background()
|
||||
if err := handler(ctx, serverURL); err != nil {
|
||||
if err := handler(ctx, serverURL, configCtx); err != nil {
|
||||
log.Fatalf("Scenario %q failed: %v", scenarioName, err)
|
||||
}
|
||||
}
|
||||
|
||||
func getConformanceContext() map[string]any {
|
||||
ctxStr := os.Getenv("MCP_CONFORMANCE_CONTEXT")
|
||||
if ctxStr == "" {
|
||||
return nil
|
||||
}
|
||||
var ctx map[string]any
|
||||
_ = json.Unmarshal([]byte(ctxStr), &ctx)
|
||||
return ctx
|
||||
}
|
||||
|
||||
func printUsageAndExit(format string, args ...any) {
|
||||
var scenarios []string
|
||||
for name := range registry {
|
||||
|
|
@ -214,6 +226,7 @@ func printUsageAndExit(format string, args ...any) {
|
|||
|
||||
type connectConfig struct {
|
||||
clientOptions *mcp.ClientOptions
|
||||
oauthHandler auth.OAuthHandler
|
||||
}
|
||||
|
||||
type connectOption func(*connectConfig)
|
||||
|
|
@ -237,11 +250,14 @@ func connectToServer(ctx context.Context, serverURL string, opts ...connectOptio
|
|||
Version: "1.0.0",
|
||||
}, config.clientOptions)
|
||||
|
||||
transport := &mcp.StreamableClientTransport{Endpoint: serverURL}
|
||||
transport := &mcp.StreamableClientTransport{
|
||||
Endpoint: serverURL,
|
||||
OAuthHandler: config.oauthHandler,
|
||||
}
|
||||
|
||||
session, err := client.Connect(ctx, transport, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("client.Connect(): %v", err)
|
||||
return nil, fmt.Errorf("client.Connect(): %w", err)
|
||||
}
|
||||
|
||||
return session, nil
|
||||
|
|
|
|||
Loading…
Reference in a new issue