@forklaunch/core 4.2.0 → 4.4.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.
Files changed (40) hide show
  1. package/bin/gateway-mock/routes/payments.mjs +5 -2
  2. package/lib/http/index.d.ts +2 -0
  3. package/lib/http/index.d.ts.map +1 -1
  4. package/lib/http/index.js +609 -219
  5. package/lib/http/index.js.map +1 -1
  6. package/lib/http/index.mjs +606 -220
  7. package/lib/http/index.mjs.map +1 -1
  8. package/lib/http/mcpGenerator/mcpAuth.d.ts +52 -0
  9. package/lib/http/mcpGenerator/mcpAuth.d.ts.map +1 -0
  10. package/lib/http/mcpGenerator/mcpGenerator.d.ts +2 -1
  11. package/lib/http/mcpGenerator/mcpGenerator.d.ts.map +1 -1
  12. package/lib/http/mcpGenerator/mcpHttpHandler.d.ts +14 -1
  13. package/lib/http/mcpGenerator/mcpHttpHandler.d.ts.map +1 -1
  14. package/lib/http/mcpGenerator/mcpOAuth.d.ts +110 -0
  15. package/lib/http/mcpGenerator/mcpOAuth.d.ts.map +1 -0
  16. package/lib/http/paymentsClient.d.ts +6 -0
  17. package/lib/http/paymentsClient.d.ts.map +1 -1
  18. package/lib/http/types/expressLikeOptions.d.ts +8 -0
  19. package/lib/http/types/expressLikeOptions.d.ts.map +1 -1
  20. package/lib/http/voiceClient.d.ts +14 -4
  21. package/lib/http/voiceClient.d.ts.map +1 -1
  22. package/lib/persistence/complianceTypes.d.ts +27 -1
  23. package/lib/persistence/complianceTypes.d.ts.map +1 -1
  24. package/lib/persistence/defineComplianceEntity.d.ts +1 -1
  25. package/lib/persistence/defineComplianceEntity.d.ts.map +1 -1
  26. package/lib/persistence/index.d.ts +2 -1
  27. package/lib/persistence/index.d.ts.map +1 -1
  28. package/lib/persistence/index.js +62 -2
  29. package/lib/persistence/index.js.map +1 -1
  30. package/lib/persistence/index.mjs +59 -2
  31. package/lib/persistence/index.mjs.map +1 -1
  32. package/lib/persistence/migrationLock.d.ts +61 -0
  33. package/lib/persistence/migrationLock.d.ts.map +1 -0
  34. package/lib/services/index.js +8 -2
  35. package/lib/services/index.js.map +1 -1
  36. package/lib/services/index.mjs +8 -2
  37. package/lib/services/index.mjs.map +1 -1
  38. package/lib/services/retentionService.d.ts +2 -2
  39. package/lib/services/retentionService.d.ts.map +1 -1
  40. package/package.json +7 -5
