This is the documentation for the v2 beta — looking for the v1 documentation?
Skip to content

MCP TypeScript SDK (V2) / @modelcontextprotocol/client / client/auth

client/auth

Classes

UnauthorizedError

Defined in: packages/client/src/client/auth.ts:490

Extends

  • Error

Constructors

Constructor

new UnauthorizedError(message?): UnauthorizedError

Defined in: packages/client/src/client/auth.ts:517

Parameters
message?

string

Returns

UnauthorizedError

Overrides

Error.constructor

Properties

cause?

optional cause?: unknown

Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es2022.error.d.ts:26

Inherited from

Error.cause

message

message: string

Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es5.d.ts:1077

Inherited from

Error.message

name

name: string

Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es5.d.ts:1076

Inherited from

Error.name

stack?

optional stack?: string

Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es5.d.ts:1078

Inherited from

Error.stack

stackTraceLimit

static stackTraceLimit: number

Defined in: node_modules/.pnpm/@types+node@24.12.0/node_modules/@types/node/globals.d.ts:68

The Error.stackTraceLimit property specifies the number of stack frames collected by a stack trace (whether generated by new Error().stack or Error.captureStackTrace(obj)).

The default value is 10 but may be set to any valid JavaScript number. Changes will affect any stack trace captured after the value has been changed.

If set to a non-number value, or set to a negative number, stack traces will not capture any frames.

Inherited from

Error.stackTraceLimit

Methods

[hasInstance]()

static [hasInstance](value): boolean

Defined in: packages/client/src/client/auth.ts:495

Parameters
value

unknown

Returns

boolean

captureStackTrace()

static captureStackTrace(targetObject, constructorOpt?): void

Defined in: node_modules/.pnpm/@types+node@24.12.0/node_modules/@types/node/globals.d.ts:52

Creates a .stack property on targetObject, which when accessed returns a string representing the location in the code at which Error.captureStackTrace() was called.

js
const myObject = {};
Error.captureStackTrace(myObject);
myObject.stack;  // Similar to `new Error().stack`

The first line of the trace will be prefixed with ${myObject.name}: ${myObject.message}.

The optional constructorOpt argument accepts a function. If given, all frames above constructorOpt, including constructorOpt, will be omitted from the generated stack trace.

The constructorOpt argument is useful for hiding implementation details of error generation from the user. For instance:

js
function a() {
  b();
}

function b() {
  c();
}

function c() {
  // Create an error without stack trace to avoid calculating the stack trace twice.
  const { stackTraceLimit } = Error;
  Error.stackTraceLimit = 0;
  const error = new Error();
  Error.stackTraceLimit = stackTraceLimit;

  // Capture the stack trace above function b
  Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace
  throw error;
}

a();
Parameters
targetObject

object

constructorOpt?

Function

Returns

void

Inherited from

Error.captureStackTrace

isError()

static isError(error): error is Error

Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.esnext.error.d.ts:23

Indicates whether the argument provided is a built-in Error instance or not.

Parameters
error

unknown

Returns

error is Error

Inherited from

Error.isError

isInstance()

static isInstance<T>(this, value): value is InstanceType<T>

Defined in: packages/client/src/client/auth.ts:508

Brand-based type guard: equivalent to value instanceof this, as an explicit static predicate (the axios/AWS-SDK isInstance style). Reads the caller's own brand via this, so every branded subclass gets a correctly-scoped guard by inheritance. Must be invoked on the class — in callback position write v => SdkError.isInstance(v), not .filter(SdkError.isInstance) (detached calls throw rather than silently matching nothing).

Type Parameters
T

T extends (...args) => unknown

Parameters
this

T

value

unknown

Returns

value is InstanceType<T>

prepareStackTrace()

static prepareStackTrace(err, stackTraces): any

Defined in: node_modules/.pnpm/@types+node@24.12.0/node_modules/@types/node/globals.d.ts:56

Parameters
err

Error

stackTraces

CallSite[]

Returns

any

See

https://v8.dev/docs/stack-trace-api#customizing-stack-traces

Inherited from

Error.prepareStackTrace

Interfaces

AuthOptions

Defined in: packages/client/src/client/auth.ts:934

Options for auth. The full OAuth flow orchestrator's input.

Properties

authorizationCode?

optional authorizationCode?: string

Defined in: packages/client/src/client/auth.ts:942

The authorization code returned by the authorization server on the redirect callback. When set, auth exchanges it for tokens; when unset, auth runs discovery and either refreshes or initiates redirect.

fetchFn?

optional fetchFn?: FetchLike

Defined in: packages/client/src/client/auth.ts:957

Custom fetch implementation.

forceReauthorization?

optional forceReauthorization?: boolean

Defined in: packages/client/src/client/auth.ts:984

When true, auth skips the refresh-token branch even when a refresh_token is available, and proceeds directly to a fresh authorization request (startAuthorization).

Set by the transport's 403 insufficient_scope step-up path when the required scope is a strict superset of the current token's granted scope: the refresh grant cannot widen scope (RFC 6749 §6), so refreshing would silently drop the new scope and the next request would 403 again. Forcing a fresh authorization request ensures the widened scope reaches the authorization server.

Hosts driving step-up themselves (with onInsufficientScope: 'throw') should set this when isStrictScopeSuperset of the union over the current token's scope is true.

Default
ts
false
iss?

optional iss?: string

Defined in: packages/client/src/client/auth.ts:951

The form-urldecoded iss query parameter from the authorization callback, if present. Passed through to RFC 9207 §2.4 issuer validation alongside authorizationCode. Validated against the recorded issuer per RFC 9207 §2.4 before the code is redeemed — see validateAuthorizationResponseIssuer and the migration guide's Authorization-server mix-up defense section.

resourceMetadataUrl?

optional resourceMetadataUrl?: URL

Defined in: packages/client/src/client/auth.ts:955

Explicit resource_metadata URL from a WWW-Authenticate challenge.

scope?

optional scope?: string

Defined in: packages/client/src/client/auth.ts:953

Scope to request; computed by Scope Selection Strategy when omitted.

serverUrl

serverUrl: string | URL

Defined in: packages/client/src/client/auth.ts:936

The MCP server URL — the protected resource the flow authorizes against.

skipIssuerMetadataValidation?

optional skipIssuerMetadataValidation?: boolean

Defined in: packages/client/src/client/auth.ts:965

Opt-out for the RFC 8414 §3.3 issuer-echo check during authorization server discovery. Disabling it is security-weakening and intended only for authorization servers known to publish a mismatched issuer.

Default
ts
false

AuthProvider

Defined in: packages/client/src/client/auth.ts:76

Minimal interface for authenticating MCP client transports with bearer tokens.

Transports call token() before every request to obtain the current token, and onUnauthorized() (if provided) when the server responds with 401, giving the provider a chance to refresh credentials before the transport retries once.

For simple cases (API keys, gateway-managed tokens), implement only token():

typescript
const authProvider: AuthProvider = { token: async () => process.env.API_KEY };

For OAuth flows, pass an OAuthClientProvider directly — transports accept either shape and adapt OAuth providers automatically via adaptOAuthProvider.

Methods

onUnauthorized()?

optional onUnauthorized(ctx): Promise<void>

Defined in: packages/client/src/client/auth.ts:91

Called when the server responds with 401. If provided, the transport will await this, then retry the request once. If the retry also gets 401, or if this method is not provided, the transport throws UnauthorizedError.

Implementations should refresh tokens, re-authenticate, etc. — whatever is needed so the next token() call returns a valid token.

Parameters
ctx

UnauthorizedContext

Returns

Promise<void>

token()

token(): Promise<string | undefined>

