@mcp-z/client 2.2.3 → 2.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 (111) hide show
  1. package/README.md +12 -1
  2. package/dist/cjs/auth/capability-discovery.d.cts +3 -1
  3. package/dist/cjs/auth/capability-discovery.d.ts +3 -1
  4. package/dist/cjs/auth/capability-discovery.js +46 -32
  5. package/dist/cjs/auth/capability-discovery.js.map +1 -1
  6. package/dist/cjs/auth/discovery-fetch.d.cts +2 -0
  7. package/dist/cjs/auth/discovery-fetch.d.ts +2 -0
  8. package/dist/cjs/auth/discovery-fetch.js +85 -31
  9. package/dist/cjs/auth/discovery-fetch.js.map +1 -1
  10. package/dist/cjs/auth/interactive-oauth-flow.d.cts +1 -1
  11. package/dist/cjs/auth/interactive-oauth-flow.d.ts +1 -1
  12. package/dist/cjs/auth/interactive-oauth-flow.js +13 -6
  13. package/dist/cjs/auth/interactive-oauth-flow.js.map +1 -1
  14. package/dist/cjs/auth/oauth-callback-listener.d.cts +1 -1
  15. package/dist/cjs/auth/oauth-callback-listener.d.ts +1 -1
  16. package/dist/cjs/auth/oauth-callback-listener.js +40 -4
  17. package/dist/cjs/auth/oauth-callback-listener.js.map +1 -1
  18. package/dist/cjs/auth/rfc9728-discovery.d.cts +7 -2
  19. package/dist/cjs/auth/rfc9728-discovery.d.ts +7 -2
  20. package/dist/cjs/auth/rfc9728-discovery.js +120 -88
  21. package/dist/cjs/auth/rfc9728-discovery.js.map +1 -1
  22. package/dist/cjs/auth/types.d.cts +4 -0
  23. package/dist/cjs/auth/types.d.ts +4 -0
  24. package/dist/cjs/auth/types.js.map +1 -1
  25. package/dist/cjs/connection/connect-client.d.cts +9 -1
  26. package/dist/cjs/connection/connect-client.d.ts +9 -1
  27. package/dist/cjs/connection/connect-client.js +282 -75
  28. package/dist/cjs/connection/connect-client.js.map +1 -1
  29. package/dist/cjs/connection/existing-process-transport.d.cts +18 -18
  30. package/dist/cjs/connection/existing-process-transport.d.ts +18 -18
  31. package/dist/cjs/connection/existing-process-transport.js +187 -82
  32. package/dist/cjs/connection/existing-process-transport.js.map +1 -1
  33. package/dist/cjs/connection/wait-for-http-ready.d.cts +1 -1
  34. package/dist/cjs/connection/wait-for-http-ready.d.ts +1 -1
  35. package/dist/cjs/connection/wait-for-http-ready.js +30 -5
  36. package/dist/cjs/connection/wait-for-http-ready.js.map +1 -1
  37. package/dist/cjs/dcr/dcr-authenticator.d.cts +1 -1
  38. package/dist/cjs/dcr/dcr-authenticator.d.ts +1 -1
  39. package/dist/cjs/dcr/dcr-authenticator.js +29 -18
  40. package/dist/cjs/dcr/dcr-authenticator.js.map +1 -1
  41. package/dist/cjs/dcr/dynamic-client-registrar.js +2 -1
  42. package/dist/cjs/dcr/dynamic-client-registrar.js.map +1 -1
  43. package/dist/cjs/index.d.cts +1 -1
  44. package/dist/cjs/index.d.ts +1 -1
  45. package/dist/cjs/index.js.map +1 -1
  46. package/dist/cjs/spawn/owned-process-tree.d.cts +12 -0
  47. package/dist/cjs/spawn/owned-process-tree.d.ts +12 -0
  48. package/dist/cjs/spawn/owned-process-tree.js +93 -0
  49. package/dist/cjs/spawn/owned-process-tree.js.map +1 -0
  50. package/dist/cjs/spawn/spawn-server.d.cts +8 -32
  51. package/dist/cjs/spawn/spawn-server.d.ts +8 -32
  52. package/dist/cjs/spawn/spawn-server.js +406 -97
  53. package/dist/cjs/spawn/spawn-server.js.map +1 -1
  54. package/dist/cjs/spawn/spawn-servers.d.cts +18 -8
  55. package/dist/cjs/spawn/spawn-servers.d.ts +18 -8
  56. package/dist/cjs/spawn/spawn-servers.js +342 -113
  57. package/dist/cjs/spawn/spawn-servers.js.map +1 -1
  58. package/dist/cjs/types.d.cts +1 -1
  59. package/dist/cjs/types.d.ts +1 -1
  60. package/dist/cjs/types.js.map +1 -1
  61. package/dist/cjs/utils/path-utils.js +7 -4
  62. package/dist/cjs/utils/path-utils.js.map +1 -1
  63. package/dist/esm/auth/capability-discovery.d.ts +3 -1
  64. package/dist/esm/auth/capability-discovery.js +21 -11
  65. package/dist/esm/auth/capability-discovery.js.map +1 -1
  66. package/dist/esm/auth/discovery-fetch.d.ts +2 -0
  67. package/dist/esm/auth/discovery-fetch.js +64 -23
  68. package/dist/esm/auth/discovery-fetch.js.map +1 -1
  69. package/dist/esm/auth/interactive-oauth-flow.d.ts +1 -1
  70. package/dist/esm/auth/interactive-oauth-flow.js +13 -6
  71. package/dist/esm/auth/interactive-oauth-flow.js.map +1 -1
  72. package/dist/esm/auth/oauth-callback-listener.d.ts +1 -1
  73. package/dist/esm/auth/oauth-callback-listener.js +34 -4
  74. package/dist/esm/auth/oauth-callback-listener.js.map +1 -1
  75. package/dist/esm/auth/rfc9728-discovery.d.ts +7 -2
  76. package/dist/esm/auth/rfc9728-discovery.js +40 -16
  77. package/dist/esm/auth/rfc9728-discovery.js.map +1 -1
  78. package/dist/esm/auth/types.d.ts +4 -0
  79. package/dist/esm/auth/types.js.map +1 -1
  80. package/dist/esm/connection/connect-client.d.ts +9 -1
  81. package/dist/esm/connection/connect-client.js +97 -35
  82. package/dist/esm/connection/connect-client.js.map +1 -1
  83. package/dist/esm/connection/existing-process-transport.d.ts +18 -18
  84. package/dist/esm/connection/existing-process-transport.js +132 -70
  85. package/dist/esm/connection/existing-process-transport.js.map +1 -1
  86. package/dist/esm/connection/wait-for-http-ready.d.ts +1 -1
  87. package/dist/esm/connection/wait-for-http-ready.js +19 -4
  88. package/dist/esm/connection/wait-for-http-ready.js.map +1 -1
  89. package/dist/esm/dcr/dcr-authenticator.d.ts +1 -1
  90. package/dist/esm/dcr/dcr-authenticator.js +26 -15
  91. package/dist/esm/dcr/dcr-authenticator.js.map +1 -1
  92. package/dist/esm/dcr/dynamic-client-registrar.js +2 -1
  93. package/dist/esm/dcr/dynamic-client-registrar.js.map +1 -1
  94. package/dist/esm/index.d.ts +1 -1
  95. package/dist/esm/index.js.map +1 -1
  96. package/dist/esm/spawn/owned-process-tree.d.ts +12 -0
  97. package/dist/esm/spawn/owned-process-tree.js +39 -0
  98. package/dist/esm/spawn/owned-process-tree.js.map +1 -0
  99. package/dist/esm/spawn/spawn-server.d.ts +8 -32
  100. package/dist/esm/spawn/spawn-server.js +228 -99
  101. package/dist/esm/spawn/spawn-server.js.map +1 -1
  102. package/dist/esm/spawn/spawn-servers.d.ts +18 -8
  103. package/dist/esm/spawn/spawn-servers.js +180 -55
  104. package/dist/esm/spawn/spawn-servers.js.map +1 -1
  105. package/dist/esm/types.d.ts +1 -1
  106. package/dist/esm/types.js.map +1 -1
  107. package/dist/esm/utils/path-utils.js +7 -4
  108. package/dist/esm/utils/path-utils.js.map +1 -1
  109. package/package.json +8 -3
  110. package/schemas/servers.d.ts +24 -0
  111. package/schemas/servers.schema.json +31 -0
@@ -46,6 +46,12 @@ function _async_to_generator(fn) {
46
46
  });
47
47
  };
48
48
  }
