@forklaunch/core 4.2.0 → 4.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1251,15 +1251,15 @@ var MAX_CLAIM_LENGTH = 128;
1251
1251
  function bounded(value) {
1252
1252
  return typeof value === "string" && value.length > 0 ? value.slice(0, MAX_CLAIM_LENGTH) : void 0;
1253
1253
  }
1254
- function authLogContext(headerValue) {
1255
- if (typeof headerValue !== "string" || headerValue.length === 0) {
1254
+ function authLogContext(headerValue2) {
1255
+ if (typeof headerValue2 !== "string" || headerValue2.length === 0) {
1256
1256
  return { hasToken: false };
1257
1257
  }
1258
1258
  const context2 = {
1259
1259
  hasToken: true,
1260
- tokenFingerprint: createHash("sha256").update(headerValue).digest("hex").slice(0, FINGERPRINT_LENGTH)
1260
+ tokenFingerprint: createHash("sha256").update(headerValue2).digest("hex").slice(0, FINGERPRINT_LENGTH)
1261
1261
  };
1262
- const parts = headerValue.trim().split(/\s+/);
1262
+ const parts = headerValue2.trim().split(/\s+/);
1263
1263
  const candidate = parts[parts.length - 1];
1264
1264
  if (candidate.split(".").length !== 3) {
1265
1265
  return context2;
@@ -3462,21 +3462,21 @@ function refuse(message) {
3462
3462
  }
3463
3463
  function addresses(value, field) {
3464
3464
  if (value === void 0) return void 0;
3465
- const list = Array.isArray(value) ? value : [value];
3466
- if (list.length === 0) refuse(`${field} must name at least one address`);
3467
- if (list.length > EMAIL_LIMITS.maxRecipients) {
3465
+ const list2 = Array.isArray(value) ? value : [value];
3466
+ if (list2.length === 0) refuse(`${field} must name at least one address`);
3467
+ if (list2.length > EMAIL_LIMITS.maxRecipients) {
3468
3468
  refuse(
3469
- `${field} has ${list.length} addresses; the limit is ${EMAIL_LIMITS.maxRecipients}`
3469
+ `${field} has ${list2.length} addresses; the limit is ${EMAIL_LIMITS.maxRecipients}`
3470
3470
  );
3471
3471
  }
3472
- for (const address of list) {
3472
+ for (const address of list2) {
3473
3473
  if (!isEmailAddress(address)) {
3474
3474
  refuse(
3475
3475
  `${field}: '${String(address).slice(0, 80)}' is not an email address`
3476
3476
  );
3477
3477
  }
3478
3478
  }
3479
- return list;
3479
+ return list2;
3480
3480
  }
3481
3481
  function fail(problem) {
3482
3482
  refuse(`listUnsubscribe: ${problem}`);
@@ -5151,7 +5151,7 @@ import {
5151
5151
  safeStringify as safeStringify3,
5152
5152
  toPlainString
5153
5153
  } from "@forklaunch/common";
5154
- import { string, ZodSchemaValidator } from "@forklaunch/validator/zod";
5154
+ import { ZodSchemaValidator } from "@forklaunch/validator/zod";
5155
5155
  import { FastMCP } from "fastmcp";
5156
5156
 
5157
5157
  // src/http/router/unpackRouters.ts
@@ -5172,16 +5172,317 @@ function unpackRouters(routers, recursiveBasePath = []) {
5172
5172
  }, []);
5173
5173
  }
5174
5174
 
5175
+ // src/http/mcpGenerator/mcpAuth.ts
5176
+ function mcpAuthHeaderNames(auth) {
5177
+ const names = /* @__PURE__ */ new Set(["authorization"]);
5178
+ if (auth?.headerName) {
5179
+ names.add(auth.headerName.toLowerCase());
5180
+ }
5181
+ return names;
5182
+ }
5183
+ function routeRequiresAuth(contractDetails) {
5184
+ return contractDetails.auth != null && contractDetails.access !== "public";
5185
+ }
5186
+ function headerValue(headers, name) {
5187
+ if (!headers) {
5188
+ return void 0;
5189
+ }
5190
+ if (typeof headers.get === "function") {
5191
+ return headers.get(name) ?? void 0;
5192
+ }
5193
+ const value = headers[name];
5194
+ return Array.isArray(value) ? value[0] : value;
5195
+ }
5196
+ function sameCredentialSource(a, b) {
5197
+ const fields = ["headerName", "tokenPrefix", "decodeResource"];
5198
+ if (fields.some((field) => a[field] !== b[field])) {
5199
+ return false;
5200
+ }
5201
+ if (isJwtAuthMethod(a) && isJwtAuthMethod(b)) {
5202
+ const ja = a.jwt;
5203
+ const jb = b.jwt;
5204
+ const keys = /* @__PURE__ */ new Set([...Object.keys(ja), ...Object.keys(jb)]);
5205
+ return [...keys].every(
5206
+ (key) => JSON.stringify(ja[key]) === JSON.stringify(jb[key])
5207
+ );
5208
+ }
5209
+ if (isBasicAuthMethod(a) && isBasicAuthMethod(b)) {
5210
+ return a.basic.login === b.basic.login;
5211
+ }
5212
+ return false;
5213
+ }
5214
+ function createRouteMcpAuthenticate(routeAuths) {
5215
+ const sources = [];
5216
+ for (const auth of routeAuths) {
5217
+ if (isHmacMethod(auth)) {
5218
+ continue;
5219
+ }
5220
+ if (!sources.some((source) => sameCredentialSource(source, auth))) {
5221
+ sources.push(auth);
5222
+ }
5223
+ }
5224
+ return async (request) => {
5225
+ for (const auth of sources) {
5226
+ const credential = headerValue(
5227
+ request.headers,
5228
+ (auth.headerName ?? "authorization").toLowerCase()
5229
+ );
5230
+ if (!credential) {
5231
+ continue;
5232
+ }
5233
+ const [prefix, ...parts] = credential.split(" ");
5234
+ const [token] = parts;
5235
+ if (!prefix || !token) {
5236
+ continue;
5237
+ }
5238
+ try {
5239
+ const method = await discriminateAuthMethod(
5240
+ auth
5241
+ );
5242
+ switch (method.type) {
5243
+ case "jwt": {
5244
+ if (prefix !== (auth.tokenPrefix ?? "Bearer")) {
5245
+ continue;
5246
+ }
5247
+ const payload = "decodeResource" in method.auth && method.auth.decodeResource ? await method.auth.decodeResource(token) : "verificationFunction" in method.auth ? await method.auth.verificationFunction(token) : void 0;
5248
+ if (payload) {
5249
+ return { ...payload };
5250
+ }
5251
+ break;
5252
+ }
5253
+ case "basic": {
5254
+ if (prefix !== (auth.tokenPrefix ?? "Basic")) {
5255
+ continue;
5256
+ }
5257
+ if (method.auth.decodeResource) {
5258
+ const payload = await method.auth.decodeResource(token);
5259
+ if (payload) {
5260
+ return { ...payload };
5261
+ }
5262
+ break;
5263
+ }
5264
+ const [username, password] = Buffer.from(token, "base64").toString("utf-8").split(":");
5265
+ if (username && password && method.auth.login(username, password)) {
5266
+ return { sub: username };
5267
+ }
5268
+ break;
5269
+ }
5270
+ case "hmac":
5271
+ break;
5272
+ }
5273
+ } catch {
5274
+ }
5275
+ }
5276
+ return void 0;
5277
+ };
5278
+ }
5279
+ var generatedAuthenticate = /* @__PURE__ */ new WeakMap();
5280
+ function setGeneratedMcpAuthenticate(mcpServer, authenticate) {
5281
+ if (authenticate) {
5282
+ generatedAuthenticate.set(mcpServer, authenticate);
5283
+ }
5284
+ }
5285
+ function getGeneratedMcpAuthenticate(mcpServer) {
5286
+ return generatedAuthenticate.get(mcpServer);
5287
+ }
5288
+
5175
5289
  // src/http/mcpGenerator/mcpHttpHandler.ts
5176
5290
  import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
5177
5291
  import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
5178
5292
  import { randomUUID as randomUUID2 } from "crypto";
5293
+
5294
+ // src/http/mcpGenerator/mcpOAuth.ts
5295
+ import {
5296
+ createRemoteJWKSet,
5297
+ jwtVerify as jwtVerify2
5298
+ } from "jose";
5299
+ var WELL_KNOWN = "/.well-known/oauth-protected-resource";
5300
+ function trimTrailingSlashes2(path) {
5301
+ let end = path.length;
5302
+ while (end > 0 && path.charCodeAt(end - 1) === 47) {
5303
+ end--;
5304
+ }
5305
+ return path.slice(0, end);
5306
+ }
5307
+ var list = (value) => value?.split(/[\s,]+/).map((item) => item.trim()).filter(Boolean);
5308
+ function canonicalMcpResource(resource) {
5309
+ const url = new URL(resource);
5310
+ if (url.protocol !== "https:" && url.protocol !== "http:") {
5311
+ throw new Error(`MCP resource must be an http(s) URL: ${resource}`);
5312
+ }
5313
+ return `${url.origin}${trimTrailingSlashes2(url.pathname)}`;
5314
+ }
5315
+ function resolveMcpOAuth(options2, server) {
5316
+ const authorizationServers = options2?.authorizationServers ?? list(process.env.MCP_AUTHORIZATION_SERVERS);
5317
+ if (!authorizationServers || authorizationServers.length === 0) {
5318
+ if (options2) {
5319
+ throw new Error(
5320
+ "mcp.oauth needs at least one authorization server (mcp.oauth.authorizationServers or MCP_AUTHORIZATION_SERVERS)."
5321
+ );
5322
+ }
5323
+ return void 0;
5324
+ }
5325
+ const resource = canonicalMcpResource(
5326
+ options2?.resource ?? process.env.MCP_RESOURCE_URL ?? `${server.protocol}://${server.host}:${server.port}${server.path}`
5327
+ );
5328
+ const resourcePath = trimTrailingSlashes2(new URL(resource).pathname);
5329
+ const metadataUrl = `${new URL(resource).origin}${WELL_KNOWN}${resourcePath}`;
5330
+ const issuer = options2?.issuer ?? authorizationServers;
5331
+ return {
5332
+ resource,
5333
+ authorizationServers,
5334
+ jwksUrl: options2?.jwksUrl ?? process.env.MCP_JWKS_URL,
5335
+ issuer: Array.isArray(issuer) ? [...issuer] : [issuer],
5336
+ algorithms: options2?.algorithms,
5337
+ scopesSupported: options2?.scopesSupported ?? list(process.env.MCP_SCOPES_SUPPORTED),
5338
+ requiredScopes: options2?.requiredScopes ?? list(process.env.MCP_REQUIRED_SCOPES),
5339
+ resourceName: options2?.resourceName,
5340
+ metadataUrl,
5341
+ metadataPaths: [
5342
+ .../* @__PURE__ */ new Set([
5343
+ WELL_KNOWN,
5344
+ `${WELL_KNOWN}${resourcePath}`,
5345
+ `${WELL_KNOWN}${trimTrailingSlashes2(server.path)}`
5346
+ ])
5347
+ ]
5348
+ };
5349
+ }
5350
+ function mcpProtectedResourceMetadata(oauth) {
5351
+ return {
5352
+ resource: oauth.resource,
5353
+ authorization_servers: oauth.authorizationServers,
5354
+ bearer_methods_supported: ["header"],
5355
+ ...oauth.scopesSupported?.length ? { scopes_supported: oauth.scopesSupported } : {},
5356
+ ...oauth.resourceName ? { resource_name: oauth.resourceName } : {}
5357
+ };
5358
+ }
5359
+ function mcpProtectedResourceMetadataResponse(oauth) {
5360
+ return new Response(JSON.stringify(mcpProtectedResourceMetadata(oauth)), {
5361
+ status: 200,
5362
+ headers: {
5363
+ "Content-Type": "application/json",
5364
+ "Cache-Control": "public, max-age=3600"
5365
+ }
5366
+ });
5367
+ }
5368
+ var quoted = (value) => `"${value.replace(/["\\]/g, "\\$&")}"`;
5369
+ function mcpBearerChallenge(oauth, error) {
5370
+ const parts = [];
5371
+ if (error) {
5372
+ parts.push(`error=${quoted(error.code)}`);
5373
+ }
5374
+ if (oauth) {
5375
+ const scope = oauth.requiredScopes?.length ? oauth.requiredScopes : oauth.scopesSupported;
5376
+ if (scope?.length) {
5377
+ parts.push(`scope=${quoted(scope.join(" "))}`);
5378
+ }
5379
+ parts.push(`resource_metadata=${quoted(oauth.metadataUrl)}`);
5380
+ }
5381
+ if (error?.description) {
5382
+ parts.push(`error_description=${quoted(error.description)}`);
5383
+ }
5384
+ return parts.length ? `Bearer ${parts.join(", ")}` : "Bearer";
5385
+ }
5386
+ var McpInsufficientScopeError = class extends Error {
5387
+ constructor(missing) {
5388
+ super(`Missing scope: ${missing.join(" ")}`);
5389
+ this.missing = missing;
5390
+ this.name = "McpInsufficientScopeError";
5391
+ }
5392
+ missing;
5393
+ };
5394
+ function tokenScopes(payload) {
5395
+ const scopes = /* @__PURE__ */ new Set();
5396
+ if (typeof payload.scope === "string") {
5397
+ payload.scope.split(" ").forEach((scope) => scope && scopes.add(scope));
5398
+ }
5399
+ if (Array.isArray(payload.scp)) {
5400
+ payload.scp.forEach(
5401
+ (scope) => typeof scope === "string" && scopes.add(scope)
5402
+ );
5403
+ }
5404
+ return scopes;
5405
+ }
5406
+ async function discoverJwksUri(issuer) {
5407
+ const url = new URL(issuer);
5408
+ const path = trimTrailingSlashes2(url.pathname);
5409
+ const candidates = [
5410
+ `${url.origin}/.well-known/oauth-authorization-server${path}`,
5411
+ `${url.origin}/.well-known/openid-configuration${path}`,
5412
+ `${url.origin}${path}/.well-known/openid-configuration`
5413
+ ];
5414
+ for (const candidate of candidates) {
5415
+ try {
5416
+ const response = await fetch(candidate, {
5417
+ headers: { accept: "application/json" },
5418
+ signal: AbortSignal.timeout(5e3)
5419
+ });
5420
+ if (!response.ok) continue;
5421
+ const metadata = await response.json();
5422
+ if (metadata.issuer === issuer && metadata.jwks_uri) {
5423
+ return metadata.jwks_uri;
5424
+ }
5425
+ } catch {
5426
+ }
5427
+ }
5428
+ throw new Error(`No jwks_uri found in the metadata of ${issuer}`);
5429
+ }
5430
+ function createMcpOAuthAuthenticate(oauth, getKey) {
5431
+ let keys = getKey ? Promise.resolve(getKey) : void 0;
5432
+ const resolveKeys = () => {
5433
+ keys ??= (async () => createRemoteJWKSet(
5434
+ new URL(
5435
+ oauth.jwksUrl ?? await discoverJwksUri(oauth.authorizationServers[0])
5436
+ )
5437
+ ))().catch((error) => {
5438
+ keys = void 0;
5439
+ throw error;
5440
+ });
5441
+ return keys;
5442
+ };
5443
+ return async (request) => {
5444
+ const header = request.headers?.authorization;
5445
+ const value = Array.isArray(header) ? header[0] : header;
5446
+ const match = value?.match(/^Bearer +([^\s]+) *$/i);
5447
+ if (!match) {
5448
+ return void 0;
5449
+ }
5450
+ const { payload } = await jwtVerify2(match[1], await resolveKeys(), {
5451
+ issuer: oauth.issuer,
5452
+ audience: oauth.resource,
5453
+ ...oauth.algorithms ? { algorithms: oauth.algorithms } : {}
5454
+ });
5455
+ if (oauth.requiredScopes?.length) {
5456
+ const granted = tokenScopes(payload);
5457
+ const missing = oauth.requiredScopes.filter(
5458
+ (scope) => !granted.has(scope)
5459
+ );
5460
+ if (missing.length) {
5461
+ throw new McpInsufficientScopeError(missing);
5462
+ }
5463
+ }
5464
+ return { ...payload };
5465
+ };
5466
+ }
5467
+ var generatedOAuth = /* @__PURE__ */ new WeakMap();
5468
+ function setGeneratedMcpOAuth(mcpServer, oauth) {
5469
+ if (oauth) {
5470
+ generatedOAuth.set(mcpServer, oauth);
5471
+ }
5472
+ }
5473
+ function getGeneratedMcpOAuth(mcpServer) {
5474
+ return generatedOAuth.get(mcpServer);
5475
+ }
5476
+
5477
+ // src/http/mcpGenerator/mcpHttpHandler.ts
5179
5478
  var DEFAULT_MCP_SESSION_IDLE_TIMEOUT_MS = 15 * 60 * 1e3;
5180
5479
  var mcpTransportHeaders = new AsyncLocalStorage2();
5181
5480
  function getMcpTransportHeaders() {
5182
5481
  return mcpTransportHeaders.getStore();
5183
5482
  }
5184
5483
  function createMcpHttpHandler(mcpServer, options2) {
5484
+ const authenticate = options2?.authenticate ?? getGeneratedMcpAuthenticate(mcpServer);
5485
+ const oauth = options2?.oauth ?? getGeneratedMcpOAuth(mcpServer);
5185
5486
  const mode = options2?.sessions ?? "stateless";
5186
5487
  if (mode === "stateful" && (options2?.workerCount ?? 1) > 1) {
5187
5488
  throw new Error(
@@ -5214,16 +5515,32 @@ function createMcpHttpHandler(mcpServer, options2) {
5214
5515
  sweepTimer.unref();
5215
5516
  }
5216
5517
  async function authenticateRequest(authRequest) {
5217
- if (!options2?.authenticate) {
5518
+ if (!authenticate) {
5218
5519
  return { ok: true, auth: void 0 };
5219
5520
  }
5220
5521
  try {
5221
- const auth = await options2.authenticate(authRequest);
5522
+ const auth = await authenticate(authRequest);
5222
5523
  return auth ? { ok: true, auth } : { ok: false };
5223
- } catch {
5224
- return { ok: false };
5524
+ } catch (error) {
5525
+ return error instanceof McpInsufficientScopeError ? { ok: false, insufficientScope: error.missing } : { ok: false };
5225
5526
  }
5226
5527
  }
5528
+ function refuse2(authRequest, insufficientScope) {
5529
+ if (insufficientScope) {
5530
+ return jsonRpcError(403, -32001, "Forbidden", {
5531
+ "WWW-Authenticate": mcpBearerChallenge(oauth, {
5532
+ code: "insufficient_scope"
5533
+ })
5534
+ });
5535
+ }
5536
+ const presented = Boolean(authRequest.headers?.authorization);
5537
+ return jsonRpcError(401, -32001, "Unauthorized", {
5538
+ "WWW-Authenticate": mcpBearerChallenge(
5539
+ oauth,
5540
+ oauth && presented ? { code: "invalid_token" } : void 0
5541
+ )
5542
+ });
5543
+ }
5227
5544
  async function handleStateless(request, auth) {
5228
5545
  if (request.method !== "POST") {
5229
5546
  return jsonRpcError(405, -32e3, "Method not allowed", {
@@ -5296,9 +5613,7 @@ function createMcpHttpHandler(mcpServer, options2) {
5296
5613
  async function handle(request, authRequest) {
5297
5614
  const authResult = await authenticateRequest(authRequest);
5298
5615
  if (!authResult.ok) {
5299
- return jsonRpcError(401, -32001, "Unauthorized", {
5300
- "WWW-Authenticate": "Bearer"
5301
- });
5616
+ return refuse2(authRequest, authResult.insufficientScope);
5302
5617
  }
5303
5618
  return mode === "stateless" ? handleStateless(request, authResult.auth) : handleStateful(request, authResult.auth);
5304
5619
  }
@@ -5310,7 +5625,9 @@ function createMcpHttpHandler(mcpServer, options2) {
5310
5625
  sessions.clear();
5311
5626
  await Promise.all(entries.map(({ session }) => session.close()));
5312
5627
  }
5313
- return { handle, close, sessions };
5628
+ const metadataPaths = oauth?.metadataPaths ?? [];
5629
+ const protectedResourceMetadata = () => oauth ? mcpProtectedResourceMetadataResponse(oauth) : jsonRpcError(404, -32601, "Not found");
5630
+ return { handle, close, sessions, metadataPaths, protectedResourceMetadata };
5314
5631
  }
5315
5632
  function closeWhenBodyEnds(response, done) {
5316
5633
  if (!response.body) {
@@ -5350,6 +5667,7 @@ function isSeparateMcpListener(configuredPort) {
5350
5667
 
5351
5668
  // src/http/mcpGenerator/mcpGenerator.ts
5352
5669
  function generateInputSchema(schemaValidator, body, params, query, requestHeaders, auth) {
5670
+ const toolHeaders = toolInputHeaders(requestHeaders, auth);
5353
5671
  let discriminatedBody;
5354
5672
  if (body) {
5355
5673
  discriminatedBody = discriminateBody(schemaValidator, body);
@@ -5365,30 +5683,38 @@ function generateInputSchema(schemaValidator, body, params, query, requestHeader
5365
5683
  ...query ? {
5366
5684
  query: schemaValidator.schemify(query)
5367
5685
  } : {},
5368
- ...requestHeaders ? {
5369
- headers: schemaValidator.schemify({
5370
- ...requestHeaders,
5371
- ...auth ? {
5372
- [auth.headerName ?? "authorization"]: string.startsWith(
5373
- auth.tokenPrefix ?? ("basic" in auth ? "Basic " : "Bearer ")
5374
- )
5375
- } : {}
5376
- })
5686
+ ...toolHeaders ? {
5687
+ headers: schemaValidator.schemify(toolHeaders)
5377
5688
  } : {}
5378
5689
  });
5379
5690
  }
5380
- function buildRouteHeaders(toolHeaders, contentType) {
5691
+ function toolInputHeaders(requestHeaders, auth) {
5692
+ if (!requestHeaders) {
5693
+ return void 0;
5694
+ }
5695
+ const credentialHeaders = mcpAuthHeaderNames(auth);
5696
+ const headers = Object.fromEntries(
5697
+ Object.entries(requestHeaders).filter(
5698
+ ([name]) => !credentialHeaders.has(name.toLowerCase())
5699
+ )
5700
+ );
5701
+ return Object.keys(headers).length > 0 ? headers : void 0;
5702
+ }
5703
+ function buildRouteHeaders(toolHeaders, contentType, auth) {
5381
5704
  const transportHeaders = getMcpTransportHeaders();
5382
5705
  const routeHeaders = new Headers();
5383
- const authorization = transportHeaders?.get("authorization");
5384
- if (authorization) {
5385
- routeHeaders.set("authorization", authorization);
5386
- }
5706
+ const credentialHeaders = mcpAuthHeaderNames(auth);
5387
5707
  for (const [name, value] of Object.entries(toolHeaders ?? {})) {
5388
- if (value != null) {
5708
+ if (value != null && !credentialHeaders.has(name.toLowerCase())) {
5389
5709
  routeHeaders.set(name, String(value));
5390
5710
  }
5391
5711
  }
5712
+ for (const name of credentialHeaders) {
5713
+ const credential = transportHeaders?.get(name);
5714
+ if (credential) {
5715
+ routeHeaders.set(name, credential);
5716
+ }
5717
+ }
5392
5718
  const correlationId = transportHeaders?.get("x-correlation-id");
5393
5719
  if (correlationId) {
5394
5720
  routeHeaders.set("x-correlation-id", correlationId);
@@ -5407,226 +5733,279 @@ function buildRouteHeaders(toolHeaders, contentType) {
5407
5733
  }
5408
5734
  return routeHeaders;
5409
5735
  }
5410
- function generateMcpServer(schemaValidator, protocol, host, port, version, application, appOptions, options2, contentTypeMap, authenticate) {
5736
+ function generateMcpServer(schemaValidator, protocol, host, port, version, application, appOptions, options2, contentTypeMap, authenticate, logger2) {
5411
5737
  if (!(schemaValidator instanceof ZodSchemaValidator)) {
5412
5738
  throw new Error(
5413
5739
  "Schema validator must be an instance of ZodSchemaValidator"
5414
5740
  );
5415
5741
  }
5742
+ const exposedRoutes = collectMcpRoutes(application, appOptions);
5743
+ const oauth = resolveMcpOAuth(appOptions ? appOptions.oauth : void 0, {
5744
+ protocol,
5745
+ host,
5746
+ port,
5747
+ path: appOptions && appOptions.path || "/mcp"
5748
+ });
5749
+ const resolvedAuthenticate = oauth ? authenticate ?? createMcpOAuthAuthenticate(oauth) : resolveMcpAuthenticate(exposedRoutes, authenticate, logger2);
5750
+ if (oauth) {
5751
+ logger2?.info(
5752
+ "MCP: OAuth on; the endpoint accepts only access tokens issued for it and publishes its Protected Resource Metadata at /.well-known/oauth-protected-resource."
5753
+ );
5754
+ }
5416
5755
  const mcpServer = new FastMCP({
5417
5756
  ...options2,
5418
5757
  name: options2?.name ?? "mcp-server",
5419
5758
  version,
5420
- authenticate
5421
- });
5422
- [
5423
- {
5424
- fullPath: application.basePath === "/" ? "" : application.basePath,
5425
- router: application
5426
- },
5427
- ...unpackRouters(application.routers, [
5428
- application.basePath === "/" ? "" : application.basePath
5429
- ])
5430
- ].forEach(({ fullPath, router }) => {
5431
- router.routes.forEach((route) => {
5432
- if (!(route.contractDetails.options?.mcp ?? router.routerOptions?.mcp ?? appOptions !== false)) {
5433
- return;
5759
+ authenticate: resolvedAuthenticate,
5760
+ ...oauth ? {
5761
+ oauth: {
5762
+ ...options2?.oauth,
5763
+ enabled: true,
5764
+ protectedResource: {
5765
+ resource: oauth.resource,
5766
+ authorizationServers: oauth.authorizationServers,
5767
+ bearerMethodsSupported: ["header"],
5768
+ ...oauth.scopesSupported?.length ? { scopesSupported: oauth.scopesSupported } : {},
5769
+ ...oauth.resourceName ? { resourceName: oauth.resourceName } : {}
5770
+ }
5434
5771
  }
5435
- const inputSchemas = [];
5436
- if (route.contractDetails.versions) {
5437
- Object.values(route.contractDetails.versions).forEach((version2) => {
5438
- inputSchemas.push(
5439
- generateInputSchema(
5440
- schemaValidator,
5441
- version2.body,
5442
- route.contractDetails.params,
5443
- version2.query,
5444
- version2.requestHeaders,
5445
- route.contractDetails.auth
5446
- )
5447
- );
5448
- });
5449
- } else {
5772
+ } : {}
5773
+ });
5774
+ setGeneratedMcpAuthenticate(mcpServer, resolvedAuthenticate);
5775
+ setGeneratedMcpOAuth(mcpServer, oauth);
5776
+ exposedRoutes.forEach(({ fullPath, route }) => {
5777
+ const inputSchemas = [];
5778
+ if (route.contractDetails.versions) {
5779
+ Object.values(route.contractDetails.versions).forEach((version2) => {
5450
5780
  inputSchemas.push(
5451
5781
  generateInputSchema(
5452
5782
  schemaValidator,
5453
- route.contractDetails.body,
5783
+ version2.body,
5454
5784
  route.contractDetails.params,
5455
- route.contractDetails.query,
5456
- route.contractDetails.requestHeaders,
5785
+ version2.query,
5786
+ version2.requestHeaders,
5457
5787
  route.contractDetails.auth
5458
5788
  )
5459
5789
  );
5460
- }
5461
- inputSchemas.forEach((inputSchema, index) => {
5462
- mcpServer.addTool({
5463
- name: route.contractDetails.name + (Object.keys(route.contractDetails.versions ?? {}).length > 1 ? ` [v${Object.keys(route.contractDetails.versions ?? {})[index]}]` : ""),
5464
- description: route.contractDetails.summary,
5465
- parameters: inputSchema,
5466
- execute: async (args) => {
5467
- const { contentType, body, params, query, headers } = args;
5468
- let url = `${protocol}://${host}:${port}${fullPath}${route.path}`;
5469
- if (params) {
5470
- for (const key in params) {
5471
- url = url.replace(
5472
- `:${key}`,
5473
- encodeURIComponent(params[key])
5474
- );
5475
- }
5790
+ });
5791
+ } else {
5792
+ inputSchemas.push(
5793
+ generateInputSchema(
5794
+ schemaValidator,
5795
+ route.contractDetails.body,
5796
+ route.contractDetails.params,
5797
+ route.contractDetails.query,
5798
+ route.contractDetails.requestHeaders,
5799
+ route.contractDetails.auth
5800
+ )
5801
+ );
5802
+ }
5803
+ inputSchemas.forEach((inputSchema, index) => {
5804
+ mcpServer.addTool({
5805
+ name: route.contractDetails.name + (Object.keys(route.contractDetails.versions ?? {}).length > 1 ? ` [v${Object.keys(route.contractDetails.versions ?? {})[index]}]` : ""),
5806
+ description: route.contractDetails.summary,
5807
+ parameters: inputSchema,
5808
+ execute: async (args) => {
5809
+ const { contentType, body, params, query, headers } = args;
5810
+ let url = `${protocol}://${host}:${port}${fullPath}${route.path}`;
5811
+ if (params) {
5812
+ for (const key in params) {
5813
+ url = url.replace(
5814
+ `:${key}`,
5815
+ encodeURIComponent(params[key])
5816
+ );
5476
5817
  }
5477
- let bodySchema;
5478
- let responsesSchemas;
5479
- if (route.contractDetails.versions) {
5480
- const version2 = Object.values(route.contractDetails.versions)[index];
5481
- responsesSchemas = version2.responses;
5482
- if (version2.body && schemaValidator.parse(inputSchema, args).ok) {
5483
- bodySchema = version2.body;
5484
- }
5485
- } else {
5486
- bodySchema = route.contractDetails.body;
5487
- responsesSchemas = route.contractDetails.responses;
5818
+ }
5819
+ let bodySchema;
5820
+ let responsesSchemas;
5821
+ if (route.contractDetails.versions) {
5822
+ const version2 = Object.values(route.contractDetails.versions)[index];
5823
+ responsesSchemas = version2.responses;
5824
+ if (version2.body && schemaValidator.parse(inputSchema, args).ok) {
5825
+ bodySchema = version2.body;
5488
5826
  }
5489
- const discriminatedBody = bodySchema ? discriminateBody(schemaValidator, bodySchema) : void 0;
5490
- let parsedBody;
5491
- if (discriminatedBody) {
5492
- switch (discriminatedBody.parserType) {
5493
- case "json": {
5494
- parsedBody = body === void 0 ? void 0 : JSON.stringify(body);
5495
- break;
5496
- }
5497
- case "text": {
5498
- parsedBody = body;
5499
- break;
5500
- }
5501
- case "file": {
5502
- parsedBody = Buffer.from(toPlainString(body));
5503
- break;
5504
- }
5505
- case "multipart": {
5506
- const formData = new FormData();
5507
- if (isRecord3(body)) {
5508
- for (const key in body) {
5509
- if (typeof body[key] === "string") {
5510
- if (schemaValidator.isInstanceOf(
5511
- body[key],
5512
- schemaValidator.file
5513
- )) {
5514
- formData.append(
5515
- key,
5516
- new Blob([new Uint8Array(Buffer.from(body[key]))])
5517
- );
5518
- } else {
5519
- formData.append(key, body[key]);
5520
- }
5827
+ } else {
5828
+ bodySchema = route.contractDetails.body;
5829
+ responsesSchemas = route.contractDetails.responses;
5830
+ }
5831
+ const discriminatedBody = bodySchema ? discriminateBody(schemaValidator, bodySchema) : void 0;
5832
+ let parsedBody;
5833
+ if (discriminatedBody) {
5834
+ switch (discriminatedBody.parserType) {
5835
+ case "json": {
5836
+ parsedBody = body === void 0 ? void 0 : JSON.stringify(body);
5837
+ break;
5838
+ }
5839
+ case "text": {
5840
+ parsedBody = body;
5841
+ break;
5842
+ }
5843
+ case "file": {
5844
+ parsedBody = Buffer.from(toPlainString(body));
5845
+ break;
5846
+ }
5847
+ case "multipart": {
5848
+ const formData = new FormData();
5849
+ if (isRecord3(body)) {
5850
+ for (const key in body) {
5851
+ if (typeof body[key] === "string") {
5852
+ if (schemaValidator.isInstanceOf(
5853
+ body[key],
5854
+ schemaValidator.file
5855
+ )) {
5856
+ formData.append(
5857
+ key,
5858
+ new Blob([new Uint8Array(Buffer.from(body[key]))])
5859
+ );
5521
5860
  } else {
5522
- throw new Error("Body is not a valid multipart object");
5861
+ formData.append(key, body[key]);
5523
5862
  }
5863
+ } else {
5864
+ throw new Error("Body is not a valid multipart object");
5524
5865
  }
5525
- } else {
5526
- throw new Error("Body is not a valid multipart object");
5527
5866
  }
5528
- parsedBody = formData;
5529
- break;
5867
+ } else {
5868
+ throw new Error("Body is not a valid multipart object");
5530
5869
  }
5531
- case "urlEncoded": {
5532
- if (isRecord3(body)) {
5533
- parsedBody = new URLSearchParams(
5534
- Object.entries(body).map(([key, value]) => [
5535
- key,
5536
- toPlainString(value)
5537
- ])
5538
- );
5539
- } else {
5540
- throw new Error("Body is not a valid url encoded object");
5541
- }
5542
- break;
5543
- }
5544
- default: {
5545
- isNever3(discriminatedBody.parserType);
5546
- parsedBody = safeStringify3(body);
5547
- break;
5870
+ parsedBody = formData;
5871
+ break;
5872
+ }
5873
+ case "urlEncoded": {
5874
+ if (isRecord3(body)) {
5875
+ parsedBody = new URLSearchParams(
5876
+ Object.entries(body).map(([key, value]) => [
5877
+ key,
5878
+ toPlainString(value)
5879
+ ])
5880
+ );
5881
+ } else {
5882
+ throw new Error("Body is not a valid url encoded object");
5548
5883
  }
5884
+ break;
5885
+ }
5886
+ default: {
5887
+ isNever3(discriminatedBody.parserType);
5888
+ parsedBody = safeStringify3(body);
5889
+ break;
5549
5890
  }
5550
5891
  }
5551
- if (query) {
5552
- const queryString = new URLSearchParams(
5553
- Object.entries(query).map(([key, value]) => [
5554
- key,
5555
- toPlainString(value)
5556
- ])
5557
- ).toString();
5558
- url += queryString ? `?${queryString}` : "";
5559
- }
5560
- const response = await fetch(url, {
5561
- method: route.method.toUpperCase(),
5562
- headers: buildRouteHeaders(
5563
- headers,
5564
- discriminatedBody?.contentType != "multipart/form-data" ? contentType ?? discriminatedBody?.contentType : void 0
5565
- ),
5566
- body: parsedBody
5567
- });
5568
- if (response.status >= 300) {
5569
- throw new Error(
5570
- `Error received while proxying request to ${url}: ${await response.text()}`
5571
- );
5572
- }
5573
- if (!responsesSchemas) {
5574
- throw new Error("No responses schemas found");
5575
- }
5576
- const contractContentType = discriminateResponseBodies(
5577
- schemaValidator,
5578
- responsesSchemas
5579
- )[response.status].contentType;
5580
- switch (contentTypeMap && contentTypeMap[contractContentType] ? contentTypeMap[contractContentType] : contractContentType) {
5581
- case "application/json":
5582
- return {
5583
- content: [
5584
- {
5585
- type: "text",
5586
- text: safeStringify3(await response.json())
5587
- }
5588
- ]
5589
- };
5590
- case "text/plain":
5591
- return {
5592
- content: [
5593
- { type: "text", text: await response.text() }
5594
- ]
5595
- };
5596
- case "application/octet-stream":
5597
- return {
5598
- content: [
5599
- {
5600
- type: "resource",
5601
- resource: {
5602
- uri: response.url,
5603
- blob: Buffer.from(
5604
- await (await response.blob()).arrayBuffer()
5605
- ).toString("base64")
5606
- }
5892
+ }
5893
+ if (query) {
5894
+ const queryString = new URLSearchParams(
5895
+ Object.entries(query).map(([key, value]) => [
5896
+ key,
5897
+ toPlainString(value)
5898
+ ])
5899
+ ).toString();
5900
+ url += queryString ? `?${queryString}` : "";
5901
+ }
5902
+ const response = await fetch(url, {
5903
+ method: route.method.toUpperCase(),
5904
+ headers: buildRouteHeaders(
5905
+ headers,
5906
+ discriminatedBody?.contentType != "multipart/form-data" ? contentType ?? discriminatedBody?.contentType : void 0,
5907
+ route.contractDetails.auth
5908
+ ),
5909
+ body: parsedBody
5910
+ });
5911
+ if (response.status >= 300) {
5912
+ throw new Error(
5913
+ `Error received while proxying request to ${url}: ${await response.text()}`
5914
+ );
5915
+ }
5916
+ if (!responsesSchemas) {
5917
+ throw new Error("No responses schemas found");
5918
+ }
5919
+ const contractContentType = discriminateResponseBodies(
5920
+ schemaValidator,
5921
+ responsesSchemas
5922
+ )[response.status].contentType;
5923
+ switch (contentTypeMap && contentTypeMap[contractContentType] ? contentTypeMap[contractContentType] : contractContentType) {
5924
+ case "application/json":
5925
+ return {
5926
+ content: [
5927
+ {
5928
+ type: "text",
5929
+ text: safeStringify3(await response.json())
5930
+ }
5931
+ ]
5932
+ };
5933
+ case "text/plain":
5934
+ return {
5935
+ content: [
5936
+ { type: "text", text: await response.text() }
5937
+ ]
5938
+ };
5939
+ case "application/octet-stream":
5940
+ return {
5941
+ content: [
5942
+ {
5943
+ type: "resource",
5944
+ resource: {
5945
+ uri: response.url,
5946
+ blob: Buffer.from(
5947
+ await (await response.blob()).arrayBuffer()
5948
+ ).toString("base64")
5607
5949
  }
5608
- ]
5609
- };
5610
- case "text/event-stream":
5611
- return {
5612
- content: [
5613
- { type: "text", text: await response.text() }
5614
- ]
5615
- };
5616
- default:
5617
- return {
5618
- content: [
5619
- { type: "text", text: await response.text() }
5620
- ]
5621
- };
5622
- }
5950
+ }
5951
+ ]
5952
+ };
5953
+ case "text/event-stream":
5954
+ return {
5955
+ content: [
5956
+ { type: "text", text: await response.text() }
5957
+ ]
5958
+ };
5959
+ default:
5960
+ return {
5961
+ content: [
5962
+ { type: "text", text: await response.text() }
5963
+ ]
5964
+ };
5623
5965
  }
5624
- });
5966
+ }
5625
5967
  });
5626
5968
  });
5627
5969
  });
5628
5970
  return mcpServer;
5629
5971
  }
5972
+ function collectMcpRoutes(application, appOptions) {
5973
+ const routes = [];
5974
+ const basePath = application.basePath === "/" ? "" : application.basePath;
5975
+ [
5976
+ { fullPath: basePath, router: application },
5977
+ ...unpackRouters(application.routers, [basePath])
5978
+ ].forEach(({ fullPath, router }) => {
5979
+ router.routes.forEach((route) => {
5980
+ if (!(route.contractDetails.options?.mcp ?? router.routerOptions?.mcp ?? appOptions !== false)) {
5981
+ return;
5982
+ }
5983
+ const globalAuth = router.routerOptions?.auth;
5984
+ routes.push({
5985
+ fullPath,
5986
+ route,
5987
+ routeAuth: routeRequiresAuth(route.contractDetails) ? {
5988
+ ...globalAuth ? globalAuth : {},
5989
+ ...route.contractDetails.auth
5990
+ } : void 0
5991
+ });
5992
+ });
5993
+ });
5994
+ return routes;
5995
+ }
5996
+ function resolveMcpAuthenticate(routes, authenticate, logger2) {
5997
+ if (authenticate) {
5998
+ return authenticate;
5999
+ }
6000
+ const routeAuths = routes.map(({ routeAuth }) => routeAuth).filter((auth) => auth != null);
6001
+ if (routeAuths.length === 0) {
6002
+ return void 0;
6003
+ }
6004
+ logger2?.info(
6005
+ `MCP: ${routeAuths.length} tool(s) call routes that require a credential, so the MCP endpoint requires one too and verifies it like those routes do. Set mcp.authenticate to replace this check.`
6006
+ );
6007
+ return createRouteMcpAuthenticate(routeAuths);
6008
+ }
5630
6009
 
5631
6010
  // src/http/middleware/response/parse.middleware.ts
5632
6011
  import {
@@ -6547,6 +6926,7 @@ export {
6547
6926
  INSTANCE_GATEWAY_MOUNT,
6548
6927
  InMemoryHmacNonceStore,
6549
6928
  InstanceGatewayRequestError,
6929
+ McpInsufficientScopeError,
6550
6930
  ModelGatewayRequestError,
6551
6931
  OPENAPI_DEFAULT_VERSION,
6552
6932
  OpenTelemetryCollector,
@@ -6570,15 +6950,18 @@ export {
6570
6950
  auditEnabled,
6571
6951
  auditEventType,
6572
6952
  bindRuntimeAuth,
6953
+ canonicalMcpResource,
6573
6954
  createContext,
6574
6955
  createEmailClient,
6575
6956
  createHmacToken,
6576
6957
  createInstanceGatewayTransport,
6577
6958
  createLocalModelGatewayClient,
6578
6959
  createMcpHttpHandler,
6960
+ createMcpOAuthAuthenticate,
6579
6961
  createModelGatewayClient,
6580
6962
  createPaymentsClient,
6581
6963
  createPreviewModelGatewayClient,
6964
+ createRouteMcpAuthenticate,
6582
6965
  createSmsClient,
6583
6966
  createStripeClient,
6584
6967
  createVoiceClient,
@@ -6624,6 +7007,8 @@ export {
6624
7007
  jwtAlgorithmsForSharedSecret,
6625
7008
  jwtClaimChecks,
6626
7009
  logger,
7010
+ mcpBearerChallenge,
7011
+ mcpProtectedResourceMetadata,
6627
7012
  meta,
6628
7013
  metricsDefinitions,
6629
7014
  middleware,
@@ -6637,6 +7022,7 @@ export {
6637
7022
  resetProcessHandlersForTesting,
6638
7023
  resolveHmacMaxSkewMs,
6639
7024
  resolveHmacNonceStore,
7025
+ resolveMcpOAuth,
6640
7026
  signPlatformEvent,
6641
7027
  smsSegments,
6642
7028
  stripeGatewayFetch,