all: stabilize client OAuth support (#861)

Also fix lint errors that were hidden because of the build tag.
This commit is contained in:
Maciej Kisiel 2026-03-31 12:36:31 +02:00 • committed by GitHub
commit 638d404e0d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
34 changed files with 387 additions and 915 deletions

View file

@ -50,7 +50,7 @@ jobs:
uses: modelcontextprotocol/conformance@a2855b03582a6c0b31065ad4d9af248316ce61a3 # v0.1.15
with:
mode: client
command: go run -tags mcp_go_client_oauth ./conformance/everything-client
command: go run ./conformance/everything-client
suite: core
expected-failures: ./conformance/baseline.yml
node-version: 22

View file

@ -2,8 +2,6 @@
// Use of this source code is governed by the license
// that can be found in the LICENSE file.
//go:build mcp_go_client_oauth
package auth
import (
@ -142,7 +140,7 @@ func NewAuthorizationCodeHandler(config *AuthorizationCodeHandlerConfig) (*Autho
dCfg := config.DynamicClientRegistrationConfig
if dCfg != nil {
if dCfg.Metadata == nil {
return nil, errors.New("Metadata is required for dynamic client registration")
return nil, errors.New("dynamic client registration requires non-nil Metadata")
}
if len(dCfg.Metadata.RedirectURIs) == 0 {
return nil, errors.New("Metadata.RedirectURIs is required for dynamic client registration")
@ -283,17 +281,14 @@ func errorFromChallenges(cs []oauthex.Challenge) string {
// If no metadata was found or the fetched metadata fails security checks,
// it returns an error.
func (h *AuthorizationCodeHandler) getProtectedResourceMetadata(ctx context.Context, wwwChallenges []oauthex.Challenge, mcpServerURL string) (*oauthex.ProtectedResourceMetadata, error) {
var errs []error
// Use MCP server URL as the resource URI per
// https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization#canonical-server-uri.
for _, url := range protectedResourceMetadataURLs(resourceMetadataURLFromChallenges(wwwChallenges), mcpServerURL) {
prm, err := oauthex.GetProtectedResourceMetadata(ctx, url.URL, url.Resource, h.config.Client)
if err != nil {
errs = append(errs, err)
continue
}
if prm == nil {
errs = append(errs, fmt.Errorf("protected resource metadata is nil"))
continue
}
if len(prm.AuthorizationServers) == 0 {

View file

@ -2,8 +2,6 @@
// Use of this source code is governed by the license
// that can be found in the LICENSE file.
//go:build mcp_go_client_oauth
package auth
import (

View file

@ -1,135 +0,0 @@
// 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)
}

View file

@ -1,153 +0,0 @@
// 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 (
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"golang.org/x/oauth2"
)
// A basicReader is an io.Reader to be used as a non-rereadable request body.
//
// net/http has special handling for strings.Reader that we want to avoid.
type basicReader struct {
r *strings.Reader
}
func (r *basicReader) Read(p []byte) (n int, err error) { return r.r.Read(p) }
// TestHTTPTransport validates the OAuth HTTPTransport.
func TestHTTPTransport(t *testing.T) {
const testToken = "test-token-123"
fakeTokenSource := oauth2.StaticTokenSource(&oauth2.Token{
AccessToken: testToken,
TokenType: "Bearer",
})
// authServer simulates a resource that requires OAuth.
authServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
// Ensure that the body was properly cloned, by reading it completely.
// If the body is not cloned, reading it the second time may yield no
// bytes.
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if len(body) == 0 {
http.Error(w, "empty body", http.StatusBadRequest)
return
}
}
authHeader := r.Header.Get("Authorization")
if authHeader == fmt.Sprintf("Bearer %s", testToken) {
w.WriteHeader(http.StatusOK)
return
}
w.Header().Set("WWW-Authenticate", `Bearer resource_metadata="http://metadata.example.com"`)
w.WriteHeader(http.StatusUnauthorized)
}))
defer authServer.Close()
t.Run("successful auth flow", func(t *testing.T) {
var handlerCalls int
handler := func(req *http.Request, res *http.Response) (oauth2.TokenSource, error) {
handlerCalls++
// Verify that the response has the expected WWW-Authenticate header
if res.Header.Get("WWW-Authenticate") != `Bearer resource_metadata="http://metadata.example.com"` {
t.Errorf("handler got WWW-Authenticate header %q", res.Header.Get("WWW-Authenticate"))
}
return fakeTokenSource, nil
}
transport, err := NewHTTPTransport(handler, nil)
if err != nil {
t.Fatalf("NewHTTPTransport() failed: %v", err)
}
client := &http.Client{Transport: transport}
resp, err := client.Get(authServer.URL)
if err != nil {
t.Fatalf("client.Get() failed: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Errorf("got status %d, want %d", resp.StatusCode, http.StatusOK)
}
if handlerCalls != 1 {
t.Errorf("handler was called %d times, want 1", handlerCalls)
}
// Second request should reuse the token and not call the handler again.
resp2, err := client.Get(authServer.URL)
if err != nil {
t.Fatalf("second client.Get() failed: %v", err)
}
defer resp2.Body.Close()
if resp2.StatusCode != http.StatusOK {
t.Errorf("second request got status %d, want %d", resp2.StatusCode, http.StatusOK)
}
if handlerCalls != 1 {
t.Errorf("handler should still be called only once, but was %d", handlerCalls)
}
})
t.Run("request body is cloned", func(t *testing.T) {
handler := func(req *http.Request, res *http.Response) (oauth2.TokenSource, error) {
// Verify that the response has the expected WWW-Authenticate header
if res.Header.Get("WWW-Authenticate") != `Bearer resource_metadata="http://metadata.example.com"` {
t.Errorf("handler got WWW-Authenticate header %q", res.Header.Get("WWW-Authenticate"))
}
return fakeTokenSource, nil
}
transport, err := NewHTTPTransport(handler, nil)
if err != nil {
t.Fatalf("NewHTTPTransport() failed: %v", err)
}
client := &http.Client{Transport: transport}
resp, err := client.Post(authServer.URL, "application/json", &basicReader{strings.NewReader("{}")})
if err != nil {
t.Fatalf("client.Post() failed: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Errorf("got status %d, want %d", resp.StatusCode, http.StatusOK)
}
})
t.Run("handler returns error", func(t *testing.T) {
handlerErr := errors.New("user rejected auth")
handler := func(req *http.Request, res *http.Response) (oauth2.TokenSource, error) {
return nil, handlerErr
}
transport, err := NewHTTPTransport(handler, nil)
if err != nil {
t.Fatalf("NewHTTPTransport() failed: %v", err)
}
client := &http.Client{Transport: transport}
_, err = client.Get(authServer.URL)
if !errors.Is(err, handlerErr) {
t.Errorf("client.Get() returned error %v, want %v", err, handlerErr)
}
})
}

View file

@ -5,8 +5,6 @@
// Package extauth provides OAuth handler implementations for MCP authorization extensions.
// This package implements Enterprise Managed Authorization as defined in SEP-990.
//go:build mcp_go_client_oauth
package extauth
import (

View file

@ -2,8 +2,6 @@
// 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 extauth
import (

View file

@ -6,8 +6,6 @@
// as part of Enterprise Managed Authorization (SEP-990).
// See https://openid.net/specs/openid-connect-core-1_0.html
//go:build mcp_go_client_oauth
package extauth
import (
@ -121,11 +119,11 @@ func initiateOIDCLogin(
return nil, nil, fmt.Errorf("RedirectURL is required")
}
if len(config.Scopes) == 0 {
return nil, nil, fmt.Errorf("Scopes is required (must include 'openid')")
return nil, nil, fmt.Errorf("at least one scope is required (must include 'openid')")
}
if !slices.Contains(config.Scopes, "openid") {
return nil, nil, fmt.Errorf("Scopes must include 'openid' for OIDC")
return nil, nil, fmt.Errorf("the 'openid' scope is required for OIDC")
}
if err := checkURLScheme(config.IssuerURL); err != nil {

View file

@ -2,8 +2,6 @@
// 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 extauth
import (
@ -161,7 +159,7 @@ func TestInitiateOIDCLogin(t *testing.T) {
c.Credentials = &oauthex.ClientCredentials{ClientID: "test"}
c.RedirectURL = "http://localhost:8080/callback"
},
expectErr: "Scopes is required",
expectErr: "at least one scope is required",
},
}
for _, tt := range tests {

View file

@ -4,8 +4,6 @@
// This file contains shared utilities for OAuth handlers.
//go:build mcp_go_client_oauth
package auth
import (

View file

@ -2,8 +2,6 @@
// 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 (

View file

@ -1,139 +0,0 @@
// 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.PreregisteredClient = &oauthex.ClientCredentials{
ClientID: clientID,
ClientSecretAuth: &oauthex.ClientSecretAuth{
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
}
}

View file

@ -12,6 +12,8 @@ import (
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
"os"
"slices"
"sort"
@ -19,6 +21,7 @@ import (
"github.com/modelcontextprotocol/go-sdk/auth"
"github.com/modelcontextprotocol/go-sdk/mcp"
"github.com/modelcontextprotocol/go-sdk/oauthex"
)
// scenarioHandler is the function signature for all conformance test scenarios.
@ -44,6 +47,29 @@ func init() {
registerScenario("tools_call", runToolsCallClient)
registerScenario("elicitation-sep1034-client-defaults", runElicitationDefaultsClient)
registerScenario("sse-retry", runSSERetryClient)
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)
}
}
// ============================================================================
@ -175,6 +201,92 @@ func runSSERetryClient(ctx context.Context, serverURL string, _ map[string]any)
return nil
}
// ============================================================================
// 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.PreregisteredClient = &oauthex.ClientCredentials{
ClientID: clientID,
ClientSecretAuth: &oauthex.ClientSecretAuth{
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
}
// ============================================================================
// Main entry point
// ============================================================================
@ -237,6 +349,12 @@ func withClientOptions(opts *mcp.ClientOptions) connectOption {
}
}
func withOAuthHandler(handler auth.OAuthHandler) connectOption {
return func(c *connectConfig) {
c.oauthHandler = handler
}
}
// connectToServer connects to the MCP server and returns a client session.
// The caller is responsible for closing the session.
func connectToServer(ctx context.Context, serverURL string, opts ...connectOption) (*mcp.ClientSession, error) {

View file

@ -307,11 +307,6 @@ The [_auth middleware example_](https://github.com/modelcontextprotocol/go-sdk/
### Client
> [!IMPORTANT]
> Client-side OAuth support is currently experimental and requires the `mcp_go_client_oauth` build tag to compile.
> API changes may still be made, based on developer feedback. The build tag will be removed in `v1.5.0`, which
> is planned to be released by the end of March 2026.
Client-side authorization is supported via the
[`StreamableClientTransport.OAuthHandler`](https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp#StreamableClientTransport.OAuthHandler)
field. If the handler is provided, the transport will automatically use it to

View file

@ -2,8 +2,6 @@
// Use of this source code is governed by the license
// that can be found in the LICENSE file.
//go:build mcp_go_client_oauth
package main
import (
@ -29,7 +27,6 @@ var (
type codeReceiver struct {
authChan chan *auth.AuthorizationResult
errChan chan error
listener net.Listener
server *http.Server
}

View file

@ -2,8 +2,6 @@
// Use of this source code is governed by the license
// that can be found in the LICENSE file.
//go:build mcp_go_client_oauth
package main
import (
@ -45,7 +43,6 @@ var (
type codeReceiver struct {
authChan chan *auth.AuthorizationResult
errChan chan error
listener net.Listener
server *http.Server
}

View file

@ -232,11 +232,6 @@ The [_auth middleware example_](https://github.com/modelcontextprotocol/go-sdk/
### Client
> [!IMPORTANT]
> Client-side OAuth support is currently experimental and requires the `mcp_go_client_oauth` build tag to compile.
> API changes may still be made, based on developer feedback. The build tag will be removed in `v1.5.0`, which
> is planned to be released by the end of March 2026.
Client-side authorization is supported via the
[`StreamableClientTransport.OAuthHandler`](https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp#StreamableClientTransport.OAuthHandler)
field. If the handler is provided, the transport will automatically use it to

View file

@ -2,8 +2,6 @@
// Use of this source code is governed by the license
// that can be found in the LICENSE file.
//go:build mcp_go_client_oauth
package oauthtest
import (

View file

@ -1,179 +0,0 @@
// Copyright 2026 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 mcp
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/modelcontextprotocol/go-sdk/auth"
"golang.org/x/oauth2"
)
type mockOAuthHandler struct {
// Embed to satisfy the interface.
auth.AuthorizationCodeHandler
token *oauth2.Token
authorizeErr error
authorizeCalled bool
}
func (h *mockOAuthHandler) TokenSource(ctx context.Context) (oauth2.TokenSource, error) {
if h.token == nil {
return nil, nil
}
return oauth2.StaticTokenSource(h.token), nil
}
func (h *mockOAuthHandler) Authorize(ctx context.Context, req *http.Request, resp *http.Response) error {
h.authorizeCalled = true
return h.authorizeErr
}
func TestStreamableClientOAuth_AuthorizationHeader(t *testing.T) {
ctx := context.Background()
token := &oauth2.Token{AccessToken: "test-token"}
oauthHandler := &mockOAuthHandler{token: token}
fake := &fakeStreamableServer{
t: t,
responses: fakeResponses{
{"POST", "", methodInitialize, ""}: {
header: header{
"Content-Type": "application/json",
sessionIDHeader: "123",
},
body: jsonBody(t, initResp),
},
{"POST", "123", notificationInitialized, ""}: {
status: http.StatusAccepted,
wantProtocolVersion: latestProtocolVersion,
},
{"GET", "123", "", ""}: {
header: header{
"Content-Type": "text/event-stream",
},
},
{"DELETE", "123", "", ""}: {},
},
}
verifier := func(ctx context.Context, token string, req *http.Request) (*auth.TokenInfo, error) {
if token != "test-token" {
return nil, auth.ErrInvalidToken
}
return &auth.TokenInfo{Expiration: time.Now().Add(time.Hour)}, nil
}
httpServer := httptest.NewServer(auth.RequireBearerToken(verifier, nil)(fake))
t.Cleanup(httpServer.Close)
transport := &StreamableClientTransport{
Endpoint: httpServer.URL,
OAuthHandler: oauthHandler,
}
client := NewClient(testImpl, nil)
session, err := client.Connect(ctx, transport, nil)
if err != nil {
t.Fatalf("client.Connect() failed: %v", err)
}
session.Close()
}
func TestStreamableClientOAuth_401(t *testing.T) {
ctx := context.Background()
oauthHandler := &mockOAuthHandler{token: nil}
fake := &fakeStreamableServer{
t: t,
responses: fakeResponses{
{"POST", "", methodInitialize, ""}: {
header: header{
"Content-Type": "application/json",
sessionIDHeader: "123",
},
body: jsonBody(t, initResp),
},
},
}
verifier := func(ctx context.Context, token string, req *http.Request) (*auth.TokenInfo, error) {
// Accept any token.
return &auth.TokenInfo{Expiration: time.Now().Add(time.Hour)}, nil
}
httpServer := httptest.NewServer(auth.RequireBearerToken(verifier, nil)(fake))
t.Cleanup(httpServer.Close)
transport := &StreamableClientTransport{
Endpoint: httpServer.URL,
OAuthHandler: oauthHandler,
}
client := NewClient(testImpl, nil)
_, err := client.Connect(ctx, transport, nil)
if err == nil || !strings.Contains(err.Error(), "Unauthorized") {
t.Fatalf("client.Connect() error does not contain 'Unauthorized': %v", err)
}
if !oauthHandler.authorizeCalled {
t.Errorf("expected Authorize to be called")
}
}
func TestTokenInfo(t *testing.T) {
ctx := context.Background()
// Create a server with a tool that returns TokenInfo.
tokenInfo := func(ctx context.Context, req *CallToolRequest, _ struct{}) (*CallToolResult, any, error) {
return &CallToolResult{Content: []Content{&TextContent{Text: fmt.Sprintf("%v", req.Extra.TokenInfo)}}}, nil, nil
}
server := NewServer(testImpl, nil)
AddTool(server, &Tool{Name: "tokenInfo", Description: "return token info"}, tokenInfo)
streamHandler := NewStreamableHTTPHandler(func(req *http.Request) *Server { return server }, nil)
verifier := func(ctx context.Context, token string, req *http.Request) (*auth.TokenInfo, error) {
if token != "test-token" {
return nil, auth.ErrInvalidToken
}
return &auth.TokenInfo{
Scopes: []string{"scope"},
// Expiration is far, far in the future.
Expiration: time.Date(5000, 1, 2, 3, 4, 5, 0, time.UTC),
}, nil
}
handler := auth.RequireBearerToken(verifier, nil)(streamHandler)
httpServer := httptest.NewServer(mustNotPanic(t, handler))
defer httpServer.Close()
transport := &StreamableClientTransport{
Endpoint: httpServer.URL,
OAuthHandler: &mockOAuthHandler{token: &oauth2.Token{AccessToken: "test-token"}},
}
client := NewClient(testImpl, nil)
session, err := client.Connect(ctx, transport, nil)
if err != nil {
t.Fatalf("client.Connect() failed: %v", err)
}
defer session.Close()
res, err := session.CallTool(ctx, &CallToolParams{Name: "tokenInfo"})
if err != nil {
t.Fatal(err)
}
if len(res.Content) == 0 {
t.Fatal("missing content")
}
tc, ok := res.Content[0].(*TextContent)
if !ok {
t.Fatal("not TextContent")
}
if g, w := tc.Text, "&{[scope] 5000-01-02 03:04:05 +0000 UTC map[]}"; g != w {
t.Errorf("got %q, want %q", g, w)
}
}

View file

@ -17,8 +17,10 @@ import (
"time"
"github.com/google/go-cmp/cmp"
"github.com/modelcontextprotocol/go-sdk/auth"
"github.com/modelcontextprotocol/go-sdk/internal/jsonrpc2"
"github.com/modelcontextprotocol/go-sdk/jsonrpc"
"golang.org/x/oauth2"
)
type streamableRequestKey struct {
@ -908,3 +910,159 @@ func TestStreamableClientDisableStandaloneSSE(t *testing.T) {
})
}
}
type mockOAuthHandler struct {
token *oauth2.Token
authorizeErr error
authorizeCalled bool
}
func (h *mockOAuthHandler) TokenSource(ctx context.Context) (oauth2.TokenSource, error) {
if h.token == nil {
return nil, nil
}
return oauth2.StaticTokenSource(h.token), nil
}
func (h *mockOAuthHandler) Authorize(ctx context.Context, req *http.Request, resp *http.Response) error {
h.authorizeCalled = true
return h.authorizeErr
}
func TestStreamableClientOAuth_AuthorizationHeader(t *testing.T) {
ctx := context.Background()
token := &oauth2.Token{AccessToken: "test-token"}
oauthHandler := &mockOAuthHandler{token: token}
fake := &fakeStreamableServer{
t: t,
responses: fakeResponses{
{"POST", "", methodInitialize, ""}: {
header: header{
"Content-Type": "application/json",
sessionIDHeader: "123",
},
body: jsonBody(t, initResp),
},
{"POST", "123", notificationInitialized, ""}: {
status: http.StatusAccepted,
wantProtocolVersion: latestProtocolVersion,
},
{"GET", "123", "", ""}: {
header: header{
"Content-Type": "text/event-stream",
},
},
{"DELETE", "123", "", ""}: {},
},
}
verifier := func(ctx context.Context, token string, req *http.Request) (*auth.TokenInfo, error) {
if token != "test-token" {
return nil, auth.ErrInvalidToken
}
return &auth.TokenInfo{Expiration: time.Now().Add(time.Hour)}, nil
}
httpServer := httptest.NewServer(auth.RequireBearerToken(verifier, nil)(fake))
t.Cleanup(httpServer.Close)
transport := &StreamableClientTransport{
Endpoint: httpServer.URL,
OAuthHandler: oauthHandler,
}
client := NewClient(testImpl, nil)
session, err := client.Connect(ctx, transport, nil)
if err != nil {
t.Fatalf("client.Connect() failed: %v", err)
}
session.Close()
}
func TestStreamableClientOAuth_401(t *testing.T) {
ctx := context.Background()
oauthHandler := &mockOAuthHandler{token: nil}
fake := &fakeStreamableServer{
t: t,
responses: fakeResponses{
{"POST", "", methodInitialize, ""}: {
header: header{
"Content-Type": "application/json",
sessionIDHeader: "123",
},
body: jsonBody(t, initResp),
},
},
}
verifier := func(ctx context.Context, token string, req *http.Request) (*auth.TokenInfo, error) {
// Accept any token.
return &auth.TokenInfo{Expiration: time.Now().Add(time.Hour)}, nil
}
httpServer := httptest.NewServer(auth.RequireBearerToken(verifier, nil)(fake))
t.Cleanup(httpServer.Close)
transport := &StreamableClientTransport{
Endpoint: httpServer.URL,
OAuthHandler: oauthHandler,
}
client := NewClient(testImpl, nil)
_, err := client.Connect(ctx, transport, nil)
if err == nil || !strings.Contains(err.Error(), "Unauthorized") {
t.Fatalf("client.Connect() error does not contain 'Unauthorized': %v", err)
}
if !oauthHandler.authorizeCalled {
t.Errorf("expected Authorize to be called")
}
}
func TestTokenInfo(t *testing.T) {
ctx := context.Background()
// Create a server with a tool that returns TokenInfo.
tokenInfo := func(ctx context.Context, req *CallToolRequest, _ struct{}) (*CallToolResult, any, error) {
return &CallToolResult{Content: []Content{&TextContent{Text: fmt.Sprintf("%v", req.Extra.TokenInfo)}}}, nil, nil
}
server := NewServer(testImpl, nil)
AddTool(server, &Tool{Name: "tokenInfo", Description: "return token info"}, tokenInfo)
streamHandler := NewStreamableHTTPHandler(func(req *http.Request) *Server { return server }, nil)
verifier := func(ctx context.Context, token string, req *http.Request) (*auth.TokenInfo, error) {
if token != "test-token" {
return nil, auth.ErrInvalidToken
}
return &auth.TokenInfo{
Scopes: []string{"scope"},
// Expiration is far, far in the future.
Expiration: time.Date(5000, 1, 2, 3, 4, 5, 0, time.UTC),
}, nil
}
handler := auth.RequireBearerToken(verifier, nil)(streamHandler)
httpServer := httptest.NewServer(mustNotPanic(t, handler))
defer httpServer.Close()
transport := &StreamableClientTransport{
Endpoint: httpServer.URL,
OAuthHandler: &mockOAuthHandler{token: &oauth2.Token{AccessToken: "test-token"}},
}
client := NewClient(testImpl, nil)
session, err := client.Connect(ctx, transport, nil)
if err != nil {
t.Fatalf("client.Connect() failed: %v", err)
}
defer session.Close()
res, err := session.CallTool(ctx, &CallToolParams{Name: "tokenInfo"})
if err != nil {
t.Fatal(err)
}
if len(res.Content) == 0 {
t.Fatal("missing content")
}
tc, ok := res.Content[0].(*TextContent)
if !ok {
t.Fatal("not TextContent")
}
if g, w := tc.Text, "&{[scope] 5000-01-02 03:04:05 +0000 UTC map[]}"; g != w {
t.Errorf("got %q, want %q", g, w)
}
}

Some files were not shown because too many files have changed in this diff Show more