@forklaunch/core 4.1.1 → 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.
Files changed (44) hide show
  1. package/bin/gateway-mock/routes/payments.mjs +5 -2
  2. package/lib/agent/agent.d.ts +14 -0
  3. package/lib/agent/agent.d.ts.map +1 -1
  4. package/lib/agent/approvals.d.ts +52 -0
  5. package/lib/agent/approvals.d.ts.map +1 -0
  6. package/lib/agent/continuation.d.ts +28 -3
  7. package/lib/agent/continuation.d.ts.map +1 -1
  8. package/lib/agent/index.d.ts +4 -2
  9. package/lib/agent/index.d.ts.map +1 -1
  10. package/lib/agent/index.js +191 -50
  11. package/lib/agent/index.js.map +1 -1
  12. package/lib/agent/index.mjs +185 -49
  13. package/lib/agent/index.mjs.map +1 -1
  14. package/lib/agent/types.d.ts +22 -2
  15. package/lib/agent/types.d.ts.map +1 -1
  16. package/lib/http/index.d.ts +2 -0
  17. package/lib/http/index.d.ts.map +1 -1
  18. package/lib/http/index.js +610 -221
  19. package/lib/http/index.js.map +1 -1
  20. package/lib/http/index.mjs +607 -222
  21. package/lib/http/index.mjs.map +1 -1
  22. package/lib/http/mcpGenerator/mcpAuth.d.ts +52 -0
  23. package/lib/http/mcpGenerator/mcpAuth.d.ts.map +1 -0
  24. package/lib/http/mcpGenerator/mcpGenerator.d.ts +2 -1
  25. package/lib/http/mcpGenerator/mcpGenerator.d.ts.map +1 -1
  26. package/lib/http/mcpGenerator/mcpHttpHandler.d.ts +14 -1
  27. package/lib/http/mcpGenerator/mcpHttpHandler.d.ts.map +1 -1
  28. package/lib/http/mcpGenerator/mcpOAuth.d.ts +110 -0
  29. package/lib/http/mcpGenerator/mcpOAuth.d.ts.map +1 -0
  30. package/lib/http/paymentsClient.d.ts +6 -0
  31. package/lib/http/paymentsClient.d.ts.map +1 -1
  32. package/lib/http/telemetry/pinoLogger.d.ts +2 -1
  33. package/lib/http/telemetry/pinoLogger.d.ts.map +1 -1
  34. package/lib/http/types/expressLikeOptions.d.ts +8 -0
  35. package/lib/http/types/expressLikeOptions.d.ts.map +1 -1
  36. package/lib/persistence/index.d.ts +1 -0
  37. package/lib/persistence/index.d.ts.map +1 -1
  38. package/lib/persistence/index.js +39 -0
  39. package/lib/persistence/index.js.map +1 -1
  40. package/lib/persistence/index.mjs +38 -0
  41. package/lib/persistence/index.mjs.map +1 -1
  42. package/lib/persistence/migrationLock.d.ts +61 -0
  43. package/lib/persistence/migrationLock.d.ts.map +1 -0
  44. package/package.json +5 -4
