@zuplo/cli 7.8.6 → 7.8.8

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 (122) hide show
  1. package/node_modules/@modelcontextprotocol/client/dist/{index-CHhhk6PQ.d.cts → index-BCtJi0p5.d.mts} +38 -6
  2. package/node_modules/@modelcontextprotocol/client/dist/index-BCtJi0p5.d.mts.map +1 -0
  3. package/node_modules/@modelcontextprotocol/client/dist/{index-D4xIIEF6.d.mts → index-CEk3qkZM.d.cts} +41 -3
  4. package/node_modules/@modelcontextprotocol/client/dist/index-CEk3qkZM.d.cts.map +1 -0
  5. package/node_modules/@modelcontextprotocol/client/dist/index.cjs +375 -60
  6. package/node_modules/@modelcontextprotocol/client/dist/index.cjs.map +1 -1
  7. package/node_modules/@modelcontextprotocol/client/dist/index.d.cts +227 -11
  8. package/node_modules/@modelcontextprotocol/client/dist/index.d.cts.map +1 -1
  9. package/node_modules/@modelcontextprotocol/client/dist/index.d.mts +227 -11
  10. package/node_modules/@modelcontextprotocol/client/dist/index.d.mts.map +1 -1
  11. package/node_modules/@modelcontextprotocol/client/dist/index.mjs +369 -61
  12. package/node_modules/@modelcontextprotocol/client/dist/index.mjs.map +1 -1
  13. package/node_modules/@modelcontextprotocol/client/dist/shimsWorkerd.cjs +1 -1
  14. package/node_modules/@modelcontextprotocol/client/dist/shimsWorkerd.mjs +1 -1
  15. package/node_modules/@modelcontextprotocol/client/dist/{src-NAgB4Mp8.cjs → src-D0qEN74R.cjs} +111 -38
  16. package/node_modules/@modelcontextprotocol/client/dist/src-D0qEN74R.cjs.map +1 -0
  17. package/node_modules/@modelcontextprotocol/client/dist/{src-D_zzAWoS.mjs → src-DDAAhLnO.mjs} +106 -33
  18. package/node_modules/@modelcontextprotocol/client/dist/src-DDAAhLnO.mjs.map +1 -0
  19. package/node_modules/@modelcontextprotocol/client/dist/stdio.cjs +8 -2
  20. package/node_modules/@modelcontextprotocol/client/dist/stdio.cjs.map +1 -1
  21. package/node_modules/@modelcontextprotocol/client/dist/stdio.d.cts +1 -1
  22. package/node_modules/@modelcontextprotocol/client/dist/stdio.d.cts.map +1 -1
  23. package/node_modules/@modelcontextprotocol/client/dist/stdio.d.mts +1 -1
  24. package/node_modules/@modelcontextprotocol/client/dist/stdio.d.mts.map +1 -1
  25. package/node_modules/@modelcontextprotocol/client/dist/stdio.mjs +8 -2
  26. package/node_modules/@modelcontextprotocol/client/dist/stdio.mjs.map +1 -1
  27. package/node_modules/@modelcontextprotocol/client/package.json +4 -4
  28. package/node_modules/@modelcontextprotocol/core/dist/{auth-BWdKR39I.d.mts → auth--n_Yzytt.d.cts} +6 -1
  29. package/node_modules/@modelcontextprotocol/core/dist/{auth-BWdKR39I.d.mts.map → auth--n_Yzytt.d.cts.map} +1 -1
  30. package/node_modules/@modelcontextprotocol/core/dist/{auth-CfDMXiII.cjs → auth-4-zilcqg.cjs} +3 -2
  31. package/node_modules/@modelcontextprotocol/core/dist/{auth-CfDMXiII.cjs.map → auth-4-zilcqg.cjs.map} +1 -1
  32. package/node_modules/@modelcontextprotocol/core/dist/{auth-CUe6YdwF.mjs → auth-CGP0BDVq.mjs} +3 -2
  33. package/node_modules/@modelcontextprotocol/core/dist/{auth-CUe6YdwF.mjs.map → auth-CGP0BDVq.mjs.map} +1 -1
  34. package/node_modules/@modelcontextprotocol/core/dist/{auth-hYtaIUZm.d.cts → auth-YUQV3RRv.d.mts} +6 -1
  35. package/node_modules/@modelcontextprotocol/core/dist/{auth-hYtaIUZm.d.cts.map → auth-YUQV3RRv.d.mts.map} +1 -1
  36. package/node_modules/@modelcontextprotocol/core/dist/index.cjs +1 -1
  37. package/node_modules/@modelcontextprotocol/core/dist/index.d.cts +1 -1
  38. package/node_modules/@modelcontextprotocol/core/dist/index.d.mts +1 -1
  39. package/node_modules/@modelcontextprotocol/core/dist/index.mjs +1 -1
  40. package/node_modules/@modelcontextprotocol/core/dist/internal.cjs +1 -1
  41. package/node_modules/@modelcontextprotocol/core/dist/internal.d.cts +1 -1
  42. package/node_modules/@modelcontextprotocol/core/dist/internal.d.mts +1 -1
  43. package/node_modules/@modelcontextprotocol/core/dist/internal.mjs +1 -1
  44. package/node_modules/@modelcontextprotocol/core/package.json +1 -1
  45. package/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/auth.d.ts +15 -4
  46. package/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/auth.d.ts.map +1 -1
  47. package/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/auth.js +22 -3
  48. package/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/auth.js.map +1 -1
  49. package/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/express.d.ts.map +1 -1
  50. package/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/express.js +3 -1
  51. package/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/express.js.map +1 -1
  52. package/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/requestBody.d.ts +25 -0
  53. package/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/requestBody.d.ts.map +1 -0
  54. package/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/requestBody.js +64 -0
  55. package/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/requestBody.js.map +1 -0
  56. package/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/webStandardStreamableHttp.d.ts +10 -1
  57. package/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/webStandardStreamableHttp.d.ts.map +1 -1
  58. package/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/webStandardStreamableHttp.js +13 -1
  59. package/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/webStandardStreamableHttp.js.map +1 -1
  60. package/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.d.ts +15 -4
  61. package/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.d.ts.map +1 -1
  62. package/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js +22 -3
  63. package/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js.map +1 -1
  64. package/node_modules/@modelcontextprotocol/sdk/dist/esm/server/express.d.ts.map +1 -1
  65. package/node_modules/@modelcontextprotocol/sdk/dist/esm/server/express.js +3 -1
  66. package/node_modules/@modelcontextprotocol/sdk/dist/esm/server/express.js.map +1 -1
  67. package/node_modules/@modelcontextprotocol/sdk/dist/esm/server/requestBody.d.ts +25 -0
  68. package/node_modules/@modelcontextprotocol/sdk/dist/esm/server/requestBody.d.ts.map +1 -0
  69. package/node_modules/@modelcontextprotocol/sdk/dist/esm/server/requestBody.js +58 -0
  70. package/node_modules/@modelcontextprotocol/sdk/dist/esm/server/requestBody.js.map +1 -0
  71. package/node_modules/@modelcontextprotocol/sdk/dist/esm/server/webStandardStreamableHttp.d.ts +10 -1
  72. package/node_modules/@modelcontextprotocol/sdk/dist/esm/server/webStandardStreamableHttp.d.ts.map +1 -1
  73. package/node_modules/@modelcontextprotocol/sdk/dist/esm/server/webStandardStreamableHttp.js +13 -1
  74. package/node_modules/@modelcontextprotocol/sdk/dist/esm/server/webStandardStreamableHttp.js.map +1 -1
  75. package/node_modules/@modelcontextprotocol/sdk/package.json +1 -1
  76. package/node_modules/@modelcontextprotocol/server/dist/{createMcpHandler-dBHMsxwf.d.cts → createMcpHandler-BLVe3qmU.d.cts} +110 -7
  77. package/node_modules/@modelcontextprotocol/server/dist/createMcpHandler-BLVe3qmU.d.cts.map +1 -0
  78. package/node_modules/@modelcontextprotocol/server/dist/{createMcpHandler-CLhGwQTn.d.mts → createMcpHandler-Bt6U_Fqb.d.mts} +110 -7
  79. package/node_modules/@modelcontextprotocol/server/dist/createMcpHandler-Bt6U_Fqb.d.mts.map +1 -0
  80. package/node_modules/@modelcontextprotocol/server/dist/index.cjs +144 -248
  81. package/node_modules/@modelcontextprotocol/server/dist/index.cjs.map +1 -1
  82. package/node_modules/@modelcontextprotocol/server/dist/index.d.cts +38 -3
  83. package/node_modules/@modelcontextprotocol/server/dist/index.d.cts.map +1 -1
  84. package/node_modules/@modelcontextprotocol/server/dist/index.d.mts +38 -3
  85. package/node_modules/@modelcontextprotocol/server/dist/index.d.mts.map +1 -1
  86. package/node_modules/@modelcontextprotocol/server/dist/index.mjs +136 -243
  87. package/node_modules/@modelcontextprotocol/server/dist/index.mjs.map +1 -1
  88. package/node_modules/@modelcontextprotocol/server/dist/{mcp-D7GmuPnv.cjs → mcp-DUcCQSTW.cjs} +426 -21
  89. package/node_modules/@modelcontextprotocol/server/dist/mcp-DUcCQSTW.cjs.map +1 -0
  90. package/node_modules/@modelcontextprotocol/server/dist/{mcp-DXXb3Vv3.mjs → mcp-Dw2OlZ1f.mjs} +367 -22
  91. package/node_modules/@modelcontextprotocol/server/dist/mcp-Dw2OlZ1f.mjs.map +1 -0
  92. package/node_modules/@modelcontextprotocol/server/dist/shimsWorkerd.cjs +1 -1
  93. package/node_modules/@modelcontextprotocol/server/dist/shimsWorkerd.mjs +1 -1
  94. package/node_modules/@modelcontextprotocol/server/dist/{src-STyD_Vvf.cjs → src-CgFsfg3E.cjs} +114 -36
  95. package/node_modules/@modelcontextprotocol/server/dist/src-CgFsfg3E.cjs.map +1 -0
  96. package/node_modules/@modelcontextprotocol/server/dist/{src-CX2iR2pK.mjs → src-D-y6h4N7.mjs} +114 -36
  97. package/node_modules/@modelcontextprotocol/server/dist/src-D-y6h4N7.mjs.map +1 -0
  98. package/node_modules/@modelcontextprotocol/server/dist/stdio.cjs +30 -3
  99. package/node_modules/@modelcontextprotocol/server/dist/stdio.cjs.map +1 -1
  100. package/node_modules/@modelcontextprotocol/server/dist/stdio.d.cts +9 -1
  101. package/node_modules/@modelcontextprotocol/server/dist/stdio.d.cts.map +1 -1
  102. package/node_modules/@modelcontextprotocol/server/dist/stdio.d.mts +9 -1
  103. package/node_modules/@modelcontextprotocol/server/dist/stdio.d.mts.map +1 -1
  104. package/node_modules/@modelcontextprotocol/server/dist/stdio.mjs +30 -3
  105. package/node_modules/@modelcontextprotocol/server/dist/stdio.mjs.map +1 -1
  106. package/node_modules/@modelcontextprotocol/server/package.json +3 -3
  107. package/node_modules/@zuplo/core/package.json +1 -1
  108. package/node_modules/@zuplo/graphql/package.json +1 -1
  109. package/node_modules/@zuplo/openapi-tools/package.json +1 -1
  110. package/node_modules/@zuplo/otel/package.json +1 -1
  111. package/node_modules/@zuplo/runtime/package.json +1 -1
  112. package/package.json +11 -11
  113. package/node_modules/@modelcontextprotocol/client/dist/index-CHhhk6PQ.d.cts.map +0 -1
  114. package/node_modules/@modelcontextprotocol/client/dist/index-D4xIIEF6.d.mts.map +0 -1
  115. package/node_modules/@modelcontextprotocol/client/dist/src-D_zzAWoS.mjs.map +0 -1
  116. package/node_modules/@modelcontextprotocol/client/dist/src-NAgB4Mp8.cjs.map +0 -1
  117. package/node_modules/@modelcontextprotocol/server/dist/createMcpHandler-CLhGwQTn.d.mts.map +0 -1
  118. package/node_modules/@modelcontextprotocol/server/dist/createMcpHandler-dBHMsxwf.d.cts.map +0 -1
  119. package/node_modules/@modelcontextprotocol/server/dist/mcp-D7GmuPnv.cjs.map +0 -1
  120. package/node_modules/@modelcontextprotocol/server/dist/mcp-DXXb3Vv3.mjs.map +0 -1
  121. package/node_modules/@modelcontextprotocol/server/dist/src-CX2iR2pK.mjs.map +0 -1
  122. package/node_modules/@modelcontextprotocol/server/dist/src-STyD_Vvf.cjs.map +0 -1