Defined in: packages/client/src/client/auth.ts:81

Returns the current bearer token, or undefined if no token is available. Called before every request.

Returns

Promise<string | undefined>


OAuthClientInformationContext

Defined in: packages/client/src/client/auth.ts:102

Context passed to the credential-persistence methods on OAuthClientProviderclientInformation / saveClientInformation and tokens / saveTokens. Carries the resolved authorization-server issuer so provider implementations can key persisted credentials per authorization server (RFC 6749 §2.2 — client identifiers are unique to the AS that issued them). Providers that store a single credential set may ignore it.

Properties

issuer

issuer: string

Defined in: packages/client/src/client/auth.ts:107

The authorization server's issuer identifier from its validated metadata document, used as the binding key for persisted credentials.


OAuthClientProvider

Defined in: packages/client/src/client/auth.ts:234

Implements an end-to-end OAuth client to be used with one MCP server.

This client relies upon a concept of an authorized "session," the exact meaning of which is application-defined. Tokens, authorization codes, and code verifiers should not cross different sessions.

Transports accept OAuthClientProvider directly via the authProvider option — they adapt it to AuthProvider internally via adaptOAuthProvider. No changes are needed to existing implementations.

Properties

addClientAuthentication?

optional addClientAuthentication?: AddClientAuthentication

Defined in: packages/client/src/client/auth.ts:342

Adds custom client authentication to OAuth token requests.

This optional method allows implementations to customize how client credentials are included in token exchange and refresh requests. When provided, this method is called instead of the default authentication logic, giving full control over the authentication mechanism.

Common use cases include:

  • Supporting authentication methods beyond the standard OAuth 2.0 methods
  • Adding custom headers for proprietary authentication schemes
  • Implementing client assertion-based authentication (e.g., JWT bearer tokens)
Param

headers

The request headers (can be modified to add authentication)

Param

params

The request body parameters (can be modified to add credentials)

Param

url

The token endpoint URL being called

Param

metadata

Optional OAuth metadata for the server, which may include supported authentication methods

clientMetadataUrl?

optional clientMetadataUrl?: string

Defined in: packages/client/src/client/auth.ts:245

External URL the server should use to fetch client metadata document

Accessors

clientMetadata
Get Signature

get clientMetadata(): object

Defined in: packages/client/src/client/auth.ts:250

Metadata about this OAuth client.

Returns
application_type?

optional application_type?: string

OIDC Dynamic Client Registration application_type. MCP clients MUST set this to 'native' or 'web' when registering (SEP-837); the SDK defaults it from redirect_uris when omitted. Typed as string (not an enum) so that parsing an authorization server's registration response — which under RFC 7591 may echo extension values — never rejects the document on this field alone.

client_name?

optional client_name?: string

client_uri?

optional client_uri?: string

contacts?

optional contacts?: string[]

grant_types?

optional grant_types?: string[]

jwks?

optional jwks?: any

jwks_uri?

optional jwks_uri?: string

logo_uri?

optional logo_uri?: string = OptionalSafeUrlSchema

policy_uri?

optional policy_uri?: string

redirect_uris

redirect_uris: string[]

response_types?

optional response_types?: string[]

scope?

optional scope?: string

software_id?

optional software_id?: string

software_statement?

optional software_statement?: string

software_version?

optional software_version?: string

token_endpoint_auth_method?

optional token_endpoint_auth_method?: string

tos_uri?

optional tos_uri?: string = OptionalSafeUrlSchema

redirectUrl
Get Signature

get redirectUrl(): string | URL | undefined

Defined in: packages/client/src/client/auth.ts:240

The URL to redirect the user agent to after authorization. Return undefined for non-interactive flows that don't require user interaction (e.g., client_credentials, jwt-bearer).

Returns

string | URL | undefined

Methods

authorizationServerUrl()?

optional authorizationServerUrl(): string | Promise<string | undefined> | undefined

Defined in: packages/client/src/client/auth.ts:417

Returns the previously saved authorization server URL, if available.

Returns

string | Promise<string | undefined> | undefined

Deprecated

Superseded by the issuer stamp on stored tokens / client credentials (SEP-2352). The SDK never reads this method; it remains for provider implementations that consume the value internally (e.g. Cross-App Access).

clientInformation()

clientInformation(ctx?): StoredOAuthClientInformation | Promise<StoredOAuthClientInformation | undefined> | undefined

Defined in: packages/client/src/client/auth.ts:266

Loads information about this OAuth client, as registered already with the server, or returns undefined if the client is not registered with the server.

Parameters
ctx?

OAuthClientInformationContext

Carries the resolved authorization-server issuer. Providers that persist credentials per authorization server should return the entry keyed by ctx.issuer. Providers with a single credential set may ignore it.

Returns

StoredOAuthClientInformation | Promise<StoredOAuthClientInformation | undefined> | undefined

codeVerifier()

codeVerifier(): string | Promise<string>

Defined in: packages/client/src/client/auth.ts:322

Loads the PKCE code verifier for the current session, necessary to validate the authorization result.

Returns

string | Promise<string>

discoveryState()?

optional discoveryState(): OAuthDiscoveryState | Promise<OAuthDiscoveryState | undefined> | undefined

Defined in: packages/client/src/client/auth.ts:470

Returns previously saved discovery state, or undefined if none is cached.

When available, auth restores the discovery state (authorization server URL, resource metadata, etc.) instead of performing RFC 9728 discovery, reducing latency on subsequent calls.

Hosts should call invalidateCredentials with scope 'discovery' on repeated 401s so a changed authorization_servers list is picked up; the SDK does not invoke that scope itself.

MUST persist with the same durability as codeVerifier (survives the redirect round-trip).

Returns

OAuthDiscoveryState | Promise<OAuthDiscoveryState | undefined> | undefined

invalidateCredentials()?

optional invalidateCredentials(scope): void | Promise<void>

Defined in: packages/client/src/client/auth.ts:358

If implemented, provides a way for the client to invalidate (e.g. delete) the specified credentials, in the case where the server has indicated that they are no longer valid. This avoids requiring the user to intervene manually.

Parameters
scope

"all" | "client" | "tokens" | "verifier" | "discovery"

Returns

void | Promise<void>

prepareTokenRequest()?

optional prepareTokenRequest(scope?): URLSearchParams | Promise<URLSearchParams | undefined> | undefined

Defined in: packages/client/src/client/auth.ts:396

Prepares grant-specific parameters for a token request.

This optional method allows providers to customize the token request based on the grant type they support. When implemented, it returns the grant type and any grant-specific parameters needed for the token exchange.

If not implemented, the default behavior depends on the flow:

  • For authorization code flow: uses code, code_verifier, and redirect_uri
  • For client_credentials: detected via grant_types in clientMetadata
Parameters
scope?

string

Optional scope to request

Returns

URLSearchParams | Promise<URLSearchParams | undefined> | undefined

Grant type and parameters, or undefined to use default behavior

Examples
ts
// For client_credentials grant:
prepareTokenRequest(scope) {
  return {
    grantType: 'client_credentials',
    params: scope ? { scope } : {}
  };
}
ts
// For authorization_code grant (default behavior):
async prepareTokenRequest() {
  return {
    grantType: 'authorization_code',
    params: {
      code: this.authorizationCode,
      code_verifier: await this.codeVerifier(),
      redirect_uri: String(this.redirectUrl)
    }
  };
}
redirectToAuthorization()

redirectToAuthorization(authorizationUrl): void | Promise<void>

Defined in: packages/client/src/client/auth.ts:310

Invoked to redirect the user agent to the given URL to begin the authorization flow.

Parameters
authorizationUrl

