1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
|
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { MCPOAuthConfig } from './oauth-provider.js';
import { getErrorMessage } from '../utils/errors.js';
/**
* OAuth authorization server metadata as per RFC 8414.
*/
export interface OAuthAuthorizationServerMetadata {
issuer: string;
authorization_endpoint: string;
token_endpoint: string;
token_endpoint_auth_methods_supported?: string[];
revocation_endpoint?: string;
revocation_endpoint_auth_methods_supported?: string[];
registration_endpoint?: string;
response_types_supported?: string[];
grant_types_supported?: string[];
code_challenge_methods_supported?: string[];
scopes_supported?: string[];
}
/**
* OAuth protected resource metadata as per RFC 9728.
*/
export interface OAuthProtectedResourceMetadata {
resource: string;
authorization_servers?: string[];
bearer_methods_supported?: string[];
resource_documentation?: string;
resource_signing_alg_values_supported?: string[];
resource_encryption_alg_values_supported?: string[];
resource_encryption_enc_values_supported?: string[];
}
/**
* Utility class for common OAuth operations.
*/
export class OAuthUtils {
/**
* Construct well-known OAuth endpoint URLs.
* By default, uses standard root-based well-known URLs.
* If includePathSuffix is true, appends any path from the base URL to the well-known endpoints.
*/
static buildWellKnownUrls(baseUrl: string, includePathSuffix = false) {
const serverUrl = new URL(baseUrl);
const base = `${serverUrl.protocol}//${serverUrl.host}`;
if (!includePathSuffix) {
// Standard discovery: use root-based well-known URLs
return {
protectedResource: new URL(
'/.well-known/oauth-protected-resource',
base,
).toString(),
authorizationServer: new URL(
'/.well-known/oauth-authorization-server',
base,
).toString(),
};
}
// Path-based discovery: append path suffix to well-known URLs
const pathSuffix = serverUrl.pathname.replace(/\/$/, ''); // Remove trailing slash
return {
protectedResource: new URL(
`/.well-known/oauth-protected-resource${pathSuffix}`,
base,
).toString(),
authorizationServer: new URL(
`/.well-known/oauth-authorization-server${pathSuffix}`,
base,
).toString(),
};
}
/**
* Fetch OAuth protected resource metadata.
*
* @param resourceMetadataUrl The protected resource metadata URL
* @returns The protected resource metadata or null if not available
*/
static async fetchProtectedResourceMetadata(
resourceMetadataUrl: string,
): Promise<OAuthProtectedResourceMetadata | null> {
try {
const response = await fetch(resourceMetadataUrl);
if (!response.ok) {
return null;
}
return (await response.json()) as OAuthProtectedResourceMetadata;
} catch (error) {
console.debug(
`Failed to fetch protected resource metadata from ${resourceMetadataUrl}: ${getErrorMessage(error)}`,
);
return null;
}
}
/**
* Fetch OAuth authorization server metadata.
*
* @param authServerMetadataUrl The authorization server metadata URL
* @returns The authorization server metadata or null if not available
*/
static async fetchAuthorizationServerMetadata(
authServerMetadataUrl: string,
): Promise<OAuthAuthorizationServerMetadata | null> {
try {
const response = await fetch(authServerMetadataUrl);
if (!response.ok) {
return null;
}
return (await response.json()) as OAuthAuthorizationServerMetadata;
} catch (error) {
console.debug(
`Failed to fetch authorization server metadata from ${authServerMetadataUrl}: ${getErrorMessage(error)}`,
);
return null;
}
}
/**
* Convert authorization server metadata to OAuth configuration.
*
* @param metadata The authorization server metadata
* @returns The OAuth configuration
*/
static metadataToOAuthConfig(
metadata: OAuthAuthorizationServerMetadata,
): MCPOAuthConfig {
return {
authorizationUrl: metadata.authorization_endpoint,
tokenUrl: metadata.token_endpoint,
scopes: metadata.scopes_supported || [],
};
}
/**
* Discover OAuth configuration using the standard well-known endpoints.
*
* @param serverUrl The base URL of the server
* @returns The discovered OAuth configuration or null if not available
*/
static async discoverOAuthConfig(
serverUrl: string,
): Promise<MCPOAuthConfig | null> {
try {
// First try standard root-based discovery
const wellKnownUrls = this.buildWellKnownUrls(serverUrl, false);
// Try to get the protected resource metadata at root
let resourceMetadata = await this.fetchProtectedResourceMetadata(
wellKnownUrls.protectedResource,
);
// If root discovery fails and we have a path, try path-based discovery
if (!resourceMetadata) {
const url = new URL(serverUrl);
if (url.pathname && url.pathname !== '/') {
const pathBasedUrls = this.buildWellKnownUrls(serverUrl, true);
resourceMetadata = await this.fetchProtectedResourceMetadata(
pathBasedUrls.protectedResource,
);
}
}
if (resourceMetadata?.authorization_servers?.length) {
// Use the first authorization server
const authServerUrl = resourceMetadata.authorization_servers[0];
// The authorization server URL may include a path (e.g., https://github.com/login/oauth)
// We need to preserve this path when constructing the metadata URL
const authServerUrlObj = new URL(authServerUrl);
const authServerPath =
authServerUrlObj.pathname === '/' ? '' : authServerUrlObj.pathname;
// Try with the authorization server's path first
let authServerMetadataUrl = new URL(
`/.well-known/oauth-authorization-server${authServerPath}`,
`${authServerUrlObj.protocol}//${authServerUrlObj.host}`,
).toString();
let authServerMetadata = await this.fetchAuthorizationServerMetadata(
authServerMetadataUrl,
);
// If that fails, try root as fallback
if (!authServerMetadata && authServerPath) {
authServerMetadataUrl = new URL(
'/.well-known/oauth-authorization-server',
`${authServerUrlObj.protocol}//${authServerUrlObj.host}`,
).toString();
authServerMetadata = await this.fetchAuthorizationServerMetadata(
authServerMetadataUrl,
);
}
if (authServerMetadata) {
const config = this.metadataToOAuthConfig(authServerMetadata);
if (authServerMetadata.registration_endpoint) {
console.log(
'Dynamic client registration is supported at:',
authServerMetadata.registration_endpoint,
);
}
return config;
}
}
// Fallback: try /.well-known/oauth-authorization-server at the base URL
console.debug(
`Trying OAuth discovery fallback at ${wellKnownUrls.authorizationServer}`,
);
const authServerMetadata = await this.fetchAuthorizationServerMetadata(
wellKnownUrls.authorizationServer,
);
if (authServerMetadata) {
const config = this.metadataToOAuthConfig(authServerMetadata);
if (authServerMetadata.registration_endpoint) {
console.log(
'Dynamic client registration is supported at:',
authServerMetadata.registration_endpoint,
);
}
return config;
}
return null;
} catch (error) {
console.debug(
`Failed to discover OAuth configuration: ${getErrorMessage(error)}`,
);
return null;
}
}
/**
* Parse WWW-Authenticate header to extract OAuth information.
*
* @param header The WWW-Authenticate header value
* @returns The resource metadata URI if found
*/
static parseWWWAuthenticateHeader(header: string): string | null {
// Parse Bearer realm and resource_metadata
const match = header.match(/resource_metadata="([^"]+)"/);
if (match) {
return match[1];
}
return null;
}
/**
* Discover OAuth configuration from WWW-Authenticate header.
*
* @param wwwAuthenticate The WWW-Authenticate header value
* @returns The discovered OAuth configuration or null if not available
*/
static async discoverOAuthFromWWWAuthenticate(
wwwAuthenticate: string,
): Promise<MCPOAuthConfig | null> {
const resourceMetadataUri =
this.parseWWWAuthenticateHeader(wwwAuthenticate);
if (!resourceMetadataUri) {
return null;
}
const resourceMetadata =
await this.fetchProtectedResourceMetadata(resourceMetadataUri);
if (!resourceMetadata?.authorization_servers?.length) {
return null;
}
const authServerUrl = resourceMetadata.authorization_servers[0];
// The authorization server URL may include a path (e.g., https://github.com/login/oauth)
// We need to preserve this path when constructing the metadata URL
const authServerUrlObj = new URL(authServerUrl);
const authServerPath =
authServerUrlObj.pathname === '/' ? '' : authServerUrlObj.pathname;
// Build auth server metadata URL with the authorization server's path
const authServerMetadataUrl = new URL(
`/.well-known/oauth-authorization-server${authServerPath}`,
`${authServerUrlObj.protocol}//${authServerUrlObj.host}`,
).toString();
let authServerMetadata = await this.fetchAuthorizationServerMetadata(
authServerMetadataUrl,
);
// If that fails and we have a path, also try the root path as a fallback
if (!authServerMetadata && authServerPath) {
const rootAuthServerMetadataUrl = new URL(
'/.well-known/oauth-authorization-server',
`${authServerUrlObj.protocol}//${authServerUrlObj.host}`,
).toString();
authServerMetadata = await this.fetchAuthorizationServerMetadata(
rootAuthServerMetadataUrl,
);
}
if (authServerMetadata) {
return this.metadataToOAuthConfig(authServerMetadata);
}
return null;
}
/**
* Extract base URL from an MCP server URL.
*
* @param mcpServerUrl The MCP server URL
* @returns The base URL
*/
static extractBaseUrl(mcpServerUrl: string): string {
const serverUrl = new URL(mcpServerUrl);
return `${serverUrl.protocol}//${serverUrl.host}`;
}
/**
* Check if a URL is an SSE endpoint.
*
* @param url The URL to check
* @returns True if the URL appears to be an SSE endpoint
*/
static isSSEEndpoint(url: string): boolean {
return url.includes('/sse') || !url.includes('/mcp');
}
/**
* Build a resource parameter for OAuth requests.
*
* @param endpointUrl The endpoint URL
* @returns The resource parameter value
*/
static buildResourceParameter(endpointUrl: string): string {
const url = new URL(endpointUrl);
return `${url.protocol}//${url.host}`;
}
}
|