@@ -1,4 +1,4 @@
1
- import { A as promptArgumentsFromStandardSchema, At as LATEST_PROTOCOL_VERSION, B as scanXMcpHeaderDeclarations, C as REQUEST_STATE_ONLY_LEG_PACING_MS, Ct as CLIENT_CAPABILITIES_META_KEY, E as sleep, H as assertCompleteRequestPrompt, Ht as requiredClientCapabilitiesForInputRequest, It as SERVER_INFO_META_KEY, Kt as SdkError, Lt as SUBSCRIPTION_ID_META_KEY, M as validateStandardSchema, N as parseSchema, T as linkedRoundAbort, U as assertCompleteRequestResourceTemplate, Vt as missingClientCapabilities, _ as mergeCapabilities, _t as normalizeContentlessToolResult, a as UriTemplate, b as withRequestStateValue, bt as legacyProtocolVersions, ct as codecForVersion, dt as ResourceNotFoundError, g as Protocol, gt as attachCacheHintFallback, ht as assertValidCacheHint, j as standardSchemaToJsonSchema, jt as LOG_LEVEL_META_KEY, lt as MissingRequiredClientCapabilityError, mt as ProtocolErrorCode, nt as LoggingLevelSchema, q as isInputRequiredResult, qt as SdkErrorCode, r as normalizeRawShapeSchema, s as validateAndWarnToolName, st as MODERN_WIRE_REVISION, ut as ProtocolError, v as requestStateAccessor, w as inputRequiredRoundsExceededMessage, xt as modernProtocolVersions, yt as isModernProtocolVersion } from "./src-CX2iR2pK.mjs";
1
+ import { A as promptArgumentsFromStandardSchema, At as LATEST_PROTOCOL_VERSION, B as scanXMcpHeaderDeclarations, C as REQUEST_STATE_ONLY_LEG_PACING_MS, Ct as CLIENT_CAPABILITIES_META_KEY, E as sleep, H as assertCompleteRequestPrompt, Ht as requiredClientCapabilitiesForInputRequest, It as SERVER_INFO_META_KEY, Kt as SdkError, Lt as SUBSCRIPTION_ID_META_KEY, M as validateStandardSchema, N as parseSchema, T as linkedRoundAbort, U as assertCompleteRequestResourceTemplate, Vt as missingClientCapabilities, Xt as OAuthErrorCode, Yt as OAuthError, _ as mergeCapabilities, _t as normalizeContentlessToolResult, a as UriTemplate, b as withRequestStateValue, bt as legacyProtocolVersions, ct as codecForVersion, dt as ResourceNotFoundError, g as Protocol, gt as attachCacheHintFallback, ht as assertValidCacheHint, j as standardSchemaToJsonSchema, jt as LOG_LEVEL_META_KEY, lt as MissingRequiredClientCapabilityError, mt as ProtocolErrorCode, nt as LoggingLevelSchema, q as isInputRequiredResult, qt as SdkErrorCode, r as normalizeRawShapeSchema, s as validateAndWarnToolName, st as MODERN_WIRE_REVISION, ut as ProtocolError, v as requestStateAccessor, w as inputRequiredRoundsExceededMessage, xt as modernProtocolVersions, yt as isModernProtocolVersion } from "./src-D-y6h4N7.mjs";
2
2
  import { DefaultJsonSchemaValidator } from "@modelcontextprotocol/server/_shims";