URL

Returns

void | Promise<void>

resourceUrl()?

optional resourceUrl(): string | Promise<string | undefined> | undefined

Defined in: packages/client/src/client/auth.ts:439

Returns the previously saved resource URL, if available.

Providers implementing Cross-App Access can use this to access the resource URL discovered during the OAuth flow.

Returns

string | Promise<string | undefined> | undefined

The resource URL, or undefined if not available

saveAuthorizationServerUrl()?

optional saveAuthorizationServerUrl(authorizationServerUrl): void | Promise<void>

Defined in: packages/client/src/client/auth.ts:408

Saves the resolved authorization-server issuer. Called after a successful token exchange (timing changed in v2: was post-discovery, now post-saveTokens).

Parameters
authorizationServerUrl

string

Returns

void | Promise<void>

Deprecated

Superseded by the issuer stamp on stored tokens / client credentials (SEP-2352). auth still writes this for back-compat with providers that read it (e.g. Cross-App Access), but the SDK never reads it. Prefer reading the issuer field on the value passed to saveTokens / saveClientInformation, or the ctx.issuer argument.

saveClientInformation()?

optional saveClientInformation(clientInformation, ctx?): void | Promise<void>

Defined in: packages/client/src/client/auth.ts:282

If implemented, this permits the OAuth client to dynamically register with the server. Client information saved this way should later be read via clientInformation().

This method is not required to be implemented if client information is statically known (e.g., pre-registered).

Parameters
clientInformation

StoredOAuthClientInformation

ctx?

OAuthClientInformationContext

Carries the resolved authorization-server issuer. Providers that persist credentials per authorization server should store the entry keyed by ctx.issuer.

Returns

void | Promise<void>

saveCodeVerifier()

saveCodeVerifier(codeVerifier): void | Promise<void>

Defined in: packages/client/src/client/auth.ts:316

Saves a PKCE code verifier for the current session, before redirecting to the authorization flow.

Parameters
codeVerifier

string

Returns

void | Promise<void>

saveDiscoveryState()?

optional saveDiscoveryState(state): void | Promise<void>

Defined in: packages/client/src/client/auth.ts:454

Saves the OAuth discovery state after RFC 9728 and authorization server metadata discovery. Providers can persist this state to avoid redundant discovery requests on subsequent auth calls.

This state can also be provided out-of-band (e.g., from a previous session or external configuration) to bootstrap the OAuth flow without discovery.

Called by auth after successful discovery.

MUST persist with the same durability as codeVerifier (survives the redirect round-trip).

Parameters
state

OAuthDiscoveryState

Returns

void | Promise<void>

saveResourceUrl()?

optional saveResourceUrl(resourceUrl): void | Promise<void>

Defined in: packages/client/src/client/auth.ts:429

Saves the resource URL after RFC 9728 discovery. This method is called by auth after successful discovery of the resource metadata.

Providers implementing Cross-App Access or other flows that need access to the discovered resource URL should implement this method.

Parameters
resourceUrl

string

The resource URL discovered via RFC 9728

Returns

void | Promise<void>

saveTokens()

saveTokens(tokens, ctx?): void | Promise<void>

Defined in: packages/client/src/client/auth.ts:305

Stores new OAuth tokens for the current session, after a successful authorization.

Parameters
tokens

StoredOAuthTokens

ctx?

OAuthClientInformationContext

Carries the resolved authorization-server issuer. Providers that persist tokens per authorization server should store the entry keyed by ctx.issuer.

Returns

void | Promise<void>

state()?

optional state(): string | Promise<string>

Defined in: packages/client/src/client/auth.ts:255

Returns an OAuth2 state parameter.

Returns

string | Promise<string>

tokens()

tokens(ctx?): StoredOAuthTokens | Promise<StoredOAuthTokens | undefined> | undefined

Defined in: packages/client/src/client/auth.ts:295

Loads any existing OAuth tokens for the current session, or returns undefined if there are no saved tokens.

Parameters
ctx?

OAuthClientInformationContext

Carries the resolved authorization-server issuer. Providers that persist tokens per authorization server should return the entry keyed by ctx.issuer. Providers with a single token set may ignore it. When called with no ctx — the transport's per-request bearer-token read — return the most-recently-saved token set; do not return undefined for ctx === undefined.

Returns

StoredOAuthTokens | Promise<StoredOAuthTokens | undefined> | undefined

validateResourceURL()?

optional validateResourceURL(serverUrl, resource?): Promise<URL | undefined>

Defined in: packages/client/src/client/auth.ts:351

If defined, overrides the selection and validation of the RFC 8707 Resource Indicator. If left undefined, default validation behavior will be used.

Implementations must verify the returned resource matches the MCP server.

Parameters
serverUrl

string | URL

resource?

string

Returns

Promise<URL | undefined>


OAuthDiscoveryState

Defined in: packages/client/src/client/auth.ts:483

Discovery state that can be persisted across sessions by an OAuthClientProvider.

Contains the results of RFC 9728 protected resource metadata discovery and authorization server metadata discovery. Persisting this state avoids redundant discovery HTTP requests on subsequent auth calls.

Extends

Properties

authorizationServerMetadata?

optional authorizationServerMetadata?: AuthorizationServerMetadata

Defined in: packages/client/src/client/auth.ts:1872

The authorization server metadata (endpoints, capabilities), or undefined if metadata discovery failed.

Inherited from

OAuthServerInfo.authorizationServerMetadata

authorizationServerUrl

authorizationServerUrl: string

Defined in: packages/client/src/client/auth.ts:1866

The authorization server URL, either discovered via RFC 9728 or derived from the MCP server URL as a fallback.

Inherited from

OAuthServerInfo.authorizationServerUrl

resourceMetadata?

optional resourceMetadata?: object

Defined in: packages/client/src/client/auth.ts:1878

The OAuth 2.0 Protected Resource Metadata from RFC 9728, or undefined if the server does not support it.

Index Signature

[key: string]: unknown

authorization_details_types_supported?

optional authorization_details_types_supported?: string[]

authorization_servers?

optional authorization_servers?: string[]

bearer_methods_supported?

optional bearer_methods_supported?: string[]

dpop_bound_access_tokens_required?

optional dpop_bound_access_tokens_required?: boolean

dpop_signing_alg_values_supported?

optional dpop_signing_alg_values_supported?: string[]

jwks_uri?

optional jwks_uri?: string

resource

resource: string

resource_documentation?

optional resource_documentation?: string

resource_name?

optional resource_name?: string

resource_policy_uri?

optional resource_policy_uri?: string

resource_signing_alg_values_supported?

optional resource_signing_alg_values_supported?: string[]

resource_tos_uri?

optional resource_tos_uri?: string

scopes_supported?

optional scopes_supported?: string[]

tls_client_certificate_bound_access_tokens?

optional tls_client_certificate_bound_access_tokens?: boolean

Inherited from

OAuthServerInfo.resourceMetadata

resourceMetadataUrl?

optional resourceMetadataUrl?: string

Defined in: packages/client/src/client/auth.ts:485

The URL at which the protected resource metadata was found, if available.


OAuthServerInfo

Defined in: packages/client/src/client/auth.ts:1861

Result of discoverOAuthServerInfo.

Extended by

Properties

authorizationServerMetadata?

optional authorizationServerMetadata?: AuthorizationServerMetadata

Defined in: packages/client/src/client/auth.ts:1872

The authorization server metadata (endpoints, capabilities), or undefined if metadata discovery failed.

authorizationServerUrl

authorizationServerUrl: string

Defined in: packages/client/src/client/auth.ts:1866

The authorization server URL, either discovered via RFC 9728 or derived from the MCP server URL as a fallback.

