Documentation
¶
Index ¶
- 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 WithOAuth(mux *http.ServeMux, cfg *Config) (mcpserver.ServerOption, error)
- func WithOAuthToken(ctx context.Context, token string) context.Context
- type CachedToken
- type Config
- 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
- type TokenCache
- type User
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
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 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()
oauthOption, err := oauth.WithOAuth(mux, &oauth.Config{...})
mcpServer := server.NewMCPServer("Server", "1.0.0", oauthOption)
This function: - Creates OAuth server internally - Registers OAuth HTTP endpoints on mux - Returns middleware as server option
Note: You must also configure HTTPContextFunc to extract the OAuth token from HTTP headers. Use CreateHTTPContextFunc() helper.
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 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 (*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.
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
}