3
3
 
4
4
  //#region src/server/completable.ts
@@ -474,6 +474,310 @@ function notificationToServerEvent(method, uri) {
474
474
  }
475
475
  }
476
476
 
477
+ //#endregion
478
+ //#region src/server/middleware/bearerAuth.ts
479
+ function headerQuotedValue(value) {
480
+ return value.replaceAll(/[\\"]/g, String.raw`\$&`).replaceAll(/[^\u0020-\u007E]/g, " ");
481
+ }
482
+ /**
483
+ * Build a `WWW-Authenticate: Bearer …` challenge header value (RFC 6750).
484
+ *
485
+ * The single formatter behind every challenge this package emits — the
486
+ * bearer-auth 401/403 answers and the per-operation scope-challenge 403 — so
487
+ * all challenges from one server agree on parameter order and quoting. Every
488
+ * parameter value is emitted as an HTTP quoted-string with `\` and `"`
489
+ * escaped and non-printable characters replaced.
490
+ */
491
+ function buildWwwAuthenticateHeader(errorCode, description, requiredScopes, resourceMetadataUrl) {
492
+ let header = `Bearer error="${headerQuotedValue(errorCode)}", error_description="${headerQuotedValue(description)}"`;
493
+ if (requiredScopes.length > 0) header += `, scope="${headerQuotedValue(requiredScopes.join(" "))}"`;
494
+ if (resourceMetadataUrl) header += `, resource_metadata="${headerQuotedValue(resourceMetadataUrl)}"`;
495
+ return header;
496
+ }
497
+ /**
498
+ * Validate a raw `Authorization` header value as a Bearer token and return
499
+ * the verified {@link AuthInfo}.
500
+ *
501
+ * The runtime-neutral core of Bearer authentication: it parses the header,
502
+ * runs the verifier, enforces `requiredScopes`, and rejects tokens without an
503
+ * expiration or past it. On any failure it throws an {@link OAuthError} —
504
+ * pass that to {@link bearerAuthChallengeResponse} for the matching HTTP
505
+ * answer, or use {@link requireBearerAuth} to get both steps as one call.
506
+ *
507
+ * Framework adapters build on this: `requireBearerAuth` from
508
+ * `@modelcontextprotocol/express` feeds it `req.headers.authorization`.
509
+ */
510
+ async function verifyBearerToken(authorizationHeader, options) {
511
+ const { verifier, requiredScopes = [] } = options;
512
+ if (!authorizationHeader) throw new OAuthError(OAuthErrorCode.InvalidToken, "Missing Authorization header");
513
+ const [type, token] = authorizationHeader.split(" ");
514
+ if (type?.toLowerCase() !== "bearer" || !token) throw new OAuthError(OAuthErrorCode.InvalidToken, "Invalid Authorization header format, expected 'Bearer TOKEN'");
515
+ const authInfo = await verifier.verifyAccessToken(token);
516
+ if (requiredScopes.length > 0) {
517
+ if (!requiredScopes.every((scope) => authInfo.scopes.includes(scope))) throw new OAuthError(OAuthErrorCode.InsufficientScope, "Insufficient scope");
518
+ }
519
+ if (typeof authInfo.expiresAt !== "number" || Number.isNaN(authInfo.expiresAt)) throw new OAuthError(OAuthErrorCode.InvalidToken, "Token has no expiration time");
520
+ else if (authInfo.expiresAt < Date.now() / 1e3) throw new OAuthError(OAuthErrorCode.InvalidToken, "Token has expired");
521
+ if (options.resourceMetadataUrl !== void 0 && authInfo.resourceMetadataUrl === void 0) return {
522
+ ...authInfo,
523
+ resourceMetadataUrl: options.resourceMetadataUrl
524
+ };
525
+ return authInfo;
526
+ }
527
+ /**
528
+ * Build the HTTP answer for a Bearer authentication failure.
529
+ *
530
+ * Maps an {@link OAuthError} to its status — `401` for `invalid_token` and
531
+ * `403` for `insufficient_scope` (both carrying the `WWW-Authenticate: Bearer …`
532
+ * challenge, with `resource_metadata` when configured so clients can discover
533
+ * the Authorization Server), `500` for `server_error`, `400` for anything
534
+ * else. A non-`OAuthError` value answers `500 server_error`. The body is the
535
+ * OAuth error JSON.
536
+ */
537
+ function bearerAuthChallengeResponse(error, options) {
538
+ const { requiredScopes = [], resourceMetadataUrl } = options ?? {};
539
+ if (!(error instanceof OAuthError)) {
540
+ const serverError = new OAuthError(OAuthErrorCode.ServerError, "Internal Server Error");
541
+ return Response.json(serverError.toResponseObject(), { status: 500 });
542
+ }
543
+ switch (error.code) {
544
+ case OAuthErrorCode.InvalidToken: {
545
+ const challenge = buildWwwAuthenticateHeader(error.code, error.message, requiredScopes, resourceMetadataUrl);
546
+ return Response.json(error.toResponseObject(), {
547
+ status: 401,
548
+ headers: { "WWW-Authenticate": challenge }
549
+ });
550
+ }
551
+ case OAuthErrorCode.InsufficientScope: {
552
+ const challenge = buildWwwAuthenticateHeader(error.code, error.message, requiredScopes, resourceMetadataUrl);
553
+ return Response.json(error.toResponseObject(), {
554
+ status: 403,
555
+ headers: { "WWW-Authenticate": challenge }
556
+ });
557
+ }
558
+ case OAuthErrorCode.ServerError: return Response.json(error.toResponseObject(), { status: 500 });
559
+ default: return Response.json(error.toResponseObject(), { status: 400 });
560
+ }
561
+ }
562
+ /**
563
+ * Require a valid Bearer token on web-standard requests.
564
+ *
565
+ * The framework-free counterpart of `requireBearerAuth` from
566
+ * `@modelcontextprotocol/express`, for hosts whose HTTP surface is a
567
+ * `fetch(request)` handler — Cloudflare Workers, Deno, Bun, Hono. The
568
+ * returned gate resolves to the verified {@link AuthInfo}, or to the
569
+ * ready-to-return challenge `Response` when the request must be refused.
570
+ *
571
+ * @example
572
+ * ```ts source="./bearerAuth.examples.ts#requireBearerAuth_fetchGate"
573
+ * const gate = requireBearerAuth({ verifier, requiredScopes: ['mcp'] });
574
+ *
575
+ * async function fetchHandler(request: Request): Promise<Response> {
576
+ * const auth: AuthInfo | Response = await gate(request);
577
+ * if (auth instanceof Response) return auth;
578
+ * return handler.fetch(request, { authInfo: auth });
579
+ * }
580
+ * ```
581
+ */
582
+ function requireBearerAuth(options) {
583
+ const { verifier, requiredScopes = [], resourceMetadataUrl } = options;
584
+ const resolved = {
585
+ verifier,
586
+ requiredScopes,
587
+ resourceMetadataUrl
588
+ };
589
+ return async (request) => {
590
+ const [authorizationHeader] = (request.headers.get("authorization") ?? "").split(",");
591
+ try {
592
+ return await verifyBearerToken(authorizationHeader || void 0, resolved);
593
+ } catch (error) {
594
+ return bearerAuthChallengeResponse(error, resolved);
595
+ }
596
+ };
597
+ }
598
+
599
+ //#endregion
600
+ //#region src/server/middleware/oauthMetadata.ts
601
+ function checkIssuerUrl(issuer, allowInsecure) {
602
+ if (issuer.protocol !== "https:" && issuer.hostname !== "localhost" && issuer.hostname !== "127.0.0.1" && !allowInsecure) throw new Error("Issuer URL must be HTTPS");
603
+ if (issuer.hash) throw new Error(`Issuer URL must not have a fragment: ${issuer}`);
604
+ if (issuer.search) throw new Error(`Issuer URL must not have a query string: ${issuer}`);
605
+ }
606
+ /**
607
+ * Derive the RFC 9728 Protected Resource Metadata document from
608
+ * {@link AuthMetadataOptions}, validating the Authorization Server issuer URL
609
+ * (HTTPS required outside localhost) in the process.
610
+ *
611
+ * `oauthMetadataResponse` and the Express `mcpAuthMetadataRouter` both build
612
+ * on this; use it directly when serving the document through your own
613
+ * routing — or call it once at startup to fail fast on a misconfigured
614
+ * issuer before any request arrives.
615
+ */
616
+ function buildOAuthProtectedResourceMetadata(options) {
617
+ checkIssuerUrl(new URL(options.oauthMetadata.issuer), options.dangerouslyAllowInsecureIssuerUrl);
618
+ return {
619
+ resource: options.resourceServerUrl.href,
620
+ authorization_servers: [options.oauthMetadata.issuer],
621
+ scopes_supported: options.scopesSupported,
622
+ resource_name: options.resourceName,
623
+ resource_documentation: options.serviceDocumentationUrl?.href
624
+ };
625
+ }
626
+ /**
627
+ * Builds the RFC 9728 Protected Resource Metadata URL for a given MCP server
628
+ * URL by inserting `/.well-known/oauth-protected-resource` ahead of the path.
629
+ *
630
+ * @example
631
+ * ```ts
632
+ * getOAuthProtectedResourceMetadataUrl(new URL('https://api.example.com/mcp'))
633
+ * // → 'https://api.example.com/.well-known/oauth-protected-resource/mcp'
634
+ * ```
635
+ */
636
+ function getOAuthProtectedResourceMetadataUrl(serverUrl) {
637
+ const metadataUrl = new URL(serverUrl);
638
+ metadataUrl.pathname = protectedResourceMetadataPath(serverUrl);
639
+ metadataUrl.hash = "";
640
+ return metadataUrl.href;
641
+ }
642
+ /** The RFC 9728 path-aware well-known path for a resource URL. */
643
+ function protectedResourceMetadataPath(resourceServerUrl) {
644
+ const rsPath = stripTrailingSlash(resourceServerUrl.pathname);
645
+ return `/.well-known/oauth-protected-resource${rsPath === "/" ? "" : rsPath}`;
646
+ }
647
+ function stripTrailingSlash(path) {
648
+ return path.length > 1 && path.endsWith("/") ? path.slice(0, -1) : path;
649
+ }
650
+ const ALLOWED_METHODS = "GET, HEAD, OPTIONS";
651
+ function metadataDocumentResponse(request, metadata) {
652
+ if (request.method === "OPTIONS") {
653
+ const requestedHeaders = request.headers.get("access-control-request-headers");
654
+ return new Response(null, {
655
+ status: 204,
656
+ headers: {
657
+ "Access-Control-Allow-Origin": "*",
658
+ "Access-Control-Allow-Methods": ALLOWED_METHODS,
659
+ ...requestedHeaders === null ? {} : {
660
+ "Access-Control-Allow-Headers": requestedHeaders,
661
+ Vary: "Access-Control-Request-Headers"
662
+ }
663
+ }
664
+ });
665
+ }
666
+ if (request.method !== "GET" && request.method !== "HEAD") {
667
+ const error = new OAuthError(OAuthErrorCode.MethodNotAllowed, `The method ${request.method} is not allowed for this endpoint`);
668
+ return Response.json(error.toResponseObject(), {
669
+ status: 405,
670
+ headers: {
671
+ Allow: ALLOWED_METHODS,
672
+ "Access-Control-Allow-Origin": "*"
673
+ }
674
+ });
675
+ }
676
+ const response = Response.json(metadata, { headers: { "Access-Control-Allow-Origin": "*" } });
677
+ return request.method === "HEAD" ? new Response(null, {
678
+ status: response.status,
679
+ headers: response.headers
680
+ }) : response;
681
+ }
682
+ /**
683
+ * Serve the two OAuth discovery documents an MCP server acting as a Resource
684
+ * Server exposes, from a web-standard `fetch(request)` handler:
685
+ *
686
+ * - `/.well-known/oauth-protected-resource[/<path>]` — RFC 9728 Protected
687
+ * Resource Metadata, derived from the supplied options (path-aware: the
688
+ * resource URL's path is reflected in the route).
689
+ * - `/.well-known/oauth-authorization-server` — RFC 8414 Authorization
690
+ * Server Metadata, passed through verbatim.
691
+ *
692
+ * Returns the matched document `Response` (JSON with permissive CORS, `405`
693
+ * with an `Allow` header for non-GET methods, `204` for CORS preflight), or
694
+ * `undefined` when the request path is neither well-known route — fall
695
+ * through to your own routing. The framework-free counterpart of
696
+ * `mcpAuthMetadataRouter` from `@modelcontextprotocol/express`; pair it with
697
+ * `requireBearerAuth` and `getOAuthProtectedResourceMetadataUrl` so
698
+ * unauthenticated clients can discover the AS from the `401` challenge.
699
+ *
700
+ * @example
701
+ * ```ts source="./oauthMetadata.examples.ts#oauthMetadataResponse_fetchHandler"
702
+ * async function fetchHandler(request: Request): Promise<Response> {
703
+ * return oauthMetadataResponse(request, options) ?? serveMcp(request);
704
+ * }
705
+ * ```
706
+ */
707
+ function oauthMetadataResponse(request, options) {
708
+ const requestPath = stripTrailingSlash(new URL(request.url).pathname);
709
+ if (requestPath === protectedResourceMetadataPath(options.resourceServerUrl)) return metadataDocumentResponse(request, buildOAuthProtectedResourceMetadata(options));
710
+ if (requestPath === "/.well-known/oauth-authorization-server") {
711
+ buildOAuthProtectedResourceMetadata(options);
712
+ return metadataDocumentResponse(request, options.oauthMetadata);
713
+ }
714
+ }
715
+
716
+ //#endregion
717
+ //#region src/server/scopeChallenge.ts
718
+ /** @internal */
719
+ function supportsScopeChallengeResolver(transport) {
720
+ return typeof transport === "object" && transport !== null && "setScopeChallengeResolver" in transport && typeof transport.setScopeChallengeResolver === "function";
721
+ }
722
+ function assertScope(scope, location) {
723
+ if (typeof scope !== "string" || !/^[\u0021\u0023-\u005B\u005D-\u007E]+$/.test(scope)) throw new TypeError(`${location} must satisfy the OAuth scope-token grammar`);
724
+ }
725
+ function validateScopeChallenge(challenge) {
726
+ if (challenge === null || typeof challenge !== "object" || !Array.isArray(challenge.scopes) || challenge.scopes.length === 0) throw new TypeError("scope challenge must contain at least one scope");
727
+ for (const [index, scope] of challenge.scopes.entries()) assertScope(scope, `scope challenge scopes[${index}]`);
728
+ if (challenge.errorDescription !== void 0 && typeof challenge.errorDescription !== "string") throw new TypeError("scope challenge errorDescription must be a string");
729
+ if (challenge.errorDescription !== void 0 && !/^[\u0020-\u0021\u0023-\u005B\u005D-\u007E]+$/.test(challenge.errorDescription)) throw new TypeError("scope challenge errorDescription must satisfy the RFC 6750 error-description grammar");
730
+ return challenge;
731
+ }
732
+ /**
733
+ * Creates a handler that requires every supplied scope exactly.
734
+ *
735
+ * Requests without authentication are left to the server's authentication gate.
736
+ */
737
+ function requireScopes(...scopes) {
738
+ if (scopes.length === 0) throw new TypeError("requireScopes must contain at least one scope");
739
+ for (const [index, scope] of scopes.entries()) assertScope(scope, `requireScopes scope[${index}]`);
740
+ const requiredScopes = [...scopes];
741
+ return ({ authInfo }) => {
742
+ if (authInfo === void 0) return;
743
+ const activeScopes = new Set(authInfo.scopes);
744
+ if (requiredScopes.every((scope) => activeScopes.has(scope))) return;
745
+ return { scopes: requiredScopes };
746
+ };
747
+ }
748
+ /** @internal */
749
+ async function findScopeChallenge(requests, authInfo, resolve) {
750
+ for (const request of requests) {
751
+ const challenge = await resolve({
752
+ request,
753
+ ...authInfo !== void 0 && { authInfo }
754
+ });
755
+ if (challenge !== void 0) return validateScopeChallenge(challenge);
756
+ }
757
+ }
758
+ /**
759
+ * The RFC 9728 Protected Resource Metadata URL to advertise on a scope
760
+ * challenge, derived from the verified {@link AuthInfo}: the URL the
761
+ * authentication gate stamped (`authInfo.resourceMetadataUrl`, set by the
762
+ * bearer-auth helpers from their `resourceMetadataUrl` option), falling back
763
+ * to the well-known location for an HTTP(S) RFC 8707 `resource` identifier, or
764
+ * `undefined` when neither is available (the `resource_metadata` parameter is
765
+ * then omitted, matching the bearer-auth challenges).
766
+ *
767
+ * @internal
768
+ */
769
+ function scopeChallengeResourceMetadataUrl(authInfo) {
770
+ if (authInfo?.resourceMetadataUrl !== void 0) return authInfo.resourceMetadataUrl;
771
+ if (authInfo?.resource?.protocol === "https:" || authInfo?.resource?.protocol === "http:") return getOAuthProtectedResourceMetadataUrl(authInfo.resource);
772
+ }
773
+ /** @internal */
774
+ function createScopeChallengeResponse(challenge, resourceMetadataUrl) {
775
+ return bearerAuthChallengeResponse(new OAuthError(OAuthErrorCode.InsufficientScope, challenge.errorDescription ?? "Insufficient scope"), {
776
+ requiredScopes: [...challenge.scopes],
777
+ resourceMetadataUrl
778
+ });
779
+ }
780
+
477
781
  //#endregion
478
782
  //#region src/server/legacyInputRequiredShim.ts
479
783
  /**
@@ -1363,6 +1667,7 @@ var McpServer = class {
1363
1667
  * ```
1364
1668
  */
1365
1669
  async connect(transport) {
1670
+ if (supportsScopeChallengeResolver(transport)) transport.setScopeChallengeResolver((context) => this.resolveScopeChallenge(context));
1366
1671
  return await this.server.connect(transport);
1367
1672
  }
1368
1673
  /**
@@ -1371,6 +1676,40 @@ var McpServer = class {
1371
1676
  async close() {
1372
1677
  await this.server.close();
1373
1678
  }
1679
+ /** @internal */
1680
+ resolveScopeChallenge = (context) => {
1681
+ switch (context.request.method) {
1682
+ case "tools/call": {
1683
+ const toolName = context.request.params?.name;
1684
+ if (typeof toolName !== "string") return;
1685
+ const tool = this._registeredTools[toolName];
1686
+ if (tool === void 0 || !tool.enabled) return;
1687
+ return tool.scopeChallenge?.(context);
1688
+ }
1689
+ case "resources/read": {
1690
+ const resourceUri = context.request.params?.uri;
1691
+ if (typeof resourceUri !== "string") return;
1692
+ let uri;
1693
+ try {
1694
+ uri = new URL(resourceUri);
1695
+ } catch {
1696
+ return;
1697
+ }
1698
+ const resource = this._registeredResources[uri.toString()];
1699
+ if (resource !== void 0) return resource.enabled ? resource.scopeChallenge?.(context) : void 0;
1700
+ for (const template of Object.values(this._registeredResourceTemplates)) if (template.resourceTemplate.uriTemplate.match(uri.toString())) return template.enabled ? template.scopeChallenge?.(context) : void 0;
1701
+ return;
1702
+ }
1703
+ case "prompts/get": {
1704
+ const promptName = context.request.params?.name;
1705
+ if (typeof promptName !== "string") return;
1706
+ const prompt = this._registeredPrompts[promptName];
1707
+ if (prompt === void 0 || !prompt.enabled) return;
1708
+ return prompt.scopeChallenge?.(context);
1709
+ }
1710
+ default: return;
1711
+ }
1712
+ };
1374
1713
  _toolHandlersInitialized = false;
1375
1714
  setToolRequestHandlers() {
1376
1715
  if (this._toolHandlersInitialized) return;
@@ -1536,7 +1875,10 @@ var McpServer = class {
1536
1875
  }
1537
1876
  for (const template of Object.values(this._registeredResourceTemplates)) {
1538
1877
  const variables = template.resourceTemplate.uriTemplate.match(uri.toString());
1539
- if (variables) return attachCacheHintFallback(await template.readCallback(uri, variables, ctx), template.cacheHint);
1878
+ if (variables) {
1879
+ if (!template.enabled) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Resource template ${template.resourceTemplate.uriTemplate} disabled`);
1880
+ return attachCacheHintFallback(await template.readCallback(uri, variables, ctx), template.cacheHint);
1881
+ }
1540
1882
  }
1541
1883
  throw new ResourceNotFoundError(request.params.uri);
1542
1884
  });
@@ -1567,36 +1909,32 @@ var McpServer = class {
1567
1909
  this._promptHandlersInitialized = true;
1568
1910
  }
1569
1911
  registerResource(name, uriOrTemplate, config, readCallback) {
1570
- const cacheHint = config.cacheHint;
1571
- let metadata = config;
1572
- if (cacheHint !== void 0) {
1573
- assertValidCacheHint(cacheHint, `resource ${name}`);
1574
- const rest = { ...config };
1575
- delete rest.cacheHint;
1576
- metadata = rest;
1577
- }
1912
+ const { cacheHint, scopeChallenge, ...resourceMetadata } = config;
1913
+ const metadata = resourceMetadata;
1914
+ if (cacheHint !== void 0) assertValidCacheHint(cacheHint, `resource ${name}`);
1578
1915
  if (typeof uriOrTemplate === "string") {
1579
1916
  if (this._registeredResources[uriOrTemplate]) throw new Error(`Resource ${uriOrTemplate} is already registered`);
1580
- const registeredResource = this._createRegisteredResource(name, config.title, uriOrTemplate, metadata, readCallback);
1917
+ const registeredResource = this._createRegisteredResource(name, config.title, uriOrTemplate, metadata, scopeChallenge, readCallback);
1581
1918
  if (cacheHint !== void 0) registeredResource.cacheHint = cacheHint;
1582
1919
  this.setResourceRequestHandlers();
1583
1920
  this.sendResourceListChanged();
1584
1921
  return registeredResource;
1585
1922
  } else {
1586
1923
  if (this._registeredResourceTemplates[name]) throw new Error(`Resource template ${name} is already registered`);
1587
- const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, config.title, uriOrTemplate, metadata, readCallback);
1924
+ const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, config.title, uriOrTemplate, metadata, scopeChallenge, readCallback);
1588
1925
  if (cacheHint !== void 0) registeredResourceTemplate.cacheHint = cacheHint;
1589
1926
  this.setResourceRequestHandlers();
1590
1927
  this.sendResourceListChanged();
1591
1928
  return registeredResourceTemplate;
1592
1929
  }
1593
1930
  }
1594
- _createRegisteredResource(name, title, uri, metadata, readCallback) {
1931
+ _createRegisteredResource(name, title, uri, metadata, scopeChallenge, readCallback) {
1595
1932
  const registeredResource = {
1596
1933
  name,
1597
1934
  title,
1598
1935
  metadata,
1599
1936
  readCallback,
1937
+ scopeChallenge,
1600
1938
  enabled: true,
1601
1939
  disable: () => registeredResource.update({ enabled: false }),
1602
1940
  enable: () => registeredResource.update({ enabled: true }),
@@ -1610,6 +1948,7 @@ var McpServer = class {
1610
1948
  if (updates.title !== void 0) registeredResource.title = updates.title;
1611
1949
  if (updates.metadata !== void 0) registeredResource.metadata = updates.metadata;
1612
1950
  if (updates.callback !== void 0) registeredResource.readCallback = updates.callback;
1951
+ if (updates.scopeChallenge !== void 0) registeredResource.scopeChallenge = updates.scopeChallenge === null ? void 0 : updates.scopeChallenge;
1613
1952
  if (updates.enabled !== void 0) registeredResource.enabled = updates.enabled;
1614
1953
  this.sendResourceListChanged();
1615
1954
  }
@@ -1617,12 +1956,13 @@ var McpServer = class {
1617
1956
  this._registeredResources[uri] = registeredResource;
1618
1957
  return registeredResource;
1619
1958
  }
1620
- _createRegisteredResourceTemplate(name, title, template, metadata, readCallback) {
1959
+ _createRegisteredResourceTemplate(name, title, template, metadata, scopeChallenge, readCallback) {
1621
1960
  const registeredResourceTemplate = {
1622
1961
  resourceTemplate: template,
1623
1962
  title,
1624
1963
  metadata,
1625
1964
  readCallback,
1965
+ scopeChallenge,
1626
1966
  enabled: true,
1627
1967
  disable: () => registeredResourceTemplate.update({ enabled: false }),
1628
1968
  enable: () => registeredResourceTemplate.update({ enabled: true }),
@@ -1636,6 +1976,7 @@ var McpServer = class {
1636
1976
  if (updates.template !== void 0) registeredResourceTemplate.resourceTemplate = updates.template;
1637
1977
  if (updates.metadata !== void 0) registeredResourceTemplate.metadata = updates.metadata;
1638
1978
  if (updates.callback !== void 0) registeredResourceTemplate.readCallback = updates.callback;
1979
+ if (updates.scopeChallenge !== void 0) registeredResourceTemplate.scopeChallenge = updates.scopeChallenge === null ? void 0 : updates.scopeChallenge;
1639
1980
  if (updates.enabled !== void 0) registeredResourceTemplate.enabled = updates.enabled;
1640
1981
  this.sendResourceListChanged();
1641
1982
  }
@@ -1645,7 +1986,7 @@ var McpServer = class {
1645
1986
  if (Array.isArray(variableNames) && variableNames.some((v) => !!template.completeCallback(v))) this.setCompletionRequestHandler();
1646
1987
  return registeredResourceTemplate;
1647
1988
  }
1648
- _createRegisteredPrompt(name, title, description, argsSchema, callback, icons, _meta) {
1989
+ _createRegisteredPrompt(name, title, description, argsSchema, callback, icons, scopeChallenge, _meta) {
1649
1990
  let currentArgsSchema = argsSchema;
1650
1991
  let currentCallback = callback;
1651
1992
  const registeredPrompt = {
@@ -1653,6 +1994,7 @@ var McpServer = class {
1653
1994
  description,
1654
1995
  argsSchema,
1655
1996
  icons,
1997
+ scopeChallenge,
1656
1998
  _meta,
1657
1999
  handler: createPromptHandler(name, argsSchema, callback),
1658
2000
  enabled: true,
@@ -1667,6 +2009,7 @@ var McpServer = class {
1667
2009
  if (updates.title !== void 0) registeredPrompt.title = updates.title;
1668
2010
  if (updates.description !== void 0) registeredPrompt.description = updates.description;
1669
2011
  if (updates.icons !== void 0) registeredPrompt.icons = updates.icons;
2012
+ if (updates.scopeChallenge !== void 0) registeredPrompt.scopeChallenge = updates.scopeChallenge === null ? void 0 : updates.scopeChallenge;
1670
2013
  if (updates._meta !== void 0) registeredPrompt._meta = updates._meta;
1671
2014
  let needsHandlerRegen = false;
1672
2015
  if (updates.argsSchema !== void 0) {
@@ -1694,7 +2037,7 @@ var McpServer = class {
1694
2037
  }
1695
2038
  return registeredPrompt;
1696
2039
  }
1697
- _createRegisteredTool(name, title, description, inputSchema, outputSchema, annotations, icons, execution, _meta, handler) {
2040
+ _createRegisteredTool(name, title, description, inputSchema, outputSchema, annotations, icons, execution, scopeChallenge, _meta, handler) {
1698
2041
  validateAndWarnToolName(name);
1699
2042
  if (inputSchema !== void 0) try {
1700
2043
  const json = standardSchemaToJsonSchema(inputSchema, "input");
@@ -1712,6 +2055,7 @@ var McpServer = class {
1712
2055
  annotations,
1713
2056
  icons,
1714
2057
  execution,
2058
+ scopeChallenge,
1715
2059
  _meta,
1716
2060
  handler,
1717
2061
  executor: createToolExecutor(inputSchema, handler),
@@ -1750,6 +2094,7 @@ var McpServer = class {
1750
2094
  }
1751
2095
  if (updates.annotations !== void 0) registeredTool.annotations = updates.annotations;
1752
2096
  if (updates.icons !== void 0) registeredTool.icons = updates.icons;
2097
+ if (updates.scopeChallenge !== void 0) registeredTool.scopeChallenge = updates.scopeChallenge === null ? void 0 : updates.scopeChallenge;
1753
2098
  if (updates._meta !== void 0) registeredTool._meta = updates._meta;
1754
2099
  if (updates.enabled !== void 0) registeredTool.enabled = updates.enabled;
1755
2100
  this.sendToolListChanged();
@@ -1762,13 +2107,13 @@ var McpServer = class {
1762
2107
  }
1763
2108
  registerTool(name, config, cb) {
1764
2109
  if (this._registeredTools[name]) throw new Error(`Tool ${name} is already registered`);
1765
- const { title, description, inputSchema, outputSchema, annotations, icons, _meta } = config;
1766
- return this._createRegisteredTool(name, title, description, normalizeRawShapeSchema(inputSchema), normalizeRawShapeSchema(outputSchema), annotations, icons, void 0, _meta, cb);
2110
+ const { title, description, inputSchema, outputSchema, annotations, icons, scopeChallenge, _meta } = config;
2111
+ return this._createRegisteredTool(name, title, description, normalizeRawShapeSchema(inputSchema), normalizeRawShapeSchema(outputSchema), annotations, icons, void 0, scopeChallenge, _meta, cb);
1767
2112
  }
1768
2113
  registerPrompt(name, config, cb) {
1769
2114
  if (this._registeredPrompts[name]) throw new Error(`Prompt ${name} is already registered`);
1770
- const { title, description, argsSchema, icons, _meta } = config;
1771
- const registeredPrompt = this._createRegisteredPrompt(name, title, description, normalizeRawShapeSchema(argsSchema), cb, icons, _meta);
2115
+ const { title, description, argsSchema, icons, scopeChallenge, _meta } = config;
2116
+ const registeredPrompt = this._createRegisteredPrompt(name, title, description, normalizeRawShapeSchema(argsSchema), cb, icons, scopeChallenge, _meta);
1772
2117
  this.setPromptRequestHandlers();
1773
2118
  this.sendPromptListChanged();
1774
2119
  return registeredPrompt;
@@ -1927,5 +2272,5 @@ function unwrapOptionalSchema(schema) {
1927
2272
  }
1928
2273
 
1929
2274
  //#endregion
1930
- export { seedClientIdentityFromEnvelope as a, StdioListenRouter as c, createServerNotifier as d, DEFAULT_SSE_KEEP_ALIVE_MS as f, isCompletable as h, installModernOnlyHandlers as i, createListenRouter as l, completable as m, ResourceTemplate as n, serverIdentityOf as o, armSseKeepAlive as p, Server as r, DEFAULT_MAX_SUBSCRIPTIONS as s, McpServer as t, InMemoryServerEventBus as u };
1931
- //# sourceMappingURL=mcp-DXXb3Vv3.mjs.map
2275
+ export { armSseKeepAlive as C, DEFAULT_SSE_KEEP_ALIVE_MS as S, isCompletable as T, DEFAULT_MAX_SUBSCRIPTIONS as _, seedClientIdentityFromEnvelope as a, InMemoryServerEventBus as b, findScopeChallenge as c, buildOAuthProtectedResourceMetadata as d, getOAuthProtectedResourceMetadataUrl as f, verifyBearerToken as g, requireBearerAuth as h, installModernOnlyHandlers as i, requireScopes as l, bearerAuthChallengeResponse as m, ResourceTemplate as n, serverIdentityOf as o, oauthMetadataResponse as p, Server as r, createScopeChallengeResponse as s, McpServer as t, scopeChallengeResourceMetadataUrl as u, StdioListenRouter as v, completable as w, createServerNotifier as x, createListenRouter as y };
2276
+ //# sourceMappingURL=mcp-Dw2OlZ1f.mjs.map