resourceMetadata?

optional resourceMetadata?: object

Defined in: packages/client/src/client/auth.ts:1878

The OAuth 2.0 Protected Resource Metadata from RFC 9728, or undefined if the server does not support it.

Index Signature

[key: string]: unknown

authorization_details_types_supported?

optional authorization_details_types_supported?: string[]

authorization_servers?

optional authorization_servers?: string[]

bearer_methods_supported?

optional bearer_methods_supported?: string[]

dpop_bound_access_tokens_required?

optional dpop_bound_access_tokens_required?: boolean

dpop_signing_alg_values_supported?

optional dpop_signing_alg_values_supported?: string[]

jwks_uri?

optional jwks_uri?: string

resource

resource: string

resource_documentation?

optional resource_documentation?: string

resource_name?

optional resource_name?: string

resource_policy_uri?

optional resource_policy_uri?: string

resource_signing_alg_values_supported?

optional resource_signing_alg_values_supported?: string[]

resource_tos_uri?

optional resource_tos_uri?: string

scopes_supported?

optional scopes_supported?: string[]

tls_client_certificate_bound_access_tokens?

optional tls_client_certificate_bound_access_tokens?: boolean


UnauthorizedContext

Defined in: packages/client/src/client/auth.ts:51

Context passed to AuthProvider.onUnauthorized when the server responds with 401. Provides everything needed to refresh credentials.

Properties

fetchFn

fetchFn: FetchLike

Defined in: packages/client/src/client/auth.ts:57

Fetch function configured with the transport's requestInit, for making auth requests.

response

response: Response

Defined in: packages/client/src/client/auth.ts:53

The 401 response — inspect WWW-Authenticate for resource metadata, scope, etc.

serverUrl

serverUrl: URL

Defined in: packages/client/src/client/auth.ts:55

The MCP server URL, for passing to auth or discovery helpers.

Type Aliases

AddClientAuthentication

AddClientAuthentication = (headers, params, url, metadata?) => void | Promise<void>

Defined in: packages/client/src/client/auth.ts:40

Function type for adding client authentication to token requests.

Parameters

headers

Headers

params

URLSearchParams

url

string | URL

metadata?

AuthorizationServerMetadata

Returns

void | Promise<void>


AuthResult

AuthResult = "AUTHORIZED" | "REDIRECT"

Defined in: packages/client/src/client/auth.ts:488


ClientAuthMethod

ClientAuthMethod = "client_secret_basic" | "client_secret_post" | "none"

Defined in: packages/client/src/client/auth.ts:702

Functions

adaptOAuthProvider()

adaptOAuthProvider(provider, extraAuthOptions?): AuthProvider

Defined in: packages/client/src/client/auth.ts:210

Adapts an OAuthClientProvider to the minimal AuthProvider interface that transports consume. Called once at transport construction — the transport stores the adapted provider for _commonHeaders() and 401 handling, while keeping the original OAuthClientProvider for OAuth-specific paths (finishAuth(), 403 insufficient_scope step-up).

SEP-2352 note: token() here is the per-request Authorization: Bearer … read for the resource server (the MCP transport URL), not an authorization server. No OAuth discovery has run at this layer, so there is no issuer to pass as ctx and no discardIfIssuerMismatch check to apply — the access token is sent only to the resource server, never to an AS, so the SEP-2352 cross-AS isolation invariant is not in scope. Providers that key storage on ctx.issuer MUST treat ctx === undefined as "return the most-recently-saved token set" (the only consumer is the resource server the token was minted for); providers that round-trip a single blob need no change.

Parameters

provider

OAuthClientProvider

extraAuthOptions?

Pick<AuthOptions, "skipIssuerMetadataValidation">

Returns

AuthProvider


applyBasicAuth()

applyBasicAuth(clientId, clientSecret, headers): void

Defined in: packages/client/src/client/auth.ts:806

Applies HTTP Basic authentication (RFC 6749 Section 2.3.1)

Parameters

clientId

string

clientSecret

string | undefined

headers

Headers

Returns

void


applyClientAuthentication()

applyClientAuthentication(method, clientInformation, headers, params): void

Defined in: packages/client/src/client/auth.ts:776

Applies client authentication to the request based on the specified method.

Implements OAuth 2.1 client authentication methods:

  • client_secret_basic: HTTP Basic authentication (RFC 6749 Section 2.3.1)
  • client_secret_post: Credentials in request body (RFC 6749 Section 2.3.1)
  • none: Public client authentication (RFC 6749 Section 2.1)

Parameters

method

ClientAuthMethod

The authentication method to use

clientInformation

OAuth client information containing credentials

client_id

string = ...

client_id_issued_at?

number = ...

client_secret?

string = ...

client_secret_expires_at?

number = ...

headers

Headers

HTTP headers object to modify

params

URLSearchParams

URL search parameters to modify

Returns

void

Throws

When required credentials are missing


applyPostAuth()

applyPostAuth(clientId, clientSecret, params): void

Defined in: packages/client/src/client/auth.ts:818

Applies POST body authentication (RFC 6749 Section 2.3.1)

Parameters

clientId

string

clientSecret

string | undefined

params

URLSearchParams

Returns

void


applyPublicAuth()

applyPublicAuth(clientId, params): void

Defined in: packages/client/src/client/auth.ts:828

Applies public client authentication (RFC 6749 Section 2.1)

Parameters

clientId

string

params

URLSearchParams

Returns

void


assertSecureTokenEndpoint()

assertSecureTokenEndpoint(tokenEndpoint): URL

Defined in: packages/client/src/client/auth.ts:841

SEP-2207: refuse to send credentials to a non-TLS, non-loopback token endpoint. Throws InsecureTokenEndpointError. Loopback hosts are exempt.

Parameters

tokenEndpoint

string | URL

Returns

URL


auth()

auth(provider, options): Promise<AuthResult>

Defined in: packages/client/src/client/auth.ts:993

Orchestrates the full auth flow with a server.

This can be used as a single entry point for all authorization functionality, instead of linking together the other lower-level functions in this module.

Parameters

provider

OAuthClientProvider

options

AuthOptions

Returns

Promise<AuthResult>


buildDiscoveryUrls()

buildDiscoveryUrls(authorizationServerUrl): object[]

Defined in: packages/client/src/client/auth.ts:1706

Builds a list of discovery URLs to try for authorization server metadata. URLs are returned in priority order:

  1. OAuth metadata at the given URL
  2. OIDC metadata endpoints at the given URL

Parameters

authorizationServerUrl

string | URL

Returns

object[]


computeScopeUnion()

computeScopeUnion(...scopes): string | undefined

Defined in: packages/client/src/client/auth.ts:602

Computes the union of one or more OAuth scope strings.

Each argument is a space-delimited scope string per RFC 6749 §3.3, or undefined. The result is a single space-delimited string containing each distinct scope token exactly once, in first-seen order, or undefined if every input is empty/undefined.

No hierarchical deduplication is performed: a union may contain semantically redundant entries (e.g., a broad scope alongside a narrower one it implies). Authorization servers normalize such redundancy during token issuance; the spec's step-up flow does not require clients to.

Used by the transport's 403 insufficient_scope step-up path to accumulate previously-requested scopes with newly-challenged scopes so re-authorization does not lose previously-granted permissions.

Parameters

scopes

...readonly (string | undefined)[]

Returns

string | undefined


determineScope()

determineScope(options): string | undefined

Defined in: packages/client/src/client/auth.ts:1020

Selects scopes per the MCP spec and augment for refresh token support.

Parameters

options
authServerMetadata?

AuthorizationServerMetadata