49
+ function _instanceof(left, right) {
50
+ "@swc/helpers - instanceof";
51
+ if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
52
+ return !!right[Symbol.hasInstance](left);
53
+ } else return left instanceof right;
54
+ }
49
55
  function _ts_generator(thisArg, body) {
50
56
  var f, y, t, _ = {
51
57
  label: 0,
@@ -146,7 +152,7 @@ function _ts_generator(thisArg, body) {
146
152
  }
147
153
  }
148
154
  function waitForHttpReady(url) {
149
- var timeoutMs = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 30000;
155
+ var timeoutMs = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 30000, signal = arguments.length > 2 ? arguments[2] : void 0;
150
156
  return _async_to_generator(function() {
151
157
  var start, maxRetries, i, response, _error, elapsed;
152
158
  return _ts_generator(this, function(_state) {
@@ -161,6 +167,7 @@ function waitForHttpReady(url) {
161
167
  3,
162
168
  8
163
169
  ];
170
+ throwIfAborted(signal);
164
171
  _state.label = 2;
165
172
  case 2:
166
173
  _state.trys.push([
@@ -171,13 +178,13 @@ function waitForHttpReady(url) {
171
178
  ]);
172
179
  return [
173
180
  4,
174
- fetch(url, {
181
+ awaitWithSignal(fetch(url, {
175
182
  method: 'HEAD',
176
183
  headers: {
177
184
  Connection: 'close'
178
185
  },
179
186
  signal: AbortSignal.timeout(500)
180
- })
187
+ }), signal)
181
188
  ];
182
189
  case 3:
183
190
  response = _state.sent();
@@ -207,9 +214,9 @@ function waitForHttpReady(url) {
207
214
  // Wait before retry
208
215
  return [
209
216
  4,
210
- new Promise(function(resolve) {
217
+ awaitWithSignal(new Promise(function(resolve) {
211
218
  return setTimeout(resolve, 100);
212
- })
219
+ }), signal)
213
220
  ];
214
221
  case 6:
215
222
  _state.sent();
@@ -226,4 +233,22 @@ function waitForHttpReady(url) {
226
233
  });
227
234
  })();
228
235
  }
236
+ function throwIfAborted(signal) {
237
+ if (signal === null || signal === void 0 ? void 0 : signal.aborted) throw _instanceof(signal.reason, Error) ? signal.reason : new Error('HTTP readiness check was cancelled');
238
+ }
239
+ function awaitWithSignal(promise, signal) {
240
+ if (!signal) return promise;
241
+ if (signal.aborted) return Promise.reject(_instanceof(signal.reason, Error) ? signal.reason : new Error('HTTP readiness check was cancelled'));
242
+ return new Promise(function(resolve, reject) {
243
+ var onAbort = function onAbort() {
244
+ return reject(_instanceof(signal.reason, Error) ? signal.reason : new Error('HTTP readiness check was cancelled'));
245
+ };
246
+ signal.addEventListener('abort', onAbort, {
247
+ once: true
248
+ });
249
+ promise.then(resolve, reject).finally(function() {
250
+ return signal.removeEventListener('abort', onAbort);
251
+ });
252
+ });
253
+ }
229
254
  /* CJS INTEROP */ if (exports.__esModule && exports.default) { try { Object.defineProperty(exports.default, '__esModule', { value: true }); for (var key in exports) { exports.default[key] = exports[key]; } } catch (_) {}; module.exports = exports.default; }
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/client/src/connection/wait-for-http-ready.ts"],"sourcesContent":["/**\n * wait-for-http-ready.ts\n *\n * Utility for waiting for HTTP servers to become ready.\n */\n\n/**\n * Wait for HTTP server to be ready by checking endpoint accessibility.\n * Used to handle HTTP servers that need time to start listening.\n *\n * @param url - URL to check for server readiness\n * @param timeoutMs - Maximum time to wait in milliseconds (default: 30000)\n * @returns Promise that resolves when server is ready\n * @throws Error if server doesn't become ready within timeout\n */\nexport async function waitForHttpReady(url: string, timeoutMs = 30000): Promise<void> {\n const start = Date.now();\n const maxRetries = Math.ceil(timeoutMs / 100); // Check every 100ms\n\n for (let i = 0; i < maxRetries; i++) {\n try {\n // Use HEAD request to check server is responding\n const response = await fetch(url, {\n method: 'HEAD',\n headers: { Connection: 'close' },\n signal: AbortSignal.timeout(500), // 500ms per attempt\n });\n\n // Server is responding if we get any HTTP status\n if (response.status >= 200 && response.status < 500) {\n return;\n }\n\n // Server error (5xx) - keep trying as it might still be starting\n } catch (_error) {\n // Connection refused, timeout, or network error\n // Server not ready yet, continue polling\n if (i === maxRetries - 1) {\n const elapsed = Date.now() - start;\n throw new Error(`HTTP server ${url} not ready after ${elapsed}ms`);\n }\n }\n\n // Wait before retry\n await new Promise((resolve) => setTimeout(resolve, 100));\n }\n\n throw new Error(`HTTP server ${url} not ready after ${timeoutMs}ms`);\n}\n"],"names":["waitForHttpReady","url","timeoutMs","start","maxRetries","i","response","_error","elapsed","Date","now","Math","ceil","fetch","method","headers","Connection","signal","AbortSignal","timeout","status","Error","Promise","resolve","setTimeout"],"mappings":"AAAA;;;;CAIC,GAED;;;;;;;;CAQC;;;;+BACqBA;;;eAAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAf,SAAeA,iBAAiBC,GAAW;QAAEC,YAAAA,iEAAY;;YACxDC,OACAC,YAEGC,GAGCC,UAYCC,QAICC;;;;oBAtBNL,QAAQM,KAAKC,GAAG;oBAChBN,aAAaO,KAAKC,IAAI,CAACV,YAAY,MAAM,oBAAoB;oBAE1DG,IAAI;;;yBAAGA,CAAAA,IAAID,UAAS;;;;;;;;;;;;oBAGR;;wBAAMS,MAAMZ,KAAK;4BAChCa,QAAQ;4BACRC,SAAS;gCAAEC,YAAY;4BAAQ;4BAC/BC,QAAQC,YAAYC,OAAO,CAAC;wBAC9B;;;oBAJMb,WAAW;oBAMjB,iDAAiD;oBACjD,IAAIA,SAASc,MAAM,IAAI,OAAOd,SAASc,MAAM,GAAG,KAAK;wBACnD;;;oBACF;;;;;;oBAGOb;oBACP,gDAAgD;oBAChD,yCAAyC;oBACzC,IAAIF,MAAMD,aAAa,GAAG;wBAClBI,UAAUC,KAAKC,GAAG,KAAKP;wBAC7B,MAAM,IAAIkB,MAAM,AAAC,eAAqCb,OAAvBP,KAAI,qBAA2B,OAARO,SAAQ;oBAChE;;;;;;oBAGF,oBAAoB;oBACpB;;wBAAM,IAAIc,QAAQ,SAACC;mCAAYC,WAAWD,SAAS;;;;oBAAnD;;;oBAzB8BlB;;;;;;oBA4BhC,MAAM,IAAIgB,MAAM,AAAC,eAAqCnB,OAAvBD,KAAI,qBAA6B,OAAVC,WAAU;;;IAClE"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/client/src/connection/wait-for-http-ready.ts"],"sourcesContent":["/**\n * wait-for-http-ready.ts\n *\n * Utility for waiting for HTTP servers to become ready.\n */\n\n/**\n * Wait for HTTP server to be ready by checking endpoint accessibility.\n * Used to handle HTTP servers that need time to start listening.\n *\n * @param url - URL to check for server readiness\n * @param timeoutMs - Maximum time to wait in milliseconds (default: 30000)\n * @returns Promise that resolves when server is ready\n * @throws Error if server doesn't become ready within timeout\n */\nexport async function waitForHttpReady(url: string, timeoutMs = 30000, signal?: AbortSignal): Promise<void> {\n const start = Date.now();\n const maxRetries = Math.ceil(timeoutMs / 100); // Check every 100ms\n\n for (let i = 0; i < maxRetries; i++) {\n throwIfAborted(signal);\n try {\n // Use HEAD request to check server is responding\n const response = await awaitWithSignal(\n fetch(url, {\n method: 'HEAD',\n headers: { Connection: 'close' },\n signal: AbortSignal.timeout(500), // 500ms per attempt\n }),\n signal\n );\n\n // Server is responding if we get any HTTP status\n if (response.status >= 200 && response.status < 500) {\n return;\n }\n\n // Server error (5xx) - keep trying as it might still be starting\n } catch (_error) {\n // Connection refused, timeout, or network error\n // Server not ready yet, continue polling\n if (i === maxRetries - 1) {\n const elapsed = Date.now() - start;\n throw new Error(`HTTP server ${url} not ready after ${elapsed}ms`);\n }\n }\n\n // Wait before retry\n await awaitWithSignal(new Promise<void>((resolve) => setTimeout(resolve, 100)), signal);\n }\n\n throw new Error(`HTTP server ${url} not ready after ${timeoutMs}ms`);\n}\n\nfunction throwIfAborted(signal?: AbortSignal): void {\n if (signal?.aborted) throw signal.reason instanceof Error ? signal.reason : new Error('HTTP readiness check was cancelled');\n}\n\nfunction awaitWithSignal<T>(promise: Promise<T>, signal?: AbortSignal): Promise<T> {\n if (!signal) return promise;\n if (signal.aborted) return Promise.reject(signal.reason instanceof Error ? signal.reason : new Error('HTTP readiness check was cancelled'));\n return new Promise<T>((resolve, reject) => {\n const onAbort = () => reject(signal.reason instanceof Error ? signal.reason : new Error('HTTP readiness check was cancelled'));\n signal.addEventListener('abort', onAbort, { once: true });\n promise.then(resolve, reject).finally(() => signal.removeEventListener('abort', onAbort));\n });\n}\n"],"names":["waitForHttpReady","url","timeoutMs","signal","start","maxRetries","i","response","_error","elapsed","Date","now","Math","ceil","throwIfAborted","awaitWithSignal","fetch","method","headers","Connection","AbortSignal","timeout","status","Error","Promise","resolve","setTimeout","aborted","reason","promise","reject","onAbort","addEventListener","once","then","finally","removeEventListener"],"mappings":"AAAA;;;;CAIC,GAED;;;;;;;;CAQC;;;;+BACqBA;;;eAAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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AAE,OAAOH,QAAQM,MAAM,CAAC3B,AAAa,YAAbA,OAAOyB,MAAM,EAAYL,SAAQpB,OAAOyB,MAAM,GAAG,IAAIL,MAAM;IACrG,OAAO,IAAIC,QAAW,SAACC,SAASK;QAC9B,IAAMC,UAAU;mBAAMD,OAAO3B,AAAa,YAAbA,OAAOyB,MAAM,EAAYL,SAAQpB,OAAOyB,MAAM,GAAG,IAAIL,MAAM;;QACxFpB,OAAO6B,gBAAgB,CAAC,SAASD,SAAS;YAAEE,MAAM;QAAK;QACvDJ,QAAQK,IAAI,CAACT,SAASK,QAAQK,OAAO,CAAC;mBAAMhC,OAAOiC,mBAAmB,CAAC,SAASL;;IAClF;AACF"}
@@ -54,7 +54,7 @@ export declare class DcrAuthenticator {
54
54
  * capabilities
55
55
  * );
56
56
  */
57
- ensureAuthenticated(mcpServerUrl: string, capabilities: AuthCapabilities): Promise<TokenSet>;
57
+ ensureAuthenticated(mcpServerUrl: string, capabilities: AuthCapabilities, signal?: AbortSignal): Promise<TokenSet>;
58
58
  /**
59
59
  * The three things a server URL is used for here, kept apart on purpose.
60
60
  *
@@ -54,7 +54,7 @@ export declare class DcrAuthenticator {
54
54
  * capabilities
55
55
  * );
56
56
  */
57
- ensureAuthenticated(mcpServerUrl: string, capabilities: AuthCapabilities): Promise<TokenSet>;
57
+ ensureAuthenticated(mcpServerUrl: string, capabilities: AuthCapabilities, signal?: AbortSignal): Promise<TokenSet>;
58
58
  /**
59
59
  * The three things a server URL is used for here, kept apart on purpose.
60
60
  *
@@ -516,12 +516,13 @@ var DcrAuthenticator = /*#__PURE__*/ function() {
516
516
  * 'https://example.com/mcp',
517
517
  * capabilities
518
518
  * );
519
- */ _proto.ensureAuthenticated = function ensureAuthenticated(mcpServerUrl, capabilities) {
519
+ */ _proto.ensureAuthenticated = function ensureAuthenticated(mcpServerUrl, capabilities, signal) {
520
520
  return _async_to_generator(function() {
521
521
  var isSelfHosted;
522
522
  return _ts_generator(this, function(_state) {
523
523
  switch(_state.label){
524
524
  case 0:
525
+ throwIfAborted(signal);
525
526
  return [
526
527
  4,
527
528
  this.detectSelfHostedMode(mcpServerUrl)
@@ -531,12 +532,12 @@ var DcrAuthenticator = /*#__PURE__*/ function() {
531
532
  if (isSelfHosted) {
532
533
  return [
533
534
  2,
534
- this.ensureAuthenticatedSelfHosted(mcpServerUrl, capabilities)
535
+ this.ensureAuthenticatedSelfHosted(mcpServerUrl, capabilities, signal)
535
536
  ];
536
537
  }
537
538
  return [
538
539
  2,
539
- this.ensureAuthenticatedExternal(mcpServerUrl, capabilities)
540
+ this.ensureAuthenticatedExternal(mcpServerUrl, capabilities, signal)
540
541
  ];
541
542
  }
542
543
  });
@@ -571,7 +572,7 @@ var DcrAuthenticator = /*#__PURE__*/ function() {
571
572
  /**
572
573
  * Handle authentication for self-hosted DCR servers
573
574
  * Self-hosted servers manage their own token storage via /oauth/verify
574
- */ _proto.ensureAuthenticatedSelfHosted = function ensureAuthenticatedSelfHosted(mcpServerUrl, capabilities) {
575
+ */ _proto.ensureAuthenticatedSelfHosted = function ensureAuthenticatedSelfHosted(mcpServerUrl, capabilities, signal) {
575
576
  return _async_to_generator(function() {
576
577
  var allowLoopback, issuer, _this_resolveUrls, serverBaseUrl, resource, storeKey, dcrTokenKey, tokens, verifyUrl, verifyResponse, verifyData, _error, port, client, flowOptions, verifyUrl1, verifyResponse1, verifyData1, error;
577
578
  return _ts_generator(this, function(_state) {
@@ -608,7 +609,8 @@ var DcrAuthenticator = /*#__PURE__*/ function() {
608
609
  headers: {
609
610
  Authorization: "Bearer ".concat(tokens.accessToken),
610
611
  Connection: 'close'
611
- }
612
+ },
613
+ signal: signal
612
614
  })
613
615
  ];
614
616
  case 3:
@@ -666,13 +668,14 @@ var DcrAuthenticator = /*#__PURE__*/ function() {
666
668
  4,
667
669
  this.dcrClient.registerClient(capabilities.registrationEndpoint, {
668
670
  redirectUri: this.redirectUri,
669
- allowLoopback: allowLoopback
671
+ allowLoopback: allowLoopback,
672
+ signal: signal
670
673
  })
671
674
  ];
672
675
  case 10:
673
676
  client = _state.sent();
674
677
  // Perform OAuth authorization flow with PKCE (RFC 7636)
675
- flowOptions = this.buildFlowOptions(port, capabilities, issuer, resource, allowLoopback);
678
+ flowOptions = this.buildFlowOptions(port, capabilities, issuer, resource, allowLoopback, signal);
676
679
  return [
677
680
  4,
678
681
  this.oauthFlow.performAuthFlow(capabilities.authorizationEndpoint, capabilities.tokenEndpoint, client.clientId, client.clientSecret, flowOptions)
@@ -694,7 +697,8 @@ var DcrAuthenticator = /*#__PURE__*/ function() {
694
697
  headers: {
695
698
  Authorization: "Bearer ".concat(tokens.accessToken),
696
699
  Connection: 'close'
697
- }
700
+ },
701
+ signal: signal
698
702
  })
699
703
  ];
700
704
  case 13:
@@ -739,7 +743,7 @@ var DcrAuthenticator = /*#__PURE__*/ function() {
739
743
  });
740
744
  }).call(this);
741
745
  };
742
- /** Handles authentication for external (non-self-hosted) OAuth providers. */ _proto.ensureAuthenticatedExternal = function ensureAuthenticatedExternal(mcpServerUrl, capabilities) {
746
+ /** Handles authentication for external (non-self-hosted) OAuth providers. */ _proto.ensureAuthenticatedExternal = function ensureAuthenticatedExternal(mcpServerUrl, capabilities, signal) {
743
747
  return _async_to_generator(function() {
744
748
  var allowLoopback, issuer, _this_resolveUrls, resource, storeKey, tokenKey, tokens, _error, port, client, flowOptions;
745
749
  return _ts_generator(this, function(_state) {
@@ -775,7 +779,7 @@ var DcrAuthenticator = /*#__PURE__*/ function() {
775
779
  ]);
776
780
  return [
777
781
  4,
778
- this.refreshTokens(tokens, capabilities.tokenEndpoint, resource, allowLoopback)
782
+ this.refreshTokens(tokens, capabilities.tokenEndpoint, resource, allowLoopback, signal)
779
783
  ];
780
784
  case 3:
781
785
  tokens = _state.sent();
@@ -829,13 +833,14 @@ var DcrAuthenticator = /*#__PURE__*/ function() {
829
833
  4,
830
834
  this.dcrClient.registerClient(capabilities.registrationEndpoint, {
831
835
  redirectUri: this.redirectUri,
832
- allowLoopback: allowLoopback
836
+ allowLoopback: allowLoopback,
837
+ signal: signal
833
838
  })
834
839
  ];
835
840
  case 9:
836
841
  client = _state.sent();
837
842
  // Perform OAuth authorization flow with PKCE (RFC 7636)
838
- flowOptions = this.buildFlowOptions(port, capabilities, issuer, resource, allowLoopback);
843
+ flowOptions = this.buildFlowOptions(port, capabilities, issuer, resource, allowLoopback, signal);
839
844
  return [
840
845
  4,
841
846
  this.oauthFlow.performAuthFlow(capabilities.authorizationEndpoint, capabilities.tokenEndpoint, client.clientId, client.clientSecret, flowOptions)
@@ -865,7 +870,7 @@ var DcrAuthenticator = /*#__PURE__*/ function() {
865
870
  * @param resource - Canonical resource server URI, audience-binding the token (RFC 8707).
866
871
  * @param allowLoopback - Loopback trust grant computed from the server actually being talked to (SSRF mitigation, see discovery-fetch.ts). Defaults to `false`.
867
872
  */ _proto.refreshTokens = function refreshTokens(tokens, tokenEndpoint, resource) {
868
- var allowLoopback = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : false;
873
+ var allowLoopback = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : false, signal = arguments.length > 4 ? arguments[4] : void 0;
869
874
  return _async_to_generator(function() {
870
875
  return _ts_generator(this, function(_state) {
871
876
  switch(_state.label){
@@ -881,7 +886,7 @@ var DcrAuthenticator = /*#__PURE__*/ function() {
881
886
  }
882
887
  return [
883
888
  4,
884
- this.oauthFlow.refreshTokens(tokenEndpoint, tokens.refreshToken, tokens.clientId, tokens.clientSecret, resource, allowLoopback)
889
+ this.oauthFlow.refreshTokens(tokenEndpoint, tokens.refreshToken, tokens.clientId, tokens.clientSecret, resource, allowLoopback, signal)
885
890
  ];
886
891
  case 1:
887
892
  return [
@@ -1041,9 +1046,9 @@ var DcrAuthenticator = /*#__PURE__*/ function() {
1041
1046
  });
1042
1047
  }).call(this);
1043
1048
  };
1044
- _proto.buildFlowOptions = function buildFlowOptions(port, capabilities, issuer, resource, allowLoopback) {
1049
+ _proto.buildFlowOptions = function buildFlowOptions(port, capabilities, issuer, resource, allowLoopback, signal) {
1045
1050
  var _capabilities_authorizationResponseIssSupported;
1046
- var flowOptions = {
1051
+ var flowOptions = _object_spread_props(_object_spread({
1047
1052
  port: port,
1048
1053
  issuer: issuer,
1049
1054
  resource: resource,
@@ -1051,9 +1056,12 @@ var DcrAuthenticator = /*#__PURE__*/ function() {
1051
1056
  redirectUri: this.redirectUri,
1052
1057
  pkce: true,
1053
1058
  logger: this.logger,
1054
- allowLoopback: allowLoopback,
1059
+ allowLoopback: allowLoopback
1060
+ }, signal && {
1061
+ signal: signal
1062
+ }), {
1055
1063
  authorizationResponseIssSupported: (_capabilities_authorizationResponseIssSupported = capabilities.authorizationResponseIssSupported) !== null && _capabilities_authorizationResponseIssSupported !== void 0 ? _capabilities_authorizationResponseIssSupported : false
1056
- };
1064
+ });
1057
1065
  if (capabilities.scopes) {
1058
1066
  flowOptions.scopes = capabilities.scopes;
1059
1067
  }
@@ -1061,4 +1069,7 @@ var DcrAuthenticator = /*#__PURE__*/ function() {
1061
1069
  };
1062
1070
  return DcrAuthenticator;
1063
1071
  }();
1072
+ function throwIfAborted(signal) {
1073
+ if (signal === null || signal === void 0 ? void 0 : signal.aborted) throw _instanceof(signal.reason, Error) ? signal.reason : new Error('Authentication was cancelled');
1074
+ }
1064
1075
  /* CJS INTEROP */ if (exports.__esModule && exports.default) { try { Object.defineProperty(exports.default, '__esModule', { value: true }); for (var key in exports) { exports.default[key] = exports[key]; } } catch (_) {}; module.exports = exports.default; }
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/client/src/dcr/dcr-authenticator.ts"],"sourcesContent":["/**\n * DCR Authenticator\n * Consolidates DCR and OAuth flow logic for MCP HTTP servers\n */\n\nimport path from 'node:path';\nimport * as fs from 'fs';\nimport Keyv from 'keyv';\nimport { KeyvFile } from 'keyv-file';\nimport { isLoopbackUrl } from '../auth/discovery-fetch.ts';\nimport { InteractiveOAuthFlow } from '../auth/interactive-oauth-flow.ts';\nimport type { AuthCapabilities, OAuthFlowOptions, TokenSet } from '../auth/types.ts';\nimport { extractBaseUrl, normalizeUrl } from '../lib/url-utils.ts';\nimport { logger as defaultLogger, type Logger } from '../utils/logger.ts';\nimport { DynamicClientRegistrar } from './dynamic-client-registrar.ts';\n\n/**\n * DcrAuthenticator configuration options\n */\nexport interface DcrAuthenticatorOptions {\n /** Custom Keyv store (for testing) - if not provided, uses default ~/.mcpeasy/tokens.json */\n tokenStore?: Keyv;\n /** Headless mode (don't open browser) */\n headless?: boolean;\n /** Required redirect URI for OAuth callback */\n redirectUri: string;\n /** Optional logger for debug output (defaults to singleton logger) */\n logger?: Logger;\n}\n\n/**\n * Buffer time before token expiry to trigger proactive refresh (5 minutes)\n */\nconst REFRESH_BUFFER_MS = 5 * 60 * 1000;\n\n/** Raised when a credential cannot be bound to, or looked up by, an issuer. */\nclass CredentialBindingError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'CredentialBindingError';\n }\n}\n\n/**\n * The issuer credentials are keyed by, so they can never be presented to a\n * different authorization server even when the resource keeps its URL (SEP-2352).\n */\nfunction requireIssuer(capabilities: AuthCapabilities): string {\n if (!capabilities.issuer) {\n throw new CredentialBindingError('Authorization server metadata has no issuer - credentials cannot be bound to an authorization server (RFC 8414 requires issuer)');\n }\n return capabilities.issuer;\n}\n\n/**\n * DcrAuthenticator manages authentication for MCP HTTP servers\n * Handles DCR registration, OAuth flows, and token management\n */\nexport class DcrAuthenticator {\n private tokenStore: Keyv;\n private dcrClient: DynamicClientRegistrar;\n private oauthFlow: InteractiveOAuthFlow;\n private headless: boolean;\n private redirectUri: string;\n private logger: Logger;\n\n constructor(options: DcrAuthenticatorOptions) {\n if (options.tokenStore) {\n this.tokenStore = options.tokenStore;\n } else {\n // Default CLI store in .mcp-z directory (per-project)\n const storePath = path.join(process.cwd(), '.mcp-z', 'tokens.json');\n\n // Ensure directory exists before creating store\n fs.mkdirSync(path.dirname(storePath), { recursive: true });\n\n this.tokenStore = new Keyv({\n store: new KeyvFile({ filename: storePath }),\n });\n }\n this.dcrClient = new DynamicClientRegistrar();\n this.oauthFlow = new InteractiveOAuthFlow();\n this.headless = options.headless || false;\n this.redirectUri = options.redirectUri;\n this.logger = options.logger ?? defaultLogger;\n }\n\n /**\n * Detect if server is self-hosted DCR (vs external OAuth provider)\n * Self-hosted servers have their own OAuth endpoints and manage token storage\n */\n private async detectSelfHostedMode(mcpServerUrl: string): Promise<boolean> {\n try {\n // Self-hosted DCR servers typically run their own OAuth server\n // Check if this is a self-hosted instance by testing OAuth metadata\n // For now, assume self-hosted if the URL matches common localhost patterns\n // TODO: Implement proper self-hosted detection logic\n return mcpServerUrl.includes('localhost') || mcpServerUrl.includes('127.0.0.1');\n } catch (_error) {\n return false; // Assume external mode if detection fails\n }\n }\n\n /**\n * Ensure server is authenticated, performing DCR and OAuth if needed\n * Proactively refreshes tokens if they're within 5 minutes of expiry\n *\n * @param mcpServerUrl - The MCP server's canonical URL, exactly as configured,\n * with its path intact (`https://example.com/mcp`). Not a deployment root:\n * the path is what identifies the resource an issued token is bound to.\n * @param capabilities - Auth capabilities from .well-known endpoint\n * @returns Valid token set ready to use\n *\n * @throws Error if authentication fails\n *\n * @example\n * const authenticator = new DcrAuthenticator({ redirectUri: 'http://localhost:3000/callback' });\n * const tokens = await authenticator.ensureAuthenticated(\n * 'https://example.com/mcp',\n * capabilities\n * );\n */\n async ensureAuthenticated(mcpServerUrl: string, capabilities: AuthCapabilities): Promise<TokenSet> {\n // Auto-detect server mode\n const isSelfHosted = await this.detectSelfHostedMode(mcpServerUrl);\n\n if (isSelfHosted) {\n return this.ensureAuthenticatedSelfHosted(mcpServerUrl, capabilities);\n }\n return this.ensureAuthenticatedExternal(mcpServerUrl, capabilities);\n }\n\n /**\n * The three things a server URL is used for here, kept apart on purpose.\n *\n * They were one value once, and collapsing them is what sent an authorization\n * server the wrong audience: `resource` was derived from the deployment root,\n * so a server at `https://host/mcp` was asked to mint a token for\n * `https://host`, and any server that validates the indicator answered\n * `invalid_target`.\n *\n * - `serverBaseUrl` builds the server's own endpoints (`/oauth/verify`), so a\n * trailing `/mcp` comes off.\n * - `resource` is the RFC 8707 audience. The resource server names itself in\n * its RFC 9728 metadata; that name wins. Only when no such document exists\n * do we fall back to the URL we were configured with.\n * - `storeKey` identifies the credential locally. It stays the configured URL\n * rather than the discovered `resource`, so it can be computed without a\n * network round trip - `deleteTokens` has only the URL to work from.\n */\n private resolveUrls(mcpServerUrl: string, capabilities: AuthCapabilities): { serverBaseUrl: string; resource: string; storeKey: string } {\n const storeKey = normalizeUrl(mcpServerUrl);\n return { serverBaseUrl: extractBaseUrl(mcpServerUrl), resource: capabilities.resource ?? storeKey, storeKey };\n }\n\n /**\n * Handle authentication for self-hosted DCR servers\n * Self-hosted servers manage their own token storage via /oauth/verify\n */\n private async ensureAuthenticatedSelfHosted(mcpServerUrl: string, capabilities: AuthCapabilities): Promise<TokenSet> {\n // Loopback trust for every discovery-derived fetch below, computed from\n // the server we're talking to, never from capabilities' endpoints (see discovery-fetch.ts).\n const allowLoopback = isLoopbackUrl(mcpServerUrl);\n const issuer = requireIssuer(capabilities);\n const { serverBaseUrl, resource, storeKey } = this.resolveUrls(mcpServerUrl, capabilities);\n const dcrTokenKey = `dcr-tokens:${issuer}:${storeKey}`;\n\n // 1. Check for existing DCR tokens (different from external tokens)\n let tokens = await this.loadTokens(dcrTokenKey, issuer);\n\n if (tokens) {\n // 2. Verify token is still valid by calling /oauth/verify\n try {\n const verifyUrl = `${serverBaseUrl}/oauth/verify`;\n const verifyResponse = await fetch(verifyUrl, {\n headers: { Authorization: `Bearer ${tokens.accessToken}`, Connection: 'close' },\n });\n\n if (verifyResponse.ok) {\n const verifyData = (await verifyResponse.json()) as { token?: string };\n if (verifyData.token === tokens.accessToken) {\n // Token is still valid with the self-hosted server\n return tokens;\n }\n }\n } catch (_error) {\n // Token verification failed - need to re-authenticate\n }\n\n // Token is expired or invalid\n await this.tokenStore.delete(dcrTokenKey);\n tokens = undefined;\n }\n\n // 3. No valid tokens - perform full DCR + OAuth flow\n if (!capabilities.registrationEndpoint || !capabilities.authorizationEndpoint || !capabilities.tokenEndpoint) {\n throw new Error('Server does not provide required OAuth endpoints');\n }\n\n this.logger.debug('🔐 No valid tokens found, starting self-hosted DCR authentication...');\n\n // Extract port from pre-resolved redirectUri\n const port = parseInt(new URL(this.redirectUri).port, 10) || (this.redirectUri.startsWith('https:') ? 443 : 80);\n\n // Register OAuth client via DCR\n this.logger.debug('📝 Registering OAuth client with self-hosted server...');\n const client = await this.dcrClient.registerClient(capabilities.registrationEndpoint, {\n redirectUri: this.redirectUri,\n allowLoopback,\n });\n\n // Perform OAuth authorization flow with PKCE (RFC 7636)\n const flowOptions = this.buildFlowOptions(port, capabilities, issuer, resource, allowLoopback);\n\n tokens = await this.oauthFlow.performAuthFlow(capabilities.authorizationEndpoint, capabilities.tokenEndpoint, client.clientId, client.clientSecret, flowOptions);\n\n // For self-hosted mode, verify the token works with /oauth/verify immediately\n try {\n const verifyUrl = `${serverBaseUrl}/oauth/verify`;\n const verifyResponse = await fetch(verifyUrl, {\n headers: { Authorization: `Bearer ${tokens.accessToken}`, Connection: 'close' },\n });\n\n if (!verifyResponse.ok) {\n throw new Error(`DCR token verification failed after authentication: ${verifyResponse.status}`);\n }\n\n const verifyData = (await verifyResponse.json()) as { token?: string };\n if (verifyData.token !== tokens.accessToken) {\n throw new Error('DCR server returned different token in verification');\n }\n\n this.logger.debug('✅ DCR token verified with self-hosted server');\n } catch (error) {\n this.logger.error('❌ DCR token verification failed:', error instanceof Error ? error.message : String(error));\n throw new Error('Self-hosted DCR authentication completed but token verification failed');\n }\n\n // Save tokens for future use\n await this.tokenStore.set(dcrTokenKey, { ...tokens, issuer });\n this.logger.debug('✅ Self-hosted DCR authentication successful, tokens saved');\n\n return tokens;\n }\n\n /** Handles authentication for external (non-self-hosted) OAuth providers. */\n private async ensureAuthenticatedExternal(mcpServerUrl: string, capabilities: AuthCapabilities): Promise<TokenSet> {\n // See ensureAuthenticatedSelfHosted - same loopback trust rule.\n const allowLoopback = isLoopbackUrl(mcpServerUrl);\n const issuer = requireIssuer(capabilities);\n const { resource, storeKey } = this.resolveUrls(mcpServerUrl, capabilities);\n const tokenKey = `tokens:${issuer}:${storeKey}`;\n\n // 1. Check for existing tokens\n let tokens = await this.loadTokens(tokenKey, issuer);\n\n if (tokens) {\n // 2. Proactive refresh if token expires within 5 minutes\n if (tokens.expiresAt < Date.now() + REFRESH_BUFFER_MS) {\n this.logger.debug('🔄 Refreshing access token...');\n\n try {\n tokens = await this.refreshTokens(tokens, capabilities.tokenEndpoint, resource, allowLoopback);\n await this.tokenStore.set(tokenKey, { ...tokens, issuer });\n this.logger.debug('✅ Token refreshed successfully');\n } catch (_error) {\n // Refresh failed - clear tokens and re-authenticate\n this.logger.warn('⚠️ Token refresh failed, re-authenticating...');\n await this.tokenStore.delete(tokenKey);\n tokens = undefined;\n }\n }\n\n if (tokens) {\n return tokens;\n }\n }\n\n // 3. No valid tokens - perform DCR + OAuth flow\n if (!capabilities.registrationEndpoint || !capabilities.authorizationEndpoint || !capabilities.tokenEndpoint) {\n throw new Error('Server does not provide required OAuth endpoints');\n }\n\n this.logger.debug('🔐 No valid tokens found, starting external OAuth authentication...');\n\n // Extract port from pre-resolved redirectUri\n const port = parseInt(new URL(this.redirectUri).port, 10) || (this.redirectUri.startsWith('https:') ? 443 : 80);\n\n // Register OAuth client via DCR\n this.logger.debug('📝 Registering OAuth client...');\n const client = await this.dcrClient.registerClient(capabilities.registrationEndpoint, {\n redirectUri: this.redirectUri,\n allowLoopback,\n });\n\n // Perform OAuth authorization flow with PKCE (RFC 7636)\n const flowOptions = this.buildFlowOptions(port, capabilities, issuer, resource, allowLoopback);\n\n tokens = await this.oauthFlow.performAuthFlow(capabilities.authorizationEndpoint, capabilities.tokenEndpoint, client.clientId, client.clientSecret, flowOptions);\n\n // Save tokens for future use\n await this.tokenStore.set(tokenKey, { ...tokens, issuer });\n this.logger.debug('✅ Authentication successful, tokens saved');\n\n return tokens;\n }\n\n /**\n * Refreshes an access token using a refresh token.\n * @param resource - Canonical resource server URI, audience-binding the token (RFC 8707).\n * @param allowLoopback - Loopback trust grant computed from the server actually being talked to (SSRF mitigation, see discovery-fetch.ts). Defaults to `false`.\n */\n private async refreshTokens(tokens: TokenSet, tokenEndpoint: string | undefined, resource: string, allowLoopback = false): Promise<TokenSet> {\n if (!tokenEndpoint) {\n throw new Error('Token endpoint not available for refresh');\n }\n\n if (!tokens.refreshToken) {\n throw new Error('No refresh token available');\n }\n\n if (!tokens.clientId || !tokens.clientSecret) {\n throw new Error('Client credentials not available for refresh');\n }\n\n return await this.oauthFlow.refreshTokens(tokenEndpoint, tokens.refreshToken, tokens.clientId, tokens.clientSecret, resource, allowLoopback);\n }\n\n /**\n * Deletes both stored token families for a server, across every issuer they were bound to.\n *\n * Takes the same `mcpServerUrl` that {@link DcrAuthenticator.ensureAuthenticated}\n * was given - keys are built from the configured URL, never from the discovered\n * RFC 8707 resource, precisely so this can find them without doing discovery.\n *\n * @throws CredentialBindingError if the configured store cannot enumerate keys.\n */\n async deleteTokens(mcpServerUrl: string): Promise<void> {\n const suffix = `:${normalizeUrl(mcpServerUrl)}`;\n if (!this.tokenStore.iterator) {\n throw new CredentialBindingError('Token store does not support key enumeration, which issuer-keyed credentials require');\n }\n\n for await (const [key] of this.tokenStore.iterator(this.tokenStore.namespace)) {\n if (typeof key === 'string' && (key.startsWith('tokens:') || key.startsWith('dcr-tokens:')) && key.endsWith(suffix)) {\n await this.tokenStore.delete(key);\n }\n }\n this.logger.debug(`🗑️ Deleted tokens for ${mcpServerUrl}`);\n }\n\n /** Discards a stored credential that is not bound to `issuer` (SEP-2352), including one stored before issuer binding existed. */\n private async loadTokens(key: string, issuer: string): Promise<TokenSet | undefined> {\n const tokens = (await this.tokenStore.get(key)) as TokenSet | undefined;\n if (!tokens) return undefined;\n if (tokens.issuer === issuer) return tokens;\n\n this.logger.debug('🔑 Stored credential is not bound to the discovered issuer, re-authorizing');\n await this.tokenStore.delete(key);\n return undefined;\n }\n\n private buildFlowOptions(port: number, capabilities: AuthCapabilities, issuer: string, resource: string, allowLoopback: boolean): OAuthFlowOptions {\n const flowOptions: OAuthFlowOptions = {\n port,\n issuer,\n resource,\n headless: this.headless,\n redirectUri: this.redirectUri,\n pkce: true,\n logger: this.logger,\n allowLoopback,\n authorizationResponseIssSupported: capabilities.authorizationResponseIssSupported ?? false,\n };\n if (capabilities.scopes) {\n flowOptions.scopes = capabilities.scopes;\n }\n return flowOptions;\n }\n}\n"],"names":["DcrAuthenticator","REFRESH_BUFFER_MS","CredentialBindingError","message","name","Error","requireIssuer","capabilities","issuer","options","tokenStore","storePath","path","join","process","cwd","fs","mkdirSync","dirname","recursive","Keyv","store","KeyvFile","filename","dcrClient","DynamicClientRegistrar","oauthFlow","InteractiveOAuthFlow","headless","redirectUri","logger","defaultLogger","detectSelfHostedMode","mcpServerUrl","includes","_error","ensureAuthenticated","isSelfHosted","ensureAuthenticatedSelfHosted","ensureAuthenticatedExternal","resolveUrls","storeKey","normalizeUrl","serverBaseUrl","extractBaseUrl","resource","allowLoopback","dcrTokenKey","tokens","verifyUrl","verifyResponse","verifyData","port","client","flowOptions","error","isLoopbackUrl","loadTokens","fetch","headers","Authorization","accessToken","Connection","ok","json","token","delete","undefined","registrationEndpoint","authorizationEndpoint","tokenEndpoint","debug","parseInt","URL","startsWith","registerClient","buildFlowOptions","performAuthFlow","clientId","clientSecret","status","String","set","tokenKey","expiresAt","Date","now","refreshTokens","warn","refreshToken","deleteTokens","suffix","key","iterator","namespace","endsWith","get","pkce","authorizationResponseIssSupported","scopes"],"mappings":"AAAA;;;CAGC;;;;+BAuDYA;;;eAAAA;;;+DArDI;0DACG;2DACH;wBACQ;gCACK;sCACO;0BAEQ;wBACQ;wCACd;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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;;;;wBAAU;;4BAAM,IAAI,CAACtC,UAAU,CAACsF,GAAG,CAACJ;;;wBAApC5C,SAAU;wBAChB,IAAI,CAACA,QAAQ;;4BAAOmB;;wBACpB,IAAInB,OAAOxC,MAAM,KAAKA,QAAQ;;4BAAOwC;;wBAErC,IAAI,CAAClB,MAAM,CAACyC,KAAK,CAAC;wBAClB;;4BAAM,IAAI,CAAC7D,UAAU,CAACwD,MAAM,CAAC0B;;;wBAA7B;wBACA;;4BAAOzB;;;;QACT;;IAEA,OAAQS,gBAgBP,GAhBD,SAAQA,iBAAiBxB,IAAY,EAAE7C,YAA8B,EAAEC,MAAc,EAAEqC,QAAgB,EAAEC,aAAsB;YAUxFvC;QATrC,IAAM+C,cAAgC;YACpCF,MAAAA;YACA5C,QAAAA;YACAqC,UAAAA;YACAjB,UAAU,IAAI,CAACA,QAAQ;YACvBC,aAAa,IAAI,CAACA,WAAW;YAC7BoE,MAAM;YACNnE,QAAQ,IAAI,CAACA,MAAM;YACnBgB,eAAAA;YACAoD,iCAAiC,GAAE3F,kDAAAA,aAAa2F,iCAAiC,cAA9C3F,6DAAAA,kDAAkD;QACvF;QACA,IAAIA,aAAa4F,MAAM,EAAE;YACvB7C,YAAY6C,MAAM,GAAG5F,aAAa4F,MAAM;QAC1C;QACA,OAAO7C;IACT;WAhUWtD"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/client/src/dcr/dcr-authenticator.ts"],"sourcesContent":["/**\n * DCR Authenticator\n * Consolidates DCR and OAuth flow logic for MCP HTTP servers\n */\n\nimport path from 'node:path';\nimport * as fs from 'fs';\nimport Keyv from 'keyv';\nimport { KeyvFile } from 'keyv-file';\nimport { isLoopbackUrl } from '../auth/discovery-fetch.ts';\nimport { InteractiveOAuthFlow } from '../auth/interactive-oauth-flow.ts';\nimport type { AuthCapabilities, OAuthFlowOptions, TokenSet } from '../auth/types.ts';\nimport { extractBaseUrl, normalizeUrl } from '../lib/url-utils.ts';\nimport { logger as defaultLogger, type Logger } from '../utils/logger.ts';\nimport { DynamicClientRegistrar } from './dynamic-client-registrar.ts';\n\n/**\n * DcrAuthenticator configuration options\n */\nexport interface DcrAuthenticatorOptions {\n /** Custom Keyv store (for testing) - if not provided, uses default ~/.mcpeasy/tokens.json */\n tokenStore?: Keyv;\n /** Headless mode (don't open browser) */\n headless?: boolean;\n /** Required redirect URI for OAuth callback */\n redirectUri: string;\n /** Optional logger for debug output (defaults to singleton logger) */\n logger?: Logger;\n}\n\n/**\n * Buffer time before token expiry to trigger proactive refresh (5 minutes)\n */\nconst REFRESH_BUFFER_MS = 5 * 60 * 1000;\n\n/** Raised when a credential cannot be bound to, or looked up by, an issuer. */\nclass CredentialBindingError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'CredentialBindingError';\n }\n}\n\n/**\n * The issuer credentials are keyed by, so they can never be presented to a\n * different authorization server even when the resource keeps its URL (SEP-2352).\n */\nfunction requireIssuer(capabilities: AuthCapabilities): string {\n if (!capabilities.issuer) {\n throw new CredentialBindingError('Authorization server metadata has no issuer - credentials cannot be bound to an authorization server (RFC 8414 requires issuer)');\n }\n return capabilities.issuer;\n}\n\n/**\n * DcrAuthenticator manages authentication for MCP HTTP servers\n * Handles DCR registration, OAuth flows, and token management\n */\nexport class DcrAuthenticator {\n private tokenStore: Keyv;\n private dcrClient: DynamicClientRegistrar;\n private oauthFlow: InteractiveOAuthFlow;\n private headless: boolean;\n private redirectUri: string;\n private logger: Logger;\n\n constructor(options: DcrAuthenticatorOptions) {\n if (options.tokenStore) {\n this.tokenStore = options.tokenStore;\n } else {\n // Default CLI store in .mcp-z directory (per-project)\n const storePath = path.join(process.cwd(), '.mcp-z', 'tokens.json');\n\n // Ensure directory exists before creating store\n fs.mkdirSync(path.dirname(storePath), { recursive: true });\n\n this.tokenStore = new Keyv({\n store: new KeyvFile({ filename: storePath }),\n });\n }\n this.dcrClient = new DynamicClientRegistrar();\n this.oauthFlow = new InteractiveOAuthFlow();\n this.headless = options.headless || false;\n this.redirectUri = options.redirectUri;\n this.logger = options.logger ?? defaultLogger;\n }\n\n /**\n * Detect if server is self-hosted DCR (vs external OAuth provider)\n * Self-hosted servers have their own OAuth endpoints and manage token storage\n */\n private async detectSelfHostedMode(mcpServerUrl: string): Promise<boolean> {\n try {\n // Self-hosted DCR servers typically run their own OAuth server\n // Check if this is a self-hosted instance by testing OAuth metadata\n // For now, assume self-hosted if the URL matches common localhost patterns\n // TODO: Implement proper self-hosted detection logic\n return mcpServerUrl.includes('localhost') || mcpServerUrl.includes('127.0.0.1');\n } catch (_error) {\n return false; // Assume external mode if detection fails\n }\n }\n\n /**\n * Ensure server is authenticated, performing DCR and OAuth if needed\n * Proactively refreshes tokens if they're within 5 minutes of expiry\n *\n * @param mcpServerUrl - The MCP server's canonical URL, exactly as configured,\n * with its path intact (`https://example.com/mcp`). Not a deployment root:\n * the path is what identifies the resource an issued token is bound to.\n * @param capabilities - Auth capabilities from .well-known endpoint\n * @returns Valid token set ready to use\n *\n * @throws Error if authentication fails\n *\n * @example\n * const authenticator = new DcrAuthenticator({ redirectUri: 'http://localhost:3000/callback' });\n * const tokens = await authenticator.ensureAuthenticated(\n * 'https://example.com/mcp',\n * capabilities\n * );\n */\n async ensureAuthenticated(mcpServerUrl: string, capabilities: AuthCapabilities, signal?: AbortSignal): Promise<TokenSet> {\n throwIfAborted(signal);\n // Auto-detect server mode\n const isSelfHosted = await this.detectSelfHostedMode(mcpServerUrl);\n\n if (isSelfHosted) {\n return this.ensureAuthenticatedSelfHosted(mcpServerUrl, capabilities, signal);\n }\n return this.ensureAuthenticatedExternal(mcpServerUrl, capabilities, signal);\n }\n\n /**\n * The three things a server URL is used for here, kept apart on purpose.\n *\n * They were one value once, and collapsing them is what sent an authorization\n * server the wrong audience: `resource` was derived from the deployment root,\n * so a server at `https://host/mcp` was asked to mint a token for\n * `https://host`, and any server that validates the indicator answered\n * `invalid_target`.\n *\n * - `serverBaseUrl` builds the server's own endpoints (`/oauth/verify`), so a\n * trailing `/mcp` comes off.\n * - `resource` is the RFC 8707 audience. The resource server names itself in\n * its RFC 9728 metadata; that name wins. Only when no such document exists\n * do we fall back to the URL we were configured with.\n * - `storeKey` identifies the credential locally. It stays the configured URL\n * rather than the discovered `resource`, so it can be computed without a\n * network round trip - `deleteTokens` has only the URL to work from.\n */\n private resolveUrls(mcpServerUrl: string, capabilities: AuthCapabilities): { serverBaseUrl: string; resource: string; storeKey: string } {\n const storeKey = normalizeUrl(mcpServerUrl);\n return { serverBaseUrl: extractBaseUrl(mcpServerUrl), resource: capabilities.resource ?? storeKey, storeKey };\n }\n\n /**\n * Handle authentication for self-hosted DCR servers\n * Self-hosted servers manage their own token storage via /oauth/verify\n */\n private async ensureAuthenticatedSelfHosted(mcpServerUrl: string, capabilities: AuthCapabilities, signal?: AbortSignal): Promise<TokenSet> {\n // Loopback trust for every discovery-derived fetch below, computed from\n // the server we're talking to, never from capabilities' endpoints (see discovery-fetch.ts).\n const allowLoopback = isLoopbackUrl(mcpServerUrl);\n const issuer = requireIssuer(capabilities);\n const { serverBaseUrl, resource, storeKey } = this.resolveUrls(mcpServerUrl, capabilities);\n const dcrTokenKey = `dcr-tokens:${issuer}:${storeKey}`;\n\n // 1. Check for existing DCR tokens (different from external tokens)\n let tokens = await this.loadTokens(dcrTokenKey, issuer);\n\n if (tokens) {\n // 2. Verify token is still valid by calling /oauth/verify\n try {\n const verifyUrl = `${serverBaseUrl}/oauth/verify`;\n const verifyResponse = await fetch(verifyUrl, {\n headers: { Authorization: `Bearer ${tokens.accessToken}`, Connection: 'close' },\n signal,\n });\n\n if (verifyResponse.ok) {\n const verifyData = (await verifyResponse.json()) as { token?: string };\n if (verifyData.token === tokens.accessToken) {\n // Token is still valid with the self-hosted server\n return tokens;\n }\n }\n } catch (_error) {\n // Token verification failed - need to re-authenticate\n }\n\n // Token is expired or invalid\n await this.tokenStore.delete(dcrTokenKey);\n tokens = undefined;\n }\n\n // 3. No valid tokens - perform full DCR + OAuth flow\n if (!capabilities.registrationEndpoint || !capabilities.authorizationEndpoint || !capabilities.tokenEndpoint) {\n throw new Error('Server does not provide required OAuth endpoints');\n }\n\n this.logger.debug('🔐 No valid tokens found, starting self-hosted DCR authentication...');\n\n // Extract port from pre-resolved redirectUri\n const port = parseInt(new URL(this.redirectUri).port, 10) || (this.redirectUri.startsWith('https:') ? 443 : 80);\n\n // Register OAuth client via DCR\n this.logger.debug('📝 Registering OAuth client with self-hosted server...');\n const client = await this.dcrClient.registerClient(capabilities.registrationEndpoint, {\n redirectUri: this.redirectUri,\n allowLoopback,\n signal,\n });\n\n // Perform OAuth authorization flow with PKCE (RFC 7636)\n const flowOptions = this.buildFlowOptions(port, capabilities, issuer, resource, allowLoopback, signal);\n\n tokens = await this.oauthFlow.performAuthFlow(capabilities.authorizationEndpoint, capabilities.tokenEndpoint, client.clientId, client.clientSecret, flowOptions);\n\n // For self-hosted mode, verify the token works with /oauth/verify immediately\n try {\n const verifyUrl = `${serverBaseUrl}/oauth/verify`;\n const verifyResponse = await fetch(verifyUrl, {\n headers: { Authorization: `Bearer ${tokens.accessToken}`, Connection: 'close' },\n signal,\n });\n\n if (!verifyResponse.ok) {\n throw new Error(`DCR token verification failed after authentication: ${verifyResponse.status}`);\n }\n\n const verifyData = (await verifyResponse.json()) as { token?: string };\n if (verifyData.token !== tokens.accessToken) {\n throw new Error('DCR server returned different token in verification');\n }\n\n this.logger.debug('✅ DCR token verified with self-hosted server');\n } catch (error) {\n this.logger.error('❌ DCR token verification failed:', error instanceof Error ? error.message : String(error));\n throw new Error('Self-hosted DCR authentication completed but token verification failed');\n }\n\n // Save tokens for future use\n await this.tokenStore.set(dcrTokenKey, { ...tokens, issuer });\n this.logger.debug('✅ Self-hosted DCR authentication successful, tokens saved');\n\n return tokens;\n }\n\n /** Handles authentication for external (non-self-hosted) OAuth providers. */\n private async ensureAuthenticatedExternal(mcpServerUrl: string, capabilities: AuthCapabilities, signal?: AbortSignal): Promise<TokenSet> {\n // See ensureAuthenticatedSelfHosted - same loopback trust rule.\n const allowLoopback = isLoopbackUrl(mcpServerUrl);\n const issuer = requireIssuer(capabilities);\n const { resource, storeKey } = this.resolveUrls(mcpServerUrl, capabilities);\n const tokenKey = `tokens:${issuer}:${storeKey}`;\n\n // 1. Check for existing tokens\n let tokens = await this.loadTokens(tokenKey, issuer);\n\n if (tokens) {\n // 2. Proactive refresh if token expires within 5 minutes\n if (tokens.expiresAt < Date.now() + REFRESH_BUFFER_MS) {\n this.logger.debug('🔄 Refreshing access token...');\n\n try {\n tokens = await this.refreshTokens(tokens, capabilities.tokenEndpoint, resource, allowLoopback, signal);\n await this.tokenStore.set(tokenKey, { ...tokens, issuer });\n this.logger.debug('✅ Token refreshed successfully');\n } catch (_error) {\n // Refresh failed - clear tokens and re-authenticate\n this.logger.warn('⚠️ Token refresh failed, re-authenticating...');\n await this.tokenStore.delete(tokenKey);\n tokens = undefined;\n }\n }\n\n if (tokens) {\n return tokens;\n }\n }\n\n // 3. No valid tokens - perform DCR + OAuth flow\n if (!capabilities.registrationEndpoint || !capabilities.authorizationEndpoint || !capabilities.tokenEndpoint) {\n throw new Error('Server does not provide required OAuth endpoints');\n }\n\n this.logger.debug('🔐 No valid tokens found, starting external OAuth authentication...');\n\n // Extract port from pre-resolved redirectUri\n const port = parseInt(new URL(this.redirectUri).port, 10) || (this.redirectUri.startsWith('https:') ? 443 : 80);\n\n // Register OAuth client via DCR\n this.logger.debug('📝 Registering OAuth client...');\n const client = await this.dcrClient.registerClient(capabilities.registrationEndpoint, {\n redirectUri: this.redirectUri,\n allowLoopback,\n signal,\n });\n\n // Perform OAuth authorization flow with PKCE (RFC 7636)\n const flowOptions = this.buildFlowOptions(port, capabilities, issuer, resource, allowLoopback, signal);\n\n tokens = await this.oauthFlow.performAuthFlow(capabilities.authorizationEndpoint, capabilities.tokenEndpoint, client.clientId, client.clientSecret, flowOptions);\n\n // Save tokens for future use\n await this.tokenStore.set(tokenKey, { ...tokens, issuer });\n this.logger.debug('✅ Authentication successful, tokens saved');\n\n return tokens;\n }\n\n /**\n * Refreshes an access token using a refresh token.\n * @param resource - Canonical resource server URI, audience-binding the token (RFC 8707).\n * @param allowLoopback - Loopback trust grant computed from the server actually being talked to (SSRF mitigation, see discovery-fetch.ts). Defaults to `false`.\n */\n private async refreshTokens(tokens: TokenSet, tokenEndpoint: string | undefined, resource: string, allowLoopback = false, signal?: AbortSignal): Promise<TokenSet> {\n if (!tokenEndpoint) {\n throw new Error('Token endpoint not available for refresh');\n }\n\n if (!tokens.refreshToken) {\n throw new Error('No refresh token available');\n }\n\n if (!tokens.clientId || !tokens.clientSecret) {\n throw new Error('Client credentials not available for refresh');\n }\n\n return await this.oauthFlow.refreshTokens(tokenEndpoint, tokens.refreshToken, tokens.clientId, tokens.clientSecret, resource, allowLoopback, signal);\n }\n\n /**\n * Deletes both stored token families for a server, across every issuer they were bound to.\n *\n * Takes the same `mcpServerUrl` that {@link DcrAuthenticator.ensureAuthenticated}\n * was given - keys are built from the configured URL, never from the discovered\n * RFC 8707 resource, precisely so this can find them without doing discovery.\n *\n * @throws CredentialBindingError if the configured store cannot enumerate keys.\n */\n async deleteTokens(mcpServerUrl: string): Promise<void> {\n const suffix = `:${normalizeUrl(mcpServerUrl)}`;\n if (!this.tokenStore.iterator) {\n throw new CredentialBindingError('Token store does not support key enumeration, which issuer-keyed credentials require');\n }\n\n for await (const [key] of this.tokenStore.iterator(this.tokenStore.namespace)) {\n if (typeof key === 'string' && (key.startsWith('tokens:') || key.startsWith('dcr-tokens:')) && key.endsWith(suffix)) {\n await this.tokenStore.delete(key);\n }\n }\n this.logger.debug(`🗑️ Deleted tokens for ${mcpServerUrl}`);\n }\n\n /** Discards a stored credential that is not bound to `issuer` (SEP-2352), including one stored before issuer binding existed. */\n private async loadTokens(key: string, issuer: string): Promise<TokenSet | undefined> {\n const tokens = (await this.tokenStore.get(key)) as TokenSet | undefined;\n if (!tokens) return undefined;\n if (tokens.issuer === issuer) return tokens;\n\n this.logger.debug('🔑 Stored credential is not bound to the discovered issuer, re-authorizing');\n await this.tokenStore.delete(key);\n return undefined;\n }\n\n private buildFlowOptions(port: number, capabilities: AuthCapabilities, issuer: string, resource: string, allowLoopback: boolean, signal?: AbortSignal): OAuthFlowOptions {\n const flowOptions: OAuthFlowOptions = {\n port,\n issuer,\n resource,\n headless: this.headless,\n redirectUri: this.redirectUri,\n pkce: true,\n logger: this.logger,\n allowLoopback,\n ...(signal && { signal }),\n authorizationResponseIssSupported: capabilities.authorizationResponseIssSupported ?? false,\n };\n if (capabilities.scopes) {\n flowOptions.scopes = capabilities.scopes;\n }\n return flowOptions;\n }\n}\n\nfunction throwIfAborted(signal?: AbortSignal): void {\n if (signal?.aborted) throw signal.reason instanceof Error ? signal.reason : new Error('Authentication was cancelled');\n}\n"],"names":["DcrAuthenticator","REFRESH_BUFFER_MS","CredentialBindingError","message","name","Error","requireIssuer","capabilities","issuer","options","tokenStore","storePath","path","join","process","cwd","fs","mkdirSync","dirname","recursive","Keyv","store","KeyvFile","filename","dcrClient","DynamicClientRegistrar","oauthFlow","InteractiveOAuthFlow","headless","redirectUri","logger","defaultLogger","detectSelfHostedMode","mcpServerUrl","includes","_error","ensureAuthenticated","signal","isSelfHosted","throwIfAborted","ensureAuthenticatedSelfHosted","ensureAuthenticatedExternal","resolveUrls","storeKey","normalizeUrl","serverBaseUrl","extractBaseUrl","resource","allowLoopback","dcrTokenKey","tokens","verifyUrl","verifyResponse","verifyData","port","client","flowOptions","error","isLoopbackUrl","loadTokens","fetch","headers","Authorization","accessToken","Connection","ok","json","token","delete","undefined","registrationEndpoint","authorizationEndpoint","tokenEndpoint","debug","parseInt","URL","startsWith","registerClient","buildFlowOptions","performAuthFlow","clientId","clientSecret","status","String","set","tokenKey","expiresAt","Date","now","refreshTokens","warn","refreshToken","deleteTokens","suffix","key","iterator","namespace","endsWith","get","pkce","authorizationResponseIssSupported","scopes","aborted","reason"],"mappings":"AAAA;;;CAGC;;;;+BAuDYA;;;eAAAA;;;+DArDI;0DACG;2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,IAAIA,mBAAAA,6BAAAA,OAAQiE,OAAO,EAAE,MAAMjE,AAAa,YAAbA,OAAOkE,MAAM,EAAYlG,SAAQgC,OAAOkE,MAAM,GAAG,IAAIlG,MAAM;AACxF"}
@@ -185,7 +185,8 @@ var DynamicClientRegistrar = /*#__PURE__*/ function() {
185
185
  Accept: 'application/json',
186
186
  Connection: 'close'
187
187
  },
188
- body: JSON.stringify(requestBody)
188
+ body: JSON.stringify(requestBody),
189
+ signal: options.signal
189
190
  }, 'registration endpoint', {
190
191
  allowLoopback: (_options_allowLoopback = options.allowLoopback) !== null && _options_allowLoopback !== void 0 ? _options_allowLoopback : false
191
192
  })
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/client/src/dcr/dynamic-client-registrar.ts"],"sourcesContent":["/**\n * Dynamic Client Registration (DCR) Client\n * Implements RFC 7591 for OAuth client registration\n */\n\nimport { discoveryFetch } from '../auth/discovery-fetch.ts';\nimport type { ClientCredentials, DcrRegistrationOptions } from '../auth/types.ts';\n\n/** DCR Registration Request (RFC 7591) */\ninterface DcrRegistrationRequest {\n client_name?: string;\n redirect_uris?: string[];\n grant_types?: string[];\n response_types?: string[];\n token_endpoint_auth_method?: string;\n application_type?: string;\n}\n\n/** DCR Registration Response (RFC 7591) */\ninterface DcrRegistrationResponse {\n client_id: string;\n client_secret?: string;\n client_id_issued_at?: number;\n client_secret_expires_at?: number;\n}\n\n/** Handles Dynamic Client Registration with OAuth servers. */\nexport class DynamicClientRegistrar {\n /**\n * Registers a new OAuth client with the authorization server (RFC 7591).\n *\n * @param registrationEndpoint - Often sourced from remote-controlled AS metadata; pass `options.allowLoopback` explicitly. Defaults to `false`.\n * @param options - Registration options (redirect URI, client name, loopback trust).\n * @returns Client credentials (client ID and secret).\n * @throws Error if registration fails or the server returns an error.\n */\n async registerClient(registrationEndpoint: string, options: DcrRegistrationOptions): Promise<ClientCredentials> {\n const requestBody: DcrRegistrationRequest = {\n client_name: options.clientName || '@mcp-z/client',\n redirect_uris: [options.redirectUri],\n grant_types: ['authorization_code', 'refresh_token'],\n response_types: ['code'],\n token_endpoint_auth_method: 'client_secret_basic',\n // The callback listener always binds an OS-assigned loopback port, so the\n // redirect URI is one an authorization server rejects for a web client (SEP-837, RFC 8252).\n application_type: 'native',\n };\n\n // registrationEndpoint is remote-controlled discovery data; allowLoopback\n // must come from the caller's own trust, never from registrationEndpoint.\n const response = await discoveryFetch(\n registrationEndpoint,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n Connection: 'close',\n },\n body: JSON.stringify(requestBody),\n },\n 'registration endpoint',\n { allowLoopback: options.allowLoopback ?? false }\n );\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`DCR registration failed (${response.status}): ${errorText}`);\n }\n\n const data = (await response.json()) as DcrRegistrationResponse;\n\n if (!data.client_id) {\n throw new Error('DCR registration response missing client_id');\n }\n\n const credentials: ClientCredentials = {\n clientId: data.client_id,\n clientSecret: data.client_secret || '',\n };\n\n if (data.client_id_issued_at) {\n credentials.issuedAt = data.client_id_issued_at;\n }\n\n return credentials;\n }\n}\n"],"names":["DynamicClientRegistrar","registerClient","registrationEndpoint","options","requestBody","response","errorText","data","credentials","client_name","clientName","redirect_uris","redirectUri","grant_types","response_types","token_endpoint_auth_method","application_type","discoveryFetch","method","headers","Accept","Connection","body","JSON","stringify","allowLoopback","ok","text","Error","status","json","client_id","clientId","clientSecret","client_secret","client_id_issued_at","issuedAt"],"mappings":"AAAA;;;CAGC;;;;+BAwBYA;;;eAAAA;;;gCAtBkB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsBxB,IAAA,AAAMA,uCAAN;;aAAMA;gCAAAA;;iBAAAA;IACX;;;;;;;GAOC,GACD,OAAMC,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amic Client Registration (DCR) Client\n * Implements RFC 7591 for OAuth client registration\n */\n\nimport { discoveryFetch } from '../auth/discovery-fetch.ts';\nimport type { ClientCredentials, DcrRegistrationOptions } from '../auth/types.ts';\n\n/** DCR Registration Request (RFC 7591) */\ninterface DcrRegistrationRequest {\n client_name?: string;\n redirect_uris?: string[];\n grant_types?: string[];\n response_types?: string[];\n token_endpoint_auth_method?: string;\n application_type?: string;\n}\n\n/** DCR Registration Response (RFC 7591) */\ninterface DcrRegistrationResponse {\n client_id: string;\n client_secret?: string;\n client_id_issued_at?: number;\n client_secret_expires_at?: number;\n}\n\n/** Handles Dynamic Client Registration with OAuth servers. */\nexport class DynamicClientRegistrar {\n /**\n * Registers a new OAuth client with the authorization server (RFC 7591).\n *\n * @param registrationEndpoint - Often sourced from remote-controlled AS metadata; pass `options.allowLoopback` explicitly. Defaults to `false`.\n * @param options - Registration options (redirect URI, client name, loopback trust).\n * @returns Client credentials (client ID and secret).\n * @throws Error if registration fails or the server returns an error.\n */\n async registerClient(registrationEndpoint: string, options: DcrRegistrationOptions): Promise<ClientCredentials> {\n const requestBody: DcrRegistrationRequest = {\n client_name: options.clientName || '@mcp-z/client',\n redirect_uris: [options.redirectUri],\n grant_types: ['authorization_code', 'refresh_token'],\n response_types: ['code'],\n token_endpoint_auth_method: 'client_secret_basic',\n // The callback listener always binds an OS-assigned loopback port, so the\n // redirect URI is one an authorization server rejects for a web client (SEP-837, RFC 8252).\n application_type: 'native',\n };\n\n // registrationEndpoint is remote-controlled discovery data; allowLoopback\n // must come from the caller's own trust, never from registrationEndpoint.\n const response = await discoveryFetch(\n registrationEndpoint,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n Connection: 'close',\n },\n body: JSON.stringify(requestBody),\n signal: options.signal,\n },\n 'registration endpoint',\n { allowLoopback: options.allowLoopback ?? false }\n );\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`DCR registration failed (${response.status}): ${errorText}`);\n }\n\n const data = (await response.json()) as DcrRegistrationResponse;\n\n if (!data.client_id) {\n throw new Error('DCR registration response missing client_id');\n }\n\n const credentials: ClientCredentials = {\n clientId: data.client_id,\n clientSecret: data.client_secret || '',\n };\n\n if (data.client_id_issued_at) {\n credentials.issuedAt = data.client_id_issued_at;\n }\n\n return credentials;\n }\n}\n"],"names":["DynamicClientRegistrar","registerClient","registrationEndpoint","options","requestBody","response","errorText","data","credentials","client_name","clientName","redirect_uris","redirectUri","grant_types","response_types","token_endpoint_auth_method","application_type","discoveryFetch","method","headers","Accept","Connection","body","JSON","stringify","signal","allowLoopback","ok","text","Error","status","json","client_id","clientId","clientSecret","client_secret","client_id_issued_at","issuedAt"],"mappings":"AAAA;;;CAGC;;;;+BAwBYA;;;eAAAA;;;gCAtBkB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsBxB,IAAA,AAAMA,uCAAN;;aAAMA;gCAAAA;;iBAAAA;IACX;;;;;;;GAOC,GACD,OAAMC,cAmDL,GAnDD,SAAMA,eAAeC,oBAA4B,EAAEC,OAA+B;;gBA2B7DA,wBA1BbC,aAaAC,UAiBEC,WAIFC,MAMAC;;;;wBAxCAJ,cAAsC;4BAC1CK,aAAaN,QAAQO,UAAU,IAAI;4BACnCC,aAAa;gCAAGR,QAAQS,WAAW;;4BACnCC,WAAW;gCAAG;gCAAsB;;4BACpCC,cAAc;gCAAG;;4BACjBC,4BAA4B;4BAC5B,0EAA0E;4BAC1E,4FAA4F;4BAC5FC,kBAAkB;wBACpB;wBAIiB;;4BAAMC,IAAAA,gCAAc,EACnCf,sBACA;gCACEgB,QAAQ;gCACRC,SAAS;oCACP,gBAAgB;oCAChBC,QAAQ;oCACRC,YAAY;gCACd;gCACAC,MAAMC,KAAKC,SAAS,CAACpB;gCACrBqB,QAAQtB,QAAQsB,MAAM;4BACxB,GACA,yBACA;gCAAEC,aAAa,GAAEvB,yBAAAA,QAAQuB,aAAa,cAArBvB,oCAAAA,yBAAyB;4BAAM;;;wBAb5CE,WAAW;6BAgBb,CAACA,SAASsB,EAAE,EAAZ;;;;wBACgB;;4BAAMtB,SAASuB,IAAI;;;wBAA/BtB,YAAY;wBAClB,MAAM,IAAIuB,MAAM,AAAC,4BAAgDvB,OAArBD,SAASyB,MAAM,EAAC,OAAe,OAAVxB;;wBAGrD;;4BAAMD,SAAS0B,IAAI;;;wBAA3BxB,OAAQ;wBAEd,IAAI,CAACA,KAAKyB,SAAS,EAAE;4BACnB,MAAM,IAAIH,MAAM;wBAClB;wBAEMrB,cAAiC;4BACrCyB,UAAU1B,KAAKyB,SAAS;4BACxBE,cAAc3B,KAAK4B,aAAa,IAAI;wBACtC;wBAEA,IAAI5B,KAAK6B,mBAAmB,EAAE;4BAC5B5B,YAAY6B,QAAQ,GAAG9B,KAAK6B,mBAAmB;wBACjD;wBAEA;;4BAAO5B;;;;QACT;;WA5DWR"}
@@ -3,7 +3,7 @@
3
3
  */
4
4
  export type { VersionNegotiationOptions } from '@modelcontextprotocol/client';
5
5
  export { SdkError, SdkErrorCode } from '@modelcontextprotocol/client';
6
- export type { McpServerEntry, StartConfig } from '../schemas/servers.d.js';
6
+ export type { McpServerEntry, StartConfig, StopCommandConfig } from '../schemas/servers.d.js';
7
7
  export { probeAuthCapabilities } from './auth/capability-discovery.js';
8
8
  export { DiscoveryFetchError, isLoopbackUrl } from './auth/discovery-fetch.js';
9
9
  export type { AuthCapabilities, CallbackResult, OAuthCallbackListenerOptions, OAuthFlowOptions, TokenSet } from './auth/index.js';
@@ -3,7 +3,7 @@
3
3
  */
4
4
  export type { VersionNegotiationOptions } from '@modelcontextprotocol/client';
5
5
  export { SdkError, SdkErrorCode } from '@modelcontextprotocol/client';
6
- export type { McpServerEntry, StartConfig } from '../schemas/servers.d.js';
6
+ export type { McpServerEntry, StartConfig, StopCommandConfig } from '../schemas/servers.d.js';
7
7
  export { probeAuthCapabilities } from './auth/capability-discovery.js';
8
8
  export { DiscoveryFetchError, isLoopbackUrl } from './auth/discovery-fetch.js';
9
9
  export type { AuthCapabilities, CallbackResult, OAuthCallbackListenerOptions, OAuthFlowOptions, TokenSet } from './auth/index.js';
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/client/src/index.ts"],"sourcesContent":["/**\n * @mcp-z/client - MCP Client Library\n */\n\nexport type { VersionNegotiationOptions } from '@modelcontextprotocol/client';\n// SDK re-exports for protocol version negotiation: the connect-option type and the typed\n// errors a negotiation can fail with, so callers can handle era mismatch without\n// depending on the SDK themselves.\nexport { SdkError, SdkErrorCode } from '@modelcontextprotocol/client';\n// Config types (from schema)\nexport type { McpServerEntry, StartConfig } from '../schemas/servers.d.ts';\n// Auth - OAuth utilities\nexport { probeAuthCapabilities } from './auth/capability-discovery.ts';\nexport { DiscoveryFetchError, isLoopbackUrl } from './auth/discovery-fetch.ts';\nexport type { AuthCapabilities, CallbackResult, OAuthCallbackListenerOptions, OAuthFlowOptions, TokenSet } from './auth/index.ts';\nexport { InteractiveOAuthFlow } from './auth/interactive-oauth-flow.ts';\nexport { OAuthCallbackListener } from './auth/oauth-callback-listener.ts';\n// Client helpers and lightweight overloads\nexport { decorateClient, type ManagedClient, type PromptArguments, type WrappedCallToolReturn, type WrappedGetPromptReturn, type WrappedReadResourceReturn } from './client-helpers.ts';\n// Config - Configuration validation\nexport { type ValidationResult, validateServers } from './config/validate-config.ts';\n// Connection - MCP client connection utilities (internal helpers exposed for advanced use)\nexport type { JsonValue, PromptArgument, ToolArguments } from './connection/types.ts';\n// DCR - Dynamic Client Registration utilities\nexport { DcrAuthenticator } from './dcr/dcr-authenticator.ts';\nexport { DynamicClientRegistrar } from './dcr/dynamic-client-registrar.ts';\nexport type { ClientCredentials, DcrAuthenticatorOptions, DcrRegistrationOptions } from './dcr/index.ts';\nexport {\n type JsonValidator,\n type NativeCallToolResponse,\n type NativeGetPromptResponse,\n type NativeReadResourceResponse,\n PromptResponseError,\n PromptResponseWrapper,\n ResourceResponseError,\n ResourceResponseWrapper,\n ToolResponseError,\n ToolResponseWrapper,\n} from './response-wrappers.ts';\nexport type { CapabilityClient, CapabilityIndex, CapabilityType, IndexedCapability, IndexedPrompt, IndexedResource, IndexedTool, SearchField, SearchOptions, SearchResponse, SearchResult } from './search/index.ts';\n// Search - Capability discovery\nexport { buildCapabilityIndex, search, searchCapabilities } from './search/index.ts';\n// Spawn - Server registry (v3 API)\nexport { type CloseResult, type CreateServerRegistryOptions, createServerRegistry, type Dialect, type ServerRegistry, type ServersConfig } from './spawn/spawn-servers.ts';\nexport type { TransportType } from './types.ts';\n// Utils - Shared utilities\nexport { getLogLevel, type Logger, type LogLevel, logger, setLogLevel } from './utils/logger.ts';\nexport { resolveArgsPaths, resolvePath } from './utils/path-utils.ts';\n"],"names":["DcrAuthenticator","DiscoveryFetchError","DynamicClientRegistrar","InteractiveOAuthFlow","OAuthCallbackListener","PromptResponseError","PromptResponseWrapper","ResourceResponseError","ResourceResponseWrapper","SdkError","SdkErrorCode","ToolResponseError","ToolResponseWrapper","buildCapabilityIndex","createServerRegistry","decorateClient","getLogLevel","isLoopbackUrl","logger","probeAuthCapabilities","resolveArgsPaths","resolvePath","search","searchCapabilities","setLogLevel","validateServers"],"mappings":"AAAA;;CAEC;;;;;;;;;;;QAsBQA;eAAAA,oCAAgB;;QAXhBC;eAAAA,qCAAmB;;QAYnBC;eAAAA,gDAAsB;;QAVtBC;eAAAA,4CAAoB;;QACpBC;eAAAA,8CAAqB;;QAgB5BC;eAAAA,uCAAmB;;QACnBC;eAAAA,yCAAqB;;QACrBC;eAAAA,yCAAqB;;QACrBC;eAAAA,2CAAuB;;QA3BhBC;eAAAA,gBAAQ;;QAAEC;eAAAA,oBAAY;;QA4B7BC;eAAAA,qCAAiB;;QACjBC;eAAAA,uCAAmB;;QAIZC;eAAAA,6BAAoB;;QAEgCC;eAAAA,oCAAoB;;QAzBxEC;eAAAA,+BAAc;;QA4BdC;eAAAA,qBAAW;;QAjCUC;eAAAA,+BAAa;;QAiCOC;eAAAA,gBAAM;;QAlC/CC;eAAAA,4CAAqB;;QAmCrBC;eAAAA,6BAAgB;;QAAEC;eAAAA,wBAAW;;QANPC;eAAAA,eAAM;;QAAEC;eAAAA,2BAAkB;;QAKCC;eAAAA,qBAAW;;QA1BrCC;eAAAA,iCAAe;;;sBAZR;qCAID;gCACa;sCAEd;uCACC;+BAE4H;gCAE3G;kCAItB;wCACM;kCAahC;uBAG0D;8BAE+E;wBAGnE;2BAC/B"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/client/src/index.ts"],"sourcesContent":["/**\n * @mcp-z/client - MCP Client Library\n */\n\nexport type { VersionNegotiationOptions } from '@modelcontextprotocol/client';\n// SDK re-exports for protocol version negotiation: the connect-option type and the typed\n// errors a negotiation can fail with, so callers can handle era mismatch without\n// depending on the SDK themselves.\nexport { SdkError, SdkErrorCode } from '@modelcontextprotocol/client';\n// Config types (from schema)\nexport type { McpServerEntry, StartConfig, StopCommandConfig } from '../schemas/servers.d.ts';\n// Auth - OAuth utilities\nexport { probeAuthCapabilities } from './auth/capability-discovery.ts';\nexport { DiscoveryFetchError, isLoopbackUrl } from './auth/discovery-fetch.ts';\nexport type { AuthCapabilities, CallbackResult, OAuthCallbackListenerOptions, OAuthFlowOptions, TokenSet } from './auth/index.ts';\nexport { InteractiveOAuthFlow } from './auth/interactive-oauth-flow.ts';\nexport { OAuthCallbackListener } from './auth/oauth-callback-listener.ts';\n// Client helpers and lightweight overloads\nexport { decorateClient, type ManagedClient, type PromptArguments, type WrappedCallToolReturn, type WrappedGetPromptReturn, type WrappedReadResourceReturn } from './client-helpers.ts';\n// Config - Configuration validation\nexport { type ValidationResult, validateServers } from './config/validate-config.ts';\n// Connection - MCP client connection utilities (internal helpers exposed for advanced use)\nexport type { JsonValue, PromptArgument, ToolArguments } from './connection/types.ts';\n// DCR - Dynamic Client Registration utilities\nexport { DcrAuthenticator } from './dcr/dcr-authenticator.ts';\nexport { DynamicClientRegistrar } from './dcr/dynamic-client-registrar.ts';\nexport type { ClientCredentials, DcrAuthenticatorOptions, DcrRegistrationOptions } from './dcr/index.ts';\nexport {\n type JsonValidator,\n type NativeCallToolResponse,\n type NativeGetPromptResponse,\n type NativeReadResourceResponse,\n PromptResponseError,\n PromptResponseWrapper,\n ResourceResponseError,\n ResourceResponseWrapper,\n ToolResponseError,\n ToolResponseWrapper,\n} from './response-wrappers.ts';\nexport type { CapabilityClient, CapabilityIndex, CapabilityType, IndexedCapability, IndexedPrompt, IndexedResource, IndexedTool, SearchField, SearchOptions, SearchResponse, SearchResult } from './search/index.ts';\n// Search - Capability discovery\nexport { buildCapabilityIndex, search, searchCapabilities } from './search/index.ts';\n// Spawn - Server registry (v3 API)\nexport { type CloseResult, type CreateServerRegistryOptions, createServerRegistry, type Dialect, type ServerRegistry, type ServersConfig } from './spawn/spawn-servers.ts';\nexport type { TransportType } from './types.ts';\n// Utils - Shared utilities\nexport { getLogLevel, type Logger, type LogLevel, logger, setLogLevel } from './utils/logger.ts';\nexport { resolveArgsPaths, resolvePath } from './utils/path-utils.ts';\n"],"names":["DcrAuthenticator","DiscoveryFetchError","DynamicClientRegistrar","InteractiveOAuthFlow","OAuthCallbackListener","PromptResponseError","PromptResponseWrapper","ResourceResponseError","ResourceResponseWrapper","SdkError","SdkErrorCode","ToolResponseError","ToolResponseWrapper","buildCapabilityIndex","createServerRegistry","decorateClient","getLogLevel","isLoopbackUrl","logger","probeAuthCapabilities","resolveArgsPaths","resolvePath","search","searchCapabilities","setLogLevel","validateServers"],"mappings":"AAAA;;CAEC;;;;;;;;;;;QAsBQA;eAAAA,oCAAgB;;QAXhBC;eAAAA,qCAAmB;;QAYnBC;eAAAA,gDAAsB;;QAVtBC;eAAAA,4CAAoB;;QACpBC;eAAAA,8CAAqB;;QAgB5BC;eAAAA,uCAAmB;;QACnBC;eAAAA,yCAAqB;;QACrBC;eAAAA,yCAAqB;;QACrBC;eAAAA,2CAAuB;;QA3BhBC;eAAAA,gBAAQ;;QAAEC;eAAAA,oBAAY;;QA4B7BC;eAAAA,qCAAiB;;QACjBC;eAAAA,uCAAmB;;QAIZC;eAAAA,6BAAoB;;QAEgCC;eAAAA,oCAAoB;;QAzBxEC;eAAAA,+BAAc;;QA4BdC;eAAAA,qBAAW;;QAjCUC;eAAAA,+BAAa;;QAiCOC;eAAAA,gBAAM;;QAlC/CC;eAAAA,4CAAqB;;QAmCrBC;eAAAA,6BAAgB;;QAAEC;eAAAA,wBAAW;;QANPC;eAAAA,eAAM;;QAAEC;eAAAA,2BAAkB;;QAKCC;eAAAA,qBAAW;;QA1BrCC;eAAAA,iCAAe;;;sBAZR;qCAID;gCACa;sCAEd;uCACC;+BAE4H;gCAE3G;kCAItB;wCACM;kCAahC;uBAG0D;8BAE+E;wBAGnE;2BAC/B"}
@@ -0,0 +1,12 @@
1
+ interface TerminationResult {
2
+ killed: boolean;
3
+ error?: Error;
4
+ }
5
+ /** Tracks the detached process group used for owned processes on POSIX. */
6
+ export declare class OwnedProcessTree {
7
+ private readonly _rootPid;
8
+ constructor(rootPid: number);
9
+ isEmpty(): boolean;
10
+ terminate(): TerminationResult;
11
+ }
12
+ export {};
@@ -0,0 +1,12 @@
1
+ interface TerminationResult {
2
+ killed: boolean;
3
+ error?: Error;
4
+ }
5
+ /** Tracks the detached process group used for owned processes on POSIX. */
6
+ export declare class OwnedProcessTree {
7
+ private readonly _rootPid;
8
+ constructor(rootPid: number);
9
+ isEmpty(): boolean;
10
+ terminate(): TerminationResult;
11
+ }
12
+ export {};