ls-mcp 1.15.1 → 1.15.3

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.
package/dist/bin/cli.cjs CHANGED
@@ -1,1813 +1,1423 @@
1
1
  #!/usr/bin/env node
2
- "use strict";
2
+ // \0rolldown/runtime.js
3
3
  var __create = Object.create;
4
4
  var __defProp = Object.defineProperty;
5
5
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
6
  var __getOwnPropNames = Object.getOwnPropertyNames;
7
7
  var __getProtoOf = Object.getPrototypeOf;
8
8
  var __hasOwnProp = Object.prototype.hasOwnProperty;
9
- var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
10
9
  var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
10
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
11
+ key = keys[i];
12
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
13
+ get: ((k) => from[k]).bind(null, key),
14
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
15
+ });
16
+ }
17
+ return to;
17
18
  };
18
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
19
- // If the importer is in node compatibility mode or this is not an ESM
20
- // file that has been converted to a CommonJS file using a Babel-
21
- // compatible transform (i.e. "__esModule" has not been set), then set
22
- // "default" to the CommonJS "module.exports" for node compatibility.
23
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
24
- mod
25
- ));
26
-
27
- // src/bin/cli.ts
28
- var import_node_util13 = require("util");
29
-
30
- // src/services/mcp-config-service.ts
31
- var import_node_os = require("os");
32
- var import_node_path = __toESM(require("path"), 1);
33
- var import_promises = __toESM(require("fs/promises"), 1);
34
- var import_node_util = __toESM(require("util"), 1);
35
- var import_agent_files = require("agent-files");
36
-
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
20
+ value: mod,
21
+ enumerable: true
22
+ }) : target, mod));
23
+ let node_util = require("node:util");
24
+ node_util = __toESM(node_util, 1);
25
+ let node_os = require("node:os");
26
+ let node_path = require("node:path");
27
+ node_path = __toESM(node_path, 1);
28
+ let node_fs_promises = require("node:fs/promises");
29
+ node_fs_promises = __toESM(node_fs_promises, 1);
30
+ let agent_files = require("agent-files");
31
+ let node_child_process = require("node:child_process");
37
32
  // src/services/credential-detection-service.ts
38
33
  var CredentialDetectionService = class {
39
- static {
40
- __name(this, "CredentialDetectionService");
41
- }
42
- /**
43
- * Credential patterns grouped by risk level for easier maintenance
44
- */
45
- static CREDENTIAL_PATTERNS = {
46
- high: [
47
- // Generic Key and Token patterns (broad matching)
48
- /.*key.*/i,
49
- /.*token.*/i,
50
- // Passwords
51
- /.*password.*/i,
52
- /.*passwd.*/i,
53
- /.*pwd.*/i,
54
- // Credentials and Secrets
55
- /.*credential.*/i,
56
- /.*creds.*/i,
57
- /.*secret.*/i
58
- ],
59
- low: [
60
- // Organization and Account IDs
61
- /org[_-]?id/i,
62
- /organization[_-]?id/i,
63
- /account[_-]?id/i,
64
- /user[_-]?id/i,
65
- /openai[_-]?org[_-]?id/i
66
- ]
67
- };
68
- /**
69
- * Argument patterns for detecting credentials in command-line arguments
70
- */
71
- static ARGUMENT_PATTERNS = {
72
- high: [
73
- // API key arguments
74
- /--api-key/i,
75
- /--apikey/i,
76
- /--key/i,
77
- // Token arguments
78
- /--token/i,
79
- /--access-token/i,
80
- /--auth-token/i,
81
- /--bearer-token/i,
82
- // Password arguments
83
- /--password/i,
84
- /--passwd/i,
85
- /--pwd/i,
86
- // Secret arguments
87
- /--secret/i,
88
- /--client-secret/i,
89
- // Authentication arguments
90
- /--auth/i,
91
- /--authorization/i,
92
- /--credentials/i,
93
- /--creds/i
94
- ],
95
- low: [
96
- // Organization and account IDs
97
- /--org-id/i,
98
- /--organization-id/i,
99
- /--account-id/i,
100
- /--user-id/i
101
- ]
102
- };
103
- /**
104
- * Header patterns for detecting credentials in HTTP headers
105
- */
106
- static HEADER_PATTERNS = {
107
- high: [
108
- // Authorization headers
109
- /authorization/i,
110
- /auth/i,
111
- // API key headers
112
- /x-api-key/i,
113
- /api-key/i,
114
- /apikey/i,
115
- // Token headers
116
- /x-access-token/i,
117
- /access-token/i,
118
- /bearer-token/i,
119
- /x-auth-token/i,
120
- /auth-token/i,
121
- // Custom authentication headers
122
- /x-.*-key/i,
123
- /x-.*-token/i,
124
- /x-.*-secret/i,
125
- // Service-specific patterns
126
- /x-github-token/i,
127
- /x-openai-key/i,
128
- /x-anthropic-key/i
129
- ],
130
- low: [
131
- // User identification headers
132
- /x-user-id/i,
133
- /x-org-id/i,
134
- /x-organization-id/i,
135
- /x-account-id/i
136
- ]
137
- };
138
- /**
139
- * Variable substitution pattern to detect safe variable references
140
- */
141
- static VARIABLE_SUBSTITUTION_PATTERN = /^\$\{[^}]+\}$/;
142
- /**
143
- * Check if a value is a variable substitution pattern (e.g., ${input:token})
144
- */
145
- static isVariableSubstitution(value) {
146
- return this.VARIABLE_SUBSTITUTION_PATTERN.test(value);
147
- }
148
- /**
149
- * Analyze command-line arguments for potential credentials
150
- */
151
- static analyzeArguments(args2) {
152
- if (!args2 || !Array.isArray(args2) || args2.length === 0) {
153
- return {
154
- hasCredentials: false,
155
- credentialVars: [],
156
- riskLevel: "none"
157
- };
158
- }
159
- const credentialVars = [];
160
- for (let i = 0; i < args2.length - 1; i++) {
161
- const arg = args2[i];
162
- const nextArg = args2[i + 1];
163
- const isHighRiskArg = this.ARGUMENT_PATTERNS.high.some((pattern) => pattern.test(arg));
164
- const isLowRiskArg = this.ARGUMENT_PATTERNS.low.some((pattern) => pattern.test(arg));
165
- if (isHighRiskArg || isLowRiskArg) {
166
- if (nextArg && !nextArg.startsWith("-")) {
167
- credentialVars.push({
168
- name: arg,
169
- value: this.maskValue(nextArg),
170
- riskLevel: isHighRiskArg ? "high" : "low",
171
- source: "args"
172
- });
173
- i++;
174
- }
175
- }
176
- }
177
- const hasCredentials = credentialVars.length > 0;
178
- const riskLevel = this.calculateOverallRiskLevel(credentialVars);
179
- return {
180
- hasCredentials,
181
- credentialVars,
182
- riskLevel
183
- };
184
- }
185
- /**
186
- * Analyze HTTP headers for potential credentials
187
- */
188
- static analyzeHeaders(headers) {
189
- if (!headers || typeof headers !== "object") {
190
- return {
191
- hasCredentials: false,
192
- credentialVars: [],
193
- riskLevel: "none"
194
- };
195
- }
196
- const credentialVars = [];
197
- for (const [name, value] of Object.entries(headers)) {
198
- if (this.isVariableSubstitution(value)) {
199
- continue;
200
- }
201
- const isHighRiskHeader = this.HEADER_PATTERNS.high.some((pattern) => pattern.test(name));
202
- const isLowRiskHeader = this.HEADER_PATTERNS.low.some((pattern) => pattern.test(name));
203
- if (isHighRiskHeader || isLowRiskHeader) {
204
- credentialVars.push({
205
- name,
206
- value: this.maskValue(value),
207
- riskLevel: isHighRiskHeader ? "high" : "low",
208
- source: "headers"
209
- });
210
- }
211
- }
212
- const hasCredentials = credentialVars.length > 0;
213
- const riskLevel = this.calculateOverallRiskLevel(credentialVars);
214
- return {
215
- hasCredentials,
216
- credentialVars,
217
- riskLevel
218
- };
219
- }
220
- /**
221
- * Comprehensive analysis of server configuration for credentials
222
- */
223
- static analyzeServerConfig(config) {
224
- const envResult = this.analyzeEnvironmentVariables(config.env);
225
- const argsResult = this.analyzeArguments(config.args);
226
- const headersResult = this.analyzeHeaders(config.headers);
227
- const allCredentialVars = [
228
- ...envResult.credentialVars,
229
- ...argsResult.credentialVars,
230
- ...headersResult.credentialVars
231
- ];
232
- const hasCredentials = allCredentialVars.length > 0;
233
- const riskLevel = this.calculateOverallRiskLevel(allCredentialVars);
234
- return {
235
- hasCredentials,
236
- credentialVars: allCredentialVars,
237
- riskLevel
238
- };
239
- }
240
- /**
241
- * Check if an environment variable name suggests it might contain credentials
242
- */
243
- static isPotentialCredential(envVarName) {
244
- return this.CREDENTIAL_PATTERNS.high.some((pattern) => pattern.test(envVarName)) || this.CREDENTIAL_PATTERNS.low.some((pattern) => pattern.test(envVarName));
245
- }
246
- /**
247
- * Analyze environment variables and return credential detection results
248
- */
249
- static analyzeEnvironmentVariables(env) {
250
- if (!env || typeof env !== "object") {
251
- return {
252
- hasCredentials: false,
253
- credentialVars: [],
254
- riskLevel: "none"
255
- };
256
- }
257
- const credentialVars = [];
258
- for (const [name, value] of Object.entries(env)) {
259
- if (this.isVariableSubstitution(value)) {
260
- continue;
261
- }
262
- if (this.isPotentialCredential(name)) {
263
- credentialVars.push({
264
- name,
265
- value: this.maskValue(value),
266
- riskLevel: this.assessRiskLevel(name),
267
- source: "env"
268
- });
269
- }
270
- }
271
- const hasCredentials = credentialVars.length > 0;
272
- const riskLevel = this.calculateOverallRiskLevel(credentialVars);
273
- return {
274
- hasCredentials,
275
- credentialVars,
276
- riskLevel
277
- };
278
- }
279
- /**
280
- * Mask sensitive values for display (show only first and last character)
281
- */
282
- static maskValue(value) {
283
- if (!value || value.length <= 2) {
284
- return value;
285
- }
286
- const first = value.charAt(0);
287
- const last = value.charAt(value.length - 1);
288
- const maskedLength = Math.min(value.length - 2, 8);
289
- return `${first}${"*".repeat(maskedLength)}${last}`;
290
- }
291
- /**
292
- * Assess risk level for a specific credential variable
293
- */
294
- static assessRiskLevel(name) {
295
- if (this.CREDENTIAL_PATTERNS.high.some((pattern) => pattern.test(name))) {
296
- return "high";
297
- }
298
- if (this.CREDENTIAL_PATTERNS.low.some((pattern) => pattern.test(name))) {
299
- return "low";
300
- }
301
- return "high";
302
- }
303
- /**
304
- * Calculate overall risk level based on all credential variables
305
- */
306
- static calculateOverallRiskLevel(credentialVars) {
307
- if (credentialVars.length === 0) {
308
- return "none";
309
- }
310
- const hasHighRisk = credentialVars.some((v) => v.riskLevel === "high");
311
- if (hasHighRisk) {
312
- return "high";
313
- }
314
- return "low";
315
- }
34
+ /**
35
+ * Credential patterns grouped by risk level for easier maintenance
36
+ */
37
+ static CREDENTIAL_PATTERNS = {
38
+ high: [
39
+ /.*key.*/i,
40
+ /.*token.*/i,
41
+ /.*password.*/i,
42
+ /.*passwd.*/i,
43
+ /.*pwd.*/i,
44
+ /.*credential.*/i,
45
+ /.*creds.*/i,
46
+ /.*secret.*/i
47
+ ],
48
+ low: [
49
+ /org[_-]?id/i,
50
+ /organization[_-]?id/i,
51
+ /account[_-]?id/i,
52
+ /user[_-]?id/i,
53
+ /openai[_-]?org[_-]?id/i
54
+ ]
55
+ };
56
+ /**
57
+ * Argument patterns for detecting credentials in command-line arguments
58
+ */
59
+ static ARGUMENT_PATTERNS = {
60
+ high: [
61
+ /--api-key/i,
62
+ /--apikey/i,
63
+ /--key/i,
64
+ /--token/i,
65
+ /--access-token/i,
66
+ /--auth-token/i,
67
+ /--bearer-token/i,
68
+ /--password/i,
69
+ /--passwd/i,
70
+ /--pwd/i,
71
+ /--secret/i,
72
+ /--client-secret/i,
73
+ /--auth/i,
74
+ /--authorization/i,
75
+ /--credentials/i,
76
+ /--creds/i
77
+ ],
78
+ low: [
79
+ /--org-id/i,
80
+ /--organization-id/i,
81
+ /--account-id/i,
82
+ /--user-id/i
83
+ ]
84
+ };
85
+ /**
86
+ * Header patterns for detecting credentials in HTTP headers
87
+ */
88
+ static HEADER_PATTERNS = {
89
+ high: [
90
+ /authorization/i,
91
+ /auth/i,
92
+ /x-api-key/i,
93
+ /api-key/i,
94
+ /apikey/i,
95
+ /x-access-token/i,
96
+ /access-token/i,
97
+ /bearer-token/i,
98
+ /x-auth-token/i,
99
+ /auth-token/i,
100
+ /x-.*-key/i,
101
+ /x-.*-token/i,
102
+ /x-.*-secret/i,
103
+ /x-github-token/i,
104
+ /x-openai-key/i,
105
+ /x-anthropic-key/i
106
+ ],
107
+ low: [
108
+ /x-user-id/i,
109
+ /x-org-id/i,
110
+ /x-organization-id/i,
111
+ /x-account-id/i
112
+ ]
113
+ };
114
+ /**
115
+ * Variable substitution pattern to detect safe variable references
116
+ */
117
+ static VARIABLE_SUBSTITUTION_PATTERN = /^\$\{[^}]+\}$/;
118
+ /**
119
+ * Check if a value is a variable substitution pattern (e.g., ${input:token})
120
+ */
121
+ static isVariableSubstitution(value) {
122
+ return this.VARIABLE_SUBSTITUTION_PATTERN.test(value);
123
+ }
124
+ /**
125
+ * Analyze command-line arguments for potential credentials
126
+ */
127
+ static analyzeArguments(args) {
128
+ if (!args || !Array.isArray(args) || args.length === 0) return {
129
+ hasCredentials: false,
130
+ credentialVars: [],
131
+ riskLevel: "none"
132
+ };
133
+ const credentialVars = [];
134
+ for (let i = 0; i < args.length - 1; i++) {
135
+ const arg = args[i];
136
+ const nextArg = args[i + 1];
137
+ const isHighRiskArg = this.ARGUMENT_PATTERNS.high.some((pattern) => pattern.test(arg));
138
+ const isLowRiskArg = this.ARGUMENT_PATTERNS.low.some((pattern) => pattern.test(arg));
139
+ if (isHighRiskArg || isLowRiskArg) {
140
+ if (nextArg && !nextArg.startsWith("-")) {
141
+ credentialVars.push({
142
+ name: arg,
143
+ value: this.maskValue(nextArg),
144
+ riskLevel: isHighRiskArg ? "high" : "low",
145
+ source: "args"
146
+ });
147
+ i++;
148
+ }
149
+ }
150
+ }
151
+ return {
152
+ hasCredentials: credentialVars.length > 0,
153
+ credentialVars,
154
+ riskLevel: this.calculateOverallRiskLevel(credentialVars)
155
+ };
156
+ }
157
+ /**
158
+ * Analyze HTTP headers for potential credentials
159
+ */
160
+ static analyzeHeaders(headers) {
161
+ if (!headers || typeof headers !== "object") return {
162
+ hasCredentials: false,
163
+ credentialVars: [],
164
+ riskLevel: "none"
165
+ };
166
+ const credentialVars = [];
167
+ for (const [name, value] of Object.entries(headers)) {
168
+ if (this.isVariableSubstitution(value)) continue;
169
+ const isHighRiskHeader = this.HEADER_PATTERNS.high.some((pattern) => pattern.test(name));
170
+ const isLowRiskHeader = this.HEADER_PATTERNS.low.some((pattern) => pattern.test(name));
171
+ if (isHighRiskHeader || isLowRiskHeader) credentialVars.push({
172
+ name,
173
+ value: this.maskValue(value),
174
+ riskLevel: isHighRiskHeader ? "high" : "low",
175
+ source: "headers"
176
+ });
177
+ }
178
+ return {
179
+ hasCredentials: credentialVars.length > 0,
180
+ credentialVars,
181
+ riskLevel: this.calculateOverallRiskLevel(credentialVars)
182
+ };
183
+ }
184
+ /**
185
+ * Comprehensive analysis of server configuration for credentials
186
+ */
187
+ static analyzeServerConfig(config) {
188
+ const envResult = this.analyzeEnvironmentVariables(config.env);
189
+ const argsResult = this.analyzeArguments(config.args);
190
+ const headersResult = this.analyzeHeaders(config.headers);
191
+ const allCredentialVars = [
192
+ ...envResult.credentialVars,
193
+ ...argsResult.credentialVars,
194
+ ...headersResult.credentialVars
195
+ ];
196
+ return {
197
+ hasCredentials: allCredentialVars.length > 0,
198
+ credentialVars: allCredentialVars,
199
+ riskLevel: this.calculateOverallRiskLevel(allCredentialVars)
200
+ };
201
+ }
202
+ /**
203
+ * Check if an environment variable name suggests it might contain credentials
204
+ */
205
+ static isPotentialCredential(envVarName) {
206
+ return this.CREDENTIAL_PATTERNS.high.some((pattern) => pattern.test(envVarName)) || this.CREDENTIAL_PATTERNS.low.some((pattern) => pattern.test(envVarName));
207
+ }
208
+ /**
209
+ * Analyze environment variables and return credential detection results
210
+ */
211
+ static analyzeEnvironmentVariables(env) {
212
+ if (!env || typeof env !== "object") return {
213
+ hasCredentials: false,
214
+ credentialVars: [],
215
+ riskLevel: "none"
216
+ };
217
+ const credentialVars = [];
218
+ for (const [name, value] of Object.entries(env)) {
219
+ if (this.isVariableSubstitution(value)) continue;
220
+ if (this.isPotentialCredential(name)) credentialVars.push({
221
+ name,
222
+ value: this.maskValue(value),
223
+ riskLevel: this.assessRiskLevel(name),
224
+ source: "env"
225
+ });
226
+ }
227
+ return {
228
+ hasCredentials: credentialVars.length > 0,
229
+ credentialVars,
230
+ riskLevel: this.calculateOverallRiskLevel(credentialVars)
231
+ };
232
+ }
233
+ /**
234
+ * Mask sensitive values for display (show only first and last character)
235
+ */
236
+ static maskValue(value) {
237
+ if (!value || value.length <= 2) return value;
238
+ const first = value.charAt(0);
239
+ const last = value.charAt(value.length - 1);
240
+ const maskedLength = Math.min(value.length - 2, 8);
241
+ return `${first}${"*".repeat(maskedLength)}${last}`;
242
+ }
243
+ /**
244
+ * Assess risk level for a specific credential variable
245
+ */
246
+ static assessRiskLevel(name) {
247
+ if (this.CREDENTIAL_PATTERNS.high.some((pattern) => pattern.test(name))) return "high";
248
+ if (this.CREDENTIAL_PATTERNS.low.some((pattern) => pattern.test(name))) return "low";
249
+ return "high";
250
+ }
251
+ /**
252
+ * Calculate overall risk level based on all credential variables
253
+ */
254
+ static calculateOverallRiskLevel(credentialVars) {
255
+ if (credentialVars.length === 0) return "none";
256
+ if (credentialVars.some((v) => v.riskLevel === "high")) return "high";
257
+ return "low";
258
+ }
316
259
  };
