mcp.auth.oauth

Undocumented in source.

Members

Enums

ClientRegistrationApproach
enum ClientRegistrationApproach

The client-registration approach an MCP client should use for an authorization server, per the spec priority order ("Client Registration Approaches", 2025-11-25 / draft).

TokenEndpointAuthMethod
enum TokenEndpointAuthMethod

How the client authenticates at the token endpoint.

Functions

authServerMetadataCandidates
string[] authServerMetadataCandidates(string issuer)

The ordered list of authorization-server metadata URLs to try for an issuer, covering RFC 8414 (oauth-authorization-server) and OpenID Connect Discovery (openid-configuration), in both path-aware and path-append forms.

base64UrlNoPad
string base64UrlNoPad(const(ubyte)[] data)

Base64url-encode without padding (RFC 7636 / RFC 4648 §5).

basicAuthHeader
string basicAuthHeader(string clientId, string clientSecret)

Build the HTTP Authorization: Basic header value for client_secret_basic. Per RFC 6749 §2.3.1, both the client identifier and password are percent-encoded (application/x-www-form-urlencoded) before concatenation.

buildAuthCodeTokenForm
string buildAuthCodeTokenForm(string code, string redirectUri, string codeVerifier, string clientId, string resource, string clientSecretForPost)

Build the application/x-www-form-urlencoded body for the authorization-code token request. clientSecret is included only for the client_secret_post auth method (pass empty otherwise).

buildAuthorizationUrl
string buildAuthorizationUrl(string authorizationEndpoint, string clientId, string redirectUri, string codeChallenge, string scopeStr, string resource, string state)

Build the authorization-request URL for the PKCE auth-code flow.

buildClientCredentialsForm
string buildClientCredentialsForm(string clientId, string scopeStr, string resource, string clientSecretForPost)

Build the token-request body for the client_credentials grant.

buildJwtBearerForm
string buildJwtBearerForm(string assertion, string scopeStr, string resource, string clientId)

Build an RFC 7523 JWT-bearer grant request body (exchange an assertion JWT for an access token).

buildRefreshTokenForm
string buildRefreshTokenForm(string refreshToken, string clientId, string resource, string clientSecretForPost)

Build the token-request body for refreshing an access token. When clientSecretForPost is non-empty it is appended (for client_secret_post upstream authentication); leave it empty for public/PKCE clients or when the secret is carried via the HTTP Basic Authorization header instead.

buildTokenExchangeForm
string buildTokenExchangeForm(string subjectToken, string subjectTokenType, string requestedTokenType, string audience, string resource, string clientId)

Build an RFC 8693 token-exchange request body (used by the cross-app / identity-assertion grant to swap an IdP id_token for an ID-JAG assertion).

canonicalResourceUri
string canonicalResourceUri(string mcpEndpoint)

The canonical resource indicator (RFC 8707) for an MCP server: the endpoint URL with a lowercased scheme+authority, any fragment dropped, and a single trailing slash stripped. The MCP "Canonical Server URI" rules prefer the no-trailing-slash form. ASCII case is folded in place (rather than via toLower) to keep this pure nothrow.

extractQueryParam
string extractQueryParam(string url, string key)

Extract a query-string parameter value from a URL (URL-decoded), or "".

generatePkce
PkcePair generatePkce()

Generate a PKCE pair from cryptographically secure OS randomness (RFC 7636 recommends a high-entropy verifier). Throws CsprngException if the OS CSPRNG is unavailable.

isSecureFetchUrl
bool isSecureFetchUrl(string url)

Whether url is safe to fetch for OAuth/discovery: it MUST use the https scheme, OR target an explicit loopback host (localhost, 127.0.0.1, [::1], and their numeric encodings) over http for local development. Plaintext http to any other host is rejected, as are URLs whose host is a private/link-local IPv4 or IPv6 literal (including alternate numeric IPv4 encodings and IPv4-mapped/compatible IPv6). Purely lexical (no DNS): it is a coarse pre-filter on the attacker-influenced resource_metadata URL. The authoritative, TOCTOU-safe SSRF guard for an actual fetch is secureRequestHTTP, which resolves, classifies and pins via the connector.

isSecureFetchUrlResolved
bool isSecureFetchUrlResolved(string url)

Non-throwing scheme/host + resolution gate (block-internal policy). Returns true only when the vibe-parsed scheme/host pass the lexical guard AND the host resolves only to safe addresses (fail CLOSED on a resolution error). Loopback and IP-literal hosts short-circuit without resolving. @safe.