package/lib/http/index.js CHANGED
@@ -50,6 +50,7 @@ __export(http_exports, {
50
50
  INSTANCE_GATEWAY_MOUNT: () => INSTANCE_GATEWAY_MOUNT,
51
51
  InMemoryHmacNonceStore: () => InMemoryHmacNonceStore,
52
52
  InstanceGatewayRequestError: () => InstanceGatewayRequestError,
53
+ McpInsufficientScopeError: () => McpInsufficientScopeError,
53
54
  ModelGatewayRequestError: () => ModelGatewayRequestError,
54
55
  OPENAPI_DEFAULT_VERSION: () => OPENAPI_DEFAULT_VERSION,
55
56
  OpenTelemetryCollector: () => OpenTelemetryCollector,
@@ -73,15 +74,18 @@ __export(http_exports, {
73
74
  auditEnabled: () => auditEnabled,
74
75
  auditEventType: () => auditEventType,
75
76
  bindRuntimeAuth: () => bindRuntimeAuth,
77
+ canonicalMcpResource: () => canonicalMcpResource,
76
78
  createContext: () => createContext,
77
79
  createEmailClient: () => createEmailClient,
78
80
  createHmacToken: () => createHmacToken,
79
81
  createInstanceGatewayTransport: () => createInstanceGatewayTransport,
80
82
  createLocalModelGatewayClient: () => createLocalModelGatewayClient,
81
83
  createMcpHttpHandler: () => createMcpHttpHandler,
84
+ createMcpOAuthAuthenticate: () => createMcpOAuthAuthenticate,
82
85
  createModelGatewayClient: () => createModelGatewayClient,
83
86
  createPaymentsClient: () => createPaymentsClient,
84
87
  createPreviewModelGatewayClient: () => createPreviewModelGatewayClient,
88
+ createRouteMcpAuthenticate: () => createRouteMcpAuthenticate,
85
89
  createSmsClient: () => createSmsClient,
86
90
  createStripeClient: () => createStripeClient,
87
91
  createVoiceClient: () => createVoiceClient,
@@ -127,6 +131,8 @@ __export(http_exports, {
127
131
  jwtAlgorithmsForSharedSecret: () => jwtAlgorithmsForSharedSecret,
128
132
  jwtClaimChecks: () => jwtClaimChecks,
129
133
  logger: () => logger,
134
+ mcpBearerChallenge: () => mcpBearerChallenge,
135
+ mcpProtectedResourceMetadata: () => mcpProtectedResourceMetadata,
130
136
  meta: () => meta,
131
137
  metricsDefinitions: () => metricsDefinitions,
132
138
  middleware: () => middleware,
@@ -140,6 +146,7 @@ __export(http_exports, {
140
146
  resetProcessHandlersForTesting: () => resetProcessHandlersForTesting,
141
147
  resolveHmacMaxSkewMs: () => resolveHmacMaxSkewMs,
142
148
  resolveHmacNonceStore: () => resolveHmacNonceStore,
149
+ resolveMcpOAuth: () => resolveMcpOAuth,
143
150
  signPlatformEvent: () => signPlatformEvent,
144
151
  smsSegments: () => smsSegments,
145
152
  stripeGatewayFetch: () => stripeGatewayFetch,
@@ -1392,15 +1399,15 @@ var MAX_CLAIM_LENGTH = 128;
1392
1399
  function bounded(value) {
1393
1400
  return typeof value === "string" && value.length > 0 ? value.slice(0, MAX_CLAIM_LENGTH) : void 0;
1394
1401
  }
1395
- function authLogContext(headerValue) {
1396
- if (typeof headerValue !== "string" || headerValue.length === 0) {
1402
+ function authLogContext(headerValue2) {
1403
+ if (typeof headerValue2 !== "string" || headerValue2.length === 0) {
1397
1404
  return { hasToken: false };
1398
1405
  }
1399
1406
  const context2 = {
1400
1407
  hasToken: true,
1401
- tokenFingerprint: (0, import_crypto3.createHash)("sha256").update(headerValue).digest("hex").slice(0, FINGERPRINT_LENGTH)
1408
+ tokenFingerprint: (0, import_crypto3.createHash)("sha256").update(headerValue2).digest("hex").slice(0, FINGERPRINT_LENGTH)
1402
1409
  };
1403
- const parts = headerValue.trim().split(/\s+/);
1410
+ const parts = headerValue2.trim().split(/\s+/);
1404
1411
  const candidate = parts[parts.length - 1];
1405
1412
  if (candidate.split(".").length !== 3) {
1406
1413
  return context2;
@@ -3599,21 +3606,21 @@ function refuse(message) {
3599
3606
  }
3600
3607
  function addresses(value, field) {
3601
3608
  if (value === void 0) return void 0;
3602
- const list = Array.isArray(value) ? value : [value];
3603
- if (list.length === 0) refuse(`${field} must name at least one address`);
3604
- if (list.length > EMAIL_LIMITS.maxRecipients) {
3609
+ const list2 = Array.isArray(value) ? value : [value];
3610
+ if (list2.length === 0) refuse(`${field} must name at least one address`);
3611
+ if (list2.length > EMAIL_LIMITS.maxRecipients) {
3605
3612
  refuse(
3606
- `${field} has ${list.length} addresses; the limit is ${EMAIL_LIMITS.maxRecipients}`
3613
+ `${field} has ${list2.length} addresses; the limit is ${EMAIL_LIMITS.maxRecipients}`
3607
3614
  );
3608
3615
  }
3609
- for (const address of list) {
3616
+ for (const address of list2) {
3610
3617
  if (!isEmailAddress(address)) {
3611
3618
  refuse(
3612
3619
  `${field}: '${String(address).slice(0, 80)}' is not an email address`
3613
3620
  );
3614
3621
  }
3615
3622
  }
3616
- return list;
3623
+ return list2;
3617
3624
  }
3618
3625
  function fail(problem) {
3619
3626
  refuse(`listUnsubscribe: ${problem}`);
@@ -5305,16 +5312,314 @@ function unpackRouters(routers, recursiveBasePath = []) {
5305
5312
  }, []);
5306
5313
  }
5307
5314
 
5315
+ // src/http/mcpGenerator/mcpAuth.ts
5316
+ function mcpAuthHeaderNames(auth) {
5317
+ const names = /* @__PURE__ */ new Set(["authorization"]);
5318
+ if (auth?.headerName) {
5319
+ names.add(auth.headerName.toLowerCase());
5320
+ }
5321
+ return names;
5322
+ }
5323
+ function routeRequiresAuth(contractDetails) {
5324
+ return contractDetails.auth != null && contractDetails.access !== "public";
5325
+ }
5326
+ function headerValue(headers, name) {
5327
+ if (!headers) {
5328
+ return void 0;
5329
+ }
5330
+ if (typeof headers.get === "function") {
5331
+ return headers.get(name) ?? void 0;
5332
+ }
5333
+ const value = headers[name];
5334
+ return Array.isArray(value) ? value[0] : value;
5335
+ }
5336
+ function sameCredentialSource(a, b) {
5337
+ const fields = ["headerName", "tokenPrefix", "decodeResource"];
5338
+ if (fields.some((field) => a[field] !== b[field])) {
5339
+ return false;
5340
+ }
5341
+ if (isJwtAuthMethod(a) && isJwtAuthMethod(b)) {
5342
+ const ja = a.jwt;
5343
+ const jb = b.jwt;
5344
+ const keys = /* @__PURE__ */ new Set([...Object.keys(ja), ...Object.keys(jb)]);
5345
+ return [...keys].every(
5346
+ (key) => JSON.stringify(ja[key]) === JSON.stringify(jb[key])
5347
+ );
5348
+ }
5349
+ if (isBasicAuthMethod(a) && isBasicAuthMethod(b)) {
5350
+ return a.basic.login === b.basic.login;
5351
+ }
5352
+ return false;
5353
+ }
5354
+ function createRouteMcpAuthenticate(routeAuths) {
5355
+ const sources = [];
5356
+ for (const auth of routeAuths) {
5357
+ if (isHmacMethod(auth)) {
5358
+ continue;
5359
+ }
5360
+ if (!sources.some((source) => sameCredentialSource(source, auth))) {
5361
+ sources.push(auth);
5362
+ }
5363
+ }
5364
+ return async (request) => {
5365
+ for (const auth of sources) {
5366
+ const credential = headerValue(
5367
+ request.headers,
5368
+ (auth.headerName ?? "authorization").toLowerCase()
5369
+ );
5370
+ if (!credential) {
5371
+ continue;
5372
+ }
5373
+ const [prefix, ...parts] = credential.split(" ");
5374
+ const [token] = parts;
5375
+ if (!prefix || !token) {
5376
+ continue;
5377
+ }
5378
+ try {
5379
+ const method = await discriminateAuthMethod(
5380
+ auth
5381
+ );
5382
+ switch (method.type) {
5383
+ case "jwt": {
5384
+ if (prefix !== (auth.tokenPrefix ?? "Bearer")) {
5385
+ continue;
5386
+ }
5387
+ 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;
5388
+ if (payload) {
5389
+ return { ...payload };
5390
+ }
5391
+ break;
5392
+ }
5393
+ case "basic": {
5394
+ if (prefix !== (auth.tokenPrefix ?? "Basic")) {
5395
+ continue;
5396
+ }
5397
+ if (method.auth.decodeResource) {
5398
+ const payload = await method.auth.decodeResource(token);
5399
+ if (payload) {
5400
+ return { ...payload };
5401
+ }
5402
+ break;
5403
+ }
5404
+ const [username, password] = Buffer.from(token, "base64").toString("utf-8").split(":");
5405
+ if (username && password && method.auth.login(username, password)) {
5406
+ return { sub: username };
5407
+ }
5408
+ break;
5409
+ }
5410
+ case "hmac":
5411
+ break;
5412
+ }
5413
+ } catch {
5414
+ }
5415
+ }
5416
+ return void 0;
5417
+ };
5418
+ }
5419
+ var generatedAuthenticate = /* @__PURE__ */ new WeakMap();
5420
+ function setGeneratedMcpAuthenticate(mcpServer, authenticate) {
5421
+ if (authenticate) {
5422
+ generatedAuthenticate.set(mcpServer, authenticate);
5423
+ }
5424
+ }
5425
+ function getGeneratedMcpAuthenticate(mcpServer) {
5426
+ return generatedAuthenticate.get(mcpServer);
5427
+ }
5428
+
5308
5429
  // src/http/mcpGenerator/mcpHttpHandler.ts
5309
5430
  var import_webStandardStreamableHttp = require("@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js");
5310
5431
  var import_async_hooks = require("async_hooks");
5311
5432
  var import_crypto6 = require("crypto");
5433
+
5434
+ // src/http/mcpGenerator/mcpOAuth.ts
5435
+ var import_jose3 = require("jose");
5436
+ var WELL_KNOWN = "/.well-known/oauth-protected-resource";
5437
+ function trimTrailingSlashes2(path) {
5438
+ let end = path.length;
5439
+ while (end > 0 && path.charCodeAt(end - 1) === 47) {
5440
+ end--;
5441
+ }
5442
+ return path.slice(0, end);
5443
+ }
5444
+ var list = (value) => value?.split(/[\s,]+/).map((item) => item.trim()).filter(Boolean);
5445
+ function canonicalMcpResource(resource) {
5446
+ const url = new URL(resource);
5447
+ if (url.protocol !== "https:" && url.protocol !== "http:") {
5448
+ throw new Error(`MCP resource must be an http(s) URL: ${resource}`);
5449
+ }
5450
+ return `${url.origin}${trimTrailingSlashes2(url.pathname)}`;
5451
+ }
5452
+ function resolveMcpOAuth(options2, server) {
5453
+ const authorizationServers = options2?.authorizationServers ?? list(process.env.MCP_AUTHORIZATION_SERVERS);
5454
+ if (!authorizationServers || authorizationServers.length === 0) {
5455
+ if (options2) {
5456
+ throw new Error(
5457
+ "mcp.oauth needs at least one authorization server (mcp.oauth.authorizationServers or MCP_AUTHORIZATION_SERVERS)."
5458
+ );
5459
+ }
5460
+ return void 0;
5461
+ }
5462
+ const resource = canonicalMcpResource(
5463
+ options2?.resource ?? process.env.MCP_RESOURCE_URL ?? `${server.protocol}://${server.host}:${server.port}${server.path}`
5464
+ );
5465
+ const resourcePath = trimTrailingSlashes2(new URL(resource).pathname);
5466
+ const metadataUrl = `${new URL(resource).origin}${WELL_KNOWN}${resourcePath}`;
5467
+ const issuer = options2?.issuer ?? authorizationServers;
5468
+ return {
5469
+ resource,
5470
+ authorizationServers,
5471
+ jwksUrl: options2?.jwksUrl ?? process.env.MCP_JWKS_URL,
5472
+ issuer: Array.isArray(issuer) ? [...issuer] : [issuer],
5473
+ algorithms: options2?.algorithms,
5474
+ scopesSupported: options2?.scopesSupported ?? list(process.env.MCP_SCOPES_SUPPORTED),
5475
+ requiredScopes: options2?.requiredScopes ?? list(process.env.MCP_REQUIRED_SCOPES),
5476
+ resourceName: options2?.resourceName,
5477
+ metadataUrl,
5478
+ metadataPaths: [
5479
+ .../* @__PURE__ */ new Set([
5480
+ WELL_KNOWN,
5481
+ `${WELL_KNOWN}${resourcePath}`,
5482
+ `${WELL_KNOWN}${trimTrailingSlashes2(server.path)}`
5483
+ ])
5484
+ ]
5485
+ };
5486
+ }
5487
+ function mcpProtectedResourceMetadata(oauth) {
5488
+ return {
5489
+ resource: oauth.resource,
5490
+ authorization_servers: oauth.authorizationServers,
5491
+ bearer_methods_supported: ["header"],
5492
+ ...oauth.scopesSupported?.length ? { scopes_supported: oauth.scopesSupported } : {},
5493
+ ...oauth.resourceName ? { resource_name: oauth.resourceName } : {}
5494
+ };
5495
+ }
5496
+ function mcpProtectedResourceMetadataResponse(oauth) {
5497
+ return new Response(JSON.stringify(mcpProtectedResourceMetadata(oauth)), {
5498
+ status: 200,
5499
+ headers: {
5500
+ "Content-Type": "application/json",
5501
+ "Cache-Control": "public, max-age=3600"
5502
+ }
5503
+ });
5504
+ }
5505
+ var quoted = (value) => `"${value.replace(/["\\]/g, "\\$&")}"`;
5506
+ function mcpBearerChallenge(oauth, error) {
5507
+ const parts = [];
5508
+ if (error) {
5509
+ parts.push(`error=${quoted(error.code)}`);
5510
+ }
5511
+ if (oauth) {
5512
+ const scope = oauth.requiredScopes?.length ? oauth.requiredScopes : oauth.scopesSupported;
5513
+ if (scope?.length) {
5514
+ parts.push(`scope=${quoted(scope.join(" "))}`);
5515
+ }
5516
+ parts.push(`resource_metadata=${quoted(oauth.metadataUrl)}`);
5517
+ }
5518
+ if (error?.description) {
5519
+ parts.push(`error_description=${quoted(error.description)}`);
5520
+ }
5521
+ return parts.length ? `Bearer ${parts.join(", ")}` : "Bearer";
5522
+ }
5523
+ var McpInsufficientScopeError = class extends Error {
5524
+ constructor(missing) {
5525
+ super(`Missing scope: ${missing.join(" ")}`);
5526
+ this.missing = missing;
5527
+ this.name = "McpInsufficientScopeError";
5528
+ }
5529
+ missing;
5530
+ };
5531
+ function tokenScopes(payload) {
5532
+ const scopes = /* @__PURE__ */ new Set();
5533
+ if (typeof payload.scope === "string") {
5534
+ payload.scope.split(" ").forEach((scope) => scope && scopes.add(scope));
5535
+ }
5536
+ if (Array.isArray(payload.scp)) {
5537
+ payload.scp.forEach(
5538
+ (scope) => typeof scope === "string" && scopes.add(scope)
5539
+ );
5540
+ }
5541
+ return scopes;
5542
+ }
5543
+ async function discoverJwksUri(issuer) {
5544
+ const url = new URL(issuer);
5545
+ const path = trimTrailingSlashes2(url.pathname);
5546
+ const candidates = [
5547
+ `${url.origin}/.well-known/oauth-authorization-server${path}`,
5548
+ `${url.origin}/.well-known/openid-configuration${path}`,
5549
+ `${url.origin}${path}/.well-known/openid-configuration`
5550
+ ];
5551
+ for (const candidate of candidates) {
5552
+ try {
5553
+ const response = await fetch(candidate, {
5554
+ headers: { accept: "application/json" },
5555
+ signal: AbortSignal.timeout(5e3)
5556
+ });
5557
+ if (!response.ok) continue;
5558
+ const metadata = await response.json();
5559
+ if (metadata.issuer === issuer && metadata.jwks_uri) {
5560
+ return metadata.jwks_uri;
5561
+ }
5562
+ } catch {
5563
+ }
5564
+ }
5565
+ throw new Error(`No jwks_uri found in the metadata of ${issuer}`);
5566
+ }
5567
+ function createMcpOAuthAuthenticate(oauth, getKey) {
5568
+ let keys = getKey ? Promise.resolve(getKey) : void 0;
5569
+ const resolveKeys = () => {
5570
+ keys ??= (async () => (0, import_jose3.createRemoteJWKSet)(
5571
+ new URL(
5572
+ oauth.jwksUrl ?? await discoverJwksUri(oauth.authorizationServers[0])
5573
+ )
5574
+ ))().catch((error) => {
5575
+ keys = void 0;
5576
+ throw error;
5577
+ });
5578
+ return keys;
5579
+ };
5580
+ return async (request) => {
5581
+ const header = request.headers?.authorization;
5582
+ const value = Array.isArray(header) ? header[0] : header;
5583
+ const match = value?.match(/^Bearer +([^\s]+) *$/i);
5584
+ if (!match) {
5585
+ return void 0;
5586
+ }
5587
+ const { payload } = await (0, import_jose3.jwtVerify)(match[1], await resolveKeys(), {
5588
+ issuer: oauth.issuer,
5589
+ audience: oauth.resource,
5590
+ ...oauth.algorithms ? { algorithms: oauth.algorithms } : {}
5591
+ });
5592
+ if (oauth.requiredScopes?.length) {
5593
+ const granted = tokenScopes(payload);
5594
+ const missing = oauth.requiredScopes.filter(
5595
+ (scope) => !granted.has(scope)
5596
+ );
5597
+ if (missing.length) {
5598
+ throw new McpInsufficientScopeError(missing);
5599
+ }
5600
+ }
5601
+ return { ...payload };
5602
+ };
5603
+ }
5604
+ var generatedOAuth = /* @__PURE__ */ new WeakMap();
5605
+ function setGeneratedMcpOAuth(mcpServer, oauth) {
5606
+ if (oauth) {
5607
+ generatedOAuth.set(mcpServer, oauth);
5608
+ }
5609
+ }
5610
+ function getGeneratedMcpOAuth(mcpServer) {
5611
+ return generatedOAuth.get(mcpServer);
5612
+ }
5613
+
5614
+ // src/http/mcpGenerator/mcpHttpHandler.ts
5312
5615
  var DEFAULT_MCP_SESSION_IDLE_TIMEOUT_MS = 15 * 60 * 1e3;
5313
5616
  var mcpTransportHeaders = new import_async_hooks.AsyncLocalStorage();
5314
5617
  function getMcpTransportHeaders() {
5315
5618
  return mcpTransportHeaders.getStore();
5316
5619
  }
5317
5620
  function createMcpHttpHandler(mcpServer, options2) {
5621
+ const authenticate = options2?.authenticate ?? getGeneratedMcpAuthenticate(mcpServer);
5622
+ const oauth = options2?.oauth ?? getGeneratedMcpOAuth(mcpServer);
5318
5623
  const mode = options2?.sessions ?? "stateless";
5319
5624
  if (mode === "stateful" && (options2?.workerCount ?? 1) > 1) {
5320
5625
  throw new Error(
@@ -5347,16 +5652,32 @@ function createMcpHttpHandler(mcpServer, options2) {
5347
5652
  sweepTimer.unref();
5348
5653
  }
5349
5654
  async function authenticateRequest(authRequest) {
5350
- if (!options2?.authenticate) {
5655
+ if (!authenticate) {
5351
5656
  return { ok: true, auth: void 0 };
5352
5657
  }
5353
5658
  try {
5354
- const auth = await options2.authenticate(authRequest);
5659
+ const auth = await authenticate(authRequest);
5355
5660
  return auth ? { ok: true, auth } : { ok: false };
5356
- } catch {
5357
- return { ok: false };
5661
+ } catch (error) {
5662
+ return error instanceof McpInsufficientScopeError ? { ok: false, insufficientScope: error.missing } : { ok: false };
5358
5663
  }
5359
5664
  }
5665
+ function refuse2(authRequest, insufficientScope) {
5666
+ if (insufficientScope) {
5667
+ return jsonRpcError(403, -32001, "Forbidden", {
5668
+ "WWW-Authenticate": mcpBearerChallenge(oauth, {
5669
+ code: "insufficient_scope"
5670
+ })
5671
+ });
5672
+ }
5673
+ const presented = Boolean(authRequest.headers?.authorization);
5674
+ return jsonRpcError(401, -32001, "Unauthorized", {
5675
+ "WWW-Authenticate": mcpBearerChallenge(
5676
+ oauth,
5677
+ oauth && presented ? { code: "invalid_token" } : void 0
5678
+ )
5679
+ });
5680
+ }
5360
5681
  async function handleStateless(request, auth) {
5361
5682
  if (request.method !== "POST") {
5362
5683
  return jsonRpcError(405, -32e3, "Method not allowed", {
@@ -5429,9 +5750,7 @@ function createMcpHttpHandler(mcpServer, options2) {
5429
5750
  async function handle(request, authRequest) {
5430
5751
  const authResult = await authenticateRequest(authRequest);
5431
5752
  if (!authResult.ok) {
5432
- return jsonRpcError(401, -32001, "Unauthorized", {
5433
- "WWW-Authenticate": "Bearer"
5434
- });
5753
+ return refuse2(authRequest, authResult.insufficientScope);
5435
5754
  }
5436
5755
  return mode === "stateless" ? handleStateless(request, authResult.auth) : handleStateful(request, authResult.auth);
5437
5756
  }
@@ -5443,7 +5762,9 @@ function createMcpHttpHandler(mcpServer, options2) {
5443
5762
  sessions.clear();
5444
5763
  await Promise.all(entries.map(({ session }) => session.close()));
5445
5764
  }
5446
- return { handle, close, sessions };
5765
+ const metadataPaths = oauth?.metadataPaths ?? [];
5766
+ const protectedResourceMetadata = () => oauth ? mcpProtectedResourceMetadataResponse(oauth) : jsonRpcError(404, -32601, "Not found");
5767
+ return { handle, close, sessions, metadataPaths, protectedResourceMetadata };
5447
5768
  }
5448
5769
  function closeWhenBodyEnds(response, done) {
5449
5770
  if (!response.body) {
@@ -5483,6 +5804,7 @@ function isSeparateMcpListener(configuredPort) {
5483
5804
 
5484
5805
  // src/http/mcpGenerator/mcpGenerator.ts
5485
5806
  function generateInputSchema(schemaValidator, body, params, query, requestHeaders, auth) {
5807
+ const toolHeaders = toolInputHeaders(requestHeaders, auth);
5486
5808
  let discriminatedBody;
5487
5809
  if (body) {
5488
5810
  discriminatedBody = discriminateBody(schemaValidator, body);
@@ -5498,30 +5820,38 @@ function generateInputSchema(schemaValidator, body, params, query, requestHeader
5498
5820
  ...query ? {
5499
5821
  query: schemaValidator.schemify(query)
5500
5822
  } : {},
5501
- ...requestHeaders ? {
5502
- headers: schemaValidator.schemify({
5503
- ...requestHeaders,
5504
- ...auth ? {
5505
- [auth.headerName ?? "authorization"]: import_zod.string.startsWith(
5506
- auth.tokenPrefix ?? ("basic" in auth ? "Basic " : "Bearer ")
5507
- )
5508
- } : {}
5509
- })
5823
+ ...toolHeaders ? {
5824
+ headers: schemaValidator.schemify(toolHeaders)
5510
5825
  } : {}
5511
5826
  });
5512
5827
  }
5513
- function buildRouteHeaders(toolHeaders, contentType) {
5828
+ function toolInputHeaders(requestHeaders, auth) {
5829
+ if (!requestHeaders) {
5830
+ return void 0;
5831
+ }
5832
+ const credentialHeaders = mcpAuthHeaderNames(auth);
5833
+ const headers = Object.fromEntries(
5834
+ Object.entries(requestHeaders).filter(
5835
+ ([name]) => !credentialHeaders.has(name.toLowerCase())
5836
+ )
5837
+ );
5838
+ return Object.keys(headers).length > 0 ? headers : void 0;
5839
+ }
5840
+ function buildRouteHeaders(toolHeaders, contentType, auth) {
5514
5841
  const transportHeaders = getMcpTransportHeaders();
5515
5842
  const routeHeaders = new Headers();
5516
- const authorization = transportHeaders?.get("authorization");
5517
- if (authorization) {
5518
- routeHeaders.set("authorization", authorization);
5519
- }
5843
+ const credentialHeaders = mcpAuthHeaderNames(auth);
5520
5844
  for (const [name, value] of Object.entries(toolHeaders ?? {})) {
5521
- if (value != null) {
5845
+ if (value != null && !credentialHeaders.has(name.toLowerCase())) {
5522
5846
  routeHeaders.set(name, String(value));
5523
5847
  }
5524
5848
  }
5849
+ for (const name of credentialHeaders) {
5850
+ const credential = transportHeaders?.get(name);
5851
+ if (credential) {
5852
+ routeHeaders.set(name, credential);
5853
+ }
5854
+ }
5525
5855
  const correlationId = transportHeaders?.get("x-correlation-id");
5526
5856
  if (correlationId) {
5527
5857
  routeHeaders.set("x-correlation-id", correlationId);
@@ -5540,226 +5870,279 @@ function buildRouteHeaders(toolHeaders, contentType) {
5540
5870
  }
5541
5871
  return routeHeaders;
5542
5872
  }
5543
- function generateMcpServer(schemaValidator, protocol, host, port, version, application, appOptions, options2, contentTypeMap, authenticate) {
5873
+ function generateMcpServer(schemaValidator, protocol, host, port, version, application, appOptions, options2, contentTypeMap, authenticate, logger2) {
5544
5874
  if (!(schemaValidator instanceof import_zod.ZodSchemaValidator)) {
5545
5875
  throw new Error(
5546
5876
  "Schema validator must be an instance of ZodSchemaValidator"
5547
5877
  );
5548
5878
  }
5879
+ const exposedRoutes = collectMcpRoutes(application, appOptions);
5880
+ const oauth = resolveMcpOAuth(appOptions ? appOptions.oauth : void 0, {
5881
+ protocol,
5882
+ host,
5883
+ port,
5884
+ path: appOptions && appOptions.path || "/mcp"
5885
+ });
5886
+ const resolvedAuthenticate = oauth ? authenticate ?? createMcpOAuthAuthenticate(oauth) : resolveMcpAuthenticate(exposedRoutes, authenticate, logger2);
5887
+ if (oauth) {
5888
+ logger2?.info(
5889
+ "MCP: OAuth on; the endpoint accepts only access tokens issued for it and publishes its Protected Resource Metadata at /.well-known/oauth-protected-resource."
5890
+ );
5891
+ }
5549
5892
  const mcpServer = new import_fastmcp.FastMCP({
5550
5893
  ...options2,
5551
5894
  name: options2?.name ?? "mcp-server",
5552
5895
  version,
5553
- authenticate
5554
- });
5555
- [
5556
- {
5557
- fullPath: application.basePath === "/" ? "" : application.basePath,
5558
- router: application
5559
- },
5560
- ...unpackRouters(application.routers, [
5561
- application.basePath === "/" ? "" : application.basePath
5562
- ])
5563
- ].forEach(({ fullPath, router }) => {
5564
- router.routes.forEach((route) => {
5565
- if (!(route.contractDetails.options?.mcp ?? router.routerOptions?.mcp ?? appOptions !== false)) {
5566
- return;
5896
+ authenticate: resolvedAuthenticate,
5897
+ ...oauth ? {
5898
+ oauth: {
5899
+ ...options2?.oauth,
5900
+ enabled: true,
5901
+ protectedResource: {
5902
+ resource: oauth.resource,
5903
+ authorizationServers: oauth.authorizationServers,
5904
+ bearerMethodsSupported: ["header"],
5905
+ ...oauth.scopesSupported?.length ? { scopesSupported: oauth.scopesSupported } : {},
5906
+ ...oauth.resourceName ? { resourceName: oauth.resourceName } : {}
5907
+ }
5567
5908
  }
5568
- const inputSchemas = [];
5569
- if (route.contractDetails.versions) {
5570
- Object.values(route.contractDetails.versions).forEach((version2) => {
5571
- inputSchemas.push(
5572
- generateInputSchema(
5573
- schemaValidator,
5574
- version2.body,
5575
- route.contractDetails.params,
5576
- version2.query,
5577
- version2.requestHeaders,
5578
- route.contractDetails.auth
5579
- )
5580
- );
5581
- });
5582
- } else {
5909
+ } : {}
5910
+ });
5911
+ setGeneratedMcpAuthenticate(mcpServer, resolvedAuthenticate);
5912
+ setGeneratedMcpOAuth(mcpServer, oauth);
5913
+ exposedRoutes.forEach(({ fullPath, route }) => {
5914
+ const inputSchemas = [];
5915
+ if (route.contractDetails.versions) {
5916
+ Object.values(route.contractDetails.versions).forEach((version2) => {
5583
5917
  inputSchemas.push(
5584
5918
  generateInputSchema(
5585
5919
  schemaValidator,
5586
- route.contractDetails.body,
5920
+ version2.body,
5587
5921
  route.contractDetails.params,
5588
- route.contractDetails.query,
5589
- route.contractDetails.requestHeaders,
5922
+ version2.query,
5923
+ version2.requestHeaders,
5590
5924
  route.contractDetails.auth
5591
5925
  )
5592
5926
  );
5593
- }
5594
- inputSchemas.forEach((inputSchema, index) => {
5595
- mcpServer.addTool({
5596
- name: route.contractDetails.name + (Object.keys(route.contractDetails.versions ?? {}).length > 1 ? ` [v${Object.keys(route.contractDetails.versions ?? {})[index]}]` : ""),
5597
- description: route.contractDetails.summary,
5598
- parameters: inputSchema,
5599
- execute: async (args) => {
5600
- const { contentType, body, params, query, headers } = args;
5601
- let url = `${protocol}://${host}:${port}${fullPath}${route.path}`;
5602
- if (params) {
5603
- for (const key in params) {
5604
- url = url.replace(
5605
- `:${key}`,
5606
- encodeURIComponent(params[key])
5607
- );
5608
- }
5927
+ });
5928
+ } else {
5929
+ inputSchemas.push(
5930
+ generateInputSchema(
5931
+ schemaValidator,
5932
+ route.contractDetails.body,
5933
+ route.contractDetails.params,
5934
+ route.contractDetails.query,
5935
+ route.contractDetails.requestHeaders,
5936
+ route.contractDetails.auth
5937
+ )
5938
+ );
5939
+ }
5940
+ inputSchemas.forEach((inputSchema, index) => {
5941
+ mcpServer.addTool({
5942
+ name: route.contractDetails.name + (Object.keys(route.contractDetails.versions ?? {}).length > 1 ? ` [v${Object.keys(route.contractDetails.versions ?? {})[index]}]` : ""),
5943
+ description: route.contractDetails.summary,
5944
+ parameters: inputSchema,
5945
+ execute: async (args) => {
5946
+ const { contentType, body, params, query, headers } = args;
5947
+ let url = `${protocol}://${host}:${port}${fullPath}${route.path}`;
5948
+ if (params) {
5949
+ for (const key in params) {
5950
+ url = url.replace(
5951
+ `:${key}`,
5952
+ encodeURIComponent(params[key])
5953
+ );
5609
5954
  }
5610
- let bodySchema;
5611
- let responsesSchemas;
5612
- if (route.contractDetails.versions) {
5613
- const version2 = Object.values(route.contractDetails.versions)[index];
5614
- responsesSchemas = version2.responses;
5615
- if (version2.body && schemaValidator.parse(inputSchema, args).ok) {
5616
- bodySchema = version2.body;
5617
- }
5618
- } else {
5619
- bodySchema = route.contractDetails.body;
5620
- responsesSchemas = route.contractDetails.responses;
5955
+ }
5956
+ let bodySchema;
5957
+ let responsesSchemas;
5958
+ if (route.contractDetails.versions) {
5959
+ const version2 = Object.values(route.contractDetails.versions)[index];
5960
+ responsesSchemas = version2.responses;
5961
+ if (version2.body && schemaValidator.parse(inputSchema, args).ok) {
5962
+ bodySchema = version2.body;
5621
5963
  }
5622
- const discriminatedBody = bodySchema ? discriminateBody(schemaValidator, bodySchema) : void 0;
5623
- let parsedBody;
5624
- if (discriminatedBody) {
5625
- switch (discriminatedBody.parserType) {
5626
- case "json": {
5627
- parsedBody = body === void 0 ? void 0 : JSON.stringify(body);
5628
- break;
5629
- }
5630
- case "text": {
5631
- parsedBody = body;
5632
- break;
5633
- }
5634
- case "file": {
5635
- parsedBody = Buffer.from((0, import_common12.toPlainString)(body));
5636
- break;
5637
- }
5638
- case "multipart": {
5639
- const formData = new FormData();
5640
- if ((0, import_common12.isRecord)(body)) {
5641
- for (const key in body) {
5642
- if (typeof body[key] === "string") {
5643
- if (schemaValidator.isInstanceOf(
5644
- body[key],
5645
- schemaValidator.file
5646
- )) {
5647
- formData.append(
5648
- key,
5649
- new Blob([new Uint8Array(Buffer.from(body[key]))])
5650
- );
5651
- } else {
5652
- formData.append(key, body[key]);
5653
- }
5964
+ } else {
5965
+ bodySchema = route.contractDetails.body;
5966
+ responsesSchemas = route.contractDetails.responses;
5967
+ }
5968
+ const discriminatedBody = bodySchema ? discriminateBody(schemaValidator, bodySchema) : void 0;
5969
+ let parsedBody;
5970
+ if (discriminatedBody) {
5971
+ switch (discriminatedBody.parserType) {
5972
+ case "json": {
5973
+ parsedBody = body === void 0 ? void 0 : JSON.stringify(body);
5974
+ break;
5975
+ }
5976
+ case "text": {
5977
+ parsedBody = body;
5978
+ break;
5979
+ }
5980
+ case "file": {
5981
+ parsedBody = Buffer.from((0, import_common12.toPlainString)(body));
5982
+ break;
5983
+ }
5984
+ case "multipart": {
5985
+ const formData = new FormData();
5986
+ if ((0, import_common12.isRecord)(body)) {
5987
+ for (const key in body) {
5988
+ if (typeof body[key] === "string") {
5989
+ if (schemaValidator.isInstanceOf(
5990
+ body[key],
5991
+ schemaValidator.file
5992
+ )) {
5993
+ formData.append(
5994
+ key,
5995
+ new Blob([new Uint8Array(Buffer.from(body[key]))])
5996
+ );
5654
5997
  } else {
5655
- throw new Error("Body is not a valid multipart object");
5998
+ formData.append(key, body[key]);
5656
5999
  }
6000
+ } else {
6001
+ throw new Error("Body is not a valid multipart object");
5657
6002
  }
5658
- } else {
5659
- throw new Error("Body is not a valid multipart object");
5660
6003
  }
5661
- parsedBody = formData;
5662
- break;
6004
+ } else {
6005
+ throw new Error("Body is not a valid multipart object");
5663
6006
  }
5664
- case "urlEncoded": {
5665
- if ((0, import_common12.isRecord)(body)) {
5666
- parsedBody = new URLSearchParams(
5667
- Object.entries(body).map(([key, value]) => [
5668
- key,
5669
- (0, import_common12.toPlainString)(value)
5670
- ])
5671
- );
5672
- } else {
5673
- throw new Error("Body is not a valid url encoded object");
5674
- }
5675
- break;
5676
- }
5677
- default: {
5678
- (0, import_common12.isNever)(discriminatedBody.parserType);
5679
- parsedBody = (0, import_common12.safeStringify)(body);
5680
- break;
6007
+ parsedBody = formData;
6008
+ break;
6009
+ }
6010
+ case "urlEncoded": {
6011
+ if ((0, import_common12.isRecord)(body)) {
6012
+ parsedBody = new URLSearchParams(
6013
+ Object.entries(body).map(([key, value]) => [
6014
+ key,
6015
+ (0, import_common12.toPlainString)(value)
6016
+ ])
6017
+ );
6018
+ } else {
6019
+ throw new Error("Body is not a valid url encoded object");
5681
6020
  }
6021
+ break;
6022
+ }
6023
+ default: {
6024
+ (0, import_common12.isNever)(discriminatedBody.parserType);
6025
+ parsedBody = (0, import_common12.safeStringify)(body);
6026
+ break;
5682
6027
  }
5683
6028
  }
5684
- if (query) {
5685
- const queryString = new URLSearchParams(
5686
- Object.entries(query).map(([key, value]) => [
5687
- key,
5688
- (0, import_common12.toPlainString)(value)
5689
- ])
5690
- ).toString();
5691
- url += queryString ? `?${queryString}` : "";
5692
- }
5693
- const response = await fetch(url, {
5694
- method: route.method.toUpperCase(),
5695
- headers: buildRouteHeaders(
5696
- headers,
5697
- discriminatedBody?.contentType != "multipart/form-data" ? contentType ?? discriminatedBody?.contentType : void 0
5698
- ),
5699
- body: parsedBody
5700
- });
5701
- if (response.status >= 300) {
5702
- throw new Error(
5703
- `Error received while proxying request to ${url}: ${await response.text()}`
5704
- );
5705
- }
5706
- if (!responsesSchemas) {
5707
- throw new Error("No responses schemas found");
5708
- }
5709
- const contractContentType = discriminateResponseBodies(
5710
- schemaValidator,
5711
- responsesSchemas
5712
- )[response.status].contentType;
5713
- switch (contentTypeMap && contentTypeMap[contractContentType] ? contentTypeMap[contractContentType] : contractContentType) {
5714
- case "application/json":
5715
- return {
5716
- content: [
5717
- {
5718
- type: "text",
5719
- text: (0, import_common12.safeStringify)(await response.json())
5720
- }
5721
- ]
5722
- };
5723
- case "text/plain":
5724
- return {
5725
- content: [
5726
- { type: "text", text: await response.text() }
5727
- ]
5728
- };
5729
- case "application/octet-stream":
5730
- return {
5731
- content: [
5732
- {
5733
- type: "resource",
5734
- resource: {
5735
- uri: response.url,
5736
- blob: Buffer.from(
5737
- await (await response.blob()).arrayBuffer()
5738
- ).toString("base64")
5739
- }
6029
+ }
6030
+ if (query) {
6031
+ const queryString = new URLSearchParams(
6032
+ Object.entries(query).map(([key, value]) => [
6033
+ key,
6034
+ (0, import_common12.toPlainString)(value)
6035
+ ])
6036
+ ).toString();
6037
+ url += queryString ? `?${queryString}` : "";
6038
+ }
6039
+ const response = await fetch(url, {
6040
+ method: route.method.toUpperCase(),
6041
+ headers: buildRouteHeaders(
6042
+ headers,
6043
+ discriminatedBody?.contentType != "multipart/form-data" ? contentType ?? discriminatedBody?.contentType : void 0,
6044
+ route.contractDetails.auth
6045
+ ),
6046
+ body: parsedBody
6047
+ });
6048
+ if (response.status >= 300) {
6049
+ throw new Error(
6050
+ `Error received while proxying request to ${url}: ${await response.text()}`
6051
+ );
6052
+ }
6053
+ if (!responsesSchemas) {
6054
+ throw new Error("No responses schemas found");
6055
+ }
6056
+ const contractContentType = discriminateResponseBodies(
6057
+ schemaValidator,
6058
+ responsesSchemas
6059
+ )[response.status].contentType;
6060
+ switch (contentTypeMap && contentTypeMap[contractContentType] ? contentTypeMap[contractContentType] : contractContentType) {
6061
+ case "application/json":
6062
+ return {
6063
+ content: [
6064
+ {
6065
+ type: "text",
6066
+ text: (0, import_common12.safeStringify)(await response.json())
6067
+ }
6068
+ ]
6069
+ };
6070
+ case "text/plain":
6071
+ return {
6072
+ content: [
6073
+ { type: "text", text: await response.text() }
6074
+ ]
6075
+ };
6076
+ case "application/octet-stream":
6077
+ return {
6078
+ content: [
6079
+ {
6080
+ type: "resource",
6081
+ resource: {
6082
+ uri: response.url,
6083
+ blob: Buffer.from(
6084
+ await (await response.blob()).arrayBuffer()
6085
+ ).toString("base64")
5740
6086
  }
5741
- ]
5742
- };
5743
- case "text/event-stream":
5744
- return {
5745
- content: [
5746
- { type: "text", text: await response.text() }
5747
- ]
5748
- };
5749
- default:
5750
- return {
5751
- content: [
5752
- { type: "text", text: await response.text() }
5753
- ]
5754
- };
5755
- }
6087
+ }
6088
+ ]
6089
+ };
6090
+ case "text/event-stream":
6091
+ return {
6092
+ content: [
6093
+ { type: "text", text: await response.text() }
6094
+ ]
6095
+ };
6096
+ default:
6097
+ return {
6098
+ content: [
6099
+ { type: "text", text: await response.text() }
6100
+ ]
6101
+ };
5756
6102
  }
5757
- });
6103
+ }
5758
6104
  });
5759
6105
  });
5760
6106
  });
5761
6107
  return mcpServer;
5762
6108
  }
6109
+ function collectMcpRoutes(application, appOptions) {
6110
+ const routes = [];
6111
+ const basePath = application.basePath === "/" ? "" : application.basePath;
6112
+ [
6113
+ { fullPath: basePath, router: application },
6114
+ ...unpackRouters(application.routers, [basePath])
6115
+ ].forEach(({ fullPath, router }) => {
6116
+ router.routes.forEach((route) => {
6117
+ if (!(route.contractDetails.options?.mcp ?? router.routerOptions?.mcp ?? appOptions !== false)) {
6118
+ return;
6119
+ }
6120
+ const globalAuth = router.routerOptions?.auth;
6121
+ routes.push({
6122
+ fullPath,
6123
+ route,
6124
+ routeAuth: routeRequiresAuth(route.contractDetails) ? {
6125
+ ...globalAuth ? globalAuth : {},
6126
+ ...route.contractDetails.auth
6127
+ } : void 0
6128
+ });
6129
+ });
6130
+ });
6131
+ return routes;
6132
+ }
6133
+ function resolveMcpAuthenticate(routes, authenticate, logger2) {
6134
+ if (authenticate) {
6135
+ return authenticate;
6136
+ }
6137
+ const routeAuths = routes.map(({ routeAuth }) => routeAuth).filter((auth) => auth != null);
6138
+ if (routeAuths.length === 0) {
6139
+ return void 0;
6140
+ }
6141
+ logger2?.info(
6142
+ `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.`
6143
+ );
6144
+ return createRouteMcpAuthenticate(routeAuths);
6145
+ }
5763
6146
 
5764
6147
  // src/http/middleware/response/parse.middleware.ts
5765
6148
  var import_validator3 = require("@forklaunch/validator");
@@ -6667,6 +7050,7 @@ function createLocalModelGatewayClient(options2 = {}) {
6667
7050
  INSTANCE_GATEWAY_MOUNT,
6668
7051
  InMemoryHmacNonceStore,
6669
7052
  InstanceGatewayRequestError,
7053
+ McpInsufficientScopeError,
6670
7054
  ModelGatewayRequestError,
6671
7055
  OPENAPI_DEFAULT_VERSION,
6672
7056
  OpenTelemetryCollector,
@@ -6690,15 +7074,18 @@ function createLocalModelGatewayClient(options2 = {}) {
6690
7074
  auditEnabled,
6691
7075
  auditEventType,
6692
7076
  bindRuntimeAuth,
7077
+ canonicalMcpResource,
6693
7078
  createContext,
6694
7079
  createEmailClient,
6695
7080
  createHmacToken,
6696
7081
  createInstanceGatewayTransport,
6697
7082
  createLocalModelGatewayClient,
6698
7083
  createMcpHttpHandler,
7084
+ createMcpOAuthAuthenticate,
6699
7085
  createModelGatewayClient,
6700
7086
  createPaymentsClient,
6701
7087
  createPreviewModelGatewayClient,
7088
+ createRouteMcpAuthenticate,
6702
7089
  createSmsClient,
6703
7090
  createStripeClient,
6704
7091
  createVoiceClient,
@@ -6744,6 +7131,8 @@ function createLocalModelGatewayClient(options2 = {}) {
6744
7131
  jwtAlgorithmsForSharedSecret,
6745
7132
  jwtClaimChecks,
6746
7133
  logger,
7134
+ mcpBearerChallenge,
7135
+ mcpProtectedResourceMetadata,
6747
7136
  meta,
6748
7137
  metricsDefinitions,
6749
7138
  middleware,
@@ -6757,6 +7146,7 @@ function createLocalModelGatewayClient(options2 = {}) {
6757
7146
  resetProcessHandlersForTesting,
6758
7147
  resolveHmacMaxSkewMs,
6759
7148
  resolveHmacNonceStore,
7149
+ resolveMcpOAuth,
6760
7150
  signPlatformEvent,
6761
7151
  smsSegments,
6762
7152
  stripeGatewayFetch,