317
-
318
260
  // src/services/mcp-version-detection-service.ts
261
+ /**
262
+ * Service for detecting version information from MCP server configurations
263
+ * Specifically handles npx-based server commands to determine if they use
264
+ * pinned versions or implicit latest versions
265
+ */
319
266
  var MCPVersionDetectionService = class {
320
- static {
321
- __name(this, "MCPVersionDetectionService");
322
- }
323
- /**
324
- * Analyze a server configuration to extract version information
325
- * @param command - The command used to run the server
326
- * @param args - Array of arguments passed to the command
327
- * @returns PackageVersionInfo if analysis is possible, null otherwise
328
- */
329
- analyzeServerVersion(command, args2) {
330
- if (!["npx", "uvx", "uv"].includes(command)) {
331
- return null;
332
- }
333
- if (!args2 || args2.length === 0) {
334
- return null;
335
- }
336
- const packageName = this.extractPackageName(command, args2);
337
- if (!packageName) {
338
- return null;
339
- }
340
- const { name, version } = this.parsePackageVersion(packageName);
341
- const isPinned = this.isPinnedVersion(version);
342
- return {
343
- packageName: name,
344
- version,
345
- isPinned,
346
- isLatest: !isPinned
347
- };
348
- }
349
- /**
350
- * Extract the package name based on the command type
351
- * @param command - The command used to run the server
352
- * @param args - Array of arguments passed to the command
353
- * @returns The package name/spec or null if not found
354
- */
355
- extractPackageName(command, args2) {
356
- switch (command) {
357
- case "npx":
358
- return this.extractNpxPackageName(args2);
359
- case "uvx":
360
- return this.extractUvxPackageName(args2);
361
- case "uv":
362
- return this.extractUvPackageName(args2);
363
- default:
364
- return null;
365
- }
366
- }
367
- /**
368
- * Extract the package name from npx arguments
369
- * @param args - Array of arguments passed to npx
370
- * @returns The package name/spec or null if not found
371
- */
372
- extractNpxPackageName(args2) {
373
- if (!args2 || args2.length === 0) {
374
- return null;
375
- }
376
- const yIndex = args2.indexOf("-y");
377
- if (yIndex !== -1 && yIndex + 1 < args2.length) {
378
- return args2[yIndex + 1];
379
- }
380
- const yesIndex = args2.indexOf("--yes");
381
- if (yesIndex !== -1 && yesIndex + 1 < args2.length) {
382
- return args2[yesIndex + 1];
383
- }
384
- for (let i = 0; i < args2.length; i++) {
385
- const arg = args2[i];
386
- if (!arg.startsWith("-")) {
387
- if (i > 0) {
388
- const prevArg = args2[i - 1];
389
- if (prevArg === "--registry" || prevArg === "-r" || prevArg === "--package" || prevArg === "-p") {
390
- continue;
391
- }
392
- }
393
- return arg;
394
- }
395
- }
396
- return null;
397
- }
398
- /**
399
- * Extract the package name from uvx arguments
400
- * @param args - Array of arguments passed to uvx
401
- * @returns The package name/spec or null if not found
402
- */
403
- extractUvxPackageName(args2) {
404
- if (!args2 || args2.length === 0) {
405
- return null;
406
- }
407
- return args2[0];
408
- }
409
- /**
410
- * Extract the package name from uv arguments
411
- * @param args - Array of arguments passed to uv
412
- * @returns The package name/spec or null if not found
413
- */
414
- extractUvPackageName(args2) {
415
- if (!args2 || args2.length === 0) {
416
- return null;
417
- }
418
- const runIndex = args2.indexOf("run");
419
- if (runIndex !== -1 && runIndex + 1 < args2.length) {
420
- return args2[runIndex + 1];
421
- }
422
- return null;
423
- }
424
- /**
425
- * Parse a package specification to extract name and version
426
- * @param packageSpec - Package specification (e.g., "package@1.0.0" or "package")
427
- * @returns Object with name and optional version
428
- */
429
- parsePackageVersion(packageSpec) {
430
- if (!packageSpec) {
431
- return { name: "", version: void 0 };
432
- }
433
- if (packageSpec.startsWith("@")) {
434
- const parts = packageSpec.split("@");
435
- if (parts.length === 2) {
436
- return { name: packageSpec, version: void 0 };
437
- } else if (parts.length === 3) {
438
- return {
439
- name: `@${parts[1]}`,
440
- version: parts[2]
441
- };
442
- }
443
- }
444
- const atIndex = packageSpec.lastIndexOf("@");
445
- if (atIndex > 0) {
446
- return {
447
- name: packageSpec.substring(0, atIndex),
448
- version: packageSpec.substring(atIndex + 1)
449
- };
450
- }
451
- return { name: packageSpec, version: void 0 };
452
- }
453
- /**
454
- * Determine if a version represents a pinned version
455
- * @param version - The version string to check
456
- * @returns true if the version is pinned, false if it's latest/implicit
457
- */
458
- isPinnedVersion(version) {
459
- if (!version) {
460
- return false;
461
- }
462
- if (version === "latest") {
463
- return false;
464
- }
465
- return true;
466
- }
267
+ /**
268
+ * Analyze a server configuration to extract version information
269
+ * @param command - The command used to run the server
270
+ * @param args - Array of arguments passed to the command
271
+ * @returns PackageVersionInfo if analysis is possible, null otherwise
272
+ */
273
+ analyzeServerVersion(command, args) {
274
+ if (![
275
+ "npx",
276
+ "uvx",
277
+ "uv"
278
+ ].includes(command)) return null;
279
+ if (!args || args.length === 0) return null;
280
+ const packageName = this.extractPackageName(command, args);
281
+ if (!packageName) return null;
282
+ const { name, version } = this.parsePackageVersion(packageName);
283
+ const isPinned = this.isPinnedVersion(version);
284
+ return {
285
+ packageName: name,
286
+ version,
287
+ isPinned,
288
+ isLatest: !isPinned
289
+ };
290
+ }
291
+ /**
292
+ * Extract the package name based on the command type
293
+ * @param command - The command used to run the server
294
+ * @param args - Array of arguments passed to the command
295
+ * @returns The package name/spec or null if not found
296
+ */
297
+ extractPackageName(command, args) {
298
+ switch (command) {
299
+ case "npx": return this.extractNpxPackageName(args);
300
+ case "uvx": return this.extractUvxPackageName(args);
301
+ case "uv": return this.extractUvPackageName(args);
302
+ default: return null;
303
+ }
304
+ }
305
+ /**
306
+ * Extract the package name from npx arguments
307
+ * @param args - Array of arguments passed to npx
308
+ * @returns The package name/spec or null if not found
309
+ */
310
+ extractNpxPackageName(args) {
311
+ if (!args || args.length === 0) return null;
312
+ const yIndex = args.indexOf("-y");
313
+ if (yIndex !== -1 && yIndex + 1 < args.length) return args[yIndex + 1];
314
+ const yesIndex = args.indexOf("--yes");
315
+ if (yesIndex !== -1 && yesIndex + 1 < args.length) return args[yesIndex + 1];
316
+ for (let i = 0; i < args.length; i++) {
317
+ const arg = args[i];
318
+ if (!arg.startsWith("-")) {
319
+ if (i > 0) {
320
+ const prevArg = args[i - 1];
321
+ if (prevArg === "--registry" || prevArg === "-r" || prevArg === "--package" || prevArg === "-p") continue;
322
+ }
323
+ return arg;
324
+ }
325
+ }
326
+ return null;
327
+ }
328
+ /**
329
+ * Extract the package name from uvx arguments
330
+ * @param args - Array of arguments passed to uvx
331
+ * @returns The package name/spec or null if not found
332
+ */
333
+ extractUvxPackageName(args) {
334
+ if (!args || args.length === 0) return null;
335
+ return args[0];
336
+ }
337
+ /**
338
+ * Extract the package name from uv arguments
339
+ * @param args - Array of arguments passed to uv
340
+ * @returns The package name/spec or null if not found
341
+ */
342
+ extractUvPackageName(args) {
343
+ if (!args || args.length === 0) return null;
344
+ const runIndex = args.indexOf("run");
345
+ if (runIndex !== -1 && runIndex + 1 < args.length) return args[runIndex + 1];
346
+ return null;
347
+ }
348
+ /**
349
+ * Parse a package specification to extract name and version
350
+ * @param packageSpec - Package specification (e.g., "package@1.0.0" or "package")
351
+ * @returns Object with name and optional version
352
+ */
353
+ parsePackageVersion(packageSpec) {
354
+ if (!packageSpec) return {
355
+ name: "",
356
+ version: void 0
357
+ };
358
+ if (packageSpec.startsWith("@")) {
359
+ const parts = packageSpec.split("@");
360
+ if (parts.length === 2) return {
361
+ name: packageSpec,
362
+ version: void 0
363
+ };
364
+ else if (parts.length === 3) return {
365
+ name: `@${parts[1]}`,
366
+ version: parts[2]
367
+ };
368
+ }
369
+ const atIndex = packageSpec.lastIndexOf("@");
370
+ if (atIndex > 0) return {
371
+ name: packageSpec.substring(0, atIndex),
372
+ version: packageSpec.substring(atIndex + 1)
373
+ };
374
+ return {
375
+ name: packageSpec,
376
+ version: void 0
377
+ };
378
+ }
379
+ /**
380
+ * Determine if a version represents a pinned version
381
+ * @param version - The version string to check
382
+ * @returns true if the version is pinned, false if it's latest/implicit
383
+ */
384
+ isPinnedVersion(version) {
385
+ if (!version) return false;
386
+ if (version === "latest") return false;
387
+ return true;
388
+ }
467
389
  };
468
-
469
390
  // src/utils/url-utils.ts
391
+ /**
392
+ * Utility functions for URL operations
393
+ */
394
+ /**
395
+ * Extract hostname from a URL string
396
+ * @param urlString - The URL string to extract hostname from
397
+ * @returns The hostname if valid URL, or the original string if parsing fails
398
+ */
470
399
  function extractHostname(urlString) {
471
- try {
472
- let urlToParse = urlString;
473
- if (!urlToParse.includes("://")) {
474
- urlToParse = `http://${urlToParse}`;
475
- }
476
- const url = new URL(urlToParse);
477
- return url.hostname;
478
- } catch (error) {
479
- return urlString;
480
- }
400
+ try {
401
+ let urlToParse = urlString;
402
+ if (!urlToParse.includes("://")) urlToParse = `http://${urlToParse}`;
403
+ return new URL(urlToParse).hostname;
404
+ } catch {
405
+ return urlString;
406
+ }
481
407
  }
482
- __name(extractHostname, "extractHostname");
483
-
484
408
  // src/services/mcp-config-service.ts
