Documentation
¶
Index ¶
- func AutoDetectServerURL(host, port string, useTLS bool) string
- func CreateHTTPContextFunc() func(context.Context, *http.Request) context.Context
- func CreateRequestAuthHook(validator provider.TokenValidator) func(context.Context, interface{}, interface{}) errordeprecated
- func GetOAuthToken(ctx context.Context) (string, bool)
- func OAuthMiddleware(validator provider.TokenValidator, enabled bool) func(server.ToolHandlerFunc) server.ToolHandlerFuncdeprecated
- func SetupOAuth(cfg *Config) (provider.TokenValidator, error)deprecated
- func WithOAuthToken(ctx context.Context, token string) context.Context
- func WithUser(ctx context.Context, user *User) context.Context
- type CachedToken
- type Config
- type ConfigBuilder
- func (b *ConfigBuilder) Build() (*Config, error)
- func (b *ConfigBuilder) WithAudience(audience string) *ConfigBuilder
- func (b *ConfigBuilder) WithClientID(clientID string) *ConfigBuilder
- func (b *ConfigBuilder) WithClientSecret(secret string) *ConfigBuilder
- func (b *ConfigBuilder) WithHost(host string) *ConfigBuilder
- func (b *ConfigBuilder) WithIssuer(issuer string) *ConfigBuilder
- func (b *ConfigBuilder) WithJWTSecret(secret []byte) *ConfigBuilder
- func (b *ConfigBuilder) WithLogger(logger Logger) *ConfigBuilder
- func (b *ConfigBuilder) WithMode(mode string) *ConfigBuilder
- func (b *ConfigBuilder) WithPort(port string) *ConfigBuilder
- func (b *ConfigBuilder) WithProvider(provider string) *ConfigBuilder
- func (b *ConfigBuilder) WithRedirectURIs(uris string) *ConfigBuilder
- func (b *ConfigBuilder) WithServerURL(url string) *ConfigBuilder
- func (b *ConfigBuilder) WithTLS(useTLS bool) *ConfigBuilder
- type Endpoint
- type Logger
- type OAuth2Config
- type OAuth2Handler
- func (h *OAuth2Handler) GetAuthorizationServerMetadata() map[string]interface{}
- func (h *OAuth2Handler) GetConfig() *OAuth2Config
- func (h *OAuth2Handler) HandleAuthorizationServerMetadata(w http.ResponseWriter, r *http.Request)
- func (h *OAuth2Handler) HandleAuthorize(w http.ResponseWriter, r *http.Request)
- func (h *OAuth2Handler) HandleCallback(w http.ResponseWriter, r *http.Request)
- func (h *OAuth2Handler) HandleCallbackRedirect(w http.ResponseWriter, r *http.Request)
- func (h *OAuth2Handler) HandleJWKS(w http.ResponseWriter, r *http.Request)
- func (h *OAuth2Handler) HandleMetadata(w http.ResponseWriter, r *http.Request)
- func (h *OAuth2Handler) HandleOIDCDiscovery(w http.ResponseWriter, r *http.Request)
- func (h *OAuth2Handler) HandleProtectedResourceMetadata(w http.ResponseWriter, r *http.Request)
- func (h *OAuth2Handler) HandleRegister(w http.ResponseWriter, r *http.Request)
- func (h *OAuth2Handler) HandleToken(w http.ResponseWriter, r *http.Request)
- type Server
- func (s *Server) GetAllEndpoints() []Endpoint
- func (s *Server) GetAuthorizationServerMetadataURL() string
- func (s *Server) GetAuthorizeURL() string
- func (s *Server) GetCallbackURL() string
- func (s *Server) GetHTTPServerOptions() []mcpserver.StreamableHTTPOption
- func (s *Server) GetOIDCDiscoveryURL() string
- func (s *Server) GetProtectedResourceMetadataURL() string
- func (s *Server) GetRegisterURL() string
- func (s *Server) GetStatusString(useTLS bool) string
- func (s *Server) GetTokenURL() string
- func (s *Server) LogStartup(useTLS bool)
- func (s *Server) Middleware() func(server.ToolHandlerFunc) server.ToolHandlerFunc
- func (s *Server) RegisterHandlers(mux *http.ServeMux)
- func (s *Server) ValidateTokenCached(ctx context.Context, token string) (*User, error)
- func (s *Server) WrapHandler(next http.Handler) http.Handler
- func (s *Server) WrapHandlerFunc(next http.HandlerFunc) http.HandlerFunc
- type TokenCache
- type User
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AutoDetectServerURL ¶ added in v0.1.0
AutoDetectServerURL constructs a server URL from components
func CreateHTTPContextFunc ¶
CreateHTTPContextFunc creates an HTTP context function that extracts OAuth tokens from Authorization headers. Use with mcpserver.WithHTTPContextFunc() to enable token extraction from HTTP requests.
Example:
streamableServer := mcpserver.NewStreamableHTTPServer(
mcpServer,
mcpserver.WithHTTPContextFunc(oauth.CreateHTTPContextFunc()),
)
This extracts "Bearer <token>" from Authorization header and adds it to context via WithOAuthToken(). The OAuth middleware then retrieves it via GetOAuthToken().
func CreateRequestAuthHook
deprecated
func CreateRequestAuthHook(validator provider.TokenValidator) func(context.Context, interface{}, interface{}) error
CreateRequestAuthHook creates a server-level authentication hook for all MCP requests.
Deprecated: This function cannot propagate context changes due to its signature limitation. Use WithOAuth() instead, which properly handles context propagation via tool-level middleware.
This function is a no-op that always returns nil. Authentication happens at the tool level via Server.Middleware() which can properly propagate the authenticated user in context.
func GetOAuthToken ¶
GetOAuthToken extracts an OAuth token from the context
func OAuthMiddleware
deprecated
func OAuthMiddleware(validator provider.TokenValidator, enabled bool) func(server.ToolHandlerFunc) server.ToolHandlerFunc
OAuthMiddleware creates an authentication middleware (legacy function for compatibility).
Deprecated: Use WithOAuth() for new code. This function creates a temporary Server instance for each call and doesn't support custom logging. Kept for backward compatibility only.
Modern usage:
oauthOption, _ := oauth.WithOAuth(mux, &oauth.Config{...})
mcpServer := server.NewMCPServer("name", "1.0.0", oauthOption)
func SetupOAuth
deprecated
func SetupOAuth(cfg *Config) (provider.TokenValidator, error)
SetupOAuth initializes OAuth validation and sets up OAuth configuration.
Deprecated: Use WithOAuth() for new code, which provides complete OAuth setup including middleware and HTTP handlers. This function only creates a validator and requires manual wiring.
Modern usage:
oauthOption, _ := oauth.WithOAuth(mux, &oauth.Config{...})
mcpServer := server.NewMCPServer("name", "1.0.0", oauthOption)
func WithOAuthToken ¶
WithOAuthToken adds an OAuth token to the context
Types ¶
type CachedToken ¶
CachedToken represents a cached token validation result
type Config ¶
type Config struct {
// OAuth settings
Mode string // "native" or "proxy"
Provider string // "hmac", "okta", "google", "azure"
RedirectURIs string // Redirect URIs (single or comma-separated)
// OIDC configuration
Issuer string
Audience string
ClientID string
ClientSecret string
// Server configuration
ServerURL string // Full URL of the MCP server
// Security
JWTSecret []byte // For HMAC provider and state signing
// Optional - Logging
// Logger allows custom logging implementation. If nil, uses default logger
// that outputs to log.Printf with level prefixes ([INFO], [ERROR], etc.).
// Implement the Logger interface (Debug, Info, Warn, Error methods) to
// integrate with your application's logging system (e.g., zap, logrus).
Logger Logger
}
Config holds OAuth configuration
type ConfigBuilder ¶ added in v0.1.0
type ConfigBuilder struct {
// contains filtered or unexported fields
}
ConfigBuilder provides a fluent API for constructing OAuth Config
func NewConfigBuilder ¶ added in v0.1.0
func NewConfigBuilder() *ConfigBuilder
NewConfigBuilder creates a new ConfigBuilder
func (*ConfigBuilder) Build ¶ added in v0.1.0
func (b *ConfigBuilder) Build() (*Config, error)
Build constructs and validates the Config
func (*ConfigBuilder) WithAudience ¶ added in v0.1.0
func (b *ConfigBuilder) WithAudience(audience string) *ConfigBuilder
WithAudience sets the audience
func (*ConfigBuilder) WithClientID ¶ added in v0.1.0
func (b *ConfigBuilder) WithClientID(clientID string) *ConfigBuilder
WithClientID sets the client ID
func (*ConfigBuilder) WithClientSecret ¶ added in v0.1.0
func (b *ConfigBuilder) WithClientSecret(secret string) *ConfigBuilder
WithClientSecret sets the client secret
func (*ConfigBuilder) WithHost ¶ added in v0.1.0
func (b *ConfigBuilder) WithHost(host string) *ConfigBuilder
WithHost sets the server host (used to construct ServerURL if not set)
func (*ConfigBuilder) WithIssuer ¶ added in v0.1.0
func (b *ConfigBuilder) WithIssuer(issuer string) *ConfigBuilder
WithIssuer sets the OIDC issuer
func (*ConfigBuilder) WithJWTSecret ¶ added in v0.1.0
func (b *ConfigBuilder) WithJWTSecret(secret []byte) *ConfigBuilder
WithJWTSecret sets the JWT secret
func (*ConfigBuilder) WithLogger ¶ added in v0.1.0
func (b *ConfigBuilder) WithLogger(logger Logger) *ConfigBuilder
WithLogger sets the logger
func (*ConfigBuilder) WithMode ¶ added in v0.1.0
func (b *ConfigBuilder) WithMode(mode string) *ConfigBuilder
WithMode sets the OAuth mode ("native" or "proxy")
func (*ConfigBuilder) WithPort ¶ added in v0.1.0
func (b *ConfigBuilder) WithPort(port string) *ConfigBuilder
WithPort sets the server port (used to construct ServerURL if not set)
func (*ConfigBuilder) WithProvider ¶ added in v0.1.0
func (b *ConfigBuilder) WithProvider(provider string) *ConfigBuilder
WithProvider sets the OAuth provider ("hmac", "okta", "google", "azure")
func (*ConfigBuilder) WithRedirectURIs ¶ added in v0.1.0
func (b *ConfigBuilder) WithRedirectURIs(uris string) *ConfigBuilder
WithRedirectURIs sets the redirect URIs
func (*ConfigBuilder) WithServerURL ¶ added in v0.1.0
func (b *ConfigBuilder) WithServerURL(url string) *ConfigBuilder
WithServerURL sets the full server URL directly
func (*ConfigBuilder) WithTLS ¶ added in v0.1.0
func (b *ConfigBuilder) WithTLS(useTLS bool) *ConfigBuilder
WithTLS enables HTTPS scheme (used to construct ServerURL if not set)
type Logger ¶
type Logger interface {
Debug(msg string, args ...interface{}) // Debug-level logging for detailed troubleshooting
Info(msg string, args ...interface{}) // Info-level logging for normal OAuth operations
Warn(msg string, args ...interface{}) // Warn-level logging for security violations
Error(msg string, args ...interface{}) // Error-level logging for OAuth failures
}
Logger interface for pluggable logging. Implement this interface to integrate oauth-mcp-proxy with your application's logging system (e.g., zap, logrus, slog). If not provided in Config, a default logger using log.Printf will be used.
Example:
type MyLogger struct{ logger *zap.Logger }
func (l *MyLogger) Info(msg string, args ...interface{}) {
l.logger.Sugar().Infof(msg, args...)
}
// ... implement Debug, Warn, Error
cfg := &oauth.Config{
Provider: "okta",
Logger: &MyLogger{logger: zapLogger},
}
type OAuth2Config ¶
type OAuth2Config struct {
Enabled bool
Mode string // "native" or "proxy"
Provider string
RedirectURIs string
// OIDC configuration
Issuer string
Audience string
ClientID string
ClientSecret string
// Server configuration
MCPHost string
MCPPort string
Scheme string
// MCPURL is the full URL of the MCP server, used for the resource endpoint in the OAuth 2.0 Protected Resource Metadata endpoint
MCPURL string
// Server version
Version string
// contains filtered or unexported fields
}
OAuth2Config holds OAuth2 configuration
func NewOAuth2ConfigFromConfig ¶
func NewOAuth2ConfigFromConfig(cfg *Config, version string) *OAuth2Config
NewOAuth2ConfigFromConfig creates OAuth2 config from generic Config
type OAuth2Handler ¶
type OAuth2Handler struct {
// contains filtered or unexported fields
}
OAuth2Handler handles OAuth2 flows using the standard library
func CreateOAuth2Handler ¶
func CreateOAuth2Handler(cfg *Config, version string, logger Logger) *OAuth2Handler
CreateOAuth2Handler creates a new OAuth2 handler for HTTP endpoints
func NewOAuth2Handler ¶
func NewOAuth2Handler(cfg *OAuth2Config, logger Logger) *OAuth2Handler
NewOAuth2Handler creates a new OAuth2 handler using the standard library
func (*OAuth2Handler) GetAuthorizationServerMetadata ¶
func (h *OAuth2Handler) GetAuthorizationServerMetadata() map[string]interface{}
GetAuthorizationServerMetadata returns the OAuth 2.0 Authorization Server Metadata with conditional responses based on OAuth mode
func (*OAuth2Handler) GetConfig ¶
func (h *OAuth2Handler) GetConfig() *OAuth2Config
GetConfig returns the OAuth2 configuration
func (*OAuth2Handler) HandleAuthorizationServerMetadata ¶
func (h *OAuth2Handler) HandleAuthorizationServerMetadata(w http.ResponseWriter, r *http.Request)
HandleAuthorizationServerMetadata handles the standard OAuth 2.0 Authorization Server Metadata endpoint
func (*OAuth2Handler) HandleAuthorize ¶
func (h *OAuth2Handler) HandleAuthorize(w http.ResponseWriter, r *http.Request)
HandleAuthorize handles OAuth2 authorization requests with PKCE
func (*OAuth2Handler) HandleCallback ¶
func (h *OAuth2Handler) HandleCallback(w http.ResponseWriter, r *http.Request)
HandleCallback handles OAuth2 callback
func (*OAuth2Handler) HandleCallbackRedirect ¶
func (h *OAuth2Handler) HandleCallbackRedirect(w http.ResponseWriter, r *http.Request)
HandleCallbackRedirect handles the /callback redirect for Claude Code compatibility
func (*OAuth2Handler) HandleJWKS ¶
func (h *OAuth2Handler) HandleJWKS(w http.ResponseWriter, r *http.Request)
HandleJWKS handles the JWKS endpoint for proxy mode
func (*OAuth2Handler) HandleMetadata ¶
func (h *OAuth2Handler) HandleMetadata(w http.ResponseWriter, r *http.Request)
HandleMetadata handles the legacy OAuth metadata endpoint for MCP compliance
func (*OAuth2Handler) HandleOIDCDiscovery ¶
func (h *OAuth2Handler) HandleOIDCDiscovery(w http.ResponseWriter, r *http.Request)
HandleOIDCDiscovery handles the OIDC discovery endpoint for MCP client compatibility
func (*OAuth2Handler) HandleProtectedResourceMetadata ¶
func (h *OAuth2Handler) HandleProtectedResourceMetadata(w http.ResponseWriter, r *http.Request)
HandleProtectedResourceMetadata handles the OAuth 2.0 Protected Resource Metadata endpoint
func (*OAuth2Handler) HandleRegister ¶
func (h *OAuth2Handler) HandleRegister(w http.ResponseWriter, r *http.Request)
HandleRegister handles OAuth dynamic client registration for mcp-remote
func (*OAuth2Handler) HandleToken ¶
func (h *OAuth2Handler) HandleToken(w http.ResponseWriter, r *http.Request)
HandleToken handles OAuth2 token exchange
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server represents an OAuth authentication server instance. Each Server maintains its own token cache and validator, allowing multiple independent OAuth configurations in the same application.
Create using NewServer(). Access middleware via Middleware() and register HTTP endpoints via RegisterHandlers().
func NewServer ¶
NewServer creates a new OAuth server with the given configuration. Validates configuration, initializes provider-specific token validator, and creates instance-scoped token cache.
Example:
server, err := oauth.NewServer(&oauth.Config{
Provider: "okta",
Issuer: "https://company.okta.com",
Audience: "api://my-server",
})
Most users should use WithOAuth() instead, which wraps NewServer() and automatically registers handlers and middleware.
func WithOAuth ¶
WithOAuth returns a server option that enables OAuth authentication This is the composable API for mcp-go v0.41.1
Usage:
mux := http.NewServeMux()
oauthServer, oauthOption, err := oauth.WithOAuth(mux, &oauth.Config{...})
mcpServer := server.NewMCPServer("Server", "1.0.0", oauthOption)
This function: - Creates OAuth server instance - Registers OAuth HTTP endpoints on mux - Returns server instance and middleware as server option
The returned Server instance provides access to: - WrapHandler() - Wrap HTTP handlers with OAuth token validation - GetHTTPServerOptions() - Get StreamableHTTPServer options - LogStartup() - Log OAuth endpoint information - Discovery URL helpers (GetCallbackURL, GetMetadataURL, etc.)
Note: You must also configure HTTPContextFunc to extract the OAuth token from HTTP headers. Use GetHTTPServerOptions() or CreateHTTPContextFunc().
func (*Server) GetAllEndpoints ¶ added in v0.1.0
GetAllEndpoints returns all OAuth endpoints with descriptions
func (*Server) GetAuthorizationServerMetadataURL ¶ added in v0.1.0
GetAuthorizationServerMetadataURL returns the OAuth 2.0 authorization server metadata URL
func (*Server) GetAuthorizeURL ¶ added in v0.1.0
GetAuthorizeURL returns the OAuth authorization URL
func (*Server) GetCallbackURL ¶ added in v0.1.0
GetCallbackURL returns the OAuth callback URL
func (*Server) GetHTTPServerOptions ¶ added in v0.1.0
func (s *Server) GetHTTPServerOptions() []mcpserver.StreamableHTTPOption
GetHTTPServerOptions returns StreamableHTTPServer options needed for OAuth. Returns WithHTTPContextFunc option to extract OAuth tokens from HTTP headers. Consumers should append these to their own options when creating StreamableHTTPServer.
Example:
oauthOpts := oauthServer.GetHTTPServerOptions()
allOpts := append(oauthOpts,
mcpserver.WithEndpointPath("/mcp"),
mcpserver.WithStateLess(false),
)
server := mcpserver.NewStreamableHTTPServer(mcpServer, allOpts...)
func (*Server) GetOIDCDiscoveryURL ¶ added in v0.1.0
GetOIDCDiscoveryURL returns the OIDC discovery URL
func (*Server) GetProtectedResourceMetadataURL ¶ added in v0.1.0
GetProtectedResourceMetadataURL returns the protected resource metadata URL
func (*Server) GetRegisterURL ¶ added in v0.1.0
GetRegisterURL returns the dynamic client registration URL
func (*Server) GetStatusString ¶ added in v0.1.0
GetStatusString returns a human-readable OAuth status string
func (*Server) GetTokenURL ¶ added in v0.1.0
GetTokenURL returns the OAuth token URL
func (*Server) LogStartup ¶ added in v0.1.0
LogStartup logs OAuth startup information including endpoints and configuration. Set useTLS to true if using HTTPS, false for HTTP (will add warning).
func (*Server) Middleware ¶
func (s *Server) Middleware() func(server.ToolHandlerFunc) server.ToolHandlerFunc
Middleware returns an authentication middleware for MCP tools. Validates OAuth tokens, caches results, and adds authenticated user to context.
The middleware:
- Extracts OAuth token from context (set by CreateHTTPContextFunc)
- Checks token cache (5-minute TTL)
- Validates token using configured provider if not cached
- Adds User to context via userContextKey
- Passes request to tool handler with authenticated context
Use GetUserFromContext(ctx) in tool handlers to access authenticated user.
Note: WithOAuth() returns this middleware wrapped as mcpserver.ServerOption. Only call directly if using NewServer() for advanced use cases.
func (*Server) RegisterHandlers ¶
RegisterHandlers registers OAuth HTTP endpoints on the provided mux. Endpoints registered:
- /.well-known/oauth-authorization-server - OAuth 2.0 metadata (RFC 8414)
- /.well-known/oauth-protected-resource - Resource metadata
- /.well-known/jwks.json - JWKS keys
- /.well-known/openid-configuration - OIDC discovery
- /oauth/authorize - Authorization endpoint (proxy mode)
- /oauth/callback - Callback handler (proxy mode)
- /oauth/token - Token exchange (proxy mode)
- /oauth/register - Dynamic client registration
Note: WithOAuth() calls this automatically. Only call directly if using NewServer() for advanced use cases.
func (*Server) ValidateTokenCached ¶ added in v1.0.0
ValidateTokenCached validates a token with caching support. This is the core validation method that SDK adapters can use.
The method:
- Checks token cache (5-minute TTL)
- Validates token using configured provider if not cached
- Caches validation result for future requests
- Returns authenticated User or error
This method is used internally by both WrapHandler and adapter middleware.
func (*Server) WrapHandler ¶ added in v0.1.0
WrapHandler wraps an http.Handler with OAuth Bearer token validation. It checks for a valid Authorization header before delegating to the wrapped handler. If the token is missing or invalid, returns 401 with WWW-Authenticate headers and proper OAuth error response per RFC 6750.
This eliminates the need for consumers to manually check Bearer tokens in their HTTP handlers. Use this to wrap MCP endpoints or any protected resource.
Example:
wrappedHandler := oauthServer.WrapHandler(mcpHandler)
mux.HandleFunc("/mcp", wrappedHandler)
func (*Server) WrapHandlerFunc ¶ added in v0.1.0
func (s *Server) WrapHandlerFunc(next http.HandlerFunc) http.HandlerFunc
WrapHandlerFunc wraps an http.HandlerFunc with OAuth Bearer token validation. Convenience wrapper around WrapHandler for HandlerFunc types.
type TokenCache ¶
type TokenCache struct {
// contains filtered or unexported fields
}
TokenCache stores validated tokens to avoid re-validation
type User ¶
Re-export User from provider for backwards compatibility
func GetUserFromContext ¶
GetUserFromContext extracts the authenticated user from context. Returns the User and true if authentication succeeded, or nil and false otherwise.
Example:
func toolHandler(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
user, ok := oauth.GetUserFromContext(ctx)
if !ok {
return nil, fmt.Errorf("authentication required")
}
// Use user.Subject, user.Email, user.Username
return mcp.NewToolResultText("Hello, " + user.Username), nil
}
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
mark3labs/advanced
command
|
|
|
mark3labs/simple
command
|
|
|
official/advanced
command
|
|
|
official/simple
command
|
|