Documentation
¶
Overview ¶
Package auth provides MCP authorization support backed by oneauth. It implements mcpkit's AuthValidator, ClaimsProvider, TokenSource, and ExtensionProvider interfaces as thin adapters over oneauth's JWT, OAuth, and discovery primitives.
This is a separate Go module (github.com/panyam/mcpkit/auth) so that the core mcpkit module stays zero-auth-deps. Import this package only when you need JWT validation, OAuth flows, or PRM endpoints.
Index ¶
- func MountAuth(mux *http.ServeMux, cfg AuthConfig)
- func ParseWWWAuthenticate(header string) (resourceMetadata string, scopes []string, err error)
- func RequireAllScopes(ctx context.Context, scopes ...string) error
- func RequireScope(ctx context.Context, scope string) error
- func WWWAuth401(resourceMetadataURL string, scopes ...string) string
- func WWWAuth403(scopes ...string) string
- type AuthConfig
- type AuthExtension
- type ClientCredentialsSource
- type JWTConfig
- type JWTValidator
- type MCPAuthInfo
- type OAuthTokenSource
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func MountAuth ¶
func MountAuth(mux *http.ServeMux, cfg AuthConfig)
MountAuth registers the OAuth Protected Resource Metadata endpoint (RFC 9728) on the given mux. This enables MCP clients to discover the authorization server via the well-known URI.
Per MCP spec (2025-11-25): MCP servers MUST implement RFC 9728 PRM.
Usage:
mux := http.NewServeMux()
mux.Handle("/mcp", srv.Handler(mcpkit.WithStreamableHTTP(true)))
auth.MountAuth(mux, auth.AuthConfig{
ResourceURI: "https://mcp.example.com",
AuthorizationServers: []string{"https://auth.example.com"},
ScopesSupported: []string{"tools:read", "tools:call", "admin:write"},
MCPPath: "/mcp",
})
func ParseWWWAuthenticate ¶
ParseWWWAuthenticate extracts the resource_metadata URL and scopes from a WWW-Authenticate: Bearer header value. Used by MCP clients to discover the PRM endpoint after receiving a 401.
Per spec: clients MUST use resource_metadata from WWW-Authenticate when present.
Delegates to mcpkit.ParseWWWAuthenticate (core module) — the parser lives in core so the client transport can use it without depending on the auth sub-module.
func RequireAllScopes ¶
RequireAllScopes checks that all given scopes are present in the context's claims.
func RequireScope ¶
RequireScope checks if the context's authenticated claims include the given scope. Returns nil if the scope is present, or an *mcpkit.AuthError with HTTP 403 and a WWW-Authenticate header with error="insufficient_scope" if missing.
Per MCP spec (2025-11-25): servers SHOULD respond with 403 and WWW-Authenticate when a client has a valid token but insufficient scopes.
Usage in a tool handler:
func adminTool(ctx context.Context, req mcpkit.ToolRequest) (mcpkit.ToolResult, error) {
if err := auth.RequireScope(ctx, "admin:write"); err != nil {
return mcpkit.ErrorResult(err.Error()), nil
}
// ... admin operation ...
}
func WWWAuth401 ¶
WWWAuth401 builds a WWW-Authenticate header value for 401 Unauthorized responses. Per MCP spec (2025-11-25): includes resource_metadata URL and optional scopes.
Example output:
Bearer resource_metadata="https://mcp.example.com/.well-known/oauth-protected-resource/mcp", scope="tools:read admin:write"
func WWWAuth403 ¶
WWWAuth403 builds a WWW-Authenticate header value for 403 Forbidden responses with insufficient scope. Per MCP spec (2025-11-25), includes error code and required scopes.
Example output:
Bearer error="insufficient_scope", scope="admin:write files:read"
Types ¶
type AuthConfig ¶
type AuthConfig struct {
// ResourceURI is the canonical URI of this MCP server (RFC 8707 resource indicator).
ResourceURI string
// AuthorizationServers lists the authorization server URLs this server trusts.
// At least one is required per RFC 9728.
AuthorizationServers []string
// ScopesSupported lists the OAuth scopes this server understands.
ScopesSupported []string
// MCPPath is the MCP endpoint path (e.g., "/mcp"). Used to construct
// the well-known URI: /.well-known/oauth-protected-resource/<mcpPath>
MCPPath string
}
AuthConfig configures the OAuth well-known endpoints for an MCP server.
type AuthExtension ¶
type AuthExtension struct{}
AuthExtension declares the MCP auth extension with its spec version and stability level. Register it on the server to advertise auth support in the initialize response.
Usage:
srv := mcpkit.NewServer(info,
mcpkit.WithAuth(jwtValidator),
mcpkit.WithExtension(auth.AuthExtension{}),
)
func (AuthExtension) Extension ¶
func (AuthExtension) Extension() mcpkit.Extension
Extension returns the MCP auth extension metadata.
type ClientCredentialsSource ¶
type ClientCredentialsSource struct {
// TokenEndpoint is the authorization server's token URL.
TokenEndpoint string
// ClientID identifies this client to the authorization server.
ClientID string
// ClientSecret authenticates this client.
ClientSecret string
// Scopes to request.
Scopes []string
// Audience is the MCP server's canonical URI (RFC 8707 resource indicator).
Audience string
// contains filtered or unexported fields
}
ClientCredentialsSource implements mcpkit.TokenSource for machine-to-machine auth. Uses the OAuth client_credentials grant (RFC 6749 §4.4).
Per MCP spec extensions: io.modelcontextprotocol/oauth-client-credentials
func (*ClientCredentialsSource) Token ¶
func (s *ClientCredentialsSource) Token() (string, error)
Token implements mcpkit.TokenSource.
func (*ClientCredentialsSource) TokenForScopes ¶
func (s *ClientCredentialsSource) TokenForScopes(scopes []string) (string, error)
TokenForScopes implements mcpkit.ScopeAwareTokenSource. Invalidates the cached token and triggers a new client_credentials flow with the requested scopes merged into the existing scope set.
type JWTConfig ¶
type JWTConfig struct {
// JWKSURL is the authorization server's JWKS endpoint for key discovery.
JWKSURL string
// Issuer is the expected "iss" claim in tokens.
Issuer string
// Audience is the expected "aud" claim — this MCP server's canonical URI (RFC 8707).
Audience string
// ResourceMetadataURL is the URL of this server's Protected Resource Metadata
// document (RFC 9728). Included in WWW-Authenticate headers.
ResourceMetadataURL string
// RequiredScopes are checked on every request (global minimum).
RequiredScopes []string
// AllScopes is the complete set of scopes this server supports.
// Included in WWW-Authenticate 401 headers for client scope selection.
AllScopes []string
}
JWTConfig configures a JWTValidator.
type JWTValidator ¶
type JWTValidator struct {
// ResourceMetadataURL is included in WWW-Authenticate headers on 401 responses.
ResourceMetadataURL string
// RequiredScopes are checked on every request. Empty means no global scope requirement.
RequiredScopes []string
// AllScopes is included in WWW-Authenticate 401 headers to guide client scope selection.
// Per spec: clients use this to request scopes upfront, reducing step-up round-trips.
AllScopes []string
// contains filtered or unexported fields
}
JWTValidator validates MCP requests using JWT Bearer tokens. It implements mcpkit.AuthValidator and mcpkit.ClaimsProvider by wrapping oneauth's APIMiddleware for JWKS-based JWT signature verification, and APIAuth for issuer/audience/scope checks.
Uses APIMiddleware (not APIAuth.ValidateAccessTokenFull) because the middleware supports kid-based key lookup from a KeyStore (including JWKSKeyStore), while APIAuth's jwtKeyFunc only supports fixed symmetric/asymmetric keys.
Usage:
validator := auth.NewJWTValidator(auth.JWTConfig{
JWKSURL: "https://auth.example.com/.well-known/jwks.json",
Issuer: "https://auth.example.com",
Audience: "https://mcp.example.com",
ResourceMetadataURL: "https://mcp.example.com/.well-known/oauth-protected-resource/mcp",
})
srv := mcpkit.NewServer(info, mcpkit.WithAuth(validator))
func NewJWTValidator ¶
func NewJWTValidator(cfg JWTConfig) *JWTValidator
NewJWTValidator creates a JWTValidator backed by oneauth's JWT validation and JWKS key discovery.
func (*JWTValidator) Claims ¶
func (v *JWTValidator) Claims(r *http.Request) *mcpkit.Claims
Claims implements mcpkit.ClaimsProvider. Returns the claims parsed during the most recent Validate call for the same token.
func (*JWTValidator) Start ¶
func (v *JWTValidator) Start()
Start begins background JWKS key refresh. Call this once at startup.
type MCPAuthInfo ¶
type MCPAuthInfo struct {
// ResourceMetadataURL is the PRM endpoint URL (from WWW-Authenticate or well-known).
ResourceMetadataURL string
// AuthorizationServers from the PRM document.
AuthorizationServers []string
// ASMetadata is the discovered authorization server metadata.
ASMetadata *client.ASMetadata
// Scopes to request, determined via the MCP scope selection strategy:
// 1. scope from WWW-Authenticate header
// 2. scopes_supported from PRM
// 3. empty (omit scope parameter)
Scopes []string
}
MCPAuthInfo holds the combined discovery results for an MCP server's auth configuration.
func DiscoverMCPAuth ¶
func DiscoverMCPAuth(serverURL string) (*MCPAuthInfo, error)
DiscoverMCPAuth performs the MCP-specific discovery chain:
- Send unauthenticated request to serverURL, expect 401
- Parse WWW-Authenticate header for resource_metadata and scope
- If no resource_metadata in header, try well-known URIs
- Fetch PRM document
- Extract authorization_servers
- Discover AS metadata via oneauth DiscoverAS (RFC 8414 + OIDC fallback)
Per MCP spec (2025-11-25): clients MUST support both WWW-Authenticate and well-known URI discovery. Must use resource_metadata from header when present.
type OAuthTokenSource ¶
type OAuthTokenSource struct {
// ServerURL is the MCP server URL (used for PRM discovery and as resource indicator).
ServerURL string
// ClientID for pre-registered clients or CIMD URL.
ClientID string
// ClientSecret for confidential clients (empty for public clients).
ClientSecret string
// Scopes to request. If empty, determined via MCP scope selection strategy.
Scopes []string
// CredStore persists tokens across sessions (optional).
CredStore client.CredentialStore
// OpenBrowser opens the authorization URL (nil = platform default).
OpenBrowser func(url string) error
// contains filtered or unexported fields
}
OAuthTokenSource implements mcpkit.TokenSource using oneauth's AuthClient. It handles the full MCP OAuth flow: cached token → refresh → discovery → browser auth.
Per MCP spec (2025-11-25): clients MUST implement PKCE with S256, MUST include resource parameter, MUST verify PKCE support in AS metadata.
func (*OAuthTokenSource) Token ¶
func (s *OAuthTokenSource) Token() (string, error)
Token implements mcpkit.TokenSource. Returns a cached token if valid, refreshes if expired, or runs the full OAuth discovery + PKCE flow.
func (*OAuthTokenSource) TokenForScopes ¶
func (s *OAuthTokenSource) TokenForScopes(scopes []string) (string, error)
TokenForScopes implements mcpkit.ScopeAwareTokenSource. Invalidates the cached token and triggers a new OAuth flow with the requested scopes merged into the existing scope set.