485
409
  var MCPConfigService = class {
486
- static {
487
- __name(this, "MCPConfigService");
488
- }
489
- pathRegistry;
490
- currentOS;
491
- debug;
492
- directoryBubbleService;
493
- versionDetectionService;
494
- enableDirectoryBubbling;
495
- constructor(options = {}) {
496
- this.pathRegistry = new import_agent_files.MCPPathRegistry();
497
- this.currentOS = (0, import_node_os.platform)();
498
- this.debug = import_node_util.default.debuglog("ls-mcp");
499
- this.directoryBubbleService = new import_agent_files.DirectoryBubbleService();
500
- this.versionDetectionService = new MCPVersionDetectionService();
501
- this.enableDirectoryBubbling = options.enableDirectoryBubbling ?? false;
502
- }
503
- /**
504
- * Get MCP configuration files for a specific AI application on the current OS
505
- */
506
- getConfigFilesPerApp(appName) {
507
- try {
508
- return this.pathRegistry.getPathsForApp(this.currentOS, appName);
509
- } catch (error) {
510
- throw new Error(`Failed to get config files for app '${appName}': ${error instanceof Error ? error.message : "Unknown error"}`);
511
- }
512
- }
513
- /**
514
- * Get MCP configuration files for all AI applications on the current OS
515
- */
516
- getAllConfigFiles() {
517
- try {
518
- return this.pathRegistry.getPathsForOS(this.currentOS);
519
- } catch (error) {
520
- throw new Error(`Failed to get all config files: ${error instanceof Error ? error.message : "Unknown error"}`);
521
- }
522
- }
523
- /**
524
- * Get MCP servers configured for a specific AI application on the current OS
525
- */
526
- async getMCPServersPerApp(appName) {
527
- try {
528
- const appPaths = this.getConfigFilesPerApp(appName);
529
- const allServers = [];
530
- for (const filePath of appPaths) {
531
- const servers = await this.parseConfigFileForServers(filePath.filePath);
532
- allServers.push(...servers);
533
- }
534
- return allServers;
535
- } catch (error) {
536
- throw new Error(`Failed to get MCP servers for app '${appName}': ${error instanceof Error ? error.message : "Unknown error"}`);
537
- }
538
- }
539
- /**
540
- * Get MCP servers configured for all AI applications on the current OS
541
- */
542
- async getAllMCPServers() {
543
- try {
544
- const allApps = this.pathRegistry.getSupportedApps(this.currentOS);
545
- const allServers = {};
546
- for (const appName of allApps) {
547
- try {
548
- allServers[appName] = await this.getMCPServersPerApp(appName);
549
- } catch (error) {
550
- this.debug(`Failed to get servers for app '${appName}': ${error instanceof Error ? error.message : "Unknown error"}`);
551
- allServers[appName] = [];
552
- }
553
- }
554
- return allServers;
555
- } catch (error) {
556
- throw new Error(`Failed to get all MCP servers: ${error instanceof Error ? error.message : "Unknown error"}`);
557
- }
558
- }
559
- /**
560
- * Get metadata for all supported AI applications on the current OS
561
- */
562
- getSupportedApps() {
563
- try {
564
- const appNames = this.pathRegistry.getSupportedApps(this.currentOS);
565
- const appPaths = this.pathRegistry.getPathsForOS(this.currentOS);
566
- return appNames.map((appName) => ({
567
- name: appName,
568
- friendlyName: this.getFriendlyName(appName),
569
- paths: appPaths[appName] || []
570
- }));
571
- } catch (error) {
572
- throw new Error(`Failed to get supported apps: ${error instanceof Error ? error.message : "Unknown error"}`);
573
- }
574
- }
575
- /**
576
- * Get all supported operating systems
577
- */
578
- getSupportedOperatingSystems() {
579
- return this.pathRegistry.getSupportedOperatingSystems();
580
- }
581
- /**
582
- * Validate if a configuration file exists and is parsable
583
- */
584
- async validateConfigFile(filePath) {
585
- try {
586
- await import_promises.default.access(filePath);
587
- const parser = this.createParser(filePath);
588
- return await parser.isValidSyntax();
589
- } catch (error) {
590
- return false;
591
- }
592
- }
593
- /**
594
- * Create a parser instance (can be overridden for testing)
595
- */
596
- createParser(filePath) {
597
- return new import_agent_files.MCPConfigParser(filePath);
598
- }
599
- /**
600
- * Get MCP file groups with resolved paths and server information
601
- */
602
- async getMCPFileGroups() {
603
- try {
604
- const appPaths = this.getAllConfigFiles();
605
- const mcpFilesPathsData = {};
606
- for (const groupName of Object.keys(appPaths)) {
607
- const paths = appPaths[groupName];
608
- mcpFilesPathsData[groupName] = {
609
- name: groupName,
610
- friendlyName: this.getFriendlyName(groupName),
611
- paths: [],
612
- stats: { serversCount: 0 }
613
- };
614
- const uniqueFilePaths = /* @__PURE__ */ new Set();
615
- let totalServersCount = 0;
616
- for (const filePathData of paths) {
617
- let resolvedPath = filePathData.filePath.replace("~", process.env.HOME || "");
618
- let absolutePath = import_node_path.default.resolve(resolvedPath);
619
- if (filePathData.type === "local" && this.enableDirectoryBubbling) {
620
- try {
621
- await import_promises.default.access(resolvedPath);
622
- } catch (error) {
623
- const bubbledPath = await this.directoryBubbleService.findLocalConfigInParentDirectories(
624
- filePathData.filePath,
625
- process.cwd()
626
- );
627
- if (bubbledPath) {
628
- resolvedPath = bubbledPath;
629
- absolutePath = import_node_path.default.resolve(resolvedPath);
630
- }
631
- }
632
- }
633
- if (uniqueFilePaths.has(absolutePath)) {
634
- continue;
635
- }
636
- uniqueFilePaths.add(absolutePath);
637
- try {
638
- await import_promises.default.access(resolvedPath);
639
- const parser = this.createParser(resolvedPath);
640
- const parsable = await parser.isValidSyntax();
641
- filePathData.parsable = parsable;
642
- if (parsable) {
643
- const configData = await parser.parseConfigFile();
644
- const servers = await this.convertToMCPServerInfo(configData.servers || {});
645
- filePathData.servers = servers;
646
- totalServersCount += servers.length;
647
- }
648
- mcpFilesPathsData[groupName].paths.push(filePathData);
649
- } catch (error) {
650
- this.debug(`Skipping file ${resolvedPath}: ${error instanceof Error ? error.message : "Unknown error"}`);
651
- }
652
- }
653
- if (mcpFilesPathsData[groupName] && mcpFilesPathsData[groupName].stats) {
654
- mcpFilesPathsData[groupName].stats.serversCount = totalServersCount;
655
- }
656
- }
657
- return mcpFilesPathsData;
658
- } catch (error) {
659
- throw new Error(`Failed to get MCP file groups: ${error instanceof Error ? error.message : "Unknown error"}`);
660
- }
661
- }
662
- /**
663
- * Parse custom configuration files provided by the user
664
- * This method processes files independently of standard app-based discovery
665
- */
666
- async parseCustomFiles(filePaths) {
667
- try {
668
- const mcpFilesPathsData = {
669
- custom: {
670
- name: "custom",
671
- friendlyName: "Custom Files",
672
- paths: [],
673
- stats: { serversCount: 0 }
674
- }
675
- };
676
- let totalServersCount = 0;
677
- for (const filePath of filePaths) {
678
- const resolvedPath = filePath.replace("~", process.env.HOME || "");
679
- const absolutePath = import_node_path.default.resolve(resolvedPath);
680
- try {
681
- await import_promises.default.access(absolutePath);
682
- const parser = this.createParser(absolutePath);
683
- const parsable = await parser.isValidSyntax();
684
- const filePathData = {
685
- filePath: absolutePath,
686
- type: "local",
687
- parsable
688
- };
689
- if (parsable) {
690
- const configData = await parser.parseConfigFile();
691
- const servers = await this.convertToMCPServerInfo(configData.servers || {});
692
- filePathData.servers = servers;
693
- totalServersCount += servers.length;
694
- } else {
695
- this.debug(`File ${absolutePath} has invalid syntax`);
696
- filePathData.servers = [];
697
- }
698
- mcpFilesPathsData.custom.paths.push(filePathData);
699
- } catch (error) {
700
- this.debug(`Skipping file ${absolutePath}: ${error instanceof Error ? error.message : "Unknown error"}`);
701
- mcpFilesPathsData.custom.paths.push({
702
- filePath: absolutePath,
703
- type: "local",
704
- parsable: false,
705
- servers: []
706
- });
707
- }
708
- }
709
- if (mcpFilesPathsData.custom.stats) {
710
- mcpFilesPathsData.custom.stats.serversCount = totalServersCount;
711
- }
712
- return mcpFilesPathsData;
713
- } catch (error) {
714
- throw new Error(`Failed to parse custom files: ${error instanceof Error ? error.message : "Unknown error"}`);
715
- }
716
- }
717
- /**
718
- * Register a custom app with custom paths for the current OS
719
- */
720
- registerCustomApp(appName, paths) {
721
- try {
722
- this.pathRegistry.registerCustomApp(this.currentOS, appName, paths);
723
- } catch (error) {
724
- throw new Error(`Failed to register custom app '${appName}': ${error instanceof Error ? error.message : "Unknown error"}`);
725
- }
726
- }
727
- /**
728
- * Parse a configuration file and return server information
729
- */
730
- async parseConfigFileForServers(filePath) {
731
- try {
732
- const parser = this.createParser(filePath);
733
- const configData = await parser.parseConfigFile();
734
- return await this.convertToMCPServerInfo(configData.servers || {});
735
- } catch (error) {
736
- this.debug(`Failed to parse config file ${filePath}: ${error instanceof Error ? error.message : "Unknown error"}`);
737
- return [];
738
- }
739
- }
740
- /**
741
- * Convert parsed server configs to MCPServerInfo format
742
- */
743
- async convertToMCPServerInfo(servers) {
744
- const serverInfos = [];
745
- for (const [serverName, serverConfig] of Object.entries(servers)) {
746
- if (serverConfig && typeof serverConfig === "object") {
747
- let source;
748
- if (serverConfig.url) {
749
- source = extractHostname(serverConfig.url);
750
- } else {
751
- source = serverConfig.command || "";
752
- }
753
- const versionInfo = this.versionDetectionService.analyzeServerVersion(
754
- serverConfig.command || "",
755
- Array.isArray(serverConfig.args) ? serverConfig.args : void 0
756
- );
757
- serverInfos.push({
758
- name: serverName,
759
- command: serverConfig.command || "",
760
- args: Array.isArray(serverConfig.args) ? serverConfig.args : void 0,
761
- transport: serverConfig.type === "streamable-http" ? "http" : serverConfig.type,
762
- // Map streamable-http to http
763
- type: serverConfig.type,
764
- source,
765
- env: serverConfig.env,
766
- headers: serverConfig.headers,
767
- status: "stopped",
768
- // Default status, will be updated by server manager
769
- versionInfo: versionInfo || void 0,
770
- credentials: CredentialDetectionService.analyzeServerConfig({
771
- env: serverConfig.env,
772
- args: serverConfig.args,
773
- headers: serverConfig.headers
774
- })
775
- });
776
- }
777
- }
778
- return serverInfos;
779
- }
780
- /**
781
- * Get friendly name for an app
782
- */
783
- getFriendlyName(appName) {
784
- const friendlyNames = {
785
- claude: "Claude Desktop",
786
- claude_code: "Claude Code",
787
- cursor: "Cursor",
788
- vscode: "VS Code",
789
- cline: "Cline",
790
- windsurf: "Windsurf",
791
- roo: "Roo",
792
- "intellij-github-copilot": "IntelliJ GitHub Copilot",
793
- junie: "IntelliJ Junie",
794
- zed: "Zed",
795
- gemini: "Gemini CLI"
796
- };
797
- return friendlyNames[appName] || appName;
798
- }
410
+ pathRegistry;
411
+ currentOS;
412
+ debug;
413
+ directoryBubbleService;
414
+ versionDetectionService;
415
+ enableDirectoryBubbling;
416
+ constructor(options = {}) {
417
+ this.pathRegistry = new agent_files.MCPPathRegistry();
418
+ this.currentOS = (0, node_os.platform)();
419
+ this.debug = node_util.default.debuglog("ls-mcp");
420
+ this.directoryBubbleService = new agent_files.DirectoryBubbleService();
421
+ this.versionDetectionService = new MCPVersionDetectionService();
422
+ this.enableDirectoryBubbling = options.enableDirectoryBubbling ?? false;
423
+ }
424
+ /**
425
+ * Get MCP configuration files for a specific AI application on the current OS
426
+ */
427
+ getConfigFilesPerApp(appName) {
428
+ try {
429
+ return this.pathRegistry.getPathsForApp(this.currentOS, appName);
430
+ } catch (error) {
431
+ throw new Error(`Failed to get config files for app '${appName}': ${error instanceof Error ? error.message : "Unknown error"}`, { cause: error });
432
+ }
433
+ }
434
+ /**
435
+ * Get MCP configuration files for all AI applications on the current OS
436
+ */
437
+ getAllConfigFiles() {
438
+ try {
439
+ return this.pathRegistry.getPathsForOS(this.currentOS);
440
+ } catch (error) {
441
+ throw new Error(`Failed to get all config files: ${error instanceof Error ? error.message : "Unknown error"}`, { cause: error });
442
+ }
443
+ }
444
+ /**
445
+ * Get MCP servers configured for a specific AI application on the current OS
446
+ */
447
+ async getMCPServersPerApp(appName) {
448
+ try {
449
+ const appPaths = this.getConfigFilesPerApp(appName);
450
+ const allServers = [];
451
+ for (const filePath of appPaths) {
452
+ const servers = await this.parseConfigFileForServers(filePath.filePath);
453
+ allServers.push(...servers);
454
+ }
455
+ return allServers;
456
+ } catch (error) {
457
+ throw new Error(`Failed to get MCP servers for app '${appName}': ${error instanceof Error ? error.message : "Unknown error"}`, { cause: error });
458
+ }
459
+ }
460
+ /**
461
+ * Get MCP servers configured for all AI applications on the current OS
462
+ */
463
+ async getAllMCPServers() {
464
+ try {
465
+ const allApps = this.pathRegistry.getSupportedApps(this.currentOS);
466
+ const allServers = {};
467
+ for (const appName of allApps) try {
468
+ allServers[appName] = await this.getMCPServersPerApp(appName);
469
+ } catch (error) {
470
+ this.debug(`Failed to get servers for app '${appName}': ${error instanceof Error ? error.message : "Unknown error"}`);
471
+ allServers[appName] = [];
472
+ }
473
+ return allServers;
474
+ } catch (error) {
475
+ throw new Error(`Failed to get all MCP servers: ${error instanceof Error ? error.message : "Unknown error"}`, { cause: error });
476
+ }
477
+ }
478
+ /**
479
+ * Get metadata for all supported AI applications on the current OS
480
+ */
481
+ getSupportedApps() {
482
+ try {
483
+ const appNames = this.pathRegistry.getSupportedApps(this.currentOS);
484
+ const appPaths = this.pathRegistry.getPathsForOS(this.currentOS);
485
+ return appNames.map((appName) => ({
486
+ name: appName,
487
+ friendlyName: this.getFriendlyName(appName),
488
+ paths: appPaths[appName] || []
489
+ }));
490
+ } catch (error) {
491
+ throw new Error(`Failed to get supported apps: ${error instanceof Error ? error.message : "Unknown error"}`, { cause: error });
492
+ }
493
+ }
494
+ /**
495
+ * Get all supported operating systems
496
+ */
497
+ getSupportedOperatingSystems() {
498
+ return this.pathRegistry.getSupportedOperatingSystems();
499
+ }
500
+ /**
501
+ * Validate if a configuration file exists and is parsable
502
+ */
503
+ async validateConfigFile(filePath) {
504
+ try {
505
+ await node_fs_promises.default.access(filePath);
506
+ return await this.createParser(filePath).isValidSyntax();
507
+ } catch {
508
+ return false;
509
+ }
510
+ }
511
+ /**
512
+ * Create a parser instance (can be overridden for testing)
513
+ */
514
+ createParser(filePath) {
515
+ return new agent_files.MCPConfigParser(filePath);
516
+ }
517
+ /**
518
+ * Get MCP file groups with resolved paths and server information
519
+ */
520
+ async getMCPFileGroups() {
521
+ try {
522
+ const appPaths = this.getAllConfigFiles();
523
+ const mcpFilesPathsData = {};
524
+ for (const groupName of Object.keys(appPaths)) {
525
+ const paths = appPaths[groupName];
526
+ mcpFilesPathsData[groupName] = {
527
+ name: groupName,
528
+ friendlyName: this.getFriendlyName(groupName),
529
+ paths: [],
530
+ stats: { serversCount: 0 }
531
+ };
532
+ const uniqueFilePaths = /* @__PURE__ */ new Set();
533
+ let totalServersCount = 0;
534
+ for (const filePathData of paths) {
535
+ let resolvedPath = filePathData.filePath.replace("~", process.env.HOME || "");
536
+ let absolutePath = node_path.default.resolve(resolvedPath);
537
+ if (filePathData.type === "local" && this.enableDirectoryBubbling) try {
538
+ await node_fs_promises.default.access(resolvedPath);
539
+ } catch {
540
+ const bubbledPath = await this.directoryBubbleService.findLocalConfigInParentDirectories(filePathData.filePath, process.cwd());
541
+ if (bubbledPath) {
542
+ resolvedPath = bubbledPath;
543
+ absolutePath = node_path.default.resolve(resolvedPath);
544
+ }
545
+ }
546
+ if (uniqueFilePaths.has(absolutePath)) continue;
547
+ uniqueFilePaths.add(absolutePath);
548
+ try {
549
+ await node_fs_promises.default.access(resolvedPath);
550
+ const parser = this.createParser(resolvedPath);
551
+ const parsable = await parser.isValidSyntax();
552
+ filePathData.parsable = parsable;
553
+ if (parsable) {
554
+ const configData = await parser.parseConfigFile();
555
+ const servers = await this.convertToMCPServerInfo(configData.servers || {});
556
+ filePathData.servers = servers;
557
+ totalServersCount += servers.length;
558
+ }
559
+ mcpFilesPathsData[groupName].paths.push(filePathData);
560
+ } catch (error) {
561
+ this.debug(`Skipping file ${resolvedPath}: ${error instanceof Error ? error.message : "Unknown error"}`);
562
+ }
563
+ }
564
+ if (mcpFilesPathsData[groupName] && mcpFilesPathsData[groupName].stats) mcpFilesPathsData[groupName].stats.serversCount = totalServersCount;
565
+ }
566
+ return mcpFilesPathsData;
567
+ } catch (error) {
568
+ throw new Error(`Failed to get MCP file groups: ${error instanceof Error ? error.message : "Unknown error"}`, { cause: error });
569
+ }
570
+ }
571
+ /**
572
+ * Parse custom configuration files provided by the user
573
+ * This method processes files independently of standard app-based discovery
574
+ */
575
+ async parseCustomFiles(filePaths) {
576
+ try {
577
+ const mcpFilesPathsData = { custom: {
578
+ name: "custom",
579
+ friendlyName: "Custom Files",
580
+ paths: [],
581
+ stats: { serversCount: 0 }
582
+ } };
583
+ let totalServersCount = 0;
584
+ for (const filePath of filePaths) {
585
+ const resolvedPath = filePath.replace("~", process.env.HOME || "");
586
+ const absolutePath = node_path.default.resolve(resolvedPath);
587
+ try {
588
+ await node_fs_promises.default.access(absolutePath);
589
+ const parser = this.createParser(absolutePath);
590
+ const parsable = await parser.isValidSyntax();
591
+ const filePathData = {
592
+ filePath: absolutePath,
593
+ type: "local",
594
+ parsable
595
+ };
596
+ if (parsable) {
597
+ const configData = await parser.parseConfigFile();
598
+ const servers = await this.convertToMCPServerInfo(configData.servers || {});
599
+ filePathData.servers = servers;
600
+ totalServersCount += servers.length;
601
+ } else {
602
+ this.debug(`File ${absolutePath} has invalid syntax`);
603
+ filePathData.servers = [];
604
+ }
605
+ mcpFilesPathsData.custom.paths.push(filePathData);
606
+ } catch (error) {
607
+ this.debug(`Skipping file ${absolutePath}: ${error instanceof Error ? error.message : "Unknown error"}`);
608
+ mcpFilesPathsData.custom.paths.push({
609
+ filePath: absolutePath,
610
+ type: "local",
611
+ parsable: false,
612
+ servers: []
613
+ });
614
+ }
615
+ }
616
+ if (mcpFilesPathsData.custom.stats) mcpFilesPathsData.custom.stats.serversCount = totalServersCount;
617
+ return mcpFilesPathsData;
618
+ } catch (error) {
619
+ throw new Error(`Failed to parse custom files: ${error instanceof Error ? error.message : "Unknown error"}`, { cause: error });
620
+ }
621
+ }
622
+ /**
623
+ * Register a custom app with custom paths for the current OS
624
+ */
625
+ registerCustomApp(appName, paths) {
626
+ try {
627
+ this.pathRegistry.registerCustomApp(this.currentOS, appName, paths);
628
+ } catch (error) {
629
+ throw new Error(`Failed to register custom app '${appName}': ${error instanceof Error ? error.message : "Unknown error"}`, { cause: error });
630
+ }
631
+ }
632
+ /**
633
+ * Parse a configuration file and return server information
634
+ */
635
+ async parseConfigFileForServers(filePath) {
636
+ try {
637
+ const configData = await this.createParser(filePath).parseConfigFile();
638
+ return await this.convertToMCPServerInfo(configData.servers || {});
639
+ } catch (error) {
640
+ this.debug(`Failed to parse config file ${filePath}: ${error instanceof Error ? error.message : "Unknown error"}`);
641
+ return [];
642
+ }
643
+ }
644
+ /**
645
+ * Convert parsed server configs to MCPServerInfo format
646
+ */
647
+ async convertToMCPServerInfo(servers) {
648
+ const serverInfos = [];
649
+ for (const [serverName, serverConfig] of Object.entries(servers)) if (serverConfig && typeof serverConfig === "object") {
650
+ let source;
651
+ if (serverConfig.url) source = extractHostname(serverConfig.url);
652
+ else source = serverConfig.command || "";
653
+ const versionInfo = this.versionDetectionService.analyzeServerVersion(serverConfig.command || "", Array.isArray(serverConfig.args) ? serverConfig.args : void 0);
654
+ serverInfos.push({
655
+ name: serverName,
656
+ command: serverConfig.command || "",
657
+ args: Array.isArray(serverConfig.args) ? serverConfig.args : void 0,
658
+ transport: serverConfig.type === "streamable-http" ? "http" : serverConfig.type,
659
+ type: serverConfig.type,
660
+ source,
661
+ env: serverConfig.env,
662
+ headers: serverConfig.headers,
663
+ status: "stopped",
664
+ versionInfo: versionInfo || void 0,
665
+ credentials: CredentialDetectionService.analyzeServerConfig({
666
+ env: serverConfig.env,
667
+ args: serverConfig.args,
668
+ headers: serverConfig.headers
669
+ })
670
+ });
671
+ }
672
+ return serverInfos;
673
+ }
674
+ /**
675
+ * Get friendly name for an app
676
+ */
677
+ getFriendlyName(appName) {
678
+ return {
679
+ claude: "Claude Desktop",
680
+ claude_code: "Claude Code",
681
+ cursor: "Cursor",
682
+ vscode: "VS Code",
683
+ cline: "Cline",
684
+ windsurf: "Windsurf",
685
+ roo: "Roo",
686
+ "intellij-github-copilot": "IntelliJ GitHub Copilot",
687
+ junie: "IntelliJ Junie",
688
+ zed: "Zed",
689
+ gemini: "Gemini CLI"
690
+ }[appName] || appName;
691
+ }
799
692
  };
