mulesoft-anypoint-cli-agent-fabric-plugin 1.1.0 → 1.1.2-beta

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 (243) hide show
  1. package/LICENSE.txt +89 -0
  2. package/README.md +2 -0
  3. package/dist/commands/agent-network/project/build.d.ts +15 -15
  4. package/dist/commands/agent-network/project/build.js +10 -4
  5. package/dist/commands/agent-network/project/build.js.map +1 -1
  6. package/dist/commands/agent-network/project/create.d.ts +20 -20
  7. package/dist/commands/agent-network/project/create.js +9 -4
  8. package/dist/commands/agent-network/project/create.js.map +1 -1
  9. package/dist/commands/agent-network/project/deploy.d.ts +26 -23
  10. package/dist/commands/agent-network/project/deploy.js +122 -17
  11. package/dist/commands/agent-network/project/deploy.js.map +1 -1
  12. package/dist/commands/agent-network/project/mcp/introspect.d.ts +226 -0
  13. package/dist/commands/agent-network/project/mcp/introspect.js +910 -0
  14. package/dist/commands/agent-network/project/mcp/introspect.js.map +1 -0
  15. package/dist/commands/agent-network/project/publish.d.ts +14 -14
  16. package/dist/commands/agent-network/project/publish.js +12 -4
  17. package/dist/commands/agent-network/project/publish.js.map +1 -1
  18. package/dist/commands/agent-network/project/undeploy.d.ts +17 -17
  19. package/dist/commands/agent-network/project/undeploy.js +9 -4
  20. package/dist/commands/agent-network/project/undeploy.js.map +1 -1
  21. package/dist/commands/agent-network/project/unpublish.d.ts +16 -16
  22. package/dist/commands/agent-network/project/unpublish.js +9 -4
  23. package/dist/commands/agent-network/project/unpublish.js.map +1 -1
  24. package/dist/commands/agent-network/setup/dependencies.d.ts +6 -6
  25. package/dist/commands/agent-network/setup/dependencies.js +6 -1
  26. package/dist/commands/agent-network/setup/dependencies.js.map +1 -1
  27. package/dist/commands/agent-network/setup/gateways.d.ts +16 -16
  28. package/dist/commands/agent-network/setup/gateways.js +12 -6
  29. package/dist/commands/agent-network/setup/gateways.js.map +1 -1
  30. package/dist/errors/base-error.js +5 -0
  31. package/dist/errors/base-error.js.map +1 -1
  32. package/dist/errors/error-factory.d.ts +26 -12
  33. package/dist/errors/error-factory.js +121 -50
  34. package/dist/errors/error-factory.js.map +1 -1
  35. package/dist/helpers/connection-id.js +6 -2
  36. package/dist/helpers/connection-id.js.map +1 -1
  37. package/dist/helpers/connection.js +5 -0
  38. package/dist/helpers/connection.js.map +1 -1
  39. package/dist/helpers/dependency-manager.d.ts +1 -1
  40. package/dist/helpers/dependency-manager.js +8 -3
  41. package/dist/helpers/dependency-manager.js.map +1 -1
  42. package/dist/helpers/entitlement-utils.js +5 -0
  43. package/dist/helpers/entitlement-utils.js.map +1 -1
  44. package/dist/helpers/policy-helper.d.ts +1 -1
  45. package/dist/helpers/policy-helper.js +13 -6
  46. package/dist/helpers/policy-helper.js.map +1 -1
  47. package/dist/helpers/project/api-project-dependency-fetcher.js +9 -3
  48. package/dist/helpers/project/api-project-dependency-fetcher.js.map +1 -1
  49. package/dist/helpers/project/constants.d.ts +0 -2
  50. package/dist/helpers/project/constants.js +6 -1
  51. package/dist/helpers/project/constants.js.map +1 -1
  52. package/dist/helpers/project/debug-messages.js +5 -0
  53. package/dist/helpers/project/debug-messages.js.map +1 -1
  54. package/dist/helpers/project/templates.js +5 -0
  55. package/dist/helpers/project/templates.js.map +1 -1
  56. package/dist/helpers/project/uris.js +5 -0
  57. package/dist/helpers/project/uris.js.map +1 -1
  58. package/dist/helpers/project/validation-commons.js +5 -0
  59. package/dist/helpers/project/validation-commons.js.map +1 -1
  60. package/dist/helpers/request-logging.js +10 -6
  61. package/dist/helpers/request-logging.js.map +1 -1
  62. package/dist/helpers/request-utils.js +6 -1
  63. package/dist/helpers/request-utils.js.map +1 -1
  64. package/dist/helpers/types.js +5 -0
  65. package/dist/helpers/types.js.map +1 -1
  66. package/dist/helpers/utils.d.ts +6 -7
  67. package/dist/helpers/utils.js +81 -105
  68. package/dist/helpers/utils.js.map +1 -1
  69. package/dist/index.js +14 -11
  70. package/dist/index.js.map +1 -1
  71. package/dist/resources/mcp-server-schema.json +574 -0
  72. package/dist/types/agent-network-v2.d.ts +1 -1
  73. package/dist/types/agent-network-v2.js +6 -1
  74. package/dist/types/agent-network-v2.js.map +1 -1
  75. package/dist/types/agent-network.js +6 -1
  76. package/dist/types/agent-network.js.map +1 -1
  77. package/dist/types/types.d.ts +30 -34
  78. package/dist/types/types.js +5 -0
  79. package/dist/types/types.js.map +1 -1
  80. package/dist/utils/access-management.js +7 -1
  81. package/dist/utils/access-management.js.map +1 -1
  82. package/dist/utils/builders/builder.d.ts +0 -1
  83. package/dist/utils/builders/builder.js +6 -10
  84. package/dist/utils/builders/builder.js.map +1 -1
  85. package/dist/utils/builders/common/agent-metadata.js +10 -6
  86. package/dist/utils/builders/common/agent-metadata.js.map +1 -1
  87. package/dist/utils/builders/common/asset-file-resolver.js +6 -2
  88. package/dist/utils/builders/common/asset-file-resolver.js.map +1 -1
  89. package/dist/utils/builders/common/connection-facet-helpers.d.ts +0 -1
  90. package/dist/utils/builders/common/connection-facet-helpers.js +9 -8
  91. package/dist/utils/builders/common/connection-facet-helpers.js.map +1 -1
  92. package/dist/utils/builders/common/connection-metadata.js +7 -3
  93. package/dist/utils/builders/common/connection-metadata.js.map +1 -1
  94. package/dist/utils/builders/common/network-builder-helpers.js +6 -2
  95. package/dist/utils/builders/common/network-builder-helpers.js.map +1 -1
  96. package/dist/utils/builders/common/network-metadata.d.ts +2 -2
  97. package/dist/utils/builders/common/network-metadata.js +9 -4
  98. package/dist/utils/builders/common/network-metadata.js.map +1 -1
  99. package/dist/utils/builders/common/registry-entry.js +6 -2
  100. package/dist/utils/builders/common/registry-entry.js.map +1 -1
  101. package/dist/utils/builders/common/types.d.ts +7 -0
  102. package/dist/utils/builders/common/types.js +5 -0
  103. package/dist/utils/builders/common/types.js.map +1 -1
  104. package/dist/utils/builders/network-lock.d.ts +38 -0
  105. package/dist/utils/builders/network-lock.js +108 -0
  106. package/dist/utils/builders/network-lock.js.map +1 -0
  107. package/dist/utils/builders/policies-factory.js +13 -9
  108. package/dist/utils/builders/policies-factory.js.map +1 -1
  109. package/dist/utils/builders/project-builder-impl.d.ts +27 -19
  110. package/dist/utils/builders/project-builder-impl.js +74 -29
  111. package/dist/utils/builders/project-builder-impl.js.map +1 -1
  112. package/dist/utils/builders/project-builder.d.ts +24 -8
  113. package/dist/utils/builders/project-builder.js +7 -2
  114. package/dist/utils/builders/project-builder.js.map +1 -1
  115. package/dist/utils/builders/remote-space-resolver.d.ts +2 -0
  116. package/dist/utils/builders/remote-space-resolver.js +38 -22
  117. package/dist/utils/builders/remote-space-resolver.js.map +1 -1
  118. package/dist/utils/builders/space-serializer.d.ts +0 -1
  119. package/dist/utils/builders/space-serializer.js +19 -35
  120. package/dist/utils/builders/space-serializer.js.map +1 -1
  121. package/dist/utils/builders/tooling-metadata.d.ts +8 -0
  122. package/dist/utils/builders/tooling-metadata.js +69 -0
  123. package/dist/utils/builders/tooling-metadata.js.map +1 -0
  124. package/dist/utils/builders/v1/agent-builder.js +5 -0
  125. package/dist/utils/builders/v1/agent-builder.js.map +1 -1
  126. package/dist/utils/builders/v1/broker-builder.js +19 -11
  127. package/dist/utils/builders/v1/broker-builder.js.map +1 -1
  128. package/dist/utils/builders/v1/connections-builder.js +5 -3
  129. package/dist/utils/builders/v1/connections-builder.js.map +1 -1
  130. package/dist/utils/builders/v1/llm-builder.js +5 -0
  131. package/dist/utils/builders/v1/llm-builder.js.map +1 -1
  132. package/dist/utils/builders/v1/mcp-builder.js +5 -0
  133. package/dist/utils/builders/v1/mcp-builder.js.map +1 -1
  134. package/dist/utils/builders/v1/network-builder.js +9 -1
  135. package/dist/utils/builders/v1/network-builder.js.map +1 -1
  136. package/dist/utils/builders/v1/path.js +5 -0
  137. package/dist/utils/builders/v1/path.js.map +1 -1
  138. package/dist/utils/builders/v2/agent-builder.js +5 -0
  139. package/dist/utils/builders/v2/agent-builder.js.map +1 -1
  140. package/dist/utils/builders/v2/broker-builder.js +13 -3
  141. package/dist/utils/builders/v2/broker-builder.js.map +1 -1
  142. package/dist/utils/builders/v2/connections-builder.js +8 -3
  143. package/dist/utils/builders/v2/connections-builder.js.map +1 -1
  144. package/dist/utils/builders/v2/llm-builder.js +5 -0
  145. package/dist/utils/builders/v2/llm-builder.js.map +1 -1
  146. package/dist/utils/builders/v2/mcp-builder.js +5 -0
  147. package/dist/utils/builders/v2/mcp-builder.js.map +1 -1
  148. package/dist/utils/builders/v2/network-builder.d.ts +1 -1
  149. package/dist/utils/builders/v2/network-builder.js +7 -2
  150. package/dist/utils/builders/v2/network-builder.js.map +1 -1
  151. package/dist/utils/builders/v2/path.js +5 -0
  152. package/dist/utils/builders/v2/path.js.map +1 -1
  153. package/dist/utils/constants.d.ts +3 -3
  154. package/dist/utils/constants.js +17 -10
  155. package/dist/utils/constants.js.map +1 -1
  156. package/dist/utils/exchange.js +16 -10
  157. package/dist/utils/exchange.js.map +1 -1
  158. package/dist/utils/facets/abstract-facet.d.ts +2 -2
  159. package/dist/utils/facets/abstract-facet.js +5 -0
  160. package/dist/utils/facets/abstract-facet.js.map +1 -1
  161. package/dist/utils/facets/agent-graph-facet.d.ts +2 -2
  162. package/dist/utils/facets/agent-graph-facet.js +25 -16
  163. package/dist/utils/facets/agent-graph-facet.js.map +1 -1
  164. package/dist/utils/facets/api-instance-facet.d.ts +3 -4
  165. package/dist/utils/facets/api-instance-facet.js +42 -97
  166. package/dist/utils/facets/api-instance-facet.js.map +1 -1
  167. package/dist/utils/facets/apim-policy-helpers.d.ts +13 -12
  168. package/dist/utils/facets/apim-policy-helpers.js +36 -22
  169. package/dist/utils/facets/apim-policy-helpers.js.map +1 -1
  170. package/dist/utils/facets/asset-facet.d.ts +2 -2
  171. package/dist/utils/facets/asset-facet.js +20 -7
  172. package/dist/utils/facets/asset-facet.js.map +1 -1
  173. package/dist/utils/facets/connection-facet.d.ts +3 -4
  174. package/dist/utils/facets/connection-facet.js +43 -98
  175. package/dist/utils/facets/connection-facet.js.map +1 -1
  176. package/dist/utils/facets/deployment-helpers.js +16 -13
  177. package/dist/utils/facets/deployment-helpers.js.map +1 -1
  178. package/dist/utils/facets/deployment-logs.d.ts +5 -0
  179. package/dist/utils/facets/deployment-logs.js +87 -0
  180. package/dist/utils/facets/deployment-logs.js.map +1 -0
  181. package/dist/utils/facets/deployment-runner.d.ts +2 -1
  182. package/dist/utils/facets/deployment-runner.js +43 -12
  183. package/dist/utils/facets/deployment-runner.js.map +1 -1
  184. package/dist/utils/facets/facets.js +33 -10
  185. package/dist/utils/facets/facets.js.map +1 -1
  186. package/dist/utils/facets/mule-application-facet.d.ts +2 -2
  187. package/dist/utils/facets/mule-application-facet.js +34 -27
  188. package/dist/utils/facets/mule-application-facet.js.map +1 -1
  189. package/dist/utils/facets/publication-metadata-patcher.js +9 -2
  190. package/dist/utils/facets/publication-metadata-patcher.js.map +1 -1
  191. package/dist/utils/facets/publication-rank.js +9 -3
  192. package/dist/utils/facets/publication-rank.js.map +1 -1
  193. package/dist/utils/facets/undeploy-helpers.d.ts +1 -1
  194. package/dist/utils/facets/undeploy-helpers.js +15 -10
  195. package/dist/utils/facets/undeploy-helpers.js.map +1 -1
  196. package/dist/utils/facets/unpublish-preflight.js +6 -2
  197. package/dist/utils/facets/unpublish-preflight.js.map +1 -1
  198. package/dist/utils/files.d.ts +0 -1
  199. package/dist/utils/files.js +5 -0
  200. package/dist/utils/files.js.map +1 -1
  201. package/dist/utils/gateway-mode.js +5 -0
  202. package/dist/utils/gateway-mode.js.map +1 -1
  203. package/dist/utils/gateway.js +14 -10
  204. package/dist/utils/gateway.js.map +1 -1
  205. package/dist/utils/logger.js +19 -14
  206. package/dist/utils/logger.js.map +1 -1
  207. package/dist/utils/mcp/mcp-metadata-mapper.d.ts +26 -0
  208. package/dist/utils/mcp/mcp-metadata-mapper.js +58 -0
  209. package/dist/utils/mcp/mcp-metadata-mapper.js.map +1 -0
  210. package/dist/utils/mcp/project-registrar.d.ts +21 -0
  211. package/dist/utils/mcp/project-registrar.js +96 -0
  212. package/dist/utils/mcp/project-registrar.js.map +1 -0
  213. package/dist/utils/mcp/registry-key.d.ts +7 -0
  214. package/dist/utils/mcp/registry-key.js +72 -0
  215. package/dist/utils/mcp/registry-key.js.map +1 -0
  216. package/dist/utils/naming.js +7 -3
  217. package/dist/utils/naming.js.map +1 -1
  218. package/dist/utils/promise/promiseCreator.js +5 -0
  219. package/dist/utils/promise/promiseCreator.js.map +1 -1
  220. package/dist/utils/report/junit-report.js +5 -0
  221. package/dist/utils/report/junit-report.js.map +1 -1
  222. package/dist/utils/report/validation-report.js +5 -0
  223. package/dist/utils/report/validation-report.js.map +1 -1
  224. package/dist/utils/request-executor.d.ts +17 -0
  225. package/dist/utils/request-executor.js +121 -0
  226. package/dist/utils/request-executor.js.map +1 -0
  227. package/dist/utils/uris.d.ts +5 -0
  228. package/dist/utils/uris.js +19 -1
  229. package/dist/utils/uris.js.map +1 -1
  230. package/dist/utils/variables.js +5 -0
  231. package/dist/utils/variables.js.map +1 -1
  232. package/dist/utils/zip-utils.d.ts +1 -3
  233. package/dist/utils/zip-utils.js +5 -0
  234. package/dist/utils/zip-utils.js.map +1 -1
  235. package/package.json +18 -13
  236. package/scripts/resolve-version.sh +132 -0
  237. package/scripts/resolve-version.test.sh +91 -0
  238. package/scripts/test-publish-npm.sh +130 -0
  239. package/templates/agentic-network/agent-network.yaml.template +3 -3
  240. package/templates/agentic-network/brokers/broker1.agent.template +4 -5
  241. package/dist/utils/retryable-requester.d.ts +0 -6
  242. package/dist/utils/retryable-requester.js +0 -43
  243. package/dist/utils/retryable-requester.js.map +0 -1
