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