@@ -300,8 +300,7 @@ function isForklaunchRequest(request) {
300
300
 
301
301
  // src/http/telemetry/pinoLogger.ts
302
302
  import { isNever } from "@forklaunch/common";
303
- import { trace } from "@opentelemetry/api";
304
- import { logs } from "@opentelemetry/api-logs";
303
+ import { logs, trace } from "@opentelemetry/api";
305
304
  import pino from "pino";
306
305
 
307
306
  // src/http/guards/isLoggerMeta.ts
@@ -1252,15 +1251,15 @@ var MAX_CLAIM_LENGTH = 128;
1252
1251
  function bounded(value) {
1253
1252
  return typeof value === "string" && value.length > 0 ? value.slice(0, MAX_CLAIM_LENGTH) : void 0;
1254
1253
  }
1255
- function authLogContext(headerValue) {
1256
- if (typeof headerValue !== "string" || headerValue.length === 0) {
1254
+ function authLogContext(headerValue2) {
1255
+ if (typeof headerValue2 !== "string" || headerValue2.length === 0) {
1257
1256
  return { hasToken: false };
1258
1257
  }
1259
1258
  const context2 = {
1260
1259
  hasToken: true,
1261
- tokenFingerprint: createHash("sha256").update(headerValue).digest("hex").slice(0, FINGERPRINT_LENGTH)
1260
+ tokenFingerprint: createHash("sha256").update(headerValue2).digest("hex").slice(0, FINGERPRINT_LENGTH)
1262
1261
  };
1263
- const parts = headerValue.trim().split(/\s+/);
1262
+ const parts = headerValue2.trim().split(/\s+/);
1264
1263
  const candidate = parts[parts.length - 1];
1265
1264
  if (candidate.split(".").length !== 3) {
1266
1265
  return context2;
@@ -3463,21 +3462,21 @@ function refuse(message) {
3463
3462
  }
3464
3463
  function addresses(value, field) {
3465
3464
  if (value === void 0) return void 0;
3466
- const list = Array.isArray(value) ? value : [value];
3467
- if (list.length === 0) refuse(`${field} must name at least one address`);
3468
- 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) {
3469
3468
  refuse(
3470
- `${field} has ${list.length} addresses; the limit is ${EMAIL_LIMITS.maxRecipients}`
3469
+ `${field} has ${list2.length} addresses; the limit is ${EMAIL_LIMITS.maxRecipients}`
3471
3470
  );
3472
3471
  }
3473
- for (const address of list) {
3472
+ for (const address of list2) {
3474
3473
  if (!isEmailAddress(address)) {
3475
3474
  refuse(
3476
3475
  `${field}: '${String(address).slice(0, 80)}' is not an email address`
3477
3476
  );
3478
3477
  }
3479
3478
  }
3480
- return list;
3479
+ return list2;
3481
3480
  }
3482
3481
  function fail(problem) {
3483
3482
  refuse(`listUnsubscribe: ${problem}`);
@@ -5152,7 +5151,7 @@ import {
5152
5151
  safeStringify as safeStringify3,
5153
5152
  toPlainString
5154
5153
  } from "@forklaunch/common";
5155
- import { string, ZodSchemaValidator } from "@forklaunch/validator/zod";
5154
+ import { ZodSchemaValidator } from "@forklaunch/validator/zod";
5156
5155
  import { FastMCP } from "fastmcp";
5157
5156
 
5158
5157
  // src/http/router/unpackRouters.ts
@@ -5173,16 +5172,317 @@ function unpackRouters(routers, recursiveBasePath = []) {
5173
5172
  }, []);
5174
5173
  }
5175
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
+
5176
5289
  // src/http/mcpGenerator/mcpHttpHandler.ts
5177
5290
  import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
5178
5291
  import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
5179
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
5180
5478
  var DEFAULT_MCP_SESSION_IDLE_TIMEOUT_MS = 15 * 60 * 1e3;
5181
5479
  var mcpTransportHeaders = new AsyncLocalStorage2();
5182
5480
  function getMcpTransportHeaders() {
5183
5481
  return mcpTransportHeaders.getStore();
5184
5482
  }
5185
5483
  function createMcpHttpHandler(mcpServer, options2) {
5484
+ const authenticate = options2?.authenticate ?? getGeneratedMcpAuthenticate(mcpServer);
5485
+ const oauth = options2?.oauth ?? getGeneratedMcpOAuth(mcpServer);
5186
5486
  const mode = options2?.sessions ?? "stateless";
5187
5487
  if (mode === "stateful" && (options2?.workerCount ?? 1) > 1) {
5188
5488
  throw new Error(
@@ -5215,16 +5515,32 @@ function createMcpHttpHandler(mcpServer, options2) {
5215
5515
  sweepTimer.unref();
5216
5516
  }
5217
5517
  async function authenticateRequest(authRequest) {
5218
- if (!options2?.authenticate) {
5518
+ if (!authenticate) {
5219
5519
  return { ok: true, auth: void 0 };
5220
5520
  }
5221
5521
  try {
5222
- const auth = await options2.authenticate(authRequest);
5522
+ const auth = await authenticate(authRequest);
5223
5523
  return auth ? { ok: true, auth } : { ok: false };
5224
- } catch {
5225
- return { ok: false };
5524
+ } catch (error) {
5525
+ return error instanceof McpInsufficientScopeError ? { ok: false, insufficientScope: error.missing } : { ok: false };
5226
5526
  }
5227
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
+ }
5228
5544
  async function handleStateless(request, auth) {
5229
5545
  if (request.method !== "POST") {
5230
5546
  return jsonRpcError(405, -32e3, "Method not allowed", {
@@ -5297,9 +5613,7 @@ function createMcpHttpHandler(mcpServer, options2) {
5297
5613
  async function handle(request, authRequest) {
5298
5614
  const authResult = await authenticateRequest(authRequest);
5299
5615
  if (!authResult.ok) {
5300
- return jsonRpcError(401, -32001, "Unauthorized", {
5301
- "WWW-Authenticate": "Bearer"
5302
- });
5616
+ return refuse2(authRequest, authResult.insufficientScope);
5303
5617
  }
5304
5618
  return mode === "stateless" ? handleStateless(request, authResult.auth) : handleStateful(request, authResult.auth);
5305
5619
  }
@@ -5311,7 +5625,9 @@ function createMcpHttpHandler(mcpServer, options2) {
5311
5625
  sessions.clear();
5312
5626
  await Promise.all(entries.map(({ session }) => session.close()));
5313
5627
  }
5314
- 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 };
5315
5631
  }
5316
5632
  function closeWhenBodyEnds(response, done) {
5317
5633
  if (!response.body) {
@@ -5351,6 +5667,7 @@ function isSeparateMcpListener(configuredPort) {
5351
5667
 
5352
5668
  // src/http/mcpGenerator/mcpGenerator.ts
5353
5669
  function generateInputSchema(schemaValidator, body, params, query, requestHeaders, auth) {
5670
+ const toolHeaders = toolInputHeaders(requestHeaders, auth);
5354
5671
  let discriminatedBody;
5355
5672
  if (body) {
5356
5673
  discriminatedBody = discriminateBody(schemaValidator, body);
@@ -5366,30 +5683,38 @@ function generateInputSchema(schemaValidator, body, params, query, requestHeader
5366
5683
  ...query ? {
5367
5684
  query: schemaValidator.schemify(query)
5368
5685
  } : {},
5369
- ...requestHeaders ? {
5370
- headers: schemaValidator.schemify({
5371
- ...requestHeaders,
5372
- ...auth ? {
5373
- [auth.headerName ?? "authorization"]: string.startsWith(
5374
- auth.tokenPrefix ?? ("basic" in auth ? "Basic " : "Bearer ")
5375
- )
5376
- } : {}
5377
- })
5686
+ ...toolHeaders ? {
5687
+ headers: schemaValidator.schemify(toolHeaders)
5378
5688
  } : {}
5379
5689
  });
5380
5690
  }
5381
- 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) {
5382
5704
  const transportHeaders = getMcpTransportHeaders();
5383
5705
  const routeHeaders = new Headers();
5384
- const authorization = transportHeaders?.get("authorization");
5385
- if (authorization) {
5386
- routeHeaders.set("authorization", authorization);
5387
- }
5706
+ const credentialHeaders = mcpAuthHeaderNames(auth);
5388
5707
  for (const [name, value] of Object.entries(toolHeaders ?? {})) {
5389
- if (value != null) {
5708
+ if (value != null && !credentialHeaders.has(name.toLowerCase())) {
5390
5709
  routeHeaders.set(name, String(value));
5391
5710
  }
5392
5711
  }
5712
+ for (const name of credentialHeaders) {
5713
+ const credential = transportHeaders?.get(name);
5714
+ if (credential) {
5715
+ routeHeaders.set(name, credential);
5716
+ }
5717
+ }
5393
5718
  const correlationId = transportHeaders?.get("x-correlation-id");
5394
5719
  if (correlationId) {
5395
5720
  routeHeaders.set("x-correlation-id", correlationId);
@@ -5408,226 +5733,279 @@ function buildRouteHeaders(toolHeaders, contentType) {
5408
5733
  }
5409
5734
  return routeHeaders;
5410
5735
  }
5411
- 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) {
5412
5737
  if (!(schemaValidator instanceof ZodSchemaValidator)) {
5413
5738
  throw new Error(
5414
5739
  "Schema validator must be an instance of ZodSchemaValidator"
5415
5740
  );
5416
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
+ }
5417
5755
  const mcpServer = new FastMCP({
5418
5756
  ...options2,
5419
5757
  name: options2?.name ?? "mcp-server",
5420
5758
  version,
5421
- authenticate
5422
- });
5423
- [
5424
- {
5425
- fullPath: application.basePath === "/" ? "" : application.basePath,
5426
- router: application
5427
- },
5428
- ...unpackRouters(application.routers, [
5429
- application.basePath === "/" ? "" : application.basePath
5430
- ])
5431
- ].forEach(({ fullPath, router }) => {
5432
- router.routes.forEach((route) => {
5433
- if (!(route.contractDetails.options?.mcp ?? router.routerOptions?.mcp ?? appOptions !== false)) {
5434
- 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
+ }
5435
5771
  }
5436
- const inputSchemas = [];
5437
- if (route.contractDetails.versions) {
5438
- Object.values(route.contractDetails.versions).forEach((version2) => {
5439
- inputSchemas.push(
5440
- generateInputSchema(
5441
- schemaValidator,
5442
- version2.body,
5443
- route.contractDetails.params,
5444
- version2.query,
5445
- version2.requestHeaders,
5446
- route.contractDetails.auth
5447
- )
5448
- );
5449
- });
5450
- } 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) => {
5451
5780
  inputSchemas.push(
5452
5781
  generateInputSchema(
5453
5782
  schemaValidator,
5454
- route.contractDetails.body,
5783
+ version2.body,
5455
5784
  route.contractDetails.params,
5456
- route.contractDetails.query,
5457
- route.contractDetails.requestHeaders,
5785
+ version2.query,
5786
+ version2.requestHeaders,
5458
5787
  route.contractDetails.auth
5459
5788
  )
5460
5789
  );
5461
- }
5462
- inputSchemas.forEach((inputSchema, index) => {
5463
- mcpServer.addTool({
5464
- name: route.contractDetails.name + (Object.keys(route.contractDetails.versions ?? {}).length > 1 ? ` [v${Object.keys(route.contractDetails.versions ?? {})[index]}]` : ""),
5465
- description: route.contractDetails.summary,
5466
- parameters: inputSchema,
5467
- execute: async (args) => {
5468
- const { contentType, body, params, query, headers } = args;
5469
- let url = `${protocol}://${host}:${port}${fullPath}${route.path}`;
5470
- if (params) {
5471
- for (const key in params) {
5472
- url = url.replace(
5473
- `:${key}`,
5474
- encodeURIComponent(params[key])
5475
- );
5476
- }
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
+ );
5477
5817
  }
5478
- let bodySchema;
5479
- let responsesSchemas;
5480
- if (route.contractDetails.versions) {
5481
- const version2 = Object.values(route.contractDetails.versions)[index];
5482
- responsesSchemas = version2.responses;
5483
- if (version2.body && schemaValidator.parse(inputSchema, args).ok) {
5484
- bodySchema = version2.body;
5485
- }
5486
- } else {
5487
- bodySchema = route.contractDetails.body;
5488
- 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;
5489
5826
  }
5490
- const discriminatedBody = bodySchema ? discriminateBody(schemaValidator, bodySchema) : void 0;
5491
- let parsedBody;
5492
- if (discriminatedBody) {
5493
- switch (discriminatedBody.parserType) {
5494
- case "json": {
5495
- parsedBody = body === void 0 ? void 0 : JSON.stringify(body);
5496
- break;
5497
- }
5498
- case "text": {
5499
- parsedBody = body;
5500
- break;
5501
- }
5502
- case "file": {
5503
- parsedBody = Buffer.from(toPlainString(body));
5504
- break;
5505
- }
5506
- case "multipart": {
5507
- const formData = new FormData();
5508
- if (isRecord3(body)) {
5509
- for (const key in body) {
5510
- if (typeof body[key] === "string") {
5511
- if (schemaValidator.isInstanceOf(
5512
- body[key],
5513
- schemaValidator.file
5514
- )) {
5515
- formData.append(
5516
- key,
5517
- new Blob([new Uint8Array(Buffer.from(body[key]))])
5518
- );
5519
- } else {
5520
- formData.append(key, body[key]);
5521
- }
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
+ );
5522
5860
  } else {
5523
- throw new Error("Body is not a valid multipart object");
5861
+ formData.append(key, body[key]);
5524
5862
  }
5863
+ } else {
5864
+ throw new Error("Body is not a valid multipart object");
5525
5865
  }
5526
- } else {
5527
- throw new Error("Body is not a valid multipart object");
5528
5866
  }
5529
- parsedBody = formData;
5530
- break;
5867
+ } else {
5868
+ throw new Error("Body is not a valid multipart object");
5531
5869
  }
5532
- case "urlEncoded": {
5533
- if (isRecord3(body)) {
5534
- parsedBody = new URLSearchParams(
5535
- Object.entries(body).map(([key, value]) => [
5536
- key,
5537
- toPlainString(value)
5538
- ])
5539
- );
5540
- } else {
5541
- throw new Error("Body is not a valid url encoded object");
5542
- }
5543
- break;
5544
- }
5545
- default: {
5546
- isNever3(discriminatedBody.parserType);
5547
- parsedBody = safeStringify3(body);
5548
- 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");
5549
5883
  }
5884
+ break;
5885
+ }
5886
+ default: {
5887
+ isNever3(discriminatedBody.parserType);
5888
+ parsedBody = safeStringify3(body);
5889
+ break;
5550
5890
  }
5551
5891
  }
5552
- if (query) {
5553
- const queryString = new URLSearchParams(
5554
- Object.entries(query).map(([key, value]) => [
5555
- key,
5556
- toPlainString(value)
5557
- ])
5558
- ).toString();
5559
- url += queryString ? `?${queryString}` : "";
5560
- }
5561
- const response = await fetch(url, {
5562
- method: route.method.toUpperCase(),
5563
- headers: buildRouteHeaders(
5564
- headers,
5565
- discriminatedBody?.contentType != "multipart/form-data" ? contentType ?? discriminatedBody?.contentType : void 0
5566
- ),
5567
- body: parsedBody
5568
- });
5569
- if (response.status >= 300) {
5570
- throw new Error(
5571
- `Error received while proxying request to ${url}: ${await response.text()}`
5572
- );
5573
- }
5574
- if (!responsesSchemas) {
5575
- throw new Error("No responses schemas found");
5576
- }
5577
- const contractContentType = discriminateResponseBodies(
5578
- schemaValidator,
5579
- responsesSchemas
5580
- )[response.status].contentType;
5581
- switch (contentTypeMap && contentTypeMap[contractContentType] ? contentTypeMap[contractContentType] : contractContentType) {
5582
- case "application/json":
5583
- return {
5584
- content: [
5585
- {
5586
- type: "text",
5587
- text: safeStringify3(await response.json())
5588
- }
5589
- ]
5590
- };
5591
- case "text/plain":
5592
- return {
5593
- content: [
5594
- { type: "text", text: await response.text() }
5595
- ]
5596
- };
5597
- case "application/octet-stream":
5598
- return {
5599
- content: [
5600
- {
5601
- type: "resource",
5602
- resource: {
5603
- uri: response.url,
5604
- blob: Buffer.from(
5605
- await (await response.blob()).arrayBuffer()
5606
- ).toString("base64")
5607
- }
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")
5608
5949
  }
5609
- ]
5610
- };
5611
- case "text/event-stream":
5612
- return {
5613
- content: [
5614
- { type: "text", text: await response.text() }
5615
- ]
5616
- };
5617
- default:
5618
- return {
5619
- content: [
5620
- { type: "text", text: await response.text() }
5621
- ]
5622
- };
5623
- }
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
+ };
5624
5965
  }
5625
- });
5966
+ }
5626
5967
  });
5627
5968
  });
5628
5969
  });
5629
5970
  return mcpServer;
5630
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
+ }
5631
6009
 
5632
6010
  // src/http/middleware/response/parse.middleware.ts
5633
6011
  import {
@@ -6548,6 +6926,7 @@ export {
6548
6926
  INSTANCE_GATEWAY_MOUNT,
6549
6927
  InMemoryHmacNonceStore,
6550
6928
  InstanceGatewayRequestError,
6929
+ McpInsufficientScopeError,
6551
6930
  ModelGatewayRequestError,
6552
6931
  OPENAPI_DEFAULT_VERSION,
6553
6932
  OpenTelemetryCollector,
@@ -6571,15 +6950,18 @@ export {
6571
6950
  auditEnabled,
6572
6951
  auditEventType,
6573
6952
  bindRuntimeAuth,
6953
+ canonicalMcpResource,
6574
6954
  createContext,
6575
6955
  createEmailClient,
6576
6956
  createHmacToken,
6577
6957
  createInstanceGatewayTransport,
6578
6958
  createLocalModelGatewayClient,
6579
6959
  createMcpHttpHandler,
6960
+ createMcpOAuthAuthenticate,
6580
6961
  createModelGatewayClient,
6581
6962
  createPaymentsClient,
6582
6963
  createPreviewModelGatewayClient,
6964
+ createRouteMcpAuthenticate,
6583
6965
  createSmsClient,
6584
6966
  createStripeClient,
6585
6967
  createVoiceClient,
@@ -6625,6 +7007,8 @@ export {
6625
7007
  jwtAlgorithmsForSharedSecret,
6626
7008
  jwtClaimChecks,
6627
7009
  logger,
7010
+ mcpBearerChallenge,
7011
+ mcpProtectedResourceMetadata,
6628
7012
  meta,
6629
7013
  metricsDefinitions,
6630
7014
  middleware,
@@ -6638,6 +7022,7 @@ export {
6638
7022
  resetProcessHandlersForTesting,
6639
7023
  resolveHmacMaxSkewMs,
6640
7024
  resolveHmacNonceStore,
7025
+ resolveMcpOAuth,
6641
7026
  signPlatformEvent,
6642
7027
  smsSegments,
6643
7028
  stripeGatewayFetch,