@@ -0,0 +1,910 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright (c) 2026, Salesforce, Inc.
4
+ * All rights reserved.
5
+ * For full license text, see the LICENSE.txt file
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.REMOTE_TRANSPORTS = exports.CLIOAuthProvider = exports.ConfOAuthStorage = exports.CallbackServer = void 0;
9
+ exports.escapeHtml = escapeHtml;
10
+ exports.isOAuthRequired = isOAuthRequired;
11
+ exports.buildMcpUrl = buildMcpUrl;
12
+ exports.isNodeVersionSupported = isNodeVersionSupported;
13
+ exports.browserOpenArgs = browserOpenArgs;
14
+ exports.buildAuthHeaders = buildAuthHeaders;
15
+ exports.attemptSilentRefresh = attemptSilentRefresh;
16
+ exports.loadMcpServerSchema = loadMcpServerSchema;
17
+ exports.validateServerJson = validateServerJson;
18
+ exports.resolveRemoteFromServerJson = resolveRemoteFromServerJson;
19
+ exports.loadServerJson = loadServerJson;
20
+ const tslib_1 = require("tslib");
21
+ const core_1 = require("@oclif/core");
22
+ const index_js_1 = require("@modelcontextprotocol/sdk/client/index.js");
23
+ const streamableHttp_js_1 = require("@modelcontextprotocol/sdk/client/streamableHttp.js");
24
+ const sse_js_1 = require("@modelcontextprotocol/sdk/client/sse.js");
25
+ const types_js_1 = require("@modelcontextprotocol/sdk/types.js");
26
+ const auth_js_1 = require("@modelcontextprotocol/sdk/client/auth.js");
27
+ const fs = tslib_1.__importStar(require("fs-extra"));
28
+ const node_child_process_1 = require("node:child_process");
29
+ const http = tslib_1.__importStar(require("node:http"));
30
+ const url = tslib_1.__importStar(require("node:url"));
31
+ const os = tslib_1.__importStar(require("node:os"));
32
+ const uuid_1 = require("uuid");
33
+ const nodePath = tslib_1.__importStar(require("node:path"));
34
+ const ajv_1 = tslib_1.__importDefault(require("ajv"));
35
+ const ajv_formats_1 = tslib_1.__importDefault(require("ajv-formats"));
36
+ const anypoint_cli_command_lib_1 = tslib_1.__importDefault(require("anypoint-cli-command-lib"));
37
+ const yaml_1 = require("yaml");
38
+ const mcp_metadata_mapper_1 = require("../../../../utils/mcp/mcp-metadata-mapper");
39
+ const registry_key_1 = require("../../../../utils/mcp/registry-key");
40
+ const project_registrar_1 = require("../../../../utils/mcp/project-registrar");
41
+ const error_factory_1 = require("../../../../errors/error-factory");
42
+ const logger_1 = require("../../../../utils/logger");
43
+ const OAUTH_CONFIG_KEY = 'mcp-oauth';
44
+ const CSP_HEADER_VALUE = "default-src 'none'";
45
+ const TRANSPORT_STREAMABLE_HTTP = 'streamable-http';
46
+ const FLAG_SERVER_JSON = 'server-json';
47
+ /**
48
+ * Writes a user-facing status/progress message to stderr so that stdout
49
+ * remains reserved for the command's actual output (which may be piped
50
+ * into other CLI tools).
51
+ */
52
+ function notify(message) {
53
+ process.stderr.write(`${message}\n`);
54
+ }
55
+ /**
56
+ * Escapes the five HTML-significant characters so untrusted values can be
57
+ * safely embedded in an HTML response body. The OAuth `error` and
58
+ * `error_description` query parameters come from the authorization server
59
+ * (RFC 6749 §4.1.2.1 allows arbitrary text) and from the query string, so
60
+ * both are untrusted. Without escaping they enable XSS at the loopback
61
+ * origin (http://127.0.0.1:3000).
62
+ */
63
+ function escapeHtml(value) {
64
+ return value
65
+ .replace(/&/g, '&')
66
+ .replace(/</g, '&lt;')
67
+ .replace(/>/g, '&gt;')
68
+ .replace(/"/g, '&quot;')
69
+ .replace(/'/g, '&#39;');
70
+ }
71
+ /**
72
+ * Normalizes a query parameter to a single string or undefined.
73
+ * url.parse with `parseQueryString: true` yields `string | string[] | undefined`.
74
+ * Repeated params (e.g., ?code=a&code=b) produce arrays; we take the first.
75
+ */
76
+ function normalizeQueryParam(value) {
77
+ return Array.isArray(value) ? value[0] : value;
78
+ }
79
+ /**
80
+ * Creates a temporary HTTP server to receive the OAuth callback
81
+ */
82
+ class CallbackServer {
83
+ constructor(port = 3000) {
84
+ this.port = port;
85
+ }
86
+ /**
87
+ * Starts the server and waits for the OAuth callback
88
+ * Returns the authorization code and state or throws on timeout/error
89
+ */
90
+ async waitForCallback(timeoutMs = 300000) {
91
+ return new Promise((resolve, reject) => {
92
+ const timeout = setTimeout(() => {
93
+ this.close();
94
+ reject(new Error('OAuth callback timeout - no response received within 5 minutes'));
95
+ }, timeoutMs);
96
+ this.server = http.createServer((req, res) => {
97
+ var _a;
98
+ const parsedUrl = url.parse(req.url || '', true);
99
+ logger_1.Log.debug(`[Callback Server] Received request to: ${parsedUrl.pathname}`);
100
+ if (parsedUrl.pathname === '/callback') {
101
+ const code = normalizeQueryParam(parsedUrl.query.code);
102
+ const error = normalizeQueryParam(parsedUrl.query.error);
103
+ const state = normalizeQueryParam(parsedUrl.query.state);
104
+ if (error) {
105
+ // error and error_description are attacker-influenced
106
+ // (see escapeHtml). Escape before embedding, and lock
107
+ // the page down with CSP so a future regression can't
108
+ // execute injected script.
109
+ const errorDescription = (_a = normalizeQueryParam(parsedUrl.query.error_description)) !== null && _a !== void 0 ? _a : '';
110
+ res.writeHead(400, { 'Content-Type': 'text/html', 'Content-Security-Policy': CSP_HEADER_VALUE });
111
+ res.end(`<html><body style="font-family: sans-serif; text-align: center; padding: 50px;"><h1>Authorization Failed</h1><p>Error: ${escapeHtml(error)}</p><p>${escapeHtml(errorDescription)}</p><p>You can close this window.</p></body></html>`);
112
+ clearTimeout(timeout);
113
+ this.close();
114
+ reject(new Error(`OAuth error: ${error}`));
115
+ return;
116
+ }
117
+ if (code) {
118
+ res.writeHead(200, { 'Content-Type': 'text/html', 'Content-Security-Policy': "default-src 'none'" });
119
+ res.end('<html><body style="font-family: sans-serif; text-align: center; padding: 50px;"><h1>Authorization Successful</h1><p>You can close this window and return to the terminal.</p></body></html>');
120
+ clearTimeout(timeout);
121
+ this.close();
122
+ resolve({ code, state });
123
+ }
124
+ else {
125
+ res.writeHead(400, { 'Content-Type': 'text/html', 'Content-Security-Policy': CSP_HEADER_VALUE });
126
+ res.end('<html><body><h1>Invalid Callback</h1><p>No authorization code received.</p></body></html>');
127
+ clearTimeout(timeout);
128
+ this.close();
129
+ reject(new Error('No authorization code in callback'));
130
+ }
131
+ }
132
+ else {
133
+ res.writeHead(404);
134
+ res.end('Not found');
135
+ }
136
+ });
137
+ // Bind to the loopback interface only. Without an explicit host,
138
+ // Node listens on all interfaces (0.0.0.0), which would let anyone
139
+ // on the same LAN/VPN race for the authorization code during the
140
+ // small window the server is open.
141
+ this.server.listen(this.port, '127.0.0.1', () => {
142
+ notify(`Callback server listening on http://127.0.0.1:${this.port}/callback`);
143
+ });
144
+ this.server.on('error', (err) => {
145
+ clearTimeout(timeout);
146
+ if (err.code === 'EADDRINUSE') {
147
+ reject(new Error(`Port ${this.port} is already in use. Please close other applications using this port.`));
148
+ }
149
+ else {
150
+ reject(err);
151
+ }
152
+ });
153
+ });
154
+ }
155
+ close() {
156
+ if (this.server) {
157
+ this.server.close();
158
+ this.server = undefined;
159
+ }
160
+ }
161
+ }
162
+ exports.CallbackServer = CallbackServer;
163
+ /**
164
+ * Default storage implementation using the conf library via anypoint-cli-command
165
+ */
166
+ class ConfOAuthStorage {
167
+ getSession(sessionId) {
168
+ const key = `${OAUTH_CONFIG_KEY}.${sessionId}`;
169
+ return anypoint_cli_command_lib_1.default.get(key);
170
+ }
171
+ saveSession(sessionId, session) {
172
+ const key = `${OAUTH_CONFIG_KEY}.${sessionId}`;
173
+ anypoint_cli_command_lib_1.default.set(key, session);
174
+ }
175
+ clearSession(sessionId) {
176
+ const key = `${OAUTH_CONFIG_KEY}.${sessionId}`;
177
+ anypoint_cli_command_lib_1.default.delete(key);
178
+ }
179
+ }
180
+ exports.ConfOAuthStorage = ConfOAuthStorage;
181
+ /**
182
+ * CLI OAuth Provider implementation for MCP authentication
183
+ * Implements the OAuth 2.1 Authorization Code flow with PKCE
184
+ */
185
+ class CLIOAuthProvider {
186
+ constructor(serverUrl, clientName, storage, redirectUrl, callbackServer) {
187
+ this._clientName = clientName;
188
+ // Default to the loopback IP so it exactly matches the host the
189
+ // callback server binds to (see CallbackServer.waitForCallback).
190
+ this._redirectUrl = redirectUrl || 'http://127.0.0.1:3000/callback';
191
+ this.storage = storage || new ConfOAuthStorage();
192
+ // Generate a stable session ID from the server URL
193
+ this.sessionId = Buffer.from(serverUrl).toString('base64url');
194
+ const redirectUrlObj = new URL(this._redirectUrl);
195
+ // An empty port component means the URL used the protocol default;
196
+ // fall back to 3000. A non-empty but unparseable port is a real
197
+ // misconfiguration: binding to a fallback would silently disagree
198
+ // with the redirect URI the auth server is told to use, so we fail
199
+ // loudly instead.
200
+ let port = 3000;
201
+ if (redirectUrlObj.port !== '') {
202
+ port = Number.parseInt(redirectUrlObj.port, 10);
203
+ if (isNaN(port)) {
204
+ throw new TypeError(`Invalid port in redirect URL: ${this._redirectUrl}`);
205
+ }
206
+ }
207
+ this.callbackServer = callbackServer || new CallbackServer(port);
208
+ }
209
+ get redirectUrl() {
210
+ return this._redirectUrl;
211
+ }
212
+ get clientMetadata() {
213
+ return {
214
+ redirect_uris: [this._redirectUrl],
215
+ client_name: this._clientName,
216
+ grant_types: ['authorization_code', 'refresh_token'],
217
+ response_types: ['code'],
218
+ token_endpoint_auth_method: 'none',
219
+ };
220
+ }
221
+ getSession() {
222
+ return this.storage.getSession(this.sessionId) || {};
223
+ }
224
+ updateSession(updates) {
225
+ const current = this.getSession();
226
+ this.storage.saveSession(this.sessionId, { ...current, ...updates });
227
+ }
228
+ clientInformation() {
229
+ return this.getSession().clientInformation;
230
+ }
231
+ saveClientInformation(clientInformation) {
232
+ this.updateSession({ clientInformation });
233
+ notify('Client registered with authorization server');
234
+ }
235
+ tokens() {
236
+ return this.getSession().tokens;
237
+ }
238
+ saveTokens(tokens) {
239
+ this.updateSession({ tokens });
240
+ notify('OAuth tokens saved successfully');
241
+ }
242
+ async redirectToAuthorization(authorizationUrl) {
243
+ notify('\n=== OAuth Authorization Required ===');
244
+ // Print the URL up front, before attempting to open a browser. On a
245
+ // headless server or SSH session the browser open will fail silently
246
+ // and the flow would otherwise just sit waiting until the 5-minute
247
+ // timeout; showing the URL first lets the user open it manually right
248
+ // away.
249
+ notify(`If the browser doesn't open automatically, visit:\n${authorizationUrl.toString()}\n`);
250
+ notify('Opening browser for authorization...\n');
251
+ this.authorizationCodePromise = this.callbackServer.waitForCallback();
252
+ await this.openBrowser(authorizationUrl.toString());
253
+ notify('Waiting for authorization... (This will timeout after 5 minutes)');
254
+ }
255
+ saveCodeVerifier(codeVerifier) {
256
+ this.updateSession({ codeVerifier });
257
+ }
258
+ codeVerifier() {
259
+ const verifier = this.getSession().codeVerifier;
260
+ if (!verifier) {
261
+ throw new Error('No code verifier found in session');
262
+ }
263
+ return verifier;
264
+ }
265
+ state() {
266
+ const generated = (0, uuid_1.v4)();
267
+ this.updateSession({ state: generated });
268
+ return generated;
269
+ }
270
+ invalidateCredentials() {
271
+ this.storage.clearSession(this.sessionId);
272
+ notify('OAuth credentials cleared');
273
+ }
274
+ /**
275
+ * Returns the authorization code received from the callback
276
+ */
277
+ async getAuthorizationCode() {
278
+ if (this.authorizationCodePromise) {
279
+ try {
280
+ const { code, state: receivedState } = await this.authorizationCodePromise;
281
+ this.authorizationCodePromise = undefined;
282
+ const expectedState = this.getSession().state;
283
+ if (expectedState && receivedState !== expectedState) {
284
+ throw new Error('OAuth state mismatch — possible CSRF, aborting');
285
+ }
286
+ return code;
287
+ }
288
+ catch (error) {
289
+ this.authorizationCodePromise = undefined;
290
+ throw error;
291
+ }
292
+ }
293
+ return undefined;
294
+ }
295
+ cleanup() {
296
+ this.callbackServer.close();
297
+ }
298
+ async openBrowser(targetUrl) {
299
+ // Only open http/https URLs. This prevents attacker-controlled
300
+ // discovery URLs from being handed to the shell with schemes like
301
+ // file:// or javascript:.
302
+ let parsed;
303
+ try {
304
+ parsed = new URL(targetUrl);
305
+ }
306
+ catch {
307
+ notify('Invalid authorization URL. Please open the URL manually.');
308
+ return;
309
+ }
310
+ if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {
311
+ notify('Refusing to open non-http(s) authorization URL. Please open it manually.');
312
+ return;
313
+ }
314
+ // Use spawn with an argv array (no shell). The URL is passed as a
315
+ // single argument so shell metacharacters inside it ($, `, ;, etc.)
316
+ // cannot trigger command substitution.
317
+ const { command, args } = browserOpenArgs(parsed.toString(), os.platform());
318
+ try {
319
+ const child = (0, node_child_process_1.spawn)(command, args, {
320
+ stdio: 'ignore',
321
+ detached: true,
322
+ shell: false,
323
+ });
324
+ child.on('error', () => {
325
+ notify('Failed to open browser automatically. Please open the URL manually.');
326
+ });
327
+ child.unref();
328
+ }
329
+ catch {
330
+ notify('Failed to open browser automatically. Please open the URL manually.');
331
+ }
332
+ }
333
+ }
334
+ exports.CLIOAuthProvider = CLIOAuthProvider;
335
+ /**
336
+ * Maximum message length to inspect when falling back to string matching.
337
+ * Bounds the work done on untrusted error text.
338
+ */
339
+ const MAX_ERROR_MESSAGE_SCAN = 1024;
340
+ /**
341
+ * Single-character alphanumeric test using char-code comparisons only.
342
+ * Avoids regex so this helper is trivially ReDoS-safe.
343
+ */
344
+ function isAlphanumeric(ch) {
345
+ const code = ch.charCodeAt(0);
346
+ const isDigit = code >= 48 && code <= 57;
347
+ const isLower = code >= 97 && code <= 122;
348
+ const isUpper = code >= 65 && code <= 90;
349
+ return isDigit || isLower || isUpper;
350
+ }
351
+ /**
352
+ * Returns true if `message` contains `prefix` followed (after optional
353
+ * whitespace, colon, or equals) by `target`. Uses plain string operations
354
+ * only — no regular expressions — so it is safe against adversarial input.
355
+ */
356
+ function messageContainsStatus(message, prefix, target) {
357
+ const lower = message.slice(0, MAX_ERROR_MESSAGE_SCAN).toLowerCase();
358
+ const needle = prefix.toLowerCase();
359
+ let searchFrom = 0;
360
+ while (searchFrom <= lower.length - needle.length) {
361
+ const idx = lower.indexOf(needle, searchFrom);
362
+ if (idx === -1) {
363
+ return false;
364
+ }
365
+ // Skip past the prefix and any separator characters (whitespace/colon/equals).
366
+ let i = idx + needle.length;
367
+ const separatorLimit = Math.min(lower.length, i + 16);
368
+ while (i < separatorLimit && (lower[i] === ' ' || lower[i] === '\t' || lower[i] === ':' || lower[i] === '=')) {
369
+ i++;
370
+ }
371
+ if (lower.startsWith(target, i)) {
372
+ // Ensure the target is not part of a larger number/word (e.g. "4011").
373
+ const charAfter = lower[i + target.length];
374
+ if (charAfter === undefined || !isAlphanumeric(charAfter)) {
375
+ return true;
376
+ }
377
+ }
378
+ searchFrom = idx + 1;
379
+ }
380
+ return false;
381
+ }
382
+ /**
383
+ * Checks if an error indicates OAuth authentication is required (HTTP 401).
384
+ * Only returns true for explicit 401 status codes on structured error objects.
385
+ */
386
+ function isOAuthRequired(error) {
387
+ var _a;
388
+ if (!error) {
389
+ return false;
390
+ }
391
+ // Explicit 401 on structured properties (most reliable)
392
+ if (error.status === 401 || error.code === 401 || ((_a = error.response) === null || _a === void 0 ? void 0 : _a.status) === 401) {
393
+ return true;
394
+ }
395
+ // Fallback: detect the well-defined shapes "HTTP 401" or "status: 401" in
396
+ // the message, but avoid matching stray "401" substrings (e.g. "abc-401-xyz").
397
+ const message = error.message || '';
398
+ return messageContainsStatus(message, 'http', '401') ||
399
+ messageContainsStatus(message, 'status', '401');
400
+ }
401
+ /**
402
+ * Builds the full MCP endpoint URL from base URL and transport path.
403
+ * If the base URL already contains the transport path, it is returned as-is
404
+ * (preserving any trailing slash the user provided, which may be required
405
+ * by some servers).
406
+ * Otherwise, the transport path is appended to the base URL.
407
+ */
408
+ function buildMcpUrl(baseUrl, transportPath) {
409
+ const base = new URL(baseUrl);
410
+ const normalizedTransportPath = transportPath.startsWith('/') ? transportPath : `/${transportPath}`;
411
+ // Strip a single trailing slash for comparison, but treat "/" (root) as empty.
412
+ const strippedPath = base.pathname === '/' ? '' : base.pathname.replace(/\/$/, '');
413
+ if (strippedPath.endsWith(normalizedTransportPath)) {
414
+ // Preserve the original path exactly as provided (including trailing slash).
415
+ return base.toString();
416
+ }
417
+ base.pathname = strippedPath + normalizedTransportPath;
418
+ return base.toString();
419
+ }
420
+ /**
421
+ * Checks if the current Node.js version supports OAuth crypto requirements
422
+ */
423
+ function isNodeVersionSupported(version = process.version) {
424
+ const majorVersion = Number.parseInt(version.split('.')[0].slice(1), 10);
425
+ return majorVersion >= 20;
426
+ }
427
+ /**
428
+ * Platform-specific argv to open a URL in the default browser.
429
+ * Returned as { command, args } so callers can invoke it via spawn
430
+ * without a shell — critical because the URL may be attacker-controlled
431
+ * (OAuth authorization URL sourced from a remote MCP server's discovery
432
+ * document). Using a shell string would allow $() and backtick injection.
433
+ * Exported for testing.
434
+ */
435
+ function browserOpenArgs(targetUrl, platform) {
436
+ switch (platform) {
437
+ case 'darwin':
438
+ return { command: 'open', args: [targetUrl] };
439
+ case 'win32':
440
+ // `start` is a cmd.exe builtin. The empty "" is the window title
441
+ // (required because `start "foo"` would treat "foo" as the title).
442
+ return { command: 'cmd', args: ['/c', 'start', '', targetUrl] };
443
+ default:
444
+ return { command: 'xdg-open', args: [targetUrl] };
445
+ }
446
+ }
447
+ /**
448
+ * Builds the authentication header for the MCP request.
449
+ *
450
+ * - bearer: sets "<header>: Bearer <value>" (default header: Authorization)
451
+ * - apikey: sets "<header>: <value>" (default header: x-api-key)
452
+ * - none: returns an empty object
453
+ */
454
+ function buildAuthHeaders(authType, authValue, authHeader) {
455
+ if (authType === 'none' || !authType) {
456
+ return {};
457
+ }
458
+ if (!authValue) {
459
+ throw new Error(`--auth-value is required when --auth-type is '${authType}'`);
460
+ }
461
+ if (authType === 'bearer') {
462
+ const headerName = authHeader || 'Authorization';
463
+ return { [headerName]: `Bearer ${authValue}` };
464
+ }
465
+ if (authType === 'apikey') {
466
+ const headerName = authHeader || 'x-api-key';
467
+ return { [headerName]: authValue };
468
+ }
469
+ throw new Error(`Unsupported auth-type: ${authType}`);
470
+ }
471
+ /**
472
+ * Attempts a silent token refresh via the provided auth() function. Returns
473
+ * the refreshed access token on success, or `undefined` if refresh is not
474
+ * possible (no refresh token, server rejected the refresh, etc.). The caller
475
+ * is responsible for falling back to an interactive browser flow when this
476
+ * returns `undefined`.
477
+ *
478
+ * Extracted so the token-refresh decision tree is unit-testable without an
479
+ * oclif test harness or a real OAuth server.
480
+ */
481
+ async function attemptSilentRefresh(provider, serverUrl, authFn) {
482
+ let result;
483
+ try {
484
+ result = await authFn(provider, { serverUrl });
485
+ }
486
+ catch {
487
+ return undefined;
488
+ }
489
+ if (result !== 'AUTHORIZED') {
490
+ return undefined;
491
+ }
492
+ const refreshed = await provider.tokens();
493
+ return refreshed === null || refreshed === void 0 ? void 0 : refreshed.access_token;
494
+ }
495
+ exports.REMOTE_TRANSPORTS = [TRANSPORT_STREAMABLE_HTTP, 'sse'];
496
+ /**
497
+ * Loads the bundled MCP server schema. The file is committed to
498
+ * src/resources/mcp-server-schema.json and copied to dist/resources
499
+ * as part of the build.
500
+ */
501
+ function loadMcpServerSchema(schemaPath) {
502
+ // __dirname resolves to .../dist/commands/agent-network/project/mcp at runtime,
503
+ // so the resources folder is five levels up. The path is injectable so
504
+ // the missing-file error path can be exercised in tests.
505
+ const resolvedPath = schemaPath ||
506
+ nodePath.resolve(__dirname, '..', '..', '..', '..', 'resources', 'mcp-server-schema.json');
507
+ try {
508
+ return fs.readJsonSync(resolvedPath);
509
+ }
510
+ catch (error) {
511
+ throw new Error(`MCP server schema file not found at ${resolvedPath}. The installation may be corrupted. ` +
512
+ `Try reinstalling the package. (${error.message})`);
513
+ }
514
+ }
515
+ /**
516
+ * Validates a server.json object against the MCP server schema.
517
+ * Throws an Error with a formatted message on validation failure.
518
+ */
519
+ function validateServerJson(data, schema = loadMcpServerSchema()) {
520
+ const ajv = new ajv_1.default({ strict: false, allErrors: true });
521
+ (0, ajv_formats_1.default)(ajv);
522
+ const validate = ajv.compile(schema);
523
+ if (!validate(data)) {
524
+ const errors = (validate.errors || [])
525
+ .map(e => ` - ${e.instancePath || '/'} ${e.message || 'invalid'}`)
526
+ .join('\n');
527
+ throw error_factory_1.ErrorFactory.mcpServerJsonSchemaValidation(errors);
528
+ }
529
+ return data;
530
+ }
531
+ /**
532
+ * Picks the remote to use from a server.json and returns both the URL
533
+ * and the transport. Rules:
534
+ * - If remotes is missing or empty, throws.
535
+ * - If exactly one remote is present, uses it (ignores requestedTransport).
536
+ * - If multiple remotes are present, requestedTransport is required and
537
+ * must match one of them.
538
+ */
539
+ function resolveRemoteFromServerJson(server, requestedTransport) {
540
+ const remotes = server.remotes || [];
541
+ if (remotes.length === 0) {
542
+ throw error_factory_1.ErrorFactory.mcpServerJsonNoRemotes();
543
+ }
544
+ let selectedRemote;
545
+ if (remotes.length === 1) {
546
+ selectedRemote = remotes[0];
547
+ }
548
+ else if (!requestedTransport) {
549
+ const available = remotes.map(r => r.type).join(', ');
550
+ throw error_factory_1.ErrorFactory.mcpServerJsonMultipleRemotes(available);
551
+ }
552
+ else {
553
+ const match = remotes.find(r => r.type === requestedTransport);
554
+ if (!match) {
555
+ const available = remotes.map(r => r.type).join(', ');
556
+ throw error_factory_1.ErrorFactory.mcpServerJsonRemoteNotFound(requestedTransport, available);
557
+ }
558
+ selectedRemote = match;
559
+ }
560
+ try {
561
+ const parsed = new URL(selectedRemote.url);
562
+ if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {
563
+ throw error_factory_1.ErrorFactory.mcpInvalidRemoteProtocol(parsed.protocol);
564
+ }
565
+ }
566
+ catch (error) {
567
+ if (error.message.includes('Invalid protocol')) {
568
+ throw error;
569
+ }
570
+ throw error_factory_1.ErrorFactory.mcpInvalidRemoteUrl(error.message);
571
+ }
572
+ return { url: selectedRemote.url, transport: selectedRemote.type };
573
+ }
574
+ /**
575
+ * Reads, parses, and validates a server.json file from disk.
576
+ */
577
+ function loadServerJson(filePath) {
578
+ let raw;
579
+ try {
580
+ raw = fs.readFileSync(filePath, 'utf8');
581
+ }
582
+ catch (error) {
583
+ throw error_factory_1.ErrorFactory.mcpServerJsonNotFound(filePath, error.message);
584
+ }
585
+ let parsed;
586
+ try {
587
+ parsed = JSON.parse(raw);
588
+ }
589
+ catch (error) {
590
+ throw error_factory_1.ErrorFactory.mcpServerJsonInvalidJson(filePath, error.message);
591
+ }
592
+ return validateServerJson(parsed);
593
+ }
594
+ class Introspect extends core_1.Command {
595
+ async run() {
596
+ const parsed = await this.parse(Introspect);
597
+ const flags = parsed.flags;
598
+ if (!isNodeVersionSupported()) {
599
+ notify('\nWarning: OAuth authentication requires Node.js 20 or higher.');
600
+ notify(` Current version: ${process.version}`);
601
+ notify(' OAuth flows will likely fail with crypto errors.\n');
602
+ }
603
+ if (flags.url && flags[FLAG_SERVER_JSON]) {
604
+ this.error(`Only one of --url or --${FLAG_SERVER_JSON} can be specified.`);
605
+ }
606
+ if (!flags.url && !flags[FLAG_SERVER_JSON]) {
607
+ this.error(`One of --url or --${FLAG_SERVER_JSON} is required.`);
608
+ }
609
+ // When using --server-json, the transport is resolved from the file
610
+ // (unless the user explicitly passes --transport to pick among multiple
611
+ // remotes). We detect an explicit --transport by inspecting the parsed
612
+ // raw tokens (not argv, which only contains positional args).
613
+ const rawTokens = parsed.raw || [];
614
+ const transportExplicit = rawTokens.some(t => t.type === 'flag' && t.flag === 'transport');
615
+ let serverUrl;
616
+ let serverJsonName;
617
+ let fullMcpUrl;
618
+ if (flags[FLAG_SERVER_JSON]) {
619
+ const server = loadServerJson(flags[FLAG_SERVER_JSON]);
620
+ serverJsonName = server.name;
621
+ const requested = transportExplicit ? flags.transport : undefined;
622
+ const resolved = resolveRemoteFromServerJson(server, requested);
623
+ serverUrl = resolved.url;
624
+ flags.transport = resolved.transport;
625
+ notify(`Using remote "${resolved.transport}" from server.json: ${serverUrl}`);
626
+ fullMcpUrl = serverUrl;
627
+ }
628
+ else {
629
+ serverUrl = flags.url.toString();
630
+ const transportPath = flags['transport-path'] || (flags.transport === 'sse' ? '/sse' : '/mcp');
631
+ fullMcpUrl = buildMcpUrl(serverUrl, transportPath);
632
+ }
633
+ logger_1.Log.debug(`[Introspect] Full MCP URL: ${fullMcpUrl}`);
634
+ const oauthProvider = new CLIOAuthProvider(fullMcpUrl, 'Anypoint CLI Agent Fabric Plugin');
635
+ try {
636
+ if (flags['oauth-reset']) {
637
+ oauthProvider.invalidateCredentials();
638
+ notify('Please re-run the command to start a new OAuth flow.');
639
+ return;
640
+ }
641
+ const client = new index_js_1.Client({
642
+ name: 'anypoint-cli-agent-fabric-plugin',
643
+ version: '1.0.0',
644
+ });
645
+ const authHeaders = buildAuthHeaders(flags['auth-type'], flags['auth-value'], flags['auth-header']);
646
+ let introspection;
647
+ try {
648
+ introspection = await this.connectAndIntrospect(client, flags, authHeaders, fullMcpUrl);
649
+ }
650
+ catch (error) {
651
+ const err = error;
652
+ logger_1.Log.debug(`[Introspect] Connection error: ${err.message}`);
653
+ if (isOAuthRequired(err)) {
654
+ notify('\nServer requires OAuth authentication');
655
+ notify('Initiating OAuth flow...\n');
656
+ introspection = await this.handleOAuthFlow(oauthProvider, fullMcpUrl, flags, client);
657
+ }
658
+ else {
659
+ throw error;
660
+ }
661
+ }
662
+ const outputPath = flags.output;
663
+ if (outputPath) {
664
+ const content = flags.format === 'yaml' ?
665
+ (0, yaml_1.stringify)(introspection) :
666
+ JSON.stringify(introspection, null, 2);
667
+ fs.writeFileSync(outputPath, content);
668
+ notify(`Introspection result written to ${outputPath}`);
669
+ }
670
+ else {
671
+ const projectPath = flags.path || '.';
672
+ const key = (0, registry_key_1.deriveRegistryKey)({
673
+ nameFlag: flags.name,
674
+ serverJsonName,
675
+ serverUrl,
676
+ });
677
+ const entry = (0, mcp_metadata_mapper_1.mapMcpMetadataToV2Entry)(introspection, { label: key });
678
+ const writtenTo = (0, project_registrar_1.registerMcpInProject)({ projectPath, key, entry });
679
+ notify(`Registered MCP "${key}" in ${writtenTo}`);
680
+ }
681
+ }
682
+ finally {
683
+ oauthProvider.cleanup();
684
+ }
685
+ }
686
+ async handleOAuthFlow(provider, serverUrl, flags, client) {
687
+ var _a, _b, _c, _d;
688
+ const existingTokens = provider.tokens();
689
+ if (existingTokens) {
690
+ notify('Using existing OAuth tokens...');
691
+ try {
692
+ return await this.connectWithToken(client, flags, existingTokens.access_token, serverUrl);
693
+ }
694
+ catch (error) {
695
+ const err = error;
696
+ // Only treat explicit 401 responses as an auth-token problem.
697
+ // A transient network failure, DNS issue, 5xx, etc. should NOT
698
+ // wipe credentials — that would force the user back through
699
+ // the browser flow needlessly.
700
+ if (!isOAuthRequired(err)) {
701
+ throw error;
702
+ }
703
+ // The access token is invalid or expired. Try a non-interactive
704
+ // refresh first — the MCP SDK's auth() will use the refresh
705
+ // token automatically if one is stored, without opening a
706
+ // browser. Only nuke the session if the refresh also fails.
707
+ notify('Access token rejected. Attempting silent refresh...');
708
+ const refreshedAccess = await attemptSilentRefresh(provider, serverUrl, auth_js_1.auth);
709
+ if (refreshedAccess) {
710
+ notify('Silent refresh succeeded. Reconnecting...');
711
+ return this.connectWithToken(client, flags, refreshedAccess, serverUrl);
712
+ }
713
+ notify('Silent refresh failed. Starting new browser-based OAuth flow...');
714
+ provider.invalidateCredentials();
715
+ }
716
+ }
717
+ try {
718
+ const result = await (0, auth_js_1.auth)(provider, { serverUrl });
719
+ if (result === 'REDIRECT') {
720
+ notify('Waiting for authorization callback...');
721
+ const authorizationCode = await provider.getAuthorizationCode();
722
+ if (!authorizationCode) {
723
+ this.error('Failed to receive authorization code');
724
+ }
725
+ notify('Authorization code received');
726
+ const finalResult = await (0, auth_js_1.auth)(provider, {
727
+ serverUrl,
728
+ authorizationCode,
729
+ });
730
+ if (finalResult !== 'AUTHORIZED') {
731
+ this.error('Failed to complete OAuth authorization');
732
+ }
733
+ }
734
+ notify('OAuth authentication successful');
735
+ const tokens = provider.tokens();
736
+ if (!tokens) {
737
+ this.error('Failed to retrieve OAuth tokens after authentication');
738
+ }
739
+ return await this.connectWithToken(client, flags, tokens.access_token, serverUrl);
740
+ }
741
+ catch (error) {
742
+ const err = error;
743
+ logger_1.Log.debug(`[OAuth Error] ${err.message}`);
744
+ if (((_a = err.message) === null || _a === void 0 ? void 0 : _a.includes('randomBytes')) || ((_b = err.message) === null || _b === void 0 ? void 0 : _b.includes('crypto'))) {
745
+ this.error('OAuth authentication failed due to a crypto error. Please upgrade to Node.js 20 or higher.');
746
+ }
747
+ if (((_c = err.message) === null || _c === void 0 ? void 0 : _c.includes('403')) || ((_d = err.message) === null || _d === void 0 ? void 0 : _d.includes('Forbidden'))) {
748
+ this.error(`OAuth discovery failed: The server returned 403 Forbidden when trying to fetch OAuth metadata.\nServer URL: ${serverUrl}`);
749
+ }
750
+ throw error;
751
+ }
752
+ }
753
+ async connectWithToken(client, flags, accessToken, serverUrl) {
754
+ const headers = {
755
+ Authorization: `Bearer ${accessToken}`,
756
+ 'content-type': 'application/json',
757
+ };
758
+ return this.connectAndIntrospect(client, flags, headers, serverUrl);
759
+ }
760
+ // Returns [] only on JSON-RPC -32601 (method-not-found); other errors propagate. Tools intentionally not wrapped.
761
+ async safeList(fn, emptyKey, methodLabel) {
762
+ try {
763
+ return await fn();
764
+ }
765
+ catch (error) {
766
+ const errCode = error instanceof types_js_1.McpError ? error.code : undefined;
767
+ const errMessage = error instanceof Error ? error.message : String(error);
768
+ logger_1.Log.debug(`[Introspect] ${methodLabel} failed (code=${errCode !== null && errCode !== void 0 ? errCode : 'n/a'}): ${errMessage}`);
769
+ if (error instanceof types_js_1.McpError && error.code === -32601) {
770
+ const result = {};
771
+ result[emptyKey] = [];
772
+ return result;
773
+ }
774
+ throw error;
775
+ }
776
+ }
777
+ async connectAndIntrospect(client, flags, headers, endpointUrl) {
778
+ const fullHeaders = { ...headers, 'content-type': 'application/json' };
779
+ const transportType = flags.transport;
780
+ const remotePath = new URL(endpointUrl).pathname || '/';
781
+ logger_1.Log.debug(`[Introspect] Connecting to: ${endpointUrl}`);
782
+ try {
783
+ if (transportType === 'sse') {
784
+ const sseTransport = new sse_js_1.SSEClientTransport(new URL(endpointUrl), { requestInit: { headers: fullHeaders } });
785
+ await client.connect(sseTransport);
786
+ }
787
+ else if (transportType === TRANSPORT_STREAMABLE_HTTP) {
788
+ const streamableHttpTransport = new streamableHttp_js_1.StreamableHTTPClientTransport(new URL(endpointUrl), { requestInit: { headers: fullHeaders } });
789
+ await client.connect(streamableHttpTransport);
790
+ }
791
+ }
792
+ catch (error) {
793
+ await client.close().catch(() => { });
794
+ if (isOAuthRequired(error)) {
795
+ throw error;
796
+ }
797
+ throw new Error(`Failed to connect to MCP server: ${error.message}`);
798
+ }
799
+ try {
800
+ const serverCapabilities = await client.getServerCapabilities();
801
+ const capabilities = {
802
+ ...((serverCapabilities === null || serverCapabilities === void 0 ? void 0 : serverCapabilities.resources) ? { resources: serverCapabilities.resources } : {}),
803
+ ...((serverCapabilities === null || serverCapabilities === void 0 ? void 0 : serverCapabilities.prompts) ? { prompts: serverCapabilities.prompts } : {}),
804
+ ...((serverCapabilities === null || serverCapabilities === void 0 ? void 0 : serverCapabilities.logging) ? { logging: serverCapabilities.logging } : {}),
805
+ ...((serverCapabilities === null || serverCapabilities === void 0 ? void 0 : serverCapabilities.tools) ? { tools: serverCapabilities.tools } : {}),
806
+ ...((serverCapabilities === null || serverCapabilities === void 0 ? void 0 : serverCapabilities.completions) ? { completions: serverCapabilities.completions } : {}),
807
+ ...((serverCapabilities === null || serverCapabilities === void 0 ? void 0 : serverCapabilities.experimental) ? { experimental: serverCapabilities.experimental } : {}),
808
+ };
809
+ const tools = await client.listTools();
810
+ const prompts = await this.safeList(() => client.listPrompts(), 'prompts', 'listPrompts');
811
+ const resources = await this.safeList(() => client.listResources(), 'resources', 'listResources');
812
+ const resourceTemplates = await this.safeList(() => client.listResourceTemplates(), 'resourceTemplates', 'listResourceTemplates');
813
+ const mcpMetadata = {
814
+ capabilities,
815
+ transport: {
816
+ kind: transportType,
817
+ ...(transportType === 'sse' ? { ssePath: remotePath } : {}),
818
+ ...(transportType === TRANSPORT_STREAMABLE_HTTP ? { path: remotePath } : {}),
819
+ },
820
+ tools: tools.tools,
821
+ prompts: prompts.prompts,
822
+ resources: resources.resources,
823
+ resourceTemplates: resourceTemplates.resourceTemplates,
824
+ };
825
+ return mcpMetadata;
826
+ }
827
+ finally {
828
+ // Always close the MCP client connection so the process can exit.
829
+ // The underlying SSE/StreamableHTTP transport keeps the event loop
830
+ // alive until the connection is closed.
831
+ try {
832
+ await client.close();
833
+ }
834
+ catch (closeError) {
835
+ logger_1.Log.debug(`[Introspect] Error closing client: ${closeError.message}`);
836
+ }
837
+ }
838
+ }
839
+ }
840
+ Introspect.description = 'Introspects an MCP server\'s capabilities and registers it under registry.mcps.<key> in the project\'s agent-network.yaml. Use --output to dump the result to a file instead.';
841
+ Introspect.examples = [
842
+ '$ agent-network project mcp introspect --url=https://mcp.example.com --path=./my-project # register into project',
843
+ '$ agent-network project mcp introspect --url=https://mcp.example.com --path=./my-project --name=myMcpServer',
844
+ '$ agent-network project mcp introspect --url=https://api.example.com/staging/mcp # path disambiguates same-host servers',
845
+ '$ agent-network project mcp introspect --url=https://mcp.example.com --output=capabilities.json',
846
+ '$ agent-network project mcp introspect --url=https://mcp.example.com --auth-type=bearer --auth-value=<token>',
847
+ '$ agent-network project mcp introspect --url=https://mcp.example.com --auth-type=apikey --auth-value=<key>',
848
+ '$ agent-network project mcp introspect --url=https://mcp.example.com --auth-type=apikey --auth-value=<key> --auth-header=X-Custom-Api-Key',
849
+ '$ agent-network project mcp introspect --server-json=./server.json',
850
+ '$ agent-network project mcp introspect --server-json=./server.json --transport=sse # pick a specific remote',
851
+ ];
852
+ Introspect.hidden = true;
853
+ Introspect.flags = {
854
+ url: core_1.Flags.url({
855
+ char: 'u',
856
+ description: 'The URL of the MCP server. Mutually exclusive with --server-json.',
857
+ required: false,
858
+ }),
859
+ 'server-json': core_1.Flags.string({
860
+ description: 'Path to an MCP server.json file (schema: https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json). Only remote servers are supported. Mutually exclusive with --url.',
861
+ required: false,
862
+ }),
863
+ transport: core_1.Flags.enum({
864
+ description: 'The transport to use for MCP communication.',
865
+ default: TRANSPORT_STREAMABLE_HTTP,
866
+ options: [TRANSPORT_STREAMABLE_HTTP, 'sse'],
867
+ }),
868
+ 'transport-path': core_1.Flags.string({
869
+ description: 'The path to use for transport. If sse is used, the default is /sse. If streamable-http is used, the default is /mcp.',
870
+ required: false,
871
+ }),
872
+ output: core_1.Flags.string({
873
+ char: 'o',
874
+ description: 'Write the introspection result to a file instead of registering it in the project. If omitted, the result is written to registry.mcps.<name> in the project\'s agent-network.yaml.',
875
+ required: false,
876
+ }),
877
+ format: core_1.Flags.enum({
878
+ description: 'The format to use for the output file. Only used if --output is provided. Default is json.',
879
+ options: ['json', 'yaml'],
880
+ default: 'json',
881
+ }),
882
+ 'oauth-reset': core_1.Flags.boolean({
883
+ description: 'Clear all stored OAuth credentials and start fresh',
884
+ required: false,
885
+ default: false,
886
+ }),
887
+ 'auth-type': core_1.Flags.enum({
888
+ description: 'Authentication method for the MCP request. Use "none" to skip manual auth (OAuth will still trigger on 401).',
889
+ options: ['none', 'bearer', 'apikey'],
890
+ default: 'none',
891
+ }),
892
+ 'auth-value': core_1.Flags.string({
893
+ description: 'The authentication value to send (token for bearer, key for apikey). Required when --auth-type is not "none".',
894
+ required: false,
895
+ }),
896
+ 'auth-header': core_1.Flags.string({
897
+ description: 'Custom header name for the auth value. Defaults: "Authorization" for bearer, "x-api-key" for apikey.',
898
+ required: false,
899
+ }),
900
+ path: core_1.Flags.file({
901
+ description: 'The path to the project (where exchange.json lives). Defaults to the current directory. Ignored when --output is provided.',
902
+ default: '.',
903
+ }),
904
+ name: core_1.Flags.string({
905
+ description: 'Override the registry key (registry.mcps.<name>). Must match [A-Za-z0-9_-]+. Defaults to the server.json name, or a slug of the URL host plus any non-default path segment (e.g. /staging/mcp → <host>-staging). Ignored when --output is provided.',
906
+ required: false,
907
+ }),
908
+ };
909
+ exports.default = Introspect;
910
+ //# sourceMappingURL=introspect.js.map