clientMetadata

{ application_type?: string; client_name?: string; client_uri?: string; contacts?: string[]; grant_types?: string[]; jwks?: any; jwks_uri?: string; logo_uri?: string; policy_uri?: string; redirect_uris: string[]; response_types?: string[]; scope?: string; software_id?: string; software_statement?: string; software_version?: string; token_endpoint_auth_method?: string; tos_uri?: string; }

clientMetadata.application_type?

string = ...

OIDC Dynamic Client Registration application_type. MCP clients MUST set this to 'native' or 'web' when registering (SEP-837); the SDK defaults it from redirect_uris when omitted. Typed as string (not an enum) so that parsing an authorization server's registration response — which under RFC 7591 may echo extension values — never rejects the document on this field alone.

clientMetadata.client_name?

string = ...

clientMetadata.client_uri?

string = ...

clientMetadata.contacts?

string[] = ...

clientMetadata.grant_types?

string[] = ...

clientMetadata.jwks?

any = ...

clientMetadata.jwks_uri?

string = ...

clientMetadata.logo_uri?

string = OptionalSafeUrlSchema

clientMetadata.policy_uri?

string = ...

clientMetadata.redirect_uris

string[] = ...

clientMetadata.response_types?

string[] = ...

clientMetadata.scope?

string = ...

clientMetadata.software_id?

string = ...

clientMetadata.software_statement?

string = ...

clientMetadata.software_version?

string = ...

clientMetadata.token_endpoint_auth_method?

string = ...

clientMetadata.tos_uri?

string = OptionalSafeUrlSchema

requestedScope?

string

resourceMetadata?

{[key: string]: unknown; authorization_details_types_supported?: string[]; authorization_servers?: string[]; bearer_methods_supported?: string[]; dpop_bound_access_tokens_required?: boolean; dpop_signing_alg_values_supported?: string[]; jwks_uri?: string; resource: string; resource_documentation?: string; resource_name?: string; resource_policy_uri?: string; resource_signing_alg_values_supported?: string[]; resource_tos_uri?: string; scopes_supported?: string[]; tls_client_certificate_bound_access_tokens?: boolean; }

resourceMetadata.authorization_details_types_supported?

string[] = ...

resourceMetadata.authorization_servers?

string[] = ...

resourceMetadata.bearer_methods_supported?

string[] = ...

resourceMetadata.dpop_bound_access_tokens_required?

boolean = ...

resourceMetadata.dpop_signing_alg_values_supported?

string[] = ...

resourceMetadata.jwks_uri?

string = ...

resourceMetadata.resource

string = ...

resourceMetadata.resource_documentation?

string = ...

resourceMetadata.resource_name?

string = ...

resourceMetadata.resource_policy_uri?

string = ...

resourceMetadata.resource_signing_alg_values_supported?

string[] = ...

resourceMetadata.resource_tos_uri?

string = ...

resourceMetadata.scopes_supported?

string[] = ...

resourceMetadata.tls_client_certificate_bound_access_tokens?

boolean = ...

Returns

string | undefined


discardIfIssuerMismatch()

discardIfIssuerMismatch<T>(stored, issuer, opts?): T | undefined

Defined in: packages/client/src/client/auth.ts:128

SEP-2352 stamp check: returns stored only when its issuer stamp matches the resolved authorization server. A stamp that names a different issuer reads back as undefined, so a credential issued by one authorization server is never reused at another — the flow falls through to re-registration / re-authorization exactly as if nothing were stored. An unstamped value (legacy provider or pre-SEP-2352 storage) is returned as-is with a console.warn; auth writes the stamp back on first use so the window closes after one call.

auth stamps every value it writes via saveTokens / saveClientInformation, so a provider that round-trips the stored object verbatim is protected with no extra code. Providers that hold credentials for multiple authorization servers key their storage on ctx.issuer instead.

Type Parameters

T

T extends object

Parameters

stored

T | undefined

issuer

string

opts?
canPersistStamp?

boolean

When false, suppresses the unstamped-credential warning: the caller cannot back-stamp (no saveClientInformation), so the "binding on first use" claim would be false and would fire on every call.

Returns

T | undefined


discoverAuthorizationServerMetadata()

discoverAuthorizationServerMetadata(authorizationServerUrl, options?): Promise<AuthorizationServerMetadata | undefined>

Defined in: packages/client/src/client/auth.ts:1787

Discovers authorization server metadata with support for RFC 8414 OAuth 2.0 Authorization Server Metadata and OpenID Connect Discovery 1.0 specifications.

This function implements a fallback strategy for authorization server discovery:

  1. Attempts RFC 8414 OAuth metadata discovery first
  2. If OAuth discovery fails, falls back to OpenID Connect Discovery

Parameters

authorizationServerUrl

string | URL

The authorization server URL obtained from the MCP Server's protected resource metadata, or the MCP server's URL if the metadata was not found. The returned metadata's issuer is validated against authorizationServerUrl per RFC 8414 §3.3 (and OIDC Discovery §4.3): if they differ the metadata is rejected with IssuerMismatchError and not returned. Set skipIssuerValidation: true to suppress this check — security-weakening, intended only for known-misconfigured authorization servers.

options?

Configuration options

fetchFn?

FetchLike = fetch

Optional fetch function for making HTTP requests, defaults to global fetch

protocolVersion?

string = LATEST_PROTOCOL_VERSION

MCP protocol version to use, defaults to LATEST_PROTOCOL_VERSION

skipIssuerValidation?

boolean = false

Skip the RFC 8414 §3.3 issuer echo check. Security-weakening.

Returns

Promise<AuthorizationServerMetadata | undefined>

Promise resolving to authorization server metadata, or undefined if discovery fails

Throws

when the metadata's issuer does not match authorizationServerUrl


discoverOAuthMetadata()

discoverOAuthMetadata(issuer, __namedParameters?, fetchFn?): Promise<{[key: string]: unknown; authorization_endpoint: string; authorization_response_iss_parameter_supported?: boolean; client_id_metadata_document_supported?: boolean; code_challenge_methods_supported?: string[]; grant_types_supported?: string[]; introspection_endpoint?: string; introspection_endpoint_auth_methods_supported?: string[]; introspection_endpoint_auth_signing_alg_values_supported?: string[]; issuer: string; registration_endpoint?: string; response_modes_supported?: string[]; response_types_supported: string[]; revocation_endpoint?: string; revocation_endpoint_auth_methods_supported?: string[]; revocation_endpoint_auth_signing_alg_values_supported?: string[]; scopes_supported?: string[]; service_documentation?: string; token_endpoint: string; token_endpoint_auth_methods_supported?: string[]; token_endpoint_auth_signing_alg_values_supported?: string[]; } | undefined>

Defined in: packages/client/src/client/auth.ts:1660

Looks up RFC 8414 OAuth 2.0 Authorization Server Metadata.

If the server returns a 404 for the well-known endpoint, this function will return undefined. Any other errors will be thrown as exceptions.

Parameters

issuer

string | URL

__namedParameters?
authorizationServerUrl?

string | URL

protocolVersion?

string

fetchFn?

FetchLike = fetch

Returns

Promise<{[key: string]: unknown; authorization_endpoint: string; authorization_response_iss_parameter_supported?: boolean; client_id_metadata_document_supported?: boolean; code_challenge_methods_supported?: string[]; grant_types_supported?: string[]; introspection_endpoint?: string; introspection_endpoint_auth_methods_supported?: string[]; introspection_endpoint_auth_signing_alg_values_supported?: string[]; issuer: string; registration_endpoint?: string; response_modes_supported?: string[]; response_types_supported: string[]; revocation_endpoint?: string; revocation_endpoint_auth_methods_supported?: string[]; revocation_endpoint_auth_signing_alg_values_supported?: string[]; scopes_supported?: string[]; service_documentation?: string; token_endpoint: string; token_endpoint_auth_methods_supported?: string[]; token_endpoint_auth_signing_alg_values_supported?: string[]; } | undefined>