isValidClientIdMetadataUrl
bool isValidClientIdMetadataUrl(string clientId)

Validate an OAuth Client ID Metadata Document client_id URL (SEP-991): it MUST use the https scheme and contain a non-empty path component.

makePkce
PkcePair makePkce(const(ubyte)[] verifierBytes)

Generate a PKCE pair using the S256 method. verifierBytes (32 random bytes) produces a 43-char base64url verifier; the challenge is base64url(SHA-256(verifier)).

parseWwwAuthenticate
WwwAuthenticate parseWwwAuthenticate(string header)

Parse a WWW-Authenticate header value such as Bearer resource_metadata="https://...", scope="a b".

protectedResourceMetadataUrls
string[] protectedResourceMetadataUrls(string mcpEndpoint)

Build the ordered list of well-known protected-resource-metadata URLs to try for an MCP endpoint URL, per RFC 9728: the path-scoped URL first, then root.

requireSecureUrl
void requireSecureUrl(string url)

Throw invalidRequest when url is not safe to fetch under the block-internal policy. Parses with vibe's own parser (the single source of truth) and classifies the host once. A check-time scheme/host gate (no fetch) suitable for paths that VALIDATE a URL without fetching it (e.g. building the authorization-request URL the host will open). The TOCTOU-safe resolve-and-pin connect for an actual fetch is performed by secureRequestHTTP.

secureRequestHTTP
void secureRequestHTTP(string url, void delegate(scope HTTPClientRequest) requester, void delegate(scope HTTPClientResponse) responder)

Consolidated SSRF-safe HTTP fetch used by every outbound OAuth/discovery request. Delegates to the connector's secureRequestHTTP with the block-internal policy: parse once with vibe's URL, classify the host once, resolve + pin to a vetted numeric address (preserving Host header + TLS SNI), and fail CLOSED on any internal/unresolvable target. Throws invalidRequest when the URL is unsafe.

selectClientRegistrationApproach
ClientRegistrationApproach selectClientRegistrationApproach(AuthorizationServerMetadata as_, bool havePreRegistered, string clientIdMetadataUrl)

Select the client-registration approach for an authorization server, following the spec priority order: 1. pre-registered client information, if available; 2. Client ID Metadata Documents, if the AS advertises support (client_id_metadata_document_supported) and a valid HTTPS-URL client_id is configured; 3. Dynamic Client Registration, if the AS exposes a registration_endpoint; 4. otherwise prompt the user.

selectScope
string selectScope(string wwwAuthScope, string[] scopesSupported)

Select the OAuth scopes to request: prefer the scopes named in the WWW-Authenticate challenge; otherwise fall back to the resource metadata's scopes_supported; otherwise none.

validateAuthorizationResponseIss
bool validateAuthorizationResponseIss(string responseIss, string recordedIssuer, bool issParameterSupported)

Validate the RFC 9207 iss authorization-response parameter against the recorded issuer of the selected authorization server, per RFC 9207 Section 2.4 (the MCP 2025-11-25 / draft "Authorization Response Validation" requirement, mitigating authorization-server mix-up attacks).

validateAuthorizationResponseState
bool validateAuthorizationResponseState(string responseState, string expectedState)

Validate the state parameter returned in an authorization redirect against the state value the client sent in the authorization request.

Structs

AuthorizationServerMetadata
struct AuthorizationServerMetadata

OAuth 2.0 Authorization Server Metadata (RFC 8414).

ClientIdMetadataDocument
struct ClientIdMetadataDocument

An OAuth Client ID Metadata Document (SEP-991) a client hosts at its HTTPS-URL client_id. The authorization server fetches this document to learn the client's metadata (name, redirect URIs, auth method) without any prior registration. clientId MUST equal the document's own URL.

ClientRegistration
struct ClientRegistration

A Dynamic Client Registration request body (RFC 7591).

PkcePair
struct PkcePair

A PKCE verifier/challenge pair. The verifier is kept by the client; the challenge is sent on the authorization request and the verifier on the token request.

ProtectedResourceMetadata
struct ProtectedResourceMetadata

OAuth 2.0 Protected Resource Metadata (RFC 9728).

RegisteredClient
struct RegisteredClient

The credentials returned by the registration endpoint.

TokenSet
struct TokenSet

A token endpoint response (RFC 6749 §5.1).

WwwAuthenticate
struct WwwAuthenticate

A parsed WWW-Authenticate challenge: the auth scheme plus its parameters.