800
-
801
693
  // src/services/mcp-server-manager-service.ts
802
- var import_node_path2 = __toESM(require("path"), 1);
803
- var import_node_child_process = require("child_process");
804
- var import_node_os2 = require("os");
805
694
  var MCPServerManagerService = class {
806
- static {
807
- __name(this, "MCPServerManagerService");
808
- }
809
- name;
810
- command;
811
- args;
812
- transport;
813
- source;
814
- env;
815
- running = false;
816
- constructor(serverConfig) {
817
- this.name = serverConfig.name;
818
- this.command = serverConfig.command;
819
- this.args = serverConfig.args || [];
820
- this.transport = serverConfig.transport || "stdio";
821
- if (serverConfig?.type && serverConfig.type === "sse") {
822
- this.transport = "sse";
823
- }
824
- if (serverConfig?.type && (serverConfig.type === "http" || serverConfig.type === "streamable-http")) {
825
- this.transport = "http";
826
- }
827
- if (serverConfig?.type && serverConfig.type === "stdio") {
828
- this.transport = "stdio";
829
- }
830
- if (serverConfig.url) {
831
- this.source = extractHostname(serverConfig.url);
832
- this.transport = "http";
833
- } else {
834
- const fullCommand = [serverConfig.command, ...serverConfig.args || []].join(" ");
835
- this.source = fullCommand;
836
- }
837
- this.env = serverConfig.env || {};
838
- }
839
- getName() {
840
- return this.name;
841
- }
842
- getCmd() {
843
- return this.command;
844
- }
845
- getArgs() {
846
- return this.args;
847
- }
848
- getTransport() {
849
- return this.transport;
850
- }
851
- getSource() {
852
- return this.source;
853
- }
854
- getEnv() {
855
- return this.env;
856
- }
857
- isRunning() {
858
- try {
859
- let psOutput;
860
- if ((0, import_node_os2.platform)() === "win32") {
861
- psOutput = (0, import_node_child_process.execSync)('powershell -Command "Get-CimInstance -ClassName Win32_Process | Select-Object ProcessId,Name,CommandLine,ParentProcessId | ConvertTo-Csv -NoTypeInformation"', {
862
- encoding: "utf8",
863
- timeout: 5e3
864
- });
865
- } else {
866
- psOutput = (0, import_node_child_process.execSync)("ps -eao pid,ppid,args", {
867
- encoding: "utf8",
868
- timeout: 5e3
869
- });
870
- }
871
- const processMap = /* @__PURE__ */ new Map();
872
- const processes = psOutput.trim().split("\n");
873
- for (const processLine of processes) {
874
- if (!processLine.trim()) continue;
875
- let pid;
876
- let ppid;
877
- let commandLine;
878
- if ((0, import_node_os2.platform)() === "win32") {
879
- if (processLine.startsWith('"ProcessId"') || processLine.startsWith("ProcessId")) continue;
880
- const parts = this.parseCSVLine(processLine);
881
- if (parts.length < 4) continue;
882
- pid = parts[0].trim() || "";
883
- commandLine = parts[2].trim() || "";
884
- ppid = parts[3].trim() || "";
885
- } else {
886
- const match = processLine.trim().match(/^\s*(\d+)\s+(\d+)\s+(.+)$/);
887
- if (!match) continue;
888
- pid = match[1].trim() || "";
889
- ppid = match[2].trim() || "";
890
- commandLine = match[3].trim() || "";
891
- }
892
- const commandTokens = this.parseCommandLine(commandLine);
893
- if (commandTokens.length > 0) {
894
- processMap.set(pid, { ppid, commandTokens });
895
- }
896
- }
897
- let mcpServerDetection;
898
- for (const [pid, processData] of processMap) {
899
- const commandMatchLinux = this.isCommandMatch(processData.commandTokens, pid, processData.ppid);
900
- let commandMatchWin32 = false;
901
- if ((0, import_node_os2.platform)() === "win32") {
902
- let commandTokensOnWin32 = processData.commandTokens;
903
- if (commandTokensOnWin32.length > 0 && commandTokensOnWin32[0].toLowerCase().startsWith("cmd")) {
904
- commandTokensOnWin32 = commandTokensOnWin32.slice(1);
905
- while (commandTokensOnWin32.length > 0 && commandTokensOnWin32[0].startsWith("/")) {
906
- commandTokensOnWin32 = commandTokensOnWin32.slice(1);
907
- }
908
- }
909
- commandMatchWin32 = this.isCommandMatch(commandTokensOnWin32, pid, processData.ppid);
910
- }
911
- const commandMatch = commandMatchLinux || commandMatchWin32;
912
- if (commandMatch) {
913
- mcpServerDetection = {
914
- pid,
915
- commandLine: processData.commandTokens.join(" "),
916
- ppid: processData.ppid
917
- };
918
- const parentProcess = processMap.get(processData.ppid);
919
- if (parentProcess) {
920
- const { estimatedVendor, estimatedProduct } = this.getVendorFromCommand(parentProcess.commandTokens) || {};
921
- if (estimatedProduct || estimatedVendor) {
922
- mcpServerDetection = {
923
- ...mcpServerDetection,
924
- parentCommandLine: parentProcess.commandTokens.join(" "),
925
- estimatedVendor,
926
- estimatedProduct
927
- };
928
- return mcpServerDetection;
929
- }
930
- }
931
- }
932
- }
933
- if (mcpServerDetection) {
934
- return mcpServerDetection;
935
- }
936
- return false;
937
- } catch (error) {
938
- return false;
939
- }
940
- }
941
- getVendorFromCommand(commandTokens) {
942
- const commandString = commandTokens.join(" ").toLowerCase();
943
- if (commandString.includes("claude.app")) {
944
- return {
945
- estimatedVendor: "anthropic",
946
- estimatedProduct: "claude-desktop"
947
- };
948
- }
949
- if (commandString.includes("claude")) {
950
- return {
951
- estimatedVendor: "anthropic",
952
- estimatedProduct: "claude-desktop"
953
- };
954
- }
955
- if (commandString.includes("cursor")) {
956
- return {
957
- estimatedVendor: "cursor",
958
- estimatedProduct: "cursor"
959
- };
960
- }
961
- if (commandString.includes("visual studio code") || commandString.includes("vscode")) {
962
- return {
963
- estimatedVendor: "vscode",
964
- estimatedProduct: "vscode"
965
- };
966
- }
967
- }
968
- isCommandMatch(commandTokens, pid, ppid) {
969
- if (commandTokens.length === 0) return false;
970
- const baseCommand = this.getBaseCommand(commandTokens[0]);
971
- const commandInConfig = this.getBaseCommand(this.command);
972
- if (commandInConfig === "uvx" && baseCommand === "uv") {
973
- return this.matchUvxProcess(commandTokens);
974
- }
975
- if (commandInConfig === "npx" && baseCommand === "npm") {
976
- return this.matchNpxProcess(commandTokens);
977
- }
978
- if (commandInConfig === "uv" && baseCommand === "uv") {
979
- return this.matchGenericArgsToArgs(commandTokens);
980
- }
981
- const commandConfigPythonBase = this.getBaseCommand(this.command);
982
- const commandAliasesPython = ["python3", "python", "python3.10", "python3.11", "python3.12", "cpython3", "cpython", "python3", "python2"];
983
- if (commandAliasesPython.includes(commandConfigPythonBase) && commandAliasesPython.includes(baseCommand)) {
984
- return this.matchGenericArgsToArgs(commandTokens);
985
- }
986
- const commandGenericBase = this.getBaseCommand(this.command);
987
- const commandGenericProcessBase = this.getBaseCommand(commandTokens[0]);
988
- if (commandGenericBase === commandGenericProcessBase) {
989
- return this.matchGenericArgsToArgs(commandTokens);
990
- }
991
- return false;
992
- }
993
- matchGenericArgsToArgs(commandTokens) {
994
- if (this.args.length === 0) {
995
- return commandTokens[0] === this.command;
996
- }
997
- if (commandTokens.length < 2) {
998
- return false;
999
- }
1000
- const commandWithoutArgs = commandTokens.slice(1);
1001
- for (let i = 0; i < this.args.length; i++) {
1002
- if (i >= commandWithoutArgs.length) return false;
1003
- const arg = this.args[i].toLowerCase();
1004
- const token = commandWithoutArgs[i].toLowerCase();
1005
- if (arg !== token && !token.includes(arg)) {
1006
- return false;
1007
- }
1008
- }
1009
- return true;
1010
- }
1011
- getBaseCommand(fullCommandPath) {
1012
- let baseCommand = import_node_path2.default.basename(fullCommandPath);
1013
- if ((0, import_node_os2.platform)() === "win32") {
1014
- baseCommand = import_node_path2.default.basename(fullCommandPath, ".exe");
1015
- }
1016
- baseCommand = baseCommand.toLowerCase();
1017
- return baseCommand;
1018
- }
1019
- /*
1020
- example1:
1021
- ```
1022
- "command": "uvx",
1023
- "args": ["--from", "mcp-alchemy==2025.5.2.210242", "--with", "oracledb",
1024
- "--refresh-package", "mcp-alchemy", "mcp-alchemy"],
1025
- ```
1026
-
1027
- example 2:
1028
- ```
1029
- "command": "uvx",
1030
- "args": [
1031
- "mcp-neo4j-memory@0.1.4",
1032
- "--db-url",
1033
- "neo4j+s://xxxx.databases.neo4j.io",
1034
- "--username",
1035
- "<your-username>",
1036
- "--password",
1037
- "<your-password>"
1038
- ]
1039
- ```
1040
-
1041
- example 3:
1042
- ```
1043
- "vefaas": {
1044
- "command": "uvx",
1045
- "args": [
1046
- "--from",
1047
- "git+https://github.com/volcengine/mcp-server#subdirectory=server/mcp_server_vefaas_function",
1048
- "mcp-server-vefaas-function"
1049
- ],
1050
- "env": {
1051
- "VOLC_ACCESSKEY": "xxx",
1052
- "VOLC_SECRETKEY": "xxx"
1053
- }
1054
- }
1055
- }
1056
- ```
1057
-
1058
- example 4:
1059
- ```
1060
- "time": {
1061
- "command": "uvx",
1062
- "args": ["mcp-server-time", "--local-timezone=America/New_York"]
1063
- }
1064
- ```
1065
- */
1066
- getUvxMcpServerNameFromArgs() {
1067
- if (this.args.length === 0) return void 0;
1068
- let mcpServerName;
1069
- if (this.args.length === 1) {
1070
- mcpServerName = this.args[0];
1071
- return mcpServerName;
1072
- }
1073
- for (let i = 0; i < this.args.length; i++) {
1074
- if (this.args[i] === "--from" && i + 1 < this.args.length) {
1075
- mcpServerName = this.args[i + 1];
1076
- return mcpServerName;
1077
- }
1078
- }
1079
- const firstArg = this.args[0];
1080
- if (firstArg.startsWith("-") || firstArg.startsWith("--")) {
1081
- const lastArg = this.args[this.args.length - 1];
1082
- mcpServerName = lastArg;
1083
- return mcpServerName;
1084
- }
1085
- mcpServerName = firstArg;
1086
- return mcpServerName;
1087
- }
1088
- matchUvxProcess(commandTokens) {
1089
- if (commandTokens.length === 0) return false;
1090
- const mcpServerName = this.getUvxMcpServerNameFromArgs();
1091
- if (!mcpServerName) return false;
1092
- return this.findMcpServerNameInProcessArguments(commandTokens, mcpServerName);
1093
- }
1094
- findMcpServerNameInProcessArguments(commandTokens, mcpServerName) {
1095
- for (let i = 0; i < commandTokens.length; i++) {
1096
- const token = commandTokens[i].toLowerCase();
1097
- const normalizedMcpServerName = mcpServerName.toLowerCase();
1098
- if (normalizedMcpServerName === token || token.includes(normalizedMcpServerName)) {
1099
- return true;
1100
- }
1101
- }
1102
- return false;
1103
- }
1104
- parseCSVLine(line) {
1105
- const result = [];
1106
- let current = "";
1107
- let inQuotes = false;
1108
- for (let i = 0; i < line.length; i++) {
1109
- const char = line[i];
1110
- if (char === '"') {
1111
- if (inQuotes && line[i + 1] === '"') {
1112
- current += '"';
1113
- i++;
1114
- } else {
1115
- inQuotes = !inQuotes;
1116
- }
1117
- } else if (char === "," && !inQuotes) {
1118
- result.push(current);
1119
- current = "";
1120
- } else {
1121
- current += char;
1122
- }
1123
- }
1124
- result.push(current);
1125
- return result;
1126
- }
1127
- parseCommandLine(commandLine) {
1128
- const tokens = [];
1129
- let current = "";
1130
- let inQuotes = false;
1131
- let quoteChar = "";
1132
- for (let i = 0; i < commandLine.length; i++) {
1133
- const char = commandLine[i];
1134
- if (!inQuotes && (char === '"' || char === "'")) {
1135
- inQuotes = true;
1136
- quoteChar = char;
1137
- } else if (inQuotes && char === quoteChar) {
1138
- inQuotes = false;
1139
- quoteChar = "";
1140
- } else if (!inQuotes && char === " ") {
1141
- if (current.trim()) {
1142
- tokens.push(current.trim());
1143
- current = "";
1144
- }
1145
- } else {
1146
- current += char;
1147
- }
1148
- }
1149
- if (current.trim()) {
1150
- tokens.push(current.trim());
1151
- }
1152
- return tokens;
1153
- }
1154
- /*
1155
- example to match:
1156
- ```
1157
- "command": "npx",
1158
- "args": [
1159
- "-y",
1160
- "@modelcontextprotocol/server-postgres",
1161
- "postgresql://localhost/mydb"
1162
- ]
1163
- }
1164
- ```
1165
-
1166
- with a process command like:
1167
- ```
1168
- npm exec @modelcontextprotocol/server-postgres postgresql://localhost/mydb
1169
- ```
1170
- */
1171
- matchNpxProcess(commandTokens) {
1172
- if (commandTokens.length < 3) return false;
1173
- if (commandTokens[1] !== "exec") return false;
1174
- let argsToMatch = [];
1175
- const yIndex = this.args.indexOf("-y");
1176
- if (yIndex !== -1 && yIndex + 1 < this.args.length) {
1177
- argsToMatch = this.args.slice(yIndex + 1);
1178
- } else {
1179
- argsToMatch = this.args;
1180
- }
1181
- if (commandTokens.length - 2 !== argsToMatch.length) {
1182
- return false;
1183
- }
1184
- for (let i = 0; i < argsToMatch.length; i++) {
1185
- const commandToken = commandTokens[i + 2].toLowerCase();
1186
- const expectedArg = argsToMatch[i].toLowerCase();
1187
- if (commandToken !== expectedArg) {
1188
- return false;
1189
- }
1190
- }
1191
- return true;
1192
- }
695
+ name;
696
+ command;
697
+ args;
698
+ transport;
699
+ source;
700
+ env;
701
+ running = false;
702
+ constructor(serverConfig) {
703
+ this.name = serverConfig.name;
704
+ this.command = serverConfig.command;
705
+ this.args = serverConfig.args || [];
706
+ this.transport = serverConfig.transport || "stdio";
707
+ if (serverConfig?.type && serverConfig.type === "sse") this.transport = "sse";
708
+ if (serverConfig?.type && (serverConfig.type === "http" || serverConfig.type === "streamable-http")) this.transport = "http";
709
+ if (serverConfig?.type && serverConfig.type === "stdio") this.transport = "stdio";
710
+ if (serverConfig.url) {
711
+ this.source = extractHostname(serverConfig.url);
712
+ this.transport = "http";
713
+ } else {
714
+ const fullCommand = [serverConfig.command, ...serverConfig.args || []].join(" ");
715
+ this.source = fullCommand;
716
+ }
717
+ this.env = serverConfig.env || {};
718
+ }
719
+ getName() {
720
+ return this.name;
721
+ }
722
+ getCmd() {
723
+ return this.command;
724
+ }
725
+ getArgs() {
726
+ return this.args;
727
+ }
728
+ getTransport() {
729
+ return this.transport;
730
+ }
731
+ getSource() {
732
+ return this.source;
733
+ }
734
+ getEnv() {
735
+ return this.env;
736
+ }
737
+ isRunning() {
738
+ try {
739
+ let psOutput;
740
+ if ((0, node_os.platform)() === "win32") psOutput = (0, node_child_process.execSync)("powershell -Command \"Get-CimInstance -ClassName Win32_Process | Select-Object ProcessId,Name,CommandLine,ParentProcessId | ConvertTo-Csv -NoTypeInformation\"", {
741
+ encoding: "utf8",
742
+ timeout: 5e3
743
+ });
744
+ else psOutput = (0, node_child_process.execSync)("ps -eao pid,ppid,args", {
745
+ encoding: "utf8",
746
+ timeout: 5e3
747
+ });
748
+ const processMap = /* @__PURE__ */ new Map();
749
+ const processes = psOutput.trim().split("\n");
750
+ for (const processLine of processes) {
751
+ if (!processLine.trim()) continue;
752
+ let pid;
753
+ let ppid;
754
+ let commandLine;
755
+ if ((0, node_os.platform)() === "win32") {
756
+ if (processLine.startsWith("\"ProcessId\"") || processLine.startsWith("ProcessId")) continue;
757
+ const parts = this.parseCSVLine(processLine);
758
+ if (parts.length < 4) continue;
759
+ pid = parts[0].trim() || "";
760
+ commandLine = parts[2].trim() || "";
761
+ ppid = parts[3].trim() || "";
762
+ } else {
763
+ const match = processLine.trim().match(/^\s*(\d+)\s+(\d+)\s+(.+)$/);
764
+ if (!match) continue;
765
+ pid = match[1].trim() || "";
766
+ ppid = match[2].trim() || "";
767
+ commandLine = match[3].trim() || "";
768
+ }
769
+ const commandTokens = this.parseCommandLine(commandLine);
770
+ if (commandTokens.length > 0) processMap.set(pid, {
771
+ ppid,
772
+ commandTokens
773
+ });
774
+ }
775
+ let mcpServerDetection;
776
+ for (const [pid, processData] of processMap) {
777
+ const commandMatchLinux = this.isCommandMatch(processData.commandTokens);
778
+ let commandMatchWin32 = false;
779
+ if ((0, node_os.platform)() === "win32") {
780
+ let commandTokensOnWin32 = processData.commandTokens;
781
+ if (commandTokensOnWin32.length > 0 && commandTokensOnWin32[0].toLowerCase().startsWith("cmd")) {
782
+ commandTokensOnWin32 = commandTokensOnWin32.slice(1);
783
+ while (commandTokensOnWin32.length > 0 && commandTokensOnWin32[0].startsWith("/")) commandTokensOnWin32 = commandTokensOnWin32.slice(1);
784
+ }
785
+ commandMatchWin32 = this.isCommandMatch(commandTokensOnWin32);
786
+ }
787
+ if (commandMatchLinux || commandMatchWin32) {
788
+ mcpServerDetection = {
789
+ pid,
790
+ commandLine: processData.commandTokens.join(" "),
791
+ ppid: processData.ppid
792
+ };
793
+ const parentProcess = processMap.get(processData.ppid);
794
+ if (parentProcess) {
795
+ const { estimatedVendor, estimatedProduct } = this.getVendorFromCommand(parentProcess.commandTokens) || {};
796
+ if (estimatedProduct || estimatedVendor) {
797
+ mcpServerDetection = {
798
+ ...mcpServerDetection,
799
+ parentCommandLine: parentProcess.commandTokens.join(" "),
800
+ estimatedVendor,
801
+ estimatedProduct
802
+ };
803
+ return mcpServerDetection;
804
+ }
805
+ }
806
+ }
807
+ }
808
+ if (mcpServerDetection) return mcpServerDetection;
809
+ return false;
810
+ } catch {
811
+ return false;
812
+ }
813
+ }
814
+ getVendorFromCommand(commandTokens) {
815
+ const commandString = commandTokens.join(" ").toLowerCase();
816
+ if (commandString.includes("claude.app")) return {
817
+ estimatedVendor: "anthropic",
818
+ estimatedProduct: "claude-desktop"
819
+ };
820
+ if (commandString.includes("claude")) return {
821
+ estimatedVendor: "anthropic",
822
+ estimatedProduct: "claude-desktop"
823
+ };
824
+ if (commandString.includes("cursor")) return {
825
+ estimatedVendor: "cursor",
826
+ estimatedProduct: "cursor"
827
+ };
828
+ if (commandString.includes("visual studio code") || commandString.includes("vscode")) return {
829
+ estimatedVendor: "vscode",
830
+ estimatedProduct: "vscode"
831
+ };
832
+ }
833
+ isCommandMatch(commandTokens) {
834
+ if (commandTokens.length === 0) return false;
835
+ const baseCommand = this.getBaseCommand(commandTokens[0]);
836
+ const commandInConfig = this.getBaseCommand(this.command);
837
+ if (commandInConfig === "uvx" && baseCommand === "uv") return this.matchUvxProcess(commandTokens);
838
+ if (commandInConfig === "npx" && baseCommand === "npm") return this.matchNpxProcess(commandTokens);
839
+ if (commandInConfig === "uv" && baseCommand === "uv") return this.matchGenericArgsToArgs(commandTokens);
840
+ const commandConfigPythonBase = this.getBaseCommand(this.command);
841
+ const commandAliasesPython = [
842
+ "python3",
843
+ "python",
844
+ "python3.10",
845
+ "python3.11",
846
+ "python3.12",
847
+ "cpython3",
848
+ "cpython",
849
+ "python3",
850
+ "python2"
851
+ ];
852
+ if (commandAliasesPython.includes(commandConfigPythonBase) && commandAliasesPython.includes(baseCommand)) return this.matchGenericArgsToArgs(commandTokens);
853
+ if (this.getBaseCommand(this.command) === this.getBaseCommand(commandTokens[0])) return this.matchGenericArgsToArgs(commandTokens);
854
+ return false;
855
+ }
856
+ matchGenericArgsToArgs(commandTokens) {
857
+ if (this.args.length === 0) return commandTokens[0] === this.command;
858
+ if (commandTokens.length < 2) return false;
859
+ const commandWithoutArgs = commandTokens.slice(1);
860
+ for (let i = 0; i < this.args.length; i++) {
861
+ if (i >= commandWithoutArgs.length) return false;
862
+ const arg = this.args[i].toLowerCase();
863
+ const token = commandWithoutArgs[i].toLowerCase();
864
+ if (arg !== token && !token.includes(arg)) return false;
865
+ }
866
+ return true;
867
+ }
868
+ getBaseCommand(fullCommandPath) {
869
+ let baseCommand = node_path.default.basename(fullCommandPath);
870
+ if ((0, node_os.platform)() === "win32") baseCommand = node_path.default.basename(fullCommandPath, ".exe");
871
+ baseCommand = baseCommand.toLowerCase();
872
+ return baseCommand;
873
+ }
874
+ getUvxMcpServerNameFromArgs() {
875
+ if (this.args.length === 0) return void 0;
876
+ let mcpServerName;
877
+ if (this.args.length === 1) {
878
+ mcpServerName = this.args[0];
879
+ return mcpServerName;
880
+ }
881
+ for (let i = 0; i < this.args.length; i++) if (this.args[i] === "--from" && i + 1 < this.args.length) {
882
+ mcpServerName = this.args[i + 1];
883
+ return mcpServerName;
884
+ }
885
+ const firstArg = this.args[0];
886
+ if (firstArg.startsWith("-") || firstArg.startsWith("--")) {
887
+ mcpServerName = this.args[this.args.length - 1];
888
+ return mcpServerName;
889
+ }
890
+ mcpServerName = firstArg;
891
+ return mcpServerName;
892
+ }
893
+ matchUvxProcess(commandTokens) {
894
+ if (commandTokens.length === 0) return false;
895
+ const mcpServerName = this.getUvxMcpServerNameFromArgs();
896
+ if (!mcpServerName) return false;
897
+ return this.findMcpServerNameInProcessArguments(commandTokens, mcpServerName);
898
+ }
899
+ findMcpServerNameInProcessArguments(commandTokens, mcpServerName) {
900
+ for (let i = 0; i < commandTokens.length; i++) {
901
+ const token = commandTokens[i].toLowerCase();
902
+ const normalizedMcpServerName = mcpServerName.toLowerCase();
903
+ if (normalizedMcpServerName === token || token.includes(normalizedMcpServerName)) return true;
904
+ }
905
+ return false;
906
+ }
907
+ parseCSVLine(line) {
908
+ const result = [];
909
+ let current = "";
910
+ let inQuotes = false;
911
+ for (let i = 0; i < line.length; i++) {
912
+ const char = line[i];
913
+ if (char === "\"") {
914
+ if (inQuotes && line[i + 1] === "\"") {
915
+ current += "\"";
916
+ i++;
917
+ } else inQuotes = !inQuotes;
918
+ } else if (char === "," && !inQuotes) {
919
+ result.push(current);
920
+ current = "";
921
+ } else current += char;
922
+ }
923
+ result.push(current);
924
+ return result;
925
+ }
926
+ parseCommandLine(commandLine) {
927
+ const tokens = [];
928
+ let current = "";
929
+ let inQuotes = false;
930
+ let quoteChar = "";
931
+ for (let i = 0; i < commandLine.length; i++) {
932
+ const char = commandLine[i];
933
+ if (!inQuotes && (char === "\"" || char === "'")) {
934
+ inQuotes = true;
935
+ quoteChar = char;
936
+ } else if (inQuotes && char === quoteChar) {
937
+ inQuotes = false;
938
+ quoteChar = "";
939
+ } else if (!inQuotes && char === " ") {
940
+ if (current.trim()) {
941
+ tokens.push(current.trim());
942
+ current = "";
943
+ }
944
+ } else current += char;
945
+ }
946
+ if (current.trim()) tokens.push(current.trim());
947
+ return tokens;
948
+ }
949
+ matchNpxProcess(commandTokens) {
950
+ if (commandTokens.length < 3) return false;
951
+ if (commandTokens[1] !== "exec") return false;
952
+ let argsToMatch;
953
+ const yIndex = this.args.indexOf("-y");
954
+ if (yIndex !== -1 && yIndex + 1 < this.args.length) argsToMatch = this.args.slice(yIndex + 1);
955
+ else argsToMatch = this.args;
956
+ if (commandTokens.length - 2 !== argsToMatch.length) return false;
957
+ for (let i = 0; i < argsToMatch.length; i++) if (commandTokens[i + 2].toLowerCase() !== argsToMatch[i].toLowerCase()) return false;
958
+ return true;
959
+ }
1193
960
  };