Deprecated

This function is deprecated in favor of discoverAuthorizationServerMetadata.


discoverOAuthProtectedResourceMetadata()

discoverOAuthProtectedResourceMetadata(serverUrl, opts?, fetchFn?): Promise<{[key: string]: unknown; authorization_details_types_supported?: string[]; authorization_servers?: string[]; bearer_methods_supported?: string[]; dpop_bound_access_tokens_required?: boolean; dpop_signing_alg_values_supported?: string[]; jwks_uri?: string; resource: string; resource_documentation?: string; resource_name?: string; resource_policy_uri?: string; resource_signing_alg_values_supported?: string[]; resource_tos_uri?: string; scopes_supported?: string[]; tls_client_certificate_bound_access_tokens?: boolean; }>

Defined in: packages/client/src/client/auth.ts:1519

Looks up RFC 9728 OAuth 2.0 Protected Resource Metadata.

If the server returns a 404 for the well-known endpoint, this function will return undefined. Any other errors will be thrown as exceptions.

Parameters

serverUrl

string | URL

opts?
protocolVersion?

string

resourceMetadataUrl?

string | URL

fetchFn?

FetchLike = fetch

Returns

Promise<{[key: string]: unknown; authorization_details_types_supported?: string[]; authorization_servers?: string[]; bearer_methods_supported?: string[]; dpop_bound_access_tokens_required?: boolean; dpop_signing_alg_values_supported?: string[]; jwks_uri?: string; resource: string; resource_documentation?: string; resource_name?: string; resource_policy_uri?: string; resource_signing_alg_values_supported?: string[]; resource_tos_uri?: string; scopes_supported?: string[]; tls_client_certificate_bound_access_tokens?: boolean; }>


discoverOAuthServerInfo()

discoverOAuthServerInfo(serverUrl, opts?): Promise<OAuthServerInfo>

Defined in: packages/client/src/client/auth.ts:1901

Discovers the authorization server for an MCP server following RFC 9728 (OAuth 2.0 Protected Resource Metadata), with fallback to treating the server URL as the authorization server.

This function combines two discovery steps into one call:

  1. Probes /.well-known/oauth-protected-resource on the MCP server to find the authorization server URL (RFC 9728).
  2. Fetches authorization server metadata from that URL (RFC 8414 / OpenID Connect Discovery).

Use this when you need the authorization server metadata for operations outside the auth orchestrator, such as token refresh or token revocation.

Parameters

serverUrl

string | URL

The MCP resource server URL

opts?

Optional configuration

fetchFn?

FetchLike

Custom fetch function for HTTP requests

resourceMetadataUrl?

URL

Override URL for the protected resource metadata endpoint

skipIssuerMetadataValidation?

boolean

Forwarded to discoverAuthorizationServerMetadata as skipIssuerValidation. Security-weakening — see AuthOptions.skipIssuerMetadataValidation.

Returns

Promise<OAuthServerInfo>

Authorization server URL, metadata, and resource metadata (if available)


exchangeAuthorization()

exchangeAuthorization(authorizationServerUrl, options): Promise<{ access_token: string; expires_in?: number; id_token?: string; refresh_token?: string; scope?: string; token_type: string; }>

Defined in: packages/client/src/client/auth.ts:2126

Exchanges an authorization code for an access token with the given server.

Supports multiple client authentication methods as specified in OAuth 2.1:

  • Automatically selects the best authentication method based on server support
  • Falls back to appropriate defaults when server metadata is unavailable

Parameters

authorizationServerUrl

string | URL

The authorization server's base URL

options

Configuration object containing client info, auth code, etc.

addClientAuthentication?

AddClientAuthentication

authorizationCode

string

clientInformation

OAuthClientInformationMixed

codeVerifier

string

fetchFn?

FetchLike

iss?

string

The form-urldecoded iss query parameter from the authorization callback. Validated per RFC 9207 §2.4 against metadata.issuer before the code is redeemed; see validateAuthorizationResponseIssuer.

metadata?

AuthorizationServerMetadata

redirectUri

string | URL

resource?

URL

Returns

Promise<{ access_token: string; expires_in?: number; id_token?: string; refresh_token?: string; scope?: string; token_type: string; }>

Promise resolving to OAuth tokens

Throws

When token exchange fails or authentication is invalid


executeTokenRequest()

executeTokenRequest(authorizationServerUrl, __namedParameters): Promise<{ access_token: string; expires_in?: number; id_token?: string; refresh_token?: string; scope?: string; token_type: string; }>

Defined in: packages/client/src/client/auth.ts:2053

Internal helper to execute a token request with the given parameters. Used by exchangeAuthorization, refreshAuthorization, and fetchToken.

Parameters

authorizationServerUrl

string | URL

__namedParameters
addClientAuthentication?

AddClientAuthentication

clientInformation?

OAuthClientInformationMixed

fetchFn?

FetchLike

metadata?

AuthorizationServerMetadata

resource?

URL

tokenRequestParams

URLSearchParams

Returns

Promise<{ access_token: string; expires_in?: number; id_token?: string; refresh_token?: string; scope?: string; token_type: string; }>


extractResourceMetadataUrl()

extractResourceMetadataUrl(res): URL | undefined

Defined in: packages/client/src/client/auth.ts:1488

Extract resource_metadata from response header.

Parameters

res

Response

Returns

URL | undefined

Deprecated

Use extractWWWAuthenticateParams instead.


extractWWWAuthenticateParams()

extractWWWAuthenticateParams(res): object

Defined in: packages/client/src/client/auth.ts:1418

Extract resource_metadata, scope, error, and error_description from a WWW-Authenticate header.

Parameters

res

Response

Returns

object

error?

optional error?: string

errorDescription?

optional errorDescription?: string

resourceMetadataUrl?

optional resourceMetadataUrl?: URL

scope?

optional scope?: string


fetchToken()

fetchToken(provider, authorizationServerUrl, options?): Promise<{ access_token: string; expires_in?: number; id_token?: string; refresh_token?: string; scope?: string; token_type: string; }>

Defined in: packages/client/src/client/auth.ts:2248

Unified token fetching that works with any grant type via prepareTokenRequest().

This function provides a single entry point for obtaining tokens regardless of the OAuth grant type. The provider's prepareTokenRequest() method determines which grant to use and supplies the grant-specific parameters.

Parameters

provider

OAuthClientProvider

OAuth client provider that implements prepareTokenRequest()

authorizationServerUrl

string | URL

The authorization server's base URL

options?

Configuration for the token request

authorizationCode?

string

Authorization code for the default authorization_code grant flow

fetchFn?

FetchLike

iss?

string

The form-urldecoded iss query parameter from the authorization callback. Validated per RFC 9207 §2.4 when authorizationCode is present; see validateAuthorizationResponseIssuer.

metadata?

AuthorizationServerMetadata

resource?

URL

scope?

string

Optional scope parameter from auth() options

Returns

Promise<{ access_token: string; expires_in?: number; id_token?: string; refresh_token?: string; scope?: string; token_type: string; }>

Promise resolving to OAuth tokens

Throws

When provider doesn't implement prepareTokenRequest or token fetch fails

Example

