Open History to see the last commit
1import { OAuthError, OAuthErrorCode } from '@modelcontextprotocol/server'
2import type { AuthInfo, OAuthTokenVerifier } from '@modelcontextprotocol/server'
3import { createRemoteJWKSet, customFetch, errors, jwtVerify } from 'jose'
4
5/**
6 * Options for {@link jwtVerifier}.
7 * `issuer` and `audience` are required. A token for another issuer or
8 * another API must not call this server.
9 */
10export type JwtVerifierOptions = {
11 /** The JWKS URL of the authorization server. */
12 jwksUrl: string
13 /** The `iss` claim the token must carry. */
14 issuer: string
15 /** The `aud` claim the token must carry. Usually this MCP server URL. */
16 audience: string
17 /** Accepted JWS algorithms. The default accepts what the key set advertises. */
18 algorithms?: Array<string>
19 /** Fetch for the JWKS request. The default is the global `fetch`. */
20 fetch?: (url: string, init?: RequestInit) => Promise<Response>
21}
22
23/**
24 * Options for {@link introspectionVerifier}.
25 * The server sends the token to `introspectionUrl` with HTTP Basic auth.
26 */
27export type IntrospectionVerifierOptions = {
28 /** The RFC 7662 introspection endpoint of the authorization server. */
29 introspectionUrl: string
30 /** The client id this MCP server uses at the authorization server. */
31 clientId: string
32 /** The client secret for `clientId`. */
33 clientSecret: string
34 /** Fetch for the introspection request. The default is the global `fetch`. */
35 fetch?: (url: string, init?: RequestInit) => Promise<Response>
36}
37
38/**
39 * Builds an `OAuthTokenVerifier` for a JWT access token.
40 *
41 * The verifier reads the keys from `jwksUrl`, caches them, and checks the
42 * signature, `iss`, `aud`, `exp`, and `nbf` with `jose`.
43 * A token that fails any check gets a 401 from `createMCPServer`.
44 * When the key set cannot be read, the caller gets a 500 `server_error`,
45 * so a provider outage does not look like a bad token.
46 *
47 * `clientId` on the result is the `client_id`, `azp`, or `sub` claim.
48 * `scopes` comes from the `scope` claim. `extra` holds every claim,
49 * so a tool can read `ctx.context.authInfo.extra.sub`.
50 *
51 * @param options - The JWKS URL, the issuer, and the audience
52 *
53 * @example
54 * ```ts
55 * const server = createMCPServer({
56 * name: 'notes',
57 * version: '1.0.0',
58 * auth: {
59 * verifier: jwtVerifier({
60 * jwksUrl: 'https://auth.example.com/.well-known/jwks.json',
61 * issuer: 'https://auth.example.com/',
62 * audience: 'https://mcp.example.com/mcp',
63 * }),
64 * },
65 * })
66 * ```
67 */
68export function jwtVerifier(options: JwtVerifierOptions): OAuthTokenVerifier {
69 const fetchImpl = options.fetch
70 const keys = createRemoteJWKSet(new URL(options.jwksUrl), {
71 ...(fetchImpl === undefined ? {} : { [customFetch]: fetchImpl }),
72 })
73 return {
74 async verifyAccessToken(token) {
75 let claims: Record<string, unknown>
76 try {
77 const verified = await jwtVerify(token, keys, {
78 issuer: options.issuer,
79 audience: options.audience,
80 algorithms: options.algorithms,
81 })
82 claims = verified.payload
83 } catch (error) {
84 if (isTokenError(error)) throw invalidToken(errorText(error))
85 throw new OAuthError(
86 'server_error',
87 `The key set could not be read: ${errorText(error)}`,
88 )
89 }
90 return authInfoFromClaims(token, claims)
91 },
92 }
93}
94
95// Key-set errors that name the token, not the key set. A timeout, a bad
96// key-set body, or a network error is an outage at the provider.
97const tokenKeySetCodes = new Set([
98 'ERR_JWKS_NO_MATCHING_KEY',
99 'ERR_JWKS_MULTIPLE_MATCHING_KEYS',
100 'ERR_JOSE_ALG_NOT_ALLOWED',
101 'ERR_JOSE_NOT_SUPPORTED',
102])
103
104function isTokenError(error: unknown) {
105 if (!(error instanceof errors.JOSEError)) return false
106 const code = error.code
107 return (
108 code.startsWith('ERR_JWT_') ||
109 code.startsWith('ERR_JWS_') ||
110 tokenKeySetCodes.has(code)
111 )
112}
113
114/**
115 * Builds an `OAuthTokenVerifier` for an opaque access token.
116 *
117 * The verifier posts the token to the RFC 7662 introspection endpoint.
118 * A token that is not `active` gets a 401 from `createMCPServer`.
119 * When the endpoint fails, the caller gets a 500 `server_error`.
120 *
121 * `clientId`, `scopes`, `expiresAt`, and `extra` come from the
122 * introspection response, the same as {@link jwtVerifier}.
123 *
124 * @param options - The introspection URL and the client credentials
125 *
126 * @example
127 * ```ts
128 * const verifier = introspectionVerifier({
129 * introspectionUrl: 'https://auth.example.com/oauth/introspect',
130 * clientId: process.env.OAUTH_CLIENT_ID ?? '',
131 * clientSecret: process.env.OAUTH_CLIENT_SECRET ?? '',
132 * })
133 * ```
134 */
135export function introspectionVerifier(
136 options: IntrospectionVerifierOptions,
137): OAuthTokenVerifier {
138 const fetchImpl = options.fetch ?? fetch
139 const credentials = btoa(`${options.clientId}:${options.clientSecret}`)
140 return {
141 async verifyAccessToken(token) {
142 const response = await fetchImpl(options.introspectionUrl, {
143 method: 'POST',
144 headers: {
145 authorization: `Basic ${credentials}`,
146 'content-type': 'application/x-www-form-urlencoded',
147 accept: 'application/json',
148 },
149 body: new URLSearchParams({ token }).toString(),
150 })
151 if (!response.ok) {
152 throw new OAuthError(
153 'server_error',
154 `The introspection endpoint answered ${response.status}.`,
155 )
156 }
157 const claims: unknown = await response.json()
158 if (!isRecord(claims) || claims.active !== true) {
159 throw invalidToken('The token is not active.')
160 }
161 return authInfoFromClaims(token, claims)
162 },
163 }
164}
165
166/**
167 * Turns the claims of a verified token into the SDK `AuthInfo`.
168 * The bearer-auth gate rejects an `AuthInfo` without `expiresAt`,
169 * so a token without `exp` is invalid.
170 */
171function authInfoFromClaims(
172 token: string,
173 claims: Record<string, unknown>,
174): AuthInfo {
175 const clientId = firstString(claims.client_id, claims.azp, claims.sub)
176 if (clientId === undefined) {
177 throw invalidToken('The token has no client_id, azp, or sub claim.')
178 }
179 const expiresAt = claims.exp
180 if (typeof expiresAt !== 'number') {
181 throw invalidToken('The token has no exp claim.')
182 }
183 const resource = resourceUrl(claims.aud)
184 return {
185 token,
186 clientId,
187 scopes: scopesOf(claims.scope),
188 expiresAt,
189 ...(resource === undefined ? {} : { resource }),
190 extra: claims,
191 }
192}
193
194function scopesOf(scope: unknown) {
195 if (typeof scope === 'string') return scope.split(' ').filter(Boolean)
196 if (!Array.isArray(scope)) return []
197 return scope.filter((item): item is string => typeof item === 'string')
198}
199
200// `aud` can be a string or a list, and an audience is not always a URL.
201function resourceUrl(aud: unknown) {
202 const first =
203 typeof aud === 'string' ? aud : Array.isArray(aud) ? aud[0] : undefined
204 if (typeof first !== 'string') return undefined
205 try {
206 return new URL(first)
207 } catch {
208 return undefined
209 }
210}
211
212function firstString(...values: Array<unknown>) {
213 return values.find(
214 (value): value is string => typeof value === 'string' && value.length > 0,
215 )
216}
217
218function invalidToken(message: string) {
219 return new OAuthError(OAuthErrorCode.InvalidToken, message)
220}
221
222function errorText(error: unknown) {
223 return error instanceof Error ? error.message : 'The token is invalid.'
224}
225
226function isRecord(value: unknown): value is Record<string, unknown> {
227 return typeof value === 'object' && value !== null && !Array.isArray(value)
228}