MCP TypeScript SDK (V2) / @modelcontextprotocol/server / server/middleware/bearerAuth
server/middleware/bearerAuth
Interfaces
BearerAuthOptions
Defined in: packages/server/src/server/middleware/bearerAuth.ts:34
Options for verifyBearerToken, requireBearerAuth, and bearerAuthChallengeResponse.
Extended by
Properties
requiredScopes?
optionalrequiredScopes?:string[]
Defined in: packages/server/src/server/middleware/bearerAuth.ts:44
Optional scopes that the token must have. When any are missing the request is refused with 403 insufficient_scope.
resourceMetadataUrl?
optionalresourceMetadataUrl?:string
Defined in: packages/server/src/server/middleware/bearerAuth.ts:60
Optional Protected Resource Metadata URL to advertise in the WWW-Authenticate header on 401/403 responses, per RFC 9728.
Typically built with getOAuthProtectedResourceMetadataUrl, exported from this package.
When verification succeeds the value is also stamped onto the returned AuthInfo (authInfo.resourceMetadataUrl, unless the verifier already set one), so challenges built after authentication — such as per-operation insufficient_scope scope challenges — advertise the same document without being configured separately.
verifier
verifier:
OAuthTokenVerifier
Defined in: packages/server/src/server/middleware/bearerAuth.ts:38
A verifier used to validate access tokens.
OAuthTokenVerifier
Defined in: packages/server/src/server/middleware/bearerAuth.ts:13
Minimal token-verifier interface for MCP servers acting as an OAuth 2.0 Resource Server. Implementations introspect or locally validate an access token and return the resulting AuthInfo, which the serving entry surfaces to MCP request handlers via ctx.http.authInfo.
This is intentionally narrower than a full OAuth Authorization Server provider — it only covers the verification step a Resource Server needs.
Methods
verifyAccessToken()
verifyAccessToken(
token):Promise<AuthInfo>
Defined in: packages/server/src/server/middleware/bearerAuth.ts:27
Verifies an access token and returns information about it.
Implementations should throw an OAuthError with OAuthErrorCode.InvalidToken when the token is unknown, revoked, or otherwise invalid; the bearer-auth helpers map that to a 401 with a WWW-Authenticate challenge.
Note: bearer-auth verification rejects tokens whose AuthInfo.expiresAt is unset (matches v1 behavior). Ensure your verifier populates it (e.g. from RFC 7662 introspection exp or the JWT exp claim).
Parameters
token
string
Returns
Promise<AuthInfo>
VerifyBearerTokenOptions
Defined in: packages/server/src/server/middleware/bearerAuth.ts:67
Options for verifyBearerToken and requireBearerAuth: BearerAuthOptions plus expectedResource.
Extends
Properties
expectedResource?
optionalexpectedResource?:URL
Defined in: packages/server/src/server/middleware/bearerAuth.ts:82
Accept only tokens issued for this resource (the token's audience): the value your authorization server puts into tokens meant for this server, usually the server's URL (its RFC 8707 resource identifier).
When set, a token is accepted only if the verifier reports that value in AuthInfo.resource. The two are compared as strings, ignoring a fragment and one trailing slash. A token reported for another value, or for none, is refused with 401 invalid_token, so the verifier has to fill AuthInfo.resource, for example from the token's aud claim. When unset, AuthInfo.resource is not compared with anything.
requiredScopes?
optionalrequiredScopes?:string[]
Defined in: packages/server/src/server/middleware/bearerAuth.ts:44
Optional scopes that the token must have. When any are missing the request is refused with 403 insufficient_scope.
Inherited from
BearerAuthOptions.requiredScopes
resourceMetadataUrl?
optionalresourceMetadataUrl?:string
Defined in: packages/server/src/server/middleware/bearerAuth.ts:60
Optional Protected Resource Metadata URL to advertise in the WWW-Authenticate header on 401/403 responses, per RFC 9728.
Typically built with getOAuthProtectedResourceMetadataUrl, exported from this package.
When verification succeeds the value is also stamped onto the returned AuthInfo (authInfo.resourceMetadataUrl, unless the verifier already set one), so challenges built after authentication — such as per-operation insufficient_scope scope challenges — advertise the same document without being configured separately.
Inherited from
BearerAuthOptions.resourceMetadataUrl
verifier
verifier:
OAuthTokenVerifier
Defined in: packages/server/src/server/middleware/bearerAuth.ts:38
A verifier used to validate access tokens.
Inherited from
Functions
bearerAuthChallengeResponse()
bearerAuthChallengeResponse(
error,options?):Response
Defined in: packages/server/src/server/middleware/bearerAuth.ts:203
Build the HTTP answer for a Bearer authentication failure.
Maps an OAuthError to its status — 401 for invalid_token and 403 for insufficient_scope (both carrying the WWW-Authenticate: Bearer … challenge, with resource_metadata when configured so clients can discover the Authorization Server), 500 for server_error, 400 for anything else. A non-OAuthError value answers 500 server_error. The body is the OAuth error JSON.
Parameters
error
unknown
options?
Pick<BearerAuthOptions, "requiredScopes" | "resourceMetadataUrl">
Returns
Response
buildWwwAuthenticateHeader()
buildWwwAuthenticateHeader(
errorCode,description,requiredScopes,resourceMetadataUrl):string
Defined in: packages/server/src/server/middleware/bearerAuth.ts:115
Build a WWW-Authenticate: Bearer … challenge header value (RFC 6750).
The single formatter behind every challenge this package emits — the bearer-auth 401/403 answers and the per-operation scope-challenge 403 — so all challenges from one server agree on parameter order and quoting. Every parameter value is emitted as an HTTP quoted-string with \ and " escaped and non-printable characters replaced.
Parameters
errorCode
string
description
string
requiredScopes
readonly string[]
resourceMetadataUrl
string | undefined
Returns
string
requireBearerAuth()
requireBearerAuth(
options): (request) =>Promise<AuthInfo|Response>
Defined in: packages/server/src/server/middleware/bearerAuth.ts:252
Require a valid Bearer token on web-standard requests.
The framework-free counterpart of requireBearerAuth from @modelcontextprotocol/express, for hosts whose HTTP surface is a fetch(request) handler — Cloudflare Workers, Deno, Bun, Hono. The returned gate resolves to the verified AuthInfo, or to the ready-to-return challenge Response when the request must be refused.
Parameters
options
Returns
(request) => Promise<AuthInfo | Response>
Example
const gate = requireBearerAuth({ verifier, requiredScopes: ['mcp'] });
async function fetchHandler(request: Request): Promise<Response> {
const auth: AuthInfo | Response = await gate(request);
if (auth instanceof Response) return auth;
return handler.fetch(request, { authInfo: auth });
}verifyBearerToken()
verifyBearerToken(
authorizationHeader,options):Promise<AuthInfo>
Defined in: packages/server/src/server/middleware/bearerAuth.ts:145
Validate a raw Authorization header value as a Bearer token and return the verified AuthInfo.
The runtime-neutral core of Bearer authentication: it parses the header, runs the verifier, compares the token's resource with expectedResource, enforces requiredScopes, and rejects tokens without an expiration or past it. On any failure it throws an OAuthError — pass that to bearerAuthChallengeResponse for the matching HTTP answer, or use requireBearerAuth to get both steps as one call.
Framework adapters build on this: requireBearerAuth from @modelcontextprotocol/express feeds it req.headers.authorization.
Parameters
authorizationHeader
string | null | undefined
options
Returns
Promise<AuthInfo>