ts
// Provider for client_credentials:
class MyProvider extends MyProviderBase implements OAuthClientProvider {
    prepareTokenRequest(scope?: string) {
        const params = new URLSearchParams({ grant_type: 'client_credentials' });
        if (scope) params.set('scope', scope);
        return params;
    }
}

const tokens = await fetchToken(new MyProvider(), authServerUrl, { metadata });

handleOAuthUnauthorized()

handleOAuthUnauthorized(provider, ctx, extraAuthOptions?): Promise<void>

Defined in: packages/client/src/client/auth.ts:177

Standard onUnauthorized behavior for OAuth providers: extracts WWW-Authenticate parameters from the 401 response and runs auth. Used by adaptOAuthProvider to bridge OAuthClientProvider to AuthProvider.

Parameters

provider

OAuthClientProvider

ctx

UnauthorizedContext

extraAuthOptions?

Pick<AuthOptions, "skipIssuerMetadataValidation">

Returns

Promise<void>


isHttpsUrl()

isHttpsUrl(value?): boolean

Defined in: packages/client/src/client/auth.ts:1379

SEP-991: URL-based Client IDs Validate that the client_id is a valid URL with https scheme

Parameters

value?

string

Returns

boolean


isOAuthClientProvider()

isOAuthClientProvider(provider): provider is OAuthClientProvider

Defined in: packages/client/src/client/auth.ts:166

Type guard distinguishing OAuthClientProvider from a minimal AuthProvider. Transports use this at construction time to classify the authProvider option.

Checks for tokens() + clientInformation() — two required OAuthClientProvider methods that a minimal AuthProvider { token: ... } would never have.

Parameters

provider

AuthProvider | OAuthClientProvider | undefined

Returns

provider is OAuthClientProvider


isStrictScopeSuperset()

isStrictScopeSuperset(union, current): boolean

Defined in: packages/client/src/client/auth.ts:630

Whether union contains at least one scope token not present in current. Both arguments are space-delimited scope strings per RFC 6749 §3.3.

Used to gate the step-up refresh bypass: when the union of previously-requested and newly-challenged scopes is a strict superset of the current token's granted scope, refreshing cannot widen the grant (RFC 6749 §6), so the transport must force a fresh authorization request instead. When the current token already covers the union, refresh remains valid.

An undefined or empty current is treated as the empty set, so any non-empty union is a strict superset. Note that per RFC 6749 §3.3 an authorization server MAY omit the token's scope field when it equals the requested scope; this helper is conservative and treats an absent token scope as empty, so step-up always forces a fresh authorization request in that case rather than risking a refresh that silently drops the widened scope.

Parameters

union

string | undefined

current

string | undefined

Returns

boolean


parseErrorResponse()

parseErrorResponse(input): Promise<OAuthError>

Defined in: packages/client/src/client/auth.ts:917

Parses an OAuth error response from a string or Response object.

If the input is a standard OAuth2.0 error response, it will be parsed according to the spec and an OAuthError will be returned with the appropriate error code. If parsing fails, it falls back to a generic ServerError that includes the response status (if available) and original content.

Parameters

input

string | Response

A Response object or string containing the error response

Returns

Promise<OAuthError>

A Promise that resolves to an OAuthError instance


prepareAuthorizationCodeRequest()

prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, redirectUri): URLSearchParams

Defined in: packages/client/src/client/auth.ts:2036

Prepares token request parameters for an authorization code exchange.

This is the default implementation used by fetchToken when the provider doesn't implement prepareTokenRequest.

Parameters

authorizationCode

string

The authorization code received from the authorization endpoint

codeVerifier

string

The PKCE code verifier

redirectUri

string | URL

The redirect URI used in the authorization request

Returns

URLSearchParams

URLSearchParams for the authorization_code grant


refreshAuthorization()

refreshAuthorization(authorizationServerUrl, options): Promise<{ access_token: string; expires_in?: number; id_token?: string; refresh_token?: string; scope?: string; token_type: string; }>

Defined in: packages/client/src/client/auth.ts:2185

Exchange a refresh token for an updated access token.

Supports multiple client authentication methods as specified in OAuth 2.1:

  • Automatically selects the best authentication method based on server support
  • Preserves the original refresh token if a new one is not returned

Parameters

authorizationServerUrl

string | URL

The authorization server's base URL

options

Configuration object containing client info, refresh token, etc.

addClientAuthentication?

AddClientAuthentication

clientInformation

OAuthClientInformationMixed

fetchFn?

FetchLike

metadata?

AuthorizationServerMetadata

refreshToken

string

resource?

URL

Returns

Promise<{ access_token: string; expires_in?: number; id_token?: string; refresh_token?: string; scope?: string; token_type: string; }>

Promise resolving to OAuth tokens (preserves original refresh_token if not replaced)

Throws

When token refresh fails or authentication is invalid


registerClient()

registerClient(authorizationServerUrl, __namedParameters): Promise<{ application_type?: string; client_id: string; client_id_issued_at?: number; client_name?: string; client_secret?: string; client_secret_expires_at?: number; client_uri?: string; contacts?: string[]; grant_types?: string[]; jwks?: any; jwks_uri?: string; logo_uri?: string; policy_uri?: string; redirect_uris: string[]; response_types?: string[]; scope?: string; software_id?: string; software_statement?: string; software_version?: string; token_endpoint_auth_method?: string; tos_uri?: string; }>

Defined in: packages/client/src/client/auth.ts:2329

Performs OAuth 2.0 Dynamic Client Registration according to RFC 7591.

If scope is provided, it overrides clientMetadata.scope in the registration request body. This allows callers to apply the Scope Selection Strategy (SEP-835) consistently across both DCR and the subsequent authorization request.

Parameters

authorizationServerUrl

string | URL

__namedParameters
clientMetadata

{ application_type?: string; client_name?: string; client_uri?: string; contacts?: string[]; grant_types?: string[]; jwks?: any; jwks_uri?: string; logo_uri?: string; policy_uri?: string; redirect_uris: string[]; response_types?: string[]; scope?: string; software_id?: string; software_statement?: string; software_version?: string; token_endpoint_auth_method?: string; tos_uri?: string; }

clientMetadata.application_type?

string = ...

OIDC Dynamic Client Registration application_type. MCP clients MUST set this to 'native' or 'web' when registering (SEP-837); the SDK defaults it from redirect_uris when omitted. Typed as string (not an enum) so that parsing an authorization server's registration response — which under RFC 7591 may echo extension values — never rejects the document on this field alone.

clientMetadata.client_name?

string = ...

clientMetadata.client_uri?

string = ...

clientMetadata.contacts?

string[] = ...

clientMetadata.grant_types?

string[] = ...

clientMetadata.jwks?

any = ...

clientMetadata.jwks_uri?

string = ...

clientMetadata.logo_uri?

string = OptionalSafeUrlSchema

clientMetadata.policy_uri?

string = ...

clientMetadata.redirect_uris

string[] = ...

clientMetadata.response_types?

string[] = ...

clientMetadata.scope?

string = ...

clientMetadata.software_id?

string = ...

clientMetadata.software_statement?

string = ...

clientMetadata.software_version?

string = ...

clientMetadata.token_endpoint_auth_method?

string = ...

clientMetadata.tos_uri?

string = OptionalSafeUrlSchema

fetchFn?

FetchLike

metadata?

AuthorizationServerMetadata

scope?

string

Returns

Promise<{ application_type?: string; client_id: string; client_id_issued_at?: number; client_name?: string; client_secret?: string; client_secret_expires_at?: number; client_uri?: string; contacts?: string[]; grant_types?: string[]; jwks?: any; jwks_uri?: string; logo_uri?: string; policy_uri?: string; redirect_uris: string[]; response_types?: string[]; scope?: string; software_id?: string; software_statement?: string; software_version?: string; token_endpoint_auth_method?: string; tos_uri?: string; }>