1194
-
1195
961
  // src/main.ts
1196
962
  var MCPFiles = class {
1197
- static {
1198
- __name(this, "MCPFiles");
1199
- }
1200
- mcpConfigService;
1201
- customFiles;
1202
- constructor(customFiles2) {
1203
- this.mcpConfigService = new MCPConfigService({ enableDirectoryBubbling: true });
1204
- this.customFiles = customFiles2;
1205
- }
1206
- /**
1207
- * Find and process all MCP configuration files
1208
- * If customFiles are provided, only those files are processed (replaces automatic discovery)
1209
- */
1210
- async findFiles() {
1211
- try {
1212
- if (this.customFiles && this.customFiles.length > 0) {
1213
- const mcpFilesPathsData2 = await this.mcpConfigService.parseCustomFiles(this.customFiles);
1214
- for (const groupName of Object.keys(mcpFilesPathsData2)) {
1215
- const group = mcpFilesPathsData2[groupName];
1216
- for (const filePathData of group.paths) {
1217
- if (filePathData.servers && filePathData.servers.length > 0) {
1218
- for (const server of filePathData.servers) {
1219
- const serverConfig = {
1220
- name: server.name,
1221
- command: server.command,
1222
- args: server.args,
1223
- transport: server.transport,
1224
- type: server.type,
1225
- env: server.env
1226
- };
1227
- const serverManager = new MCPServerManagerService(serverConfig);
1228
- const processDetection = serverManager.isRunning();
1229
- let isRunning = false;
1230
- if (processDetection) {
1231
- if (typeof processDetection === "object" && processDetection.estimatedProduct === group.name) {
1232
- isRunning = true;
1233
- }
1234
- }
1235
- server.status = isRunning ? "running" : "stopped";
1236
- }
1237
- }
1238
- }
1239
- }
1240
- return mcpFilesPathsData2;
1241
- }
1242
- const mcpFilesPathsData = await this.mcpConfigService.getMCPFileGroups();
1243
- for (const groupName of Object.keys(mcpFilesPathsData)) {
1244
- const group = mcpFilesPathsData[groupName];
1245
- for (const filePathData of group.paths) {
1246
- if (filePathData.servers && filePathData.servers.length > 0) {
1247
- for (const server of filePathData.servers) {
1248
- const serverConfig = {
1249
- name: server.name,
1250
- command: server.command,
1251
- args: server.args,
1252
- transport: server.transport,
1253
- // transport is always populated from type in the data layer
1254
- type: server.type,
1255
- env: server.env
1256
- };
1257
- const serverManager = new MCPServerManagerService(serverConfig);
1258
- const processDetection = serverManager.isRunning();
1259
- let isRunning = false;
1260
- if (processDetection) {
1261
- if (typeof processDetection === "object" && processDetection.estimatedProduct === group.name) {
1262
- isRunning = true;
1263
- }
1264
- }
1265
- server.status = isRunning ? "running" : "stopped";
1266
- }
1267
- }
1268
- }
1269
- }
1270
- return mcpFilesPathsData;
1271
- } catch (error) {
1272
- throw new Error(`Failed to find MCP files: ${error instanceof Error ? error.message : "Unknown error"}`);
1273
- }
1274
- }
1275
- /**
1276
- * Get MCP configuration service instance for advanced operations
1277
- */
1278
- getMCPConfigService() {
1279
- return this.mcpConfigService;
1280
- }
963
+ mcpConfigService;
964
+ customFiles;
965
+ constructor(customFiles) {
966
+ this.mcpConfigService = new MCPConfigService({ enableDirectoryBubbling: true });
967
+ this.customFiles = customFiles;
968
+ }
969
+ /**
970
+ * Find and process all MCP configuration files
971
+ * If customFiles are provided, only those files are processed (replaces automatic discovery)
972
+ */
973
+ async findFiles() {
974
+ try {
975
+ if (this.customFiles && this.customFiles.length > 0) {
976
+ const mcpFilesPathsData = await this.mcpConfigService.parseCustomFiles(this.customFiles);
977
+ for (const groupName of Object.keys(mcpFilesPathsData)) {
978
+ const group = mcpFilesPathsData[groupName];
979
+ for (const filePathData of group.paths) if (filePathData.servers && filePathData.servers.length > 0) for (const server of filePathData.servers) {
980
+ const processDetection = new MCPServerManagerService({
981
+ name: server.name,
982
+ command: server.command,
983
+ args: server.args,
984
+ transport: server.transport,
985
+ type: server.type,
986
+ env: server.env
987
+ }).isRunning();
988
+ let isRunning = false;
989
+ if (processDetection) {
990
+ if (typeof processDetection === "object" && processDetection.estimatedProduct === group.name) isRunning = true;
991
+ }
992
+ server.status = isRunning ? "running" : "stopped";
993
+ }
994
+ }
995
+ return mcpFilesPathsData;
996
+ }
997
+ const mcpFilesPathsData = await this.mcpConfigService.getMCPFileGroups();
998
+ for (const groupName of Object.keys(mcpFilesPathsData)) {
999
+ const group = mcpFilesPathsData[groupName];
1000
+ for (const filePathData of group.paths) if (filePathData.servers && filePathData.servers.length > 0) for (const server of filePathData.servers) {
1001
+ const processDetection = new MCPServerManagerService({
1002
+ name: server.name,
1003
+ command: server.command,
1004
+ args: server.args,
1005
+ transport: server.transport,
1006
+ type: server.type,
1007
+ env: server.env
1008
+ }).isRunning();
1009
+ let isRunning = false;
1010
+ if (processDetection) {
1011
+ if (typeof processDetection === "object" && processDetection.estimatedProduct === group.name) isRunning = true;
1012
+ }
1013
+ server.status = isRunning ? "running" : "stopped";
1014
+ }
1015
+ }
1016
+ return mcpFilesPathsData;
1017
+ } catch (error) {
1018
+ throw new Error(`Failed to find MCP files: ${error instanceof Error ? error.message : "Unknown error"}`, { cause: error });
1019
+ }
1020
+ }
1021
+ /**
1022
+ * Get MCP configuration service instance for advanced operations
1023
+ */
1024
+ getMCPConfigService() {
1025
+ return this.mcpConfigService;
1026
+ }
1281
1027
  };