Deprecated

Dynamic Client Registration is deprecated as of protocol version 2026-07-28 (SEP-2577) in favor of Client ID Metadata Documents (SEP-991). Remains functional during the deprecation window (at least twelve months). Prefer a CIMD URL client_id when the authorization server advertises client_id_metadata_document_supported; the SDK already gates on this for you.


resolveAuthorizationCallbackParams()

resolveAuthorizationCallbackParams(codeOrParams, iss, provider, serverUrl, opts?): Promise<{ authorizationCode: string; iss: string | undefined; }>

Defined in: packages/client/src/client/auth.ts:657

Internal

Shared finishAuth resolver for the (code, iss?) and (URLSearchParams) overloads.

For the URLSearchParams form, only iss and code are read up front. When a code is present the returned values flow into auth, which runs validateAuthorizationResponseIssuer against freshly-discovered metadata before the code is redeemed — so on mismatch the thrown IssuerMismatchError carries no error/error_description/error_uri text from the callback (those are attacker-controlled in a mix-up). When no code is present (an error-shaped callback), iss is validated here against the provider's recorded discovery state — or, when the provider does not implement discoveryState, against freshly-discovered metadata mirroring what auth does on the code-present path — before the callback's error parameters are read; only after that passes are they surfaced as an OAuthError. When no issuer baseline can be obtained either way, a generic UnauthorizedError is thrown without surfacing the callback's error/error_description/error_uri.

Exported for the transport finishAuth overloads; not part of the public barrel.

Parameters

codeOrParams

string | URLSearchParams

iss

string | undefined

provider

OAuthClientProvider

serverUrl

string | URL

opts?
fetchFn?

FetchLike

resourceMetadataUrl?

URL

Returns

Promise<{ authorizationCode: string; iss: string | undefined; }>


resolveClientMetadata()

resolveClientMetadata(provider): object

Defined in: packages/client/src/client/auth.ts:896

Reads clientMetadata from the provider and fills the SEP-837 / SEP-2207 defaults the SDK relies on, so registerClient sees a consistent, fully-populated document.

  • grant_types defaults to ['authorization_code', 'refresh_token'] for interactive providers (those with a redirectUrl) so authorization servers that gate refresh-token issuance on the registered grant types issue one (SEP-2207). Non-interactive providers (no redirectUrl) get no grant_types default. This default applies to the Dynamic Client Registration body only — it does not drive determineScope's offline_access augmentation.
  • application_type defaults from redirect_uris: loopback redirect hosts and custom URI schemes → 'native', otherwise 'web' (SEP-837 / RFC 8252).

A field the consumer set explicitly is never overwritten. auth calls this once at the top of the flow; direct callers of registerClient that want the same defaults should pass the result of this function as clientMetadata.

Parameters

provider

Pick<OAuthClientProvider, "clientMetadata" | "redirectUrl">

Returns

application_type?

optional application_type?: string

OIDC Dynamic Client Registration application_type. MCP clients MUST set this to 'native' or 'web' when registering (SEP-837); the SDK defaults it from redirect_uris when omitted. Typed as string (not an enum) so that parsing an authorization server's registration response — which under RFC 7591 may echo extension values — never rejects the document on this field alone.

client_name?

optional client_name?: string

client_uri?

optional client_uri?: string

contacts?

optional contacts?: string[]

grant_types?

optional grant_types?: string[]

jwks?

optional jwks?: any

jwks_uri?

optional jwks_uri?: string

logo_uri?

optional logo_uri?: string = OptionalSafeUrlSchema

policy_uri?

optional policy_uri?: string

redirect_uris

redirect_uris: string[]

response_types?

optional response_types?: string[]

scope?

optional scope?: string

software_id?

optional software_id?: string

software_statement?

optional software_statement?: string

software_version?

optional software_version?: string

token_endpoint_auth_method?

optional token_endpoint_auth_method?: string

tos_uri?

optional tos_uri?: string = OptionalSafeUrlSchema


selectClientAuthMethod()

selectClientAuthMethod(clientInformation, supportedMethods): ClientAuthMethod

Defined in: packages/client/src/client/auth.ts:723

Determines the best client authentication method to use based on server support and client configuration.

Priority order (highest to lowest):

  1. client_secret_basic (if client secret is available)
  2. client_secret_post (if client secret is available)
  3. none (for public clients)

Parameters

clientInformation

OAuthClientInformationMixed

OAuth client information containing credentials

supportedMethods

string[]

Authentication methods supported by the authorization server

Returns

ClientAuthMethod

The selected authentication method


selectResourceURL()

selectResourceURL(serverUrl, provider, resourceMetadata?): Promise<URL | undefined>

Defined in: packages/client/src/client/auth.ts:1389

Parameters

serverUrl

string | URL

provider

OAuthClientProvider

resourceMetadata?
authorization_details_types_supported?

string[] = ...

authorization_servers?

string[] = ...

bearer_methods_supported?

string[] = ...

dpop_bound_access_tokens_required?

boolean = ...

dpop_signing_alg_values_supported?

string[] = ...

jwks_uri?

string = ...

resource

string = ...

resource_documentation?

string = ...

resource_name?

string = ...

resource_policy_uri?

string = ...

resource_signing_alg_values_supported?

string[] = ...

resource_tos_uri?

string = ...

scopes_supported?

string[] = ...

tls_client_certificate_bound_access_tokens?

boolean = ...

Returns

Promise<URL | undefined>


startAuthorization()

startAuthorization(authorizationServerUrl, __namedParameters): Promise<{ authorizationUrl: URL; codeVerifier: string; }>

Defined in: packages/client/src/client/auth.ts:1956

Begins the authorization flow with the given server, by generating a PKCE challenge and constructing the authorization URL.

Parameters

authorizationServerUrl

string | URL

__namedParameters
clientInformation

OAuthClientInformationMixed

metadata?

AuthorizationServerMetadata

redirectUrl

string | URL

resource?

URL

scope?

string

state?

string

Returns

Promise<{ authorizationUrl: URL; codeVerifier: string; }>


validateAuthorizationResponseIssuer()

validateAuthorizationResponseIssuer(__namedParameters): void

Defined in: packages/client/src/client/auth.ts:555

Parameters

__namedParameters
expectedIssuer

string | undefined

The issuer value from the authorization server's validated metadata document.

iss

string | undefined

The form-urldecoded iss query parameter from the authorization callback, or undefined if absent.

issParameterSupported

boolean

Whether the metadata advertised authorization_response_iss_parameter_supported: true.

Returns

void


validateClientMetadataUrl()

validateClientMetadataUrl(url): void

Defined in: packages/client/src/client/auth.ts:1366

Validates that the given clientMetadataUrl is a valid HTTPS URL with a non-root pathname.

No-op when url is undefined or empty (providers that do not use URL-based client IDs are unaffected). When the value is defined but invalid, throws an OAuthError with code OAuthErrorCode.InvalidClientMetadata.

OAuthClientProvider implementations that accept a clientMetadataUrl should call this in their constructors for early validation.

Parameters

url

string | undefined

The clientMetadataUrl value to validate (from OAuthClientProvider.clientMetadataUrl)

Returns

void

Throws

When url is defined but is not a valid HTTPS URL with a non-root pathname

References

AuthorizationServerMismatchError

Re-exports AuthorizationServerMismatchError


InsecureTokenEndpointError

Re-exports InsecureTokenEndpointError


IssuerMismatchError

Re-exports IssuerMismatchError


RegistrationRejectedError

Re-exports RegistrationRejectedError