1282
-
1283
- // src/services/render-service.ts
1284
- var import_node_util12 = require("util");
1285
-
1286
1028
  // src/components/transport.ts
1287
- var import_node_util2 = require("util");
1288
- function render(text) {
1289
- const formattedText = text.toUpperCase();
1290
- let data = "";
1291
- if (formattedText === "STDIO") {
1292
- data = (0, import_node_util2.styleText)(["magenta"], formattedText);
1293
- }
1294
- if (formattedText === "SSE") {
1295
- data = (0, import_node_util2.styleText)(["blue"], formattedText);
1296
- }
1297
- if (formattedText === "HTTP") {
1298
- data = (0, import_node_util2.styleText)(["blue"], formattedText);
1299
- }
1300
- return data;
1029
+ function render$7(text) {
1030
+ const formattedText = text.toUpperCase();
1031
+ let data = "";
1032
+ if (formattedText === "STDIO") data = (0, node_util.styleText)(["magenta"], formattedText);
1033
+ if (formattedText === "SSE") data = (0, node_util.styleText)(["blue"], formattedText);
1034
+ if (formattedText === "HTTP") data = (0, node_util.styleText)(["blue"], formattedText);
1035
+ return data;
1301
1036
  }
1302
- __name(render, "render");
1303
-
1304
1037
  // src/components/column-name.ts
1305
- var import_node_util3 = require("util");
1306
- function render2(text) {
1307
- const formattedText = String(text).toUpperCase();
1308
- const data = (0, import_node_util3.styleText)(["dim"], formattedText);
1309
- return data;
1038
+ function render$6(text) {
1039
+ const formattedText = String(text).toUpperCase();
1040
+ return (0, node_util.styleText)(["dim"], formattedText);
1310
1041
  }
1311
- __name(render2, "render");
1312
-
1313
1042
  // src/components/mcp-server-status.ts
1314
- var import_node_util4 = require("util");
1315
- function render3(text) {
1316
- const formattedText = text.toLowerCase();
1317
- let data = "";
1318
- if (formattedText === "running") {
1319
- data = (0, import_node_util4.styleText)(["green"], "\u25CF");
1320
- } else {
1321
- data = (0, import_node_util4.styleText)(["red"], "\u25CF");
1322
- }
1323
- return data;
1043
+ function render$5(text) {
1044
+ const formattedText = text.toLowerCase();
1045
+ let data;
1046
+ if (formattedText === "running") data = (0, node_util.styleText)(["green"], "●");
1047
+ else data = (0, node_util.styleText)(["red"], "●");
1048
+ return data;
1324
1049
  }
1325
- __name(render3, "render");
1326
-
1327
1050
  // src/components/mcp-server-name.ts
1328
- var import_node_util5 = require("util");
1329
- function render4(text) {
1330
- const formattedText = text.toLowerCase();
1331
- const data = (0, import_node_util5.styleText)(["bold", "white"], formattedText);
1332
- return data;
1051
+ function render$4(text) {
1052
+ const formattedText = text.toLowerCase();
1053
+ return (0, node_util.styleText)(["bold", "white"], formattedText);
1333
1054
  }
1334
- __name(render4, "render");
1335
-
1336
1055
  // src/components/mcp-server-source.ts
1337
- var import_node_util6 = require("util");
1338
- function render5(text) {
1339
- const formattedText = String(text).trim();
1340
- return (0, import_node_util6.styleText)(["gray"], formattedText);
1056
+ function render$3(text) {
1057
+ const formattedText = String(text).trim();
1058
+ return (0, node_util.styleText)(["gray"], formattedText);
1341
1059
  }
1342
- __name(render5, "render");
1343
-
1344
1060
  // src/components/mcp-server-version.ts
1345
- var import_node_util7 = require("util");
1346
- function render6(versionInfo) {
1347
- if (!versionInfo) {
1348
- return "";
1349
- }
1350
- const version = versionInfo.version || "LATEST";
1351
- const displayVersion = version === "latest" ? "LATEST" : version;
1352
- if (versionInfo.isPinned) {
1353
- return (0, import_node_util7.styleText)(["green"], "\u25CF") + " " + displayVersion;
1354
- } else {
1355
- return (0, import_node_util7.styleText)(["red"], "\u25CF") + " LATEST";
1356
- }
1061
+ function render$2(versionInfo) {
1062
+ if (!versionInfo) return "";
1063
+ const version = versionInfo.version || "LATEST";
1064
+ const displayVersion = version === "latest" ? "LATEST" : version;
1065
+ if (versionInfo.isPinned) return (0, node_util.styleText)(["green"], "●") + " " + displayVersion;
1066
+ else return (0, node_util.styleText)(["red"], "●") + " LATEST";
1357
1067
  }
1358
- __name(render6, "render");
1359
-
1360
1068
  // src/components/file-path.ts
1361
- var import_node_util8 = require("util");
1362
- function render7(text) {
1363
- const formattedText = text;
1364
- const data = (0, import_node_util8.styleText)(["underline"], formattedText);
1365
- return data;
1069
+ function render$1(text) {
1070
+ const formattedText = text;
1071
+ return (0, node_util.styleText)(["underline"], formattedText);
1366
1072
  }
1367
- __name(render7, "render");
1368
-
1369
1073
  // src/components/mcp-servers-config-parsable.ts
1370
- var import_node_util9 = require("util");
1371
- function render8(text) {
1372
- const formattedText = text.toUpperCase().replace(/_/g, " ");
1373
- let data = formattedText;
1374
- if (formattedText === "VALID") {
1375
- data = (0, import_node_util9.styleText)(["green"], "\u25CF");
1376
- } else {
1377
- data = (0, import_node_util9.styleText)(["red"], "\u25CF");
1378
- }
1379
- return data;
1074
+ function render(text) {
1075
+ const formattedText = text.toUpperCase().replace(/_/g, " ");
1076
+ let data;
1077
+ if (formattedText === "VALID") data = (0, node_util.styleText)(["green"], "●");
1078
+ else data = (0, node_util.styleText)(["red"], "●");
1079
+ return data;
1380
1080
  }
1381
- __name(render8, "render");
1382
-
1383
1081
  // src/components/credential-warning.ts
1384
- var import_node_util10 = require("util");
1385
1082
  function CredentialWarningComponent(credentials) {
1386
- if (!credentials || !credentials.hasCredentials) {
1387
- return "";
1388
- }
1389
- const { riskLevel, credentialVars } = credentials;
1390
- let riskColor;
1391
- let riskIcon;
1392
- switch (riskLevel) {
1393
- case "high":
1394
- riskColor = "red";
1395
- riskIcon = (0, import_node_util10.styleText)(["red"], "\u25CF");
1396
- break;
1397
- case "low":
1398
- riskColor = "blue";
1399
- riskIcon = (0, import_node_util10.styleText)(["blue"], "\u25CF");
1400
- break;
1401
- default:
1402
- riskColor = "blue";
1403
- riskIcon = (0, import_node_util10.styleText)(["blue"], "\u25CF");
1404
- }
1405
- const riskText = (0, import_node_util10.styleText)([riskColor], `${riskIcon} ${riskLevel.toUpperCase()} RISK`);
1406
- const credsBySource = credentialVars.reduce((acc, cv) => {
1407
- const source = cv.source || "env";
1408
- if (!acc[source]) {
1409
- acc[source] = [];
1410
- }
1411
- acc[source].push(cv);
1412
- return acc;
1413
- }, {});
1414
- const sourceSummaries = Object.entries(credsBySource).map(([source, creds]) => {
1415
- const sourceIcon = getSourceIcon(source);
1416
- const credList = creds.map((cv) => `${cv.name}=${cv.value}`).join(", ");
1417
- return `${sourceIcon}${source}: ${credList}`;
1418
- });
1419
- const credentialSummary = sourceSummaries.join(" | ");
1420
- return `${riskText} ${(0, import_node_util10.styleText)(["dim"], `(${credentialVars.length} creds: ${credentialSummary})`)}`;
1083
+ if (!credentials || !credentials.hasCredentials) return "";
1084
+ const { riskLevel, credentialVars } = credentials;
1085
+ let riskColor;
1086
+ let riskIcon;
1087
+ switch (riskLevel) {
1088
+ case "high":
1089
+ riskColor = "red";
1090
+ riskIcon = (0, node_util.styleText)(["red"], "●");
1091
+ break;
1092
+ case "low":
1093
+ riskColor = "blue";
1094
+ riskIcon = (0, node_util.styleText)(["blue"], "●");
1095
+ break;
1096
+ default:
1097
+ riskColor = "blue";
1098
+ riskIcon = (0, node_util.styleText)(["blue"], "●");
1099
+ }
1100
+ const riskText = (0, node_util.styleText)([riskColor], `${riskIcon} ${riskLevel.toUpperCase()} RISK`);
1101
+ const credsBySource = credentialVars.reduce((acc, cv) => {
1102
+ const source = cv.source || "env";
1103
+ if (!acc[source]) acc[source] = [];
1104
+ acc[source].push(cv);
1105
+ return acc;
1106
+ }, {});
1107
+ const credentialSummary = Object.entries(credsBySource).map(([source, creds]) => {
1108
+ return `${getSourceIcon(source)}${source}: ${creds.map((cv) => `${cv.name}=${cv.value}`).join(", ")}`;
1109
+ }).join(" | ");
1110
+ return `${riskText} ${(0, node_util.styleText)(["dim"], `(${credentialVars.length} creds: ${credentialSummary})`)}`;
1421
1111
  }
1422
- __name(CredentialWarningComponent, "CredentialWarningComponent");
1112
+ /**
1113
+ * Get an icon/symbol for different credential sources
1114
+ */
1423
1115
  function getSourceIcon(source) {
1424
- switch (source) {
1425
- case "env":
1426
- return "\u{1F331} ";
1427
- // Environment variable
1428
- case "args":
1429
- return "\u26A1 ";
1430
- // Command argument
1431
- case "headers":
1432
- return "\u{1F517} ";
1433
- // HTTP header
1434
- default:
1435
- return "\u{1F4CB} ";
1436
- }
1116
+ switch (source) {
1117
+ case "env": return "🌱 ";
1118
+ case "args": return "⚡ ";
1119
+ case "headers": return "🔗 ";
1120
+ default: return "📋 ";
1121
+ }
1437
1122
  }
1438
- __name(getSourceIcon, "getSourceIcon");
1439
-
1440
1123
  // src/components/summary.ts
1441
- var import_node_util11 = require("util");
1442
1124
  function SummaryComponent(stats) {
1443
- const { totalServers, runningServers, highRiskCredentials, implicitLatestVersions, transportBreakdown } = stats;
1444
- const runningBar = createProgressBar(runningServers, totalServers, 20, "green", false);
1445
- const securityBar = createProgressBar(highRiskCredentials, totalServers, 20, "red", true);
1446
- const versionBar = createProgressBar(implicitLatestVersions, totalServers, 20, "red", true);
1447
- const transportText = `stdio: ${transportBreakdown.stdio} | SSE: ${transportBreakdown.sse} | HTTP: ${transportBreakdown.http}`;
1448
- const lines = [
1449
- "SUMMARY",
1450
- ` SERVERS ${runningBar} ${runningServers} / ${totalServers} Running`,
1451
- ` SECURITY ${securityBar} ${highRiskCredentials} / ${totalServers} High Risk Credentials`,
1452
- ` VERSION ${versionBar} ${implicitLatestVersions} / ${totalServers} Implicit Latest`,
1453
- ` TRANSPORT ${transportText}`
1454
- ];
1455
- return lines.join("\n");
1125
+ const { totalServers, runningServers, highRiskCredentials, implicitLatestVersions, transportBreakdown } = stats;
1126
+ const runningBar = createProgressBar(runningServers, totalServers, 20, "green", false);
1127
+ const securityBar = createProgressBar(highRiskCredentials, totalServers, 20, "red", true);
1128
+ const versionBar = createProgressBar(implicitLatestVersions, totalServers, 20, "red", true);
1129
+ const transportText = `stdio: ${transportBreakdown.stdio} | SSE: ${transportBreakdown.sse} | HTTP: ${transportBreakdown.http}`;
1130
+ return [
1131
+ "SUMMARY",
1132
+ ` SERVERS ${runningBar} ${runningServers} / ${totalServers} Running`,
1133
+ ` SECURITY ${securityBar} ${highRiskCredentials} / ${totalServers} High Risk Credentials`,
1134
+ ` VERSION ${versionBar} ${implicitLatestVersions} / ${totalServers} Implicit Latest`,
1135
+ ` TRANSPORT ${transportText}`
1136
+ ].join("\n");
1456
1137
  }
1457
- __name(SummaryComponent, "SummaryComponent");
1458
1138
  function createProgressBar(count, total, width, color, emptyIsGood = false) {
1459
- if (total === 0) {
1460
- const emptyBar = "\u2591".repeat(width);
1461
- return emptyBar;
1462
- }
1463
- const progress = Math.min(count / total, 1);
1464
- const filledWidth = Math.round(progress * width);
1465
- const emptyWidth = width - filledWidth;
1466
- let filled;
1467
- let empty;
1468
- if (color === "green") {
1469
- filled = (0, import_node_util11.styleText)(["greenBright"], "\u2588".repeat(filledWidth));
1470
- empty = (0, import_node_util11.styleText)(["green"], "\u2591".repeat(emptyWidth));
1471
- } else {
1472
- filled = (0, import_node_util11.styleText)(["redBright"], "\u2588".repeat(filledWidth));
1473
- if (count === 0 && emptyIsGood) {
1474
- empty = (0, import_node_util11.styleText)(["green"], "\u2591".repeat(emptyWidth));
1475
- } else {
1476
- empty = (0, import_node_util11.styleText)(["red"], "\u2591".repeat(emptyWidth));
1477
- }
1478
- }
1479
- return `${filled}${empty}`;
1139
+ if (total === 0) return "░".repeat(width);
1140
+ const progress = Math.min(count / total, 1);
1141
+ const filledWidth = Math.round(progress * width);
1142
+ const emptyWidth = width - filledWidth;
1143
+ let filled;
1144
+ let empty;
1145
+ if (color === "green") {
1146
+ filled = (0, node_util.styleText)(["greenBright"], "█".repeat(filledWidth));
1147
+ empty = (0, node_util.styleText)(["green"], "░".repeat(emptyWidth));
1148
+ } else {
1149
+ filled = (0, node_util.styleText)(["redBright"], "█".repeat(filledWidth));
1150
+ if (count === 0 && emptyIsGood) empty = (0, node_util.styleText)(["green"], "░".repeat(emptyWidth));
1151
+ else empty = (0, node_util.styleText)(["red"], "░".repeat(emptyWidth));
1152
+ }
1153
+ return `${filled}${empty}`;
1480
1154
  }
1481
- __name(createProgressBar, "createProgressBar");
1482
-
1483
1155
  // src/services/render-service.ts
1484
- var RenderService = class _RenderService {
1485
- static {
1486
- __name(this, "RenderService");
1487
- }
1488
- // Example mocked data for rendering the servers information
1489
- // const mcpServersDataMock = [
1490
- // { status: '●', name: 'logging-server', type: 'SSE', version: '2.3.0', tools: '6', resources: '2' },
1491
- // { status: '●', name: 'git-logging-server', type: 'SSE', version: '2.3.0', tools: '6', resources: '2' },
1492
- // { status: '○', name: 'mcp-server', type: 'STDIO', version: '2.3.0', tools: '62', resources: '0' }
1493
- // ]
1494
- static getVisibleLength(text) {
1495
- return text.replace(/\u001b\[[0-9;]*m/g, "").length;
1496
- }
1497
- static printMcpServers(data) {
1498
- if (data.length === 0) return;
1499
- const headers = ["STATUS", "NAME", "VERSION", "SOURCE", "TRANSPORT", "CREDENTIALS"];
1500
- const keys = ["status", "name", "versionInfo", "source", "transport", "credentials"];
1501
- const centerColumns = [0, 3, 4];
1502
- const leftPadding = " ";
1503
- const columnWidths = headers.map((header, index) => {
1504
- const headerWidth = _RenderService.getVisibleLength(render2(header));
1505
- const dataWidth = Math.max(...data.map((row) => {
1506
- let text = String(row[keys[index]]);
1507
- if (keys[index] === "transport") {
1508
- text = render(text);
1509
- }
1510
- if (keys[index] === "status") {
1511
- text = render3(text);
1512
- }
1513
- if (keys[index] === "source") {
1514
- text = render5(text);
1515
- }
1516
- if (keys[index] === "name") {
1517
- text = render4(text);
1518
- }
1519
- if (keys[index] === "versionInfo") {
1520
- text = render6(row[keys[index]]);
1521
- }
1522
- if (keys[index] === "credentials") {
1523
- text = CredentialWarningComponent(row[keys[index]]);
1524
- }
1525
- return _RenderService.getVisibleLength(text);
1526
- }));
1527
- return Math.max(headerWidth, dataWidth);
1528
- });
1529
- const centerText = /* @__PURE__ */ __name((text, width) => {
1530
- const visibleLength = _RenderService.getVisibleLength(text);
1531
- const padding = width - visibleLength;
1532
- const leftPad = Math.floor(padding / 2);
1533
- const rightPad = padding - leftPad;
1534
- return " ".repeat(leftPad) + text + " ".repeat(rightPad);
1535
- }, "centerText");
1536
- const padRight = /* @__PURE__ */ __name((text, width) => {
1537
- const visibleLength = _RenderService.getVisibleLength(text);
1538
- const padding = Math.max(0, width - visibleLength);
1539
- return text + " ".repeat(padding);
1540
- }, "padRight");
1541
- const totalWidth = columnWidths.reduce((sum, width) => sum + width, 0) + (columnWidths.length - 1) * 2;
1542
- const separator = "\u2500".repeat(totalWidth);
1543
- console.log("\n" + leftPadding + separator);
1544
- const headerRow = headers.map((header, index) => {
1545
- const headerText = render2(header);
1546
- if (centerColumns.includes(index)) {
1547
- return centerText(headerText, columnWidths[index]);
1548
- }
1549
- return padRight(headerText, columnWidths[index]);
1550
- }).join(" ");
1551
- console.log(leftPadding + headerRow);
1552
- console.log(leftPadding + separator);
1553
- for (const row of data) {
1554
- const dataRow = keys.map((key, index) => {
1555
- let text = String(row[key]);
1556
- if (key === "transport") {
1557
- text = render(text);
1558
- }
1559
- if (key === "status") {
1560
- text = render3(text);
1561
- }
1562
- if (keys[index] === "source") {
1563
- text = render5(text);
1564
- }
1565
- if (key === "name") {
1566
- text = render4(text);
1567
- }
1568
- if (key === "versionInfo") {
1569
- text = render6(row[key]);
1570
- }
1571
- if (key === "credentials") {
1572
- text = CredentialWarningComponent(row[key]);
1573
- }
1574
- if (centerColumns.includes(index)) {
1575
- return centerText(text, columnWidths[index]);
1576
- }
1577
- return padRight(text, columnWidths[index]);
1578
- }).join(" ");
1579
- console.log(leftPadding + dataRow);
1580
- }
1581
- console.log("\n");
1582
- console.log(`${leftPadding}\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584`);
1583
- }
1584
- // Example mocked data for rendering the group information
1585
- // const mcpGroupDataMock = [
1586
- // { key: 'PROVIDER', value: 'Claude Desktop', },
1587
- // { key: 'FILE', value: '~/Library/Application Support/Claude/claude_desktop_config.json' },
1588
- // { key: 'STATUS', value: '[✓ VALID] [GLOBAL] [5 MCP SERVERS]' }
1589
- // ]
1590
- static printMcpGroup(id, data, groupMetadata = {}) {
1591
- if (data.length === 0) return;
1592
- console.log("\n");
1593
- const headers = ["KEY", "VALUE"];
1594
- const keys = ["key", "value"];
1595
- const indexText = `[${id}]`;
1596
- const leftPaddingGroupLead = indexText + " ".repeat(6 - indexText.length);
1597
- const leftPaddingGroupData = " ".repeat(6);
1598
- if (Object.keys(groupMetadata).length > 0) {
1599
- const runningCount = groupMetadata.mcpServersRunning || 0;
1600
- const totalCount = groupMetadata.mcpServersTotal || 0;
1601
- const metadataRow = _RenderService.renderProgressBar(runningCount, totalCount, "Running");
1602
- data.push({ key: "MCP SERVERS", value: metadataRow });
1603
- }
1604
- const columnWidths = headers.map((header, index) => {
1605
- const dataWidth = Math.max(...data.map((row) => {
1606
- const columnText = render2(row[keys[index]]);
1607
- const columnTextLength = _RenderService.getVisibleLength(columnText);
1608
- return columnTextLength;
1609
- }));
1610
- return Math.max(header.length, dataWidth);
1611
- });
1612
- for (const [index, row] of data.entries()) {
1613
- const dataRow = keys.map((key, index2) => {
1614
- const paddingNormalizer = render2(row[key]).length - row[key].length;
1615
- if (key === "key") {
1616
- return render2(row[key]).padEnd(columnWidths[index2] + paddingNormalizer);
1617
- }
1618
- if (row["key"] === "FILE") {
1619
- return render7(row[key]).padEnd(columnWidths[index2] + paddingNormalizer);
1620
- }
1621
- if (row["key"] === "PARSABLE") {
1622
- return render8(row[key]).padEnd(columnWidths[index2] + paddingNormalizer);
1623
- }
1624
- return String(row[key]).padEnd(columnWidths[index2] + paddingNormalizer);
1625
- }).join(" ");
1626
- const leftPadding = index === 0 ? leftPaddingGroupLead : leftPaddingGroupData;
1627
- console.log(leftPadding + dataRow);
1628
- }
1629
- }
1630
- // draws progress bar components like this
1631
- // "███████░░░░░░░░░░░░░ 3 / 9 Running"
1632
- static renderProgressBar(count, total, label, width = 20) {
1633
- if (total === 0) {
1634
- const emptyBar = "\u2591".repeat(width);
1635
- return `${emptyBar} 0 / 0 ${label}`;
1636
- }
1637
- const progress = Math.min(count / total, 1);
1638
- const filledWidth = Math.round(progress * width);
1639
- const emptyWidth = width - filledWidth;
1640
- let filled;
1641
- let empty;
1642
- if (count > 0) {
1643
- filled = (0, import_node_util12.styleText)(["greenBright"], "\u2588".repeat(filledWidth));
1644
- empty = (0, import_node_util12.styleText)(["green"], "\u2591".repeat(emptyWidth));
1645
- } else {
1646
- filled = "\u2588".repeat(filledWidth);
1647
- empty = "\u2591".repeat(emptyWidth);
1648
- }
1649
- return `${filled}${empty} ${count} / ${total} ${label}`;
1650
- }
1651
- /**
1652
- * Print summary statistics at the end of the output
1653
- */
1654
- static printSummary(stats) {
1655
- console.log("\n");
1656
- console.log(" \u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584");
1657
- console.log();
1658
- const summaryOutput = SummaryComponent(stats);
1659
- const lines = summaryOutput.split("\n");
1660
- for (const line of lines) {
1661
- if (line === "SUMMARY") {
1662
- console.log(" " + line);
1663
- } else {
1664
- console.log(" " + line);
1665
- }
1666
- }
1667
- console.log();
1668
- console.log(" \u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584");
1669
- }
1156
+ var RenderService = class RenderService {
1157
+ static getVisibleLength(text) {
1158
+ return text.replace(/\u001b\[[0-9;]*m/g, "").length;
1159
+ }
1160
+ static printMcpServers(data) {
1161
+ if (data.length === 0) return;
1162
+ const headers = [
1163
+ "STATUS",
1164
+ "NAME",
1165
+ "VERSION",
1166
+ "SOURCE",
1167
+ "TRANSPORT",
1168
+ "CREDENTIALS"
1169
+ ];
1170
+ const keys = [
1171
+ "status",
1172
+ "name",
1173
+ "versionInfo",
1174
+ "source",
1175
+ "transport",
1176
+ "credentials"
1177
+ ];
1178
+ const centerColumns = [
1179
+ 0,
1180
+ 3,
1181
+ 4
1182
+ ];
1183
+ const leftPadding = " ";
1184
+ const columnWidths = headers.map((header, index) => {
1185
+ const headerWidth = RenderService.getVisibleLength(render$6(header));
1186
+ const dataWidth = Math.max(...data.map((row) => {
1187
+ let text = String(row[keys[index]]);
1188
+ if (keys[index] === "transport") text = render$7(text);
1189
+ if (keys[index] === "status") text = render$5(text);
1190
+ if (keys[index] === "source") text = render$3(text);
1191
+ if (keys[index] === "name") text = render$4(text);
1192
+ if (keys[index] === "versionInfo") text = render$2(row.versionInfo);
1193
+ if (keys[index] === "credentials") text = CredentialWarningComponent(row.credentials);
1194
+ return RenderService.getVisibleLength(text);
1195
+ }));
1196
+ return Math.max(headerWidth, dataWidth);
1197
+ });
1198
+ const centerText = (text, width) => {
1199
+ const padding = width - RenderService.getVisibleLength(text);
1200
+ const leftPad = Math.floor(padding / 2);
1201
+ const rightPad = padding - leftPad;
1202
+ return " ".repeat(leftPad) + text + " ".repeat(rightPad);
1203
+ };
1204
+ const padRight = (text, width) => {
1205
+ const visibleLength = RenderService.getVisibleLength(text);
1206
+ const padding = Math.max(0, width - visibleLength);
1207
+ return text + " ".repeat(padding);
1208
+ };
1209
+ const totalWidth = columnWidths.reduce((sum, width) => sum + width, 0) + (columnWidths.length - 1) * 2;
1210
+ const separator = "─".repeat(totalWidth);
1211
+ console.log("\n " + separator);
1212
+ const headerRow = headers.map((header, index) => {
1213
+ const headerText = render$6(header);
1214
+ if (centerColumns.includes(index)) return centerText(headerText, columnWidths[index]);
1215
+ return padRight(headerText, columnWidths[index]);
1216
+ }).join(" ");
1217
+ console.log(leftPadding + headerRow);
1218
+ console.log(leftPadding + separator);
1219
+ for (const row of data) {
1220
+ const dataRow = keys.map((key, index) => {
1221
+ let text = String(row[key]);
1222
+ if (key === "transport") text = render$7(text);
1223
+ if (key === "status") text = render$5(text);
1224
+ if (keys[index] === "source") text = render$3(text);
1225
+ if (key === "name") text = render$4(text);
1226
+ if (key === "versionInfo") text = render$2(row.versionInfo);
1227
+ if (key === "credentials") text = CredentialWarningComponent(row.credentials);
1228
+ if (centerColumns.includes(index)) return centerText(text, columnWidths[index]);
1229
+ return padRight(text, columnWidths[index]);
1230
+ }).join(" ");
1231
+ console.log(leftPadding + dataRow);
1232
+ }
1233
+ }
1234
+ static printMcpGroup(id, data, groupMetadata = {}) {
1235
+ if (data.length === 0) return;
1236
+ console.log("\n");
1237
+ const headers = ["KEY", "VALUE"];
1238
+ const keys = ["key", "value"];
1239
+ const indexText = `[${id}]`;
1240
+ const leftPaddingGroupLead = indexText + " ".repeat(6 - indexText.length);
1241
+ const leftPaddingGroupData = " ".repeat(6);
1242
+ if (Object.keys(groupMetadata).length > 0) {
1243
+ const runningCount = groupMetadata.mcpServersRunning || 0;
1244
+ const totalCount = groupMetadata.mcpServersTotal || 0;
1245
+ const metadataRow = RenderService.renderProgressBar(runningCount, totalCount, "Running");
1246
+ data.push({
1247
+ key: "MCP SERVERS",
1248
+ value: metadataRow
1249
+ });
1250
+ }
1251
+ const columnWidths = headers.map((header, index) => {
1252
+ const dataWidth = Math.max(...data.map((row) => {
1253
+ const columnText = render$6(row[keys[index]]);
1254
+ return RenderService.getVisibleLength(columnText);
1255
+ }));
1256
+ return Math.max(header.length, dataWidth);
1257
+ });
1258
+ for (const [index, row] of data.entries()) {
1259
+ const dataRow = keys.map((key, index) => {
1260
+ const paddingNormalizer = render$6(row[key]).length - row[key].length;
1261
+ if (key === "key") return render$6(row[key]).padEnd(columnWidths[index] + paddingNormalizer);
1262
+ if (row["key"] === "FILE") return render$1(row[key]).padEnd(columnWidths[index] + paddingNormalizer);
1263
+ if (row["key"] === "PARSABLE") return render(row[key]).padEnd(columnWidths[index] + paddingNormalizer);
1264
+ return String(row[key]).padEnd(columnWidths[index] + paddingNormalizer);
1265
+ }).join(" ");
1266
+ console.log((index === 0 ? leftPaddingGroupLead : leftPaddingGroupData) + dataRow);
1267
+ }
1268
+ }
1269
+ static renderProgressBar(count, total, label, width = 20) {
1270
+ if (total === 0) return `${"░".repeat(width)} 0 / 0 ${label}`;
1271
+ const progress = Math.min(count / total, 1);
1272
+ const filledWidth = Math.round(progress * width);
1273
+ const emptyWidth = width - filledWidth;
1274
+ let filled;
1275
+ let empty;
1276
+ if (count > 0) {
1277
+ filled = (0, node_util.styleText)(["greenBright"], "█".repeat(filledWidth));
1278
+ empty = (0, node_util.styleText)(["green"], "░".repeat(emptyWidth));
1279
+ } else {
1280
+ filled = "█".repeat(filledWidth);
1281
+ empty = "░".repeat(emptyWidth);
1282
+ }
1283
+ return `${filled}${empty} ${count} / ${total} ${label}`;
1284
+ }
1285
+ /**
1286
+ * Print summary statistics at the end of the output
1287
+ */
1288
+ static printSummary(stats) {
1289
+ console.log("\n");
1290
+ console.log(" ▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄");
1291
+ console.log();
1292
+ const lines = SummaryComponent(stats).split("\n");
1293
+ for (const line of lines) if (line === "SUMMARY") console.log(" " + line);
1294
+ else console.log(" " + line);
1295
+ console.log();
1296
+ console.log(" ▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄");
1297
+ }
1670
1298
  };
1671
-
1672
1299
  // src/bin/cli.ts
1673
- var args = process.argv.slice(2);
1674
- var jsonOutput = args.includes("--json");
1675
- var showAll = args.includes("--all") || args.includes("-a");
1676
- var customFiles;
1677
- var filesIndex = args.findIndex((arg) => arg === "--files");
1300
+ const args = process.argv.slice(2);
1301
+ const jsonOutput = args.includes("--json");
1302
+ const showAll = args.includes("--all") || args.includes("-a");
1303
+ let customFiles;
1304
+ const filesIndex = args.findIndex((arg) => arg === "--files");
1678
1305
  if (filesIndex !== -1 && filesIndex < args.length - 1) {
1679
- const fileArgs = [];
1680
- for (let i = filesIndex + 1; i < args.length; i++) {
1681
- if (args[i].startsWith("--")) {
1682
- break;
1683
- }
1684
- fileArgs.push(args[i]);
1685
- }
1686
- customFiles = fileArgs.flatMap(
1687
- (arg) => arg.includes(",") ? arg.split(",").map((f) => f.trim()) : [arg.trim()]
1688
- ).filter((f) => f.length > 0);
1306
+ const fileArgs = [];
1307
+ for (let i = filesIndex + 1; i < args.length; i++) {
1308
+ if (args[i].startsWith("--")) break;
1309
+ fileArgs.push(args[i]);
1310
+ }
1311
+ customFiles = fileArgs.flatMap((arg) => arg.includes(",") ? arg.split(",").map((f) => f.trim()) : [arg.trim()]).filter((f) => f.length > 0);
1689
1312
  }
1690
1313
  async function init() {
1691
- if (!jsonOutput) {
1692
- console.log();
1693
- if (customFiles && customFiles.length > 0) {
1694
- console.log("[+] Analyzing specified MCP configuration files...");
1695
- } else {
1696
- console.log("[+] Detecting MCP Server configurations...");
1697
- }
1698
- }
1699
- const mcpFilesManager = new MCPFiles(customFiles);
1700
- const mcpFilesList = await mcpFilesManager.findFiles();
1701
- if (Object.keys(mcpFilesList).length === 0) {
1702
- exitWithError("No configuration for MCP Server applications found.");
1703
- }
1704
- let pathIndex = 0;
1705
- let totalServers = 0;
1706
- let totalRunning = 0;
1707
- let totalHighRiskCredentials = 0;
1708
- let totalImplicitLatestVersions = 0;
1709
- const transportCounts = { stdio: 0, sse: 0, http: 0 };
1710
- for (const groupName of Object.keys(mcpFilesList)) {
1711
- const group = mcpFilesList[groupName];
1712
- const isCustomFilesMode = customFiles && customFiles.length > 0;
1713
- const shouldSkipGroup = !showAll && !isCustomFilesMode && group.stats?.serversCount === 0;
1714
- if (shouldSkipGroup) {
1715
- continue;
1716
- }
1717
- if (group.paths.length > 0) {
1718
- for (const filePathData of group.paths) {
1719
- const totalMCPServers = filePathData.servers ? filePathData.servers.length : 0;
1720
- const shouldSkipFile = !showAll && !isCustomFilesMode && totalMCPServers === 0;
1721
- if (shouldSkipFile) {
1722
- continue;
1723
- }
1724
- pathIndex++;
1725
- const filePath = filePathData.filePath.replace("~", process.env.HOME || "");
1726
- const filePathValid = filePathData.parsable ? "VALID" : "INVALID";
1727
- const filePathDataType = filePathData.type.toUpperCase();
1728
- const mcpServers = filePathData.servers || [];
1729
- const totalMCPServersRunning = mcpServers.filter((server) => server.status === "running").length;
1730
- totalServers += totalMCPServers;
1731
- totalRunning += totalMCPServersRunning;
1732
- for (const server of mcpServers) {
1733
- if (server.transport) {
1734
- const transport = server.transport.toLowerCase();
1735
- if (transport in transportCounts) {
1736
- transportCounts[transport]++;
1737
- }
1738
- }
1739
- if (server.credentials?.hasCredentials && server.credentials?.riskLevel === "high") {
1740
- totalHighRiskCredentials++;
1741
- }
1742
- if (server.versionInfo?.isLatest) {
1743
- totalImplicitLatestVersions++;
1744
- }
1745
- }
1746
- if (!jsonOutput) {
1747
- const mcpGroupData = [
1748
- { key: "PROVIDER", value: group.friendlyName },
1749
- { key: "FILE", value: filePath },
1750
- { key: "TYPE", value: filePathDataType },
1751
- { key: "PARSABLE", value: filePathValid }
1752
- ];
1753
- const groupMetadata = {
1754
- mcpServersTotal: totalMCPServers,
1755
- mcpServersRunning: totalMCPServersRunning
1756
- };
1757
- RenderService.printMcpGroup(pathIndex, mcpGroupData, groupMetadata);
1758
- RenderService.printMcpServers(mcpServers);
1759
- }
1760
- }
1761
- }
1762
- }
1763
- if (pathIndex === 0) {
1764
- const isCustomFilesMode = customFiles && customFiles.length > 0;
1765
- if (isCustomFilesMode) {
1766
- exitWithError("No MCP servers found in specified configuration files.");
1767
- } else {
1768
- exitWithError("No MCP servers found in known configuration files.");
1769
- }
1770
- }
1771
- const summaryStats = {
1772
- totalServers,
1773
- runningServers: totalRunning,
1774
- highRiskCredentials: totalHighRiskCredentials,
1775
- implicitLatestVersions: totalImplicitLatestVersions,
1776
- transportBreakdown: transportCounts
1777
- };
1778
- if (jsonOutput) {
1779
- const isCustomFilesMode = customFiles && customFiles.length > 0;
1780
- const filteredMcpFiles = Object.fromEntries(
1781
- Object.entries(mcpFilesList).map(([groupName, group]) => {
1782
- const filteredPaths = group.paths.filter((filePathData) => {
1783
- const fileServerCount = filePathData.servers ? filePathData.servers.length : 0;
1784
- if (showAll || isCustomFilesMode) {
1785
- return true;
1786
- }
1787
- return fileServerCount > 0;
1788
- });
1789
- return [groupName, { ...group, paths: filteredPaths }];
1790
- }).filter((entry) => {
1791
- const [, group] = entry;
1792
- return group.paths.length > 0;
1793
- })
1794
- );
1795
- const output = {
1796
- mcpFiles: filteredMcpFiles,
1797
- summary: summaryStats
1798
- };
1799
- console.log(JSON.stringify(output, null, 2));
1800
- } else {
1801
- RenderService.printSummary(summaryStats);
1802
- }
1314
+ if (!jsonOutput) {
1315
+ console.log();
1316
+ if (customFiles && customFiles.length > 0) console.log("[+] Analyzing specified MCP configuration files...");
1317
+ else console.log("[+] Detecting MCP Server configurations...");
1318
+ }
1319
+ const mcpFilesList = await new MCPFiles(customFiles).findFiles();
1320
+ if (Object.keys(mcpFilesList).length === 0) exitWithError("No configuration for MCP Server applications found.");
1321
+ let pathIndex = 0;
1322
+ let totalServers = 0;
1323
+ let totalRunning = 0;
1324
+ let totalHighRiskCredentials = 0;
1325
+ let totalImplicitLatestVersions = 0;
1326
+ const transportCounts = {
1327
+ stdio: 0,
1328
+ sse: 0,
1329
+ http: 0
1330
+ };
1331
+ for (const groupName of Object.keys(mcpFilesList)) {
1332
+ const group = mcpFilesList[groupName];
1333
+ const isCustomFilesMode = customFiles && customFiles.length > 0;
1334
+ if (!showAll && !isCustomFilesMode && group.stats?.serversCount === 0) continue;
1335
+ if (group.paths.length > 0) for (const filePathData of group.paths) {
1336
+ const totalMCPServers = filePathData.servers ? filePathData.servers.length : 0;
1337
+ if (!showAll && !isCustomFilesMode && totalMCPServers === 0) continue;
1338
+ pathIndex++;
1339
+ const filePath = filePathData.filePath.replace("~", process.env.HOME || "");
1340
+ const filePathValid = filePathData.parsable ? "VALID" : "INVALID";
1341
+ const filePathDataType = filePathData.type.toUpperCase();
1342
+ const mcpServers = filePathData.servers || [];
1343
+ const totalMCPServersRunning = mcpServers.filter((server) => server.status === "running").length;
1344
+ totalServers += totalMCPServers;
1345
+ totalRunning += totalMCPServersRunning;
1346
+ for (const server of mcpServers) {
1347
+ if (server.transport) {
1348
+ const transport = server.transport.toLowerCase();
1349
+ if (transport in transportCounts) transportCounts[transport]++;
1350
+ }
1351
+ if (server.credentials?.hasCredentials && server.credentials?.riskLevel === "high") totalHighRiskCredentials++;
1352
+ if (server.versionInfo?.isLatest) totalImplicitLatestVersions++;
1353
+ }
1354
+ if (!jsonOutput) {
1355
+ const mcpGroupData = [
1356
+ {
1357
+ key: "PROVIDER",
1358
+ value: group.friendlyName
1359
+ },
1360
+ {
1361
+ key: "FILE",
1362
+ value: filePath
1363
+ },
1364
+ {
1365
+ key: "TYPE",
1366
+ value: filePathDataType
1367
+ },
1368
+ {
1369
+ key: "PARSABLE",
1370
+ value: filePathValid
1371
+ }
1372
+ ];
1373
+ const groupMetadata = {
1374
+ mcpServersTotal: totalMCPServers,
1375
+ mcpServersRunning: totalMCPServersRunning
1376
+ };
1377
+ RenderService.printMcpGroup(pathIndex, mcpGroupData, groupMetadata);
1378
+ RenderService.printMcpServers(mcpServers);
1379
+ }
1380
+ }
1381
+ }
1382
+ if (pathIndex === 0) {
1383
+ if (customFiles && customFiles.length > 0) exitWithError("No MCP servers found in specified configuration files.");
1384
+ else exitWithError("No MCP servers found in known configuration files.");
1385
+ }
1386
+ const summaryStats = {
1387
+ totalServers,
1388
+ runningServers: totalRunning,
1389
+ highRiskCredentials: totalHighRiskCredentials,
1390
+ implicitLatestVersions: totalImplicitLatestVersions,
1391
+ transportBreakdown: transportCounts
1392
+ };
1393
+ if (jsonOutput) {
1394
+ const isCustomFilesMode = customFiles && customFiles.length > 0;
1395
+ const output = {
1396
+ mcpFiles: Object.fromEntries(Object.entries(mcpFilesList).map(([groupName, group]) => {
1397
+ const filteredPaths = group.paths.filter((filePathData) => {
1398
+ const fileServerCount = filePathData.servers ? filePathData.servers.length : 0;
1399
+ if (showAll || isCustomFilesMode) return true;
1400
+ return fileServerCount > 0;
1401
+ });
1402
+ return [groupName, {
1403
+ ...group,
1404
+ paths: filteredPaths
1405
+ }];
1406
+ }).filter((entry) => {
1407
+ const [, group] = entry;
1408
+ return group.paths.length > 0;
1409
+ })),
1410
+ summary: summaryStats
1411
+ };
1412
+ console.log(JSON.stringify(output, null, 2));
1413
+ } else RenderService.printSummary(summaryStats);
1803
1414
  }
1804
- __name(init, "init");
1805
1415
  init().then(() => {
1806
- console.log("\n");
1416
+ console.log("\n");
1807
1417
  });
1808
1418
  function exitWithError(message) {
1809
- console.error(`${(0, import_node_util13.styleText)(["red"], "\u25CF")} ${message}
1810
- `);
1811
- process.exit(1);
1419
+ console.error(`${(0, node_util.styleText)(["red"], "●")} ${message}\n`);
1420
+ process.exit(1);
1812
1421
  }
1813
- __name(exitWithError, "exitWithError");
1422
+
1423
+ //# sourceMappingURL=cli.cjs.map