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/main.mjs CHANGED
@@ -1,1258 +1,1003 @@
1
- var __defProp = Object.defineProperty;
2
- var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
-
4
- // src/services/mcp-config-service.ts
5
- import { platform } from "os";
6
- import path from "path";
7
- import fs from "fs/promises";
8
- import util from "util";
9
- import { MCPPathRegistry, MCPConfigParser, DirectoryBubbleService } from "agent-files";
10
-
1
+ import { platform } from "node:os";
2
+ import path from "node:path";
3
+ import fs from "node:fs/promises";
4
+ import util from "node:util";
5
+ import { DirectoryBubbleService, MCPConfigParser, MCPPathRegistry } from "agent-files";
6
+ import { execSync } from "node:child_process";
11
7
  // src/services/credential-detection-service.ts
12
8
  var CredentialDetectionService = class {
13
- static {
14
- __name(this, "CredentialDetectionService");
15
- }
16
- /**
17
- * Credential patterns grouped by risk level for easier maintenance
18
- */
19
- static CREDENTIAL_PATTERNS = {
20
- high: [
21
- // Generic Key and Token patterns (broad matching)
22
- /.*key.*/i,
23
- /.*token.*/i,
24
- // Passwords
25
- /.*password.*/i,
26
- /.*passwd.*/i,
27
- /.*pwd.*/i,
28
- // Credentials and Secrets
29
- /.*credential.*/i,
30
- /.*creds.*/i,
31
- /.*secret.*/i
32
- ],
33
- low: [
34
- // Organization and Account IDs
35
- /org[_-]?id/i,
36
- /organization[_-]?id/i,
37
- /account[_-]?id/i,
38
- /user[_-]?id/i,
39
- /openai[_-]?org[_-]?id/i
40
- ]
41
- };
42
- /**
43
- * Argument patterns for detecting credentials in command-line arguments
44
- */
45
- static ARGUMENT_PATTERNS = {
46
- high: [
47
- // API key arguments
48
- /--api-key/i,
49
- /--apikey/i,
50
- /--key/i,
51
- // Token arguments
52
- /--token/i,
53
- /--access-token/i,
54
- /--auth-token/i,
55
- /--bearer-token/i,
56
- // Password arguments
57
- /--password/i,
58
- /--passwd/i,
59
- /--pwd/i,
60
- // Secret arguments
61
- /--secret/i,
62
- /--client-secret/i,
63
- // Authentication arguments
64
- /--auth/i,
65
- /--authorization/i,
66
- /--credentials/i,
67
- /--creds/i
68
- ],
69
- low: [
70
- // Organization and account IDs
71
- /--org-id/i,
72
- /--organization-id/i,
73
- /--account-id/i,
74
- /--user-id/i
75
- ]
76
- };
77
- /**
78
- * Header patterns for detecting credentials in HTTP headers
79
- */
80
- static HEADER_PATTERNS = {
81
- high: [
82
- // Authorization headers
83
- /authorization/i,
84
- /auth/i,
85
- // API key headers
86
- /x-api-key/i,
87
- /api-key/i,
88
- /apikey/i,
89
- // Token headers
90
- /x-access-token/i,
91
- /access-token/i,
92
- /bearer-token/i,
93
- /x-auth-token/i,
94
- /auth-token/i,
95
- // Custom authentication headers
96
- /x-.*-key/i,
97
- /x-.*-token/i,
98
- /x-.*-secret/i,
99
- // Service-specific patterns
100
- /x-github-token/i,
101
- /x-openai-key/i,
102
- /x-anthropic-key/i
103
- ],
104
- low: [
105
- // User identification headers
106
- /x-user-id/i,
107
- /x-org-id/i,
108
- /x-organization-id/i,
109
- /x-account-id/i
110
- ]
111
- };
112
- /**
113
- * Variable substitution pattern to detect safe variable references
114
- */
115
- static VARIABLE_SUBSTITUTION_PATTERN = /^\$\{[^}]+\}$/;
116
- /**
117
- * Check if a value is a variable substitution pattern (e.g., ${input:token})
118
- */
119
- static isVariableSubstitution(value) {
120
- return this.VARIABLE_SUBSTITUTION_PATTERN.test(value);
121
- }
122
- /**
123
- * Analyze command-line arguments for potential credentials
124
- */
125
- static analyzeArguments(args) {
126
- if (!args || !Array.isArray(args) || args.length === 0) {
127
- return {
128
- hasCredentials: false,
129
- credentialVars: [],
130
- riskLevel: "none"
131
- };
132
- }
133
- const credentialVars = [];
134
- for (let i = 0; i < args.length - 1; i++) {
135
- const arg = args[i];
136
- const nextArg = args[i + 1];
137
- const isHighRiskArg = this.ARGUMENT_PATTERNS.high.some((pattern) => pattern.test(arg));
138
- const isLowRiskArg = this.ARGUMENT_PATTERNS.low.some((pattern) => pattern.test(arg));
139
- if (isHighRiskArg || isLowRiskArg) {
140
- if (nextArg && !nextArg.startsWith("-")) {
141
- credentialVars.push({
142
- name: arg,
143
- value: this.maskValue(nextArg),
144
- riskLevel: isHighRiskArg ? "high" : "low",
145
- source: "args"
146
- });
147
- i++;
148
- }
149
- }
150
- }
151
- const hasCredentials = credentialVars.length > 0;
152
- const riskLevel = this.calculateOverallRiskLevel(credentialVars);
153
- return {
154
- hasCredentials,
155
- credentialVars,
156
- riskLevel
157
- };
158
- }
159
- /**
160
- * Analyze HTTP headers for potential credentials
161
- */
162
- static analyzeHeaders(headers) {
163
- if (!headers || typeof headers !== "object") {
164
- return {
165
- hasCredentials: false,
166
- credentialVars: [],
167
- riskLevel: "none"
168
- };
169
- }
170
- const credentialVars = [];
171
- for (const [name, value] of Object.entries(headers)) {
172
- if (this.isVariableSubstitution(value)) {
173
- continue;
174
- }
175
- const isHighRiskHeader = this.HEADER_PATTERNS.high.some((pattern) => pattern.test(name));
176
- const isLowRiskHeader = this.HEADER_PATTERNS.low.some((pattern) => pattern.test(name));
177
- if (isHighRiskHeader || isLowRiskHeader) {
178
- credentialVars.push({
179
- name,
180
- value: this.maskValue(value),
181
- riskLevel: isHighRiskHeader ? "high" : "low",
182
- source: "headers"
183
- });
184
- }
185
- }
186
- const hasCredentials = credentialVars.length > 0;
187
- const riskLevel = this.calculateOverallRiskLevel(credentialVars);
188
- return {
189
- hasCredentials,
190
- credentialVars,
191
- riskLevel
192
- };
193
- }
194
- /**
195
- * Comprehensive analysis of server configuration for credentials
196
- */
197
- static analyzeServerConfig(config) {
198
- const envResult = this.analyzeEnvironmentVariables(config.env);
199
- const argsResult = this.analyzeArguments(config.args);
200
- const headersResult = this.analyzeHeaders(config.headers);
201
- const allCredentialVars = [
202
- ...envResult.credentialVars,
203
- ...argsResult.credentialVars,
204
- ...headersResult.credentialVars
205
- ];
206
- const hasCredentials = allCredentialVars.length > 0;
207
- const riskLevel = this.calculateOverallRiskLevel(allCredentialVars);
208
- return {
209
- hasCredentials,
210
- credentialVars: allCredentialVars,
211
- riskLevel
212
- };
213
- }
214
- /**
215
- * Check if an environment variable name suggests it might contain credentials
216
- */
217
- static isPotentialCredential(envVarName) {
218
- return this.CREDENTIAL_PATTERNS.high.some((pattern) => pattern.test(envVarName)) || this.CREDENTIAL_PATTERNS.low.some((pattern) => pattern.test(envVarName));
219
- }
220
- /**
221
- * Analyze environment variables and return credential detection results
222
- */
223
- static analyzeEnvironmentVariables(env) {
224
- if (!env || typeof env !== "object") {
225
- return {
226
- hasCredentials: false,
227
- credentialVars: [],
228
- riskLevel: "none"
229
- };
230
- }
231
- const credentialVars = [];
232
- for (const [name, value] of Object.entries(env)) {
233
- if (this.isVariableSubstitution(value)) {
234
- continue;
235
- }
236
- if (this.isPotentialCredential(name)) {
237
- credentialVars.push({
238
- name,
239
- value: this.maskValue(value),
240
- riskLevel: this.assessRiskLevel(name),
241
- source: "env"
242
- });
243
- }
244
- }
245
- const hasCredentials = credentialVars.length > 0;
246
- const riskLevel = this.calculateOverallRiskLevel(credentialVars);
247
- return {
248
- hasCredentials,
249
- credentialVars,
250
- riskLevel
251
- };
252
- }
253
- /**
254
- * Mask sensitive values for display (show only first and last character)
255
- */
256
- static maskValue(value) {
257
- if (!value || value.length <= 2) {
258
- return value;
259
- }
260
- const first = value.charAt(0);
261
- const last = value.charAt(value.length - 1);
262
- const maskedLength = Math.min(value.length - 2, 8);
263
- return `${first}${"*".repeat(maskedLength)}${last}`;
264
- }
265
- /**
266
- * Assess risk level for a specific credential variable
267
- */
268
- static assessRiskLevel(name) {
269
- if (this.CREDENTIAL_PATTERNS.high.some((pattern) => pattern.test(name))) {
270
- return "high";
271
- }
272
- if (this.CREDENTIAL_PATTERNS.low.some((pattern) => pattern.test(name))) {
273
- return "low";
274
- }
275
- return "high";
276
- }
277
- /**
278
- * Calculate overall risk level based on all credential variables
279
- */
280
- static calculateOverallRiskLevel(credentialVars) {
281
- if (credentialVars.length === 0) {
282
- return "none";
283
- }
284
- const hasHighRisk = credentialVars.some((v) => v.riskLevel === "high");
285
- if (hasHighRisk) {
286
- return "high";
287
- }
288
- return "low";
289
- }
9
+ /**
10
+ * Credential patterns grouped by risk level for easier maintenance
11
+ */
12
+ static CREDENTIAL_PATTERNS = {
13
+ high: [
14
+ /.*key.*/i,
15
+ /.*token.*/i,
16
+ /.*password.*/i,
17
+ /.*passwd.*/i,
18
+ /.*pwd.*/i,
19
+ /.*credential.*/i,
20
+ /.*creds.*/i,
21
+ /.*secret.*/i
22
+ ],
23
+ low: [
24
+ /org[_-]?id/i,
25
+ /organization[_-]?id/i,
26
+ /account[_-]?id/i,
27
+ /user[_-]?id/i,
28
+ /openai[_-]?org[_-]?id/i
29
+ ]
30
+ };
31
+ /**
32
+ * Argument patterns for detecting credentials in command-line arguments
33
+ */
34
+ static ARGUMENT_PATTERNS = {
35
+ high: [
36
+ /--api-key/i,
37
+ /--apikey/i,
38
+ /--key/i,
39
+ /--token/i,
40
+ /--access-token/i,
41
+ /--auth-token/i,
42
+ /--bearer-token/i,
43
+ /--password/i,
44
+ /--passwd/i,
45
+ /--pwd/i,
46
+ /--secret/i,
47
+ /--client-secret/i,
48
+ /--auth/i,
49
+ /--authorization/i,
50
+ /--credentials/i,
51
+ /--creds/i
52
+ ],
53
+ low: [
54
+ /--org-id/i,
55
+ /--organization-id/i,
56
+ /--account-id/i,
57
+ /--user-id/i
58
+ ]
59
+ };
60
+ /**
61
+ * Header patterns for detecting credentials in HTTP headers
62
+ */
63
+ static HEADER_PATTERNS = {
64
+ high: [
65
+ /authorization/i,
66
+ /auth/i,
67
+ /x-api-key/i,
68
+ /api-key/i,
69
+ /apikey/i,
70
+ /x-access-token/i,
71
+ /access-token/i,
72
+ /bearer-token/i,
73
+ /x-auth-token/i,
74
+ /auth-token/i,
75
+ /x-.*-key/i,
76
+ /x-.*-token/i,
77
+ /x-.*-secret/i,
78
+ /x-github-token/i,
79
+ /x-openai-key/i,
80
+ /x-anthropic-key/i
81
+ ],
82
+ low: [
83
+ /x-user-id/i,
84
+ /x-org-id/i,
85
+ /x-organization-id/i,
86
+ /x-account-id/i
87
+ ]
88
+ };
89
+ /**
90
+ * Variable substitution pattern to detect safe variable references
91
+ */
92
+ static VARIABLE_SUBSTITUTION_PATTERN = /^\$\{[^}]+\}$/;
93
+ /**
94
+ * Check if a value is a variable substitution pattern (e.g., ${input:token})
95
+ */
96
+ static isVariableSubstitution(value) {
97
+ return this.VARIABLE_SUBSTITUTION_PATTERN.test(value);
98
+ }
99
+ /**
100
+ * Analyze command-line arguments for potential credentials
101
+ */
102
+ static analyzeArguments(args) {
103
+ if (!args || !Array.isArray(args) || args.length === 0) return {
104
+ hasCredentials: false,
105
+ credentialVars: [],
106
+ riskLevel: "none"
107
+ };
108
+ const credentialVars = [];
109
+ for (let i = 0; i < args.length - 1; i++) {
110
+ const arg = args[i];
111
+ const nextArg = args[i + 1];
112
+ const isHighRiskArg = this.ARGUMENT_PATTERNS.high.some((pattern) => pattern.test(arg));
113
+ const isLowRiskArg = this.ARGUMENT_PATTERNS.low.some((pattern) => pattern.test(arg));
114
+ if (isHighRiskArg || isLowRiskArg) {
115
+ if (nextArg && !nextArg.startsWith("-")) {
116
+ credentialVars.push({
117
+ name: arg,
118
+ value: this.maskValue(nextArg),
119
+ riskLevel: isHighRiskArg ? "high" : "low",
120
+ source: "args"
121
+ });
122
+ i++;
123
+ }
124
+ }
125
+ }
126
+ return {
127
+ hasCredentials: credentialVars.length > 0,
128
+ credentialVars,
129
+ riskLevel: this.calculateOverallRiskLevel(credentialVars)
130
+ };
131
+ }
132
+ /**
133
+ * Analyze HTTP headers for potential credentials
134
+ */
135
+ static analyzeHeaders(headers) {
136
+ if (!headers || typeof headers !== "object") return {
137
+ hasCredentials: false,
138
+ credentialVars: [],
139
+ riskLevel: "none"
140
+ };
141
+ const credentialVars = [];
142
+ for (const [name, value] of Object.entries(headers)) {
143
+ if (this.isVariableSubstitution(value)) continue;
144
+ const isHighRiskHeader = this.HEADER_PATTERNS.high.some((pattern) => pattern.test(name));
145
+ const isLowRiskHeader = this.HEADER_PATTERNS.low.some((pattern) => pattern.test(name));
146
+ if (isHighRiskHeader || isLowRiskHeader) credentialVars.push({
147
+ name,
148
+ value: this.maskValue(value),
149
+ riskLevel: isHighRiskHeader ? "high" : "low",
150
+ source: "headers"
151
+ });
152
+ }
153
+ return {
154
+ hasCredentials: credentialVars.length > 0,
155
+ credentialVars,
156
+ riskLevel: this.calculateOverallRiskLevel(credentialVars)
157
+ };
158
+ }
159
+ /**
160
+ * Comprehensive analysis of server configuration for credentials
161
+ */
162
+ static analyzeServerConfig(config) {
163
+ const envResult = this.analyzeEnvironmentVariables(config.env);
164
+ const argsResult = this.analyzeArguments(config.args);
165
+ const headersResult = this.analyzeHeaders(config.headers);
166
+ const allCredentialVars = [
167
+ ...envResult.credentialVars,
168
+ ...argsResult.credentialVars,
169
+ ...headersResult.credentialVars
170
+ ];
171
+ return {
172
+ hasCredentials: allCredentialVars.length > 0,
173
+ credentialVars: allCredentialVars,
174
+ riskLevel: this.calculateOverallRiskLevel(allCredentialVars)
175
+ };
176
+ }
177
+ /**
178
+ * Check if an environment variable name suggests it might contain credentials
179
+ */
180
+ static isPotentialCredential(envVarName) {
181
+ return this.CREDENTIAL_PATTERNS.high.some((pattern) => pattern.test(envVarName)) || this.CREDENTIAL_PATTERNS.low.some((pattern) => pattern.test(envVarName));
182
+ }
183
+ /**
184
+ * Analyze environment variables and return credential detection results
185
+ */
186
+ static analyzeEnvironmentVariables(env) {
187
+ if (!env || typeof env !== "object") return {
188
+ hasCredentials: false,
189
+ credentialVars: [],
190
+ riskLevel: "none"
191
+ };
192
+ const credentialVars = [];
193
+ for (const [name, value] of Object.entries(env)) {
194
+ if (this.isVariableSubstitution(value)) continue;
195
+ if (this.isPotentialCredential(name)) credentialVars.push({
196
+ name,
197
+ value: this.maskValue(value),
198
+ riskLevel: this.assessRiskLevel(name),
199
+ source: "env"
200
+ });
201
+ }
202
+ return {
203
+ hasCredentials: credentialVars.length > 0,
204
+ credentialVars,
205
+ riskLevel: this.calculateOverallRiskLevel(credentialVars)
206
+ };
207
+ }
208
+ /**
209
+ * Mask sensitive values for display (show only first and last character)
210
+ */
211
+ static maskValue(value) {
212
+ if (!value || value.length <= 2) return value;
213
+ const first = value.charAt(0);
214
+ const last = value.charAt(value.length - 1);
215
+ const maskedLength = Math.min(value.length - 2, 8);
216
+ return `${first}${"*".repeat(maskedLength)}${last}`;
217
+ }
218
+ /**
219
+ * Assess risk level for a specific credential variable
220
+ */
221
+ static assessRiskLevel(name) {
222
+ if (this.CREDENTIAL_PATTERNS.high.some((pattern) => pattern.test(name))) return "high";
223
+ if (this.CREDENTIAL_PATTERNS.low.some((pattern) => pattern.test(name))) return "low";
224
+ return "high";
225
+ }
226
+ /**
227
+ * Calculate overall risk level based on all credential variables
228
+ */
229
+ static calculateOverallRiskLevel(credentialVars) {
230
+ if (credentialVars.length === 0) return "none";
231
+ if (credentialVars.some((v) => v.riskLevel === "high")) return "high";
232
+ return "low";
233
+ }
290
234
  };
291
-
292
235
  // src/services/mcp-version-detection-service.ts
236
+ /**
237
+ * Service for detecting version information from MCP server configurations
238
+ * Specifically handles npx-based server commands to determine if they use
239
+ * pinned versions or implicit latest versions
240
+ */
293
241
  var MCPVersionDetectionService = class {
294
- static {
295
- __name(this, "MCPVersionDetectionService");
296
- }
297
- /**
298
- * Analyze a server configuration to extract version information
299
- * @param command - The command used to run the server
300
- * @param args - Array of arguments passed to the command
301
- * @returns PackageVersionInfo if analysis is possible, null otherwise
302
- */
303
- analyzeServerVersion(command, args) {
304
- if (!["npx", "uvx", "uv"].includes(command)) {
305
- return null;
306
- }
307
- if (!args || args.length === 0) {
308
- return null;
309
- }
310
- const packageName = this.extractPackageName(command, args);
311
- if (!packageName) {
312
- return null;
313
- }
314
- const { name, version } = this.parsePackageVersion(packageName);
315
- const isPinned = this.isPinnedVersion(version);
316
- return {
317
- packageName: name,
318
- version,
319
- isPinned,
320
- isLatest: !isPinned
321
- };
322
- }
323
- /**
324
- * Extract the package name based on the command type
325
- * @param command - The command used to run the server
326
- * @param args - Array of arguments passed to the command
327
- * @returns The package name/spec or null if not found
328
- */
329
- extractPackageName(command, args) {
330
- switch (command) {
331
- case "npx":
332
- return this.extractNpxPackageName(args);
333
- case "uvx":
334
- return this.extractUvxPackageName(args);
335
- case "uv":
336
- return this.extractUvPackageName(args);
337
- default:
338
- return null;
339
- }
340
- }
341
- /**
342
- * Extract the package name from npx arguments
343
- * @param args - Array of arguments passed to npx
344
- * @returns The package name/spec or null if not found
345
- */
346
- extractNpxPackageName(args) {
347
- if (!args || args.length === 0) {
348
- return null;
349
- }
350
- const yIndex = args.indexOf("-y");
351
- if (yIndex !== -1 && yIndex + 1 < args.length) {
352
- return args[yIndex + 1];
353
- }
354
- const yesIndex = args.indexOf("--yes");
355
- if (yesIndex !== -1 && yesIndex + 1 < args.length) {
356
- return args[yesIndex + 1];
357
- }
358
- for (let i = 0; i < args.length; i++) {
359
- const arg = args[i];
360
- if (!arg.startsWith("-")) {
361
- if (i > 0) {
362
- const prevArg = args[i - 1];
363
- if (prevArg === "--registry" || prevArg === "-r" || prevArg === "--package" || prevArg === "-p") {
364
- continue;
365
- }
366
- }
367
- return arg;
368
- }
369
- }
370
- return null;
371
- }
372
- /**
373
- * Extract the package name from uvx arguments
374
- * @param args - Array of arguments passed to uvx
375
- * @returns The package name/spec or null if not found
376
- */
377
- extractUvxPackageName(args) {
378
- if (!args || args.length === 0) {
379
- return null;
380
- }
381
- return args[0];
382
- }
383
- /**
384
- * Extract the package name from uv arguments
385
- * @param args - Array of arguments passed to uv
386
- * @returns The package name/spec or null if not found
387
- */
388
- extractUvPackageName(args) {
389
- if (!args || args.length === 0) {
390
- return null;
391
- }
392
- const runIndex = args.indexOf("run");
393
- if (runIndex !== -1 && runIndex + 1 < args.length) {
394
- return args[runIndex + 1];
395
- }
396
- return null;
397
- }
398
- /**
399
- * Parse a package specification to extract name and version
400
- * @param packageSpec - Package specification (e.g., "package@1.0.0" or "package")
401
- * @returns Object with name and optional version
402
- */
403
- parsePackageVersion(packageSpec) {
404
- if (!packageSpec) {
405
- return { name: "", version: void 0 };
406
- }
407
- if (packageSpec.startsWith("@")) {
408
- const parts = packageSpec.split("@");
409
- if (parts.length === 2) {
410
- return { name: packageSpec, version: void 0 };
411
- } else if (parts.length === 3) {
412
- return {
413
- name: `@${parts[1]}`,
414
- version: parts[2]
415
- };
416
- }
417
- }
418
- const atIndex = packageSpec.lastIndexOf("@");
419
- if (atIndex > 0) {
420
- return {
421
- name: packageSpec.substring(0, atIndex),
422
- version: packageSpec.substring(atIndex + 1)
423
- };
424
- }
425
- return { name: packageSpec, version: void 0 };
426
- }
427
- /**
428
- * Determine if a version represents a pinned version
429
- * @param version - The version string to check
430
- * @returns true if the version is pinned, false if it's latest/implicit
431
- */
432
- isPinnedVersion(version) {
433
- if (!version) {
434
- return false;
435
- }
436
- if (version === "latest") {
437
- return false;
438
- }
439
- return true;
440
- }
242
+ /**
243
+ * Analyze a server configuration to extract version information
244
+ * @param command - The command used to run the server
245
+ * @param args - Array of arguments passed to the command
246
+ * @returns PackageVersionInfo if analysis is possible, null otherwise
247
+ */
248
+ analyzeServerVersion(command, args) {
249
+ if (![
250
+ "npx",
251
+ "uvx",
252
+ "uv"
253
+ ].includes(command)) return null;
254
+ if (!args || args.length === 0) return null;
255
+ const packageName = this.extractPackageName(command, args);
256
+ if (!packageName) return null;
257
+ const { name, version } = this.parsePackageVersion(packageName);
258
+ const isPinned = this.isPinnedVersion(version);
259
+ return {
260
+ packageName: name,
261
+ version,
262
+ isPinned,
263
+ isLatest: !isPinned
264
+ };
265
+ }
266
+ /**
267
+ * Extract the package name based on the command type
268
+ * @param command - The command used to run the server
269
+ * @param args - Array of arguments passed to the command
270
+ * @returns The package name/spec or null if not found
271
+ */
272
+ extractPackageName(command, args) {
273
+ switch (command) {
274
+ case "npx": return this.extractNpxPackageName(args);
275
+ case "uvx": return this.extractUvxPackageName(args);
276
+ case "uv": return this.extractUvPackageName(args);
277
+ default: return null;
278
+ }
279
+ }
280
+ /**
281
+ * Extract the package name from npx arguments
282
+ * @param args - Array of arguments passed to npx
283
+ * @returns The package name/spec or null if not found
284
+ */
285
+ extractNpxPackageName(args) {
286
+ if (!args || args.length === 0) return null;
287
+ const yIndex = args.indexOf("-y");
288
+ if (yIndex !== -1 && yIndex + 1 < args.length) return args[yIndex + 1];
289
+ const yesIndex = args.indexOf("--yes");
290
+ if (yesIndex !== -1 && yesIndex + 1 < args.length) return args[yesIndex + 1];
291
+ for (let i = 0; i < args.length; i++) {
292
+ const arg = args[i];
293
+ if (!arg.startsWith("-")) {
294
+ if (i > 0) {
295
+ const prevArg = args[i - 1];
296
+ if (prevArg === "--registry" || prevArg === "-r" || prevArg === "--package" || prevArg === "-p") continue;
297
+ }
298
+ return arg;
299
+ }
300
+ }
301
+ return null;
302
+ }
303
+ /**
304
+ * Extract the package name from uvx arguments
305
+ * @param args - Array of arguments passed to uvx
306
+ * @returns The package name/spec or null if not found
307
+ */
308
+ extractUvxPackageName(args) {
309
+ if (!args || args.length === 0) return null;
310
+ return args[0];
311
+ }
312
+ /**
313
+ * Extract the package name from uv arguments
314
+ * @param args - Array of arguments passed to uv
315
+ * @returns The package name/spec or null if not found
316
+ */
317
+ extractUvPackageName(args) {
318
+ if (!args || args.length === 0) return null;
319
+ const runIndex = args.indexOf("run");
320
+ if (runIndex !== -1 && runIndex + 1 < args.length) return args[runIndex + 1];
321
+ return null;
322
+ }
323
+ /**
324
+ * Parse a package specification to extract name and version
325
+ * @param packageSpec - Package specification (e.g., "package@1.0.0" or "package")
326
+ * @returns Object with name and optional version
327
+ */
328
+ parsePackageVersion(packageSpec) {
329
+ if (!packageSpec) return {
330
+ name: "",
331
+ version: void 0
332
+ };
333
+ if (packageSpec.startsWith("@")) {
334
+ const parts = packageSpec.split("@");
335
+ if (parts.length === 2) return {
336
+ name: packageSpec,
337
+ version: void 0
338
+ };
339
+ else if (parts.length === 3) return {
340
+ name: `@${parts[1]}`,
341
+ version: parts[2]
342
+ };
343
+ }
344
+ const atIndex = packageSpec.lastIndexOf("@");
345
+ if (atIndex > 0) return {
346
+ name: packageSpec.substring(0, atIndex),
347
+ version: packageSpec.substring(atIndex + 1)
348
+ };
349
+ return {
350
+ name: packageSpec,
351
+ version: void 0
352
+ };
353
+ }
354
+ /**
355
+ * Determine if a version represents a pinned version
356
+ * @param version - The version string to check
357
+ * @returns true if the version is pinned, false if it's latest/implicit
358
+ */
359
+ isPinnedVersion(version) {
360
+ if (!version) return false;
361
+ if (version === "latest") return false;
362
+ return true;
363
+ }
441
364
  };
442
-
443
365
  // src/utils/url-utils.ts
366
+ /**
367
+ * Utility functions for URL operations
368
+ */
369
+ /**
370
+ * Extract hostname from a URL string
371
+ * @param urlString - The URL string to extract hostname from
372
+ * @returns The hostname if valid URL, or the original string if parsing fails
373
+ */
444
374
  function extractHostname(urlString) {
445
- try {
446
- let urlToParse = urlString;
447
- if (!urlToParse.includes("://")) {
448
- urlToParse = `http://${urlToParse}`;
449
- }
450
- const url = new URL(urlToParse);
451
- return url.hostname;
452
- } catch (error) {
453
- return urlString;
454
- }
375
+ try {
376
+ let urlToParse = urlString;
377
+ if (!urlToParse.includes("://")) urlToParse = `http://${urlToParse}`;
378
+ return new URL(urlToParse).hostname;
379
+ } catch {
380
+ return urlString;
381
+ }
455
382
  }
456
- __name(extractHostname, "extractHostname");
457
-
458
383
  // src/services/mcp-config-service.ts
459
384
  var MCPConfigService = class {
460
- static {
461
- __name(this, "MCPConfigService");
462
- }
463
- pathRegistry;
464
- currentOS;
465
- debug;
466
- directoryBubbleService;
467
- versionDetectionService;
468
- enableDirectoryBubbling;
469
- constructor(options = {}) {
470
- this.pathRegistry = new MCPPathRegistry();
471
- this.currentOS = platform();
472
- this.debug = util.debuglog("ls-mcp");
473
- this.directoryBubbleService = new DirectoryBubbleService();
474
- this.versionDetectionService = new MCPVersionDetectionService();
475
- this.enableDirectoryBubbling = options.enableDirectoryBubbling ?? false;
476
- }
477
- /**
478
- * Get MCP configuration files for a specific AI application on the current OS
479
- */
480
- getConfigFilesPerApp(appName) {
481
- try {
482
- return this.pathRegistry.getPathsForApp(this.currentOS, appName);
483
- } catch (error) {
484
- throw new Error(`Failed to get config files for app '${appName}': ${error instanceof Error ? error.message : "Unknown error"}`);
485
- }
486
- }
487
- /**
488
- * Get MCP configuration files for all AI applications on the current OS
489
- */
490
- getAllConfigFiles() {
491
- try {
492
- return this.pathRegistry.getPathsForOS(this.currentOS);
493
- } catch (error) {
494
- throw new Error(`Failed to get all config files: ${error instanceof Error ? error.message : "Unknown error"}`);
495
- }
496
- }
497
- /**
498
- * Get MCP servers configured for a specific AI application on the current OS
499
- */
500
- async getMCPServersPerApp(appName) {
501
- try {
502
- const appPaths = this.getConfigFilesPerApp(appName);
503
- const allServers = [];
504
- for (const filePath of appPaths) {
505
- const servers = await this.parseConfigFileForServers(filePath.filePath);
506
- allServers.push(...servers);
507
- }
508
- return allServers;
509
- } catch (error) {
510
- throw new Error(`Failed to get MCP servers for app '${appName}': ${error instanceof Error ? error.message : "Unknown error"}`);
511
- }
512
- }
513
- /**
514
- * Get MCP servers configured for all AI applications on the current OS
515
- */
516
- async getAllMCPServers() {
517
- try {
518
- const allApps = this.pathRegistry.getSupportedApps(this.currentOS);
519
- const allServers = {};
520
- for (const appName of allApps) {
521
- try {
522
- allServers[appName] = await this.getMCPServersPerApp(appName);
523
- } catch (error) {
524
- this.debug(`Failed to get servers for app '${appName}': ${error instanceof Error ? error.message : "Unknown error"}`);
525
- allServers[appName] = [];
526
- }
527
- }
528
- return allServers;
529
- } catch (error) {
530
- throw new Error(`Failed to get all MCP servers: ${error instanceof Error ? error.message : "Unknown error"}`);
531
- }
532
- }
533
- /**
534
- * Get metadata for all supported AI applications on the current OS
535
- */
536
- getSupportedApps() {
537
- try {
538
- const appNames = this.pathRegistry.getSupportedApps(this.currentOS);
539
- const appPaths = this.pathRegistry.getPathsForOS(this.currentOS);
540
- return appNames.map((appName) => ({
541
- name: appName,
542
- friendlyName: this.getFriendlyName(appName),
543
- paths: appPaths[appName] || []
544
- }));
545
- } catch (error) {
546
- throw new Error(`Failed to get supported apps: ${error instanceof Error ? error.message : "Unknown error"}`);
547
- }
548
- }
549
- /**
550
- * Get all supported operating systems
551
- */
552
- getSupportedOperatingSystems() {
553
- return this.pathRegistry.getSupportedOperatingSystems();
554
- }
555
- /**
556
- * Validate if a configuration file exists and is parsable
557
- */
558
- async validateConfigFile(filePath) {
559
- try {
560
- await fs.access(filePath);
561
- const parser = this.createParser(filePath);
562
- return await parser.isValidSyntax();
563
- } catch (error) {
564
- return false;
565
- }
566
- }
567
- /**
568
- * Create a parser instance (can be overridden for testing)
569
- */
570
- createParser(filePath) {
571
- return new MCPConfigParser(filePath);
572
- }
573
- /**
574
- * Get MCP file groups with resolved paths and server information
575
- */
576
- async getMCPFileGroups() {
577
- try {
578
- const appPaths = this.getAllConfigFiles();
579
- const mcpFilesPathsData = {};
580
- for (const groupName of Object.keys(appPaths)) {
581
- const paths = appPaths[groupName];
582
- mcpFilesPathsData[groupName] = {
583
- name: groupName,
584
- friendlyName: this.getFriendlyName(groupName),
585
- paths: [],
586
- stats: { serversCount: 0 }
587
- };
588
- const uniqueFilePaths = /* @__PURE__ */ new Set();
589
- let totalServersCount = 0;
590
- for (const filePathData of paths) {
591
- let resolvedPath = filePathData.filePath.replace("~", process.env.HOME || "");
592
- let absolutePath = path.resolve(resolvedPath);
593
- if (filePathData.type === "local" && this.enableDirectoryBubbling) {
594
- try {
595
- await fs.access(resolvedPath);
596
- } catch (error) {
597
- const bubbledPath = await this.directoryBubbleService.findLocalConfigInParentDirectories(
598
- filePathData.filePath,
599
- process.cwd()
600
- );
601
- if (bubbledPath) {
602
- resolvedPath = bubbledPath;
603
- absolutePath = path.resolve(resolvedPath);
604
- }
605
- }
606
- }
607
- if (uniqueFilePaths.has(absolutePath)) {
608
- continue;
609
- }
610
- uniqueFilePaths.add(absolutePath);
611
- try {
612
- await fs.access(resolvedPath);
613
- const parser = this.createParser(resolvedPath);
614
- const parsable = await parser.isValidSyntax();
615
- filePathData.parsable = parsable;
616
- if (parsable) {
617
- const configData = await parser.parseConfigFile();
618
- const servers = await this.convertToMCPServerInfo(configData.servers || {});
619
- filePathData.servers = servers;
620
- totalServersCount += servers.length;
621
- }
622
- mcpFilesPathsData[groupName].paths.push(filePathData);
623
- } catch (error) {
624
- this.debug(`Skipping file ${resolvedPath}: ${error instanceof Error ? error.message : "Unknown error"}`);
625
- }
626
- }
627
- if (mcpFilesPathsData[groupName] && mcpFilesPathsData[groupName].stats) {
628
- mcpFilesPathsData[groupName].stats.serversCount = totalServersCount;
629
- }
630
- }
631
- return mcpFilesPathsData;
632
- } catch (error) {
633
- throw new Error(`Failed to get MCP file groups: ${error instanceof Error ? error.message : "Unknown error"}`);
634
- }
635
- }
636
- /**
637
- * Parse custom configuration files provided by the user
638
- * This method processes files independently of standard app-based discovery
639
- */
640
- async parseCustomFiles(filePaths) {
641
- try {
642
- const mcpFilesPathsData = {
643
- custom: {
644
- name: "custom",
645
- friendlyName: "Custom Files",
646
- paths: [],
647
- stats: { serversCount: 0 }
648
- }
649
- };
650
- let totalServersCount = 0;
651
- for (const filePath of filePaths) {
652
- const resolvedPath = filePath.replace("~", process.env.HOME || "");
653
- const absolutePath = path.resolve(resolvedPath);
654
- try {
655
- await fs.access(absolutePath);
656
- const parser = this.createParser(absolutePath);
657
- const parsable = await parser.isValidSyntax();
658
- const filePathData = {
659
- filePath: absolutePath,
660
- type: "local",
661
- parsable
662
- };
663
- if (parsable) {
664
- const configData = await parser.parseConfigFile();
665
- const servers = await this.convertToMCPServerInfo(configData.servers || {});
666
- filePathData.servers = servers;
667
- totalServersCount += servers.length;
668
- } else {
669
- this.debug(`File ${absolutePath} has invalid syntax`);
670
- filePathData.servers = [];
671
- }
672
- mcpFilesPathsData.custom.paths.push(filePathData);
673
- } catch (error) {
674
- this.debug(`Skipping file ${absolutePath}: ${error instanceof Error ? error.message : "Unknown error"}`);
675
- mcpFilesPathsData.custom.paths.push({
676
- filePath: absolutePath,
677
- type: "local",
678
- parsable: false,
679
- servers: []
680
- });
681
- }
682
- }
683
- if (mcpFilesPathsData.custom.stats) {
684
- mcpFilesPathsData.custom.stats.serversCount = totalServersCount;
685
- }
686
- return mcpFilesPathsData;
687
- } catch (error) {
688
- throw new Error(`Failed to parse custom files: ${error instanceof Error ? error.message : "Unknown error"}`);
689
- }
690
- }
691
- /**
692
- * Register a custom app with custom paths for the current OS
693
- */
694
- registerCustomApp(appName, paths) {
695
- try {
696
- this.pathRegistry.registerCustomApp(this.currentOS, appName, paths);
697
- } catch (error) {
698
- throw new Error(`Failed to register custom app '${appName}': ${error instanceof Error ? error.message : "Unknown error"}`);
699
- }
700
- }
701
- /**
702
- * Parse a configuration file and return server information
703
- */
704
- async parseConfigFileForServers(filePath) {
705
- try {
706
- const parser = this.createParser(filePath);
707
- const configData = await parser.parseConfigFile();
708
- return await this.convertToMCPServerInfo(configData.servers || {});
709
- } catch (error) {
710
- this.debug(`Failed to parse config file ${filePath}: ${error instanceof Error ? error.message : "Unknown error"}`);
711
- return [];
712
- }
713
- }
714
- /**
715
- * Convert parsed server configs to MCPServerInfo format
716
- */
717
- async convertToMCPServerInfo(servers) {
718
- const serverInfos = [];
719
- for (const [serverName, serverConfig] of Object.entries(servers)) {
720
- if (serverConfig && typeof serverConfig === "object") {
721
- let source;
722
- if (serverConfig.url) {
723
- source = extractHostname(serverConfig.url);
724
- } else {
725
- source = serverConfig.command || "";
726
- }
727
- const versionInfo = this.versionDetectionService.analyzeServerVersion(
728
- serverConfig.command || "",
729
- Array.isArray(serverConfig.args) ? serverConfig.args : void 0
730
- );
731
- serverInfos.push({
732
- name: serverName,
733
- command: serverConfig.command || "",
734
- args: Array.isArray(serverConfig.args) ? serverConfig.args : void 0,
735
- transport: serverConfig.type === "streamable-http" ? "http" : serverConfig.type,
736
- // Map streamable-http to http
737
- type: serverConfig.type,
738
- source,
739
- env: serverConfig.env,
740
- headers: serverConfig.headers,
741
- status: "stopped",
742
- // Default status, will be updated by server manager
743
- versionInfo: versionInfo || void 0,
744
- credentials: CredentialDetectionService.analyzeServerConfig({
745
- env: serverConfig.env,
746
- args: serverConfig.args,
747
- headers: serverConfig.headers
748
- })
749
- });
750
- }
751
- }
752
- return serverInfos;
753
- }
754
- /**
755
- * Get friendly name for an app
756
- */
757
- getFriendlyName(appName) {
758
- const friendlyNames = {
759
- claude: "Claude Desktop",
760
- claude_code: "Claude Code",
761
- cursor: "Cursor",
762
- vscode: "VS Code",
763
- cline: "Cline",
764
- windsurf: "Windsurf",
765
- roo: "Roo",
766
- "intellij-github-copilot": "IntelliJ GitHub Copilot",
767
- junie: "IntelliJ Junie",
768
- zed: "Zed",
769
- gemini: "Gemini CLI"
770
- };
771
- return friendlyNames[appName] || appName;
772
- }
385
+ pathRegistry;
386
+ currentOS;
387
+ debug;
388
+ directoryBubbleService;
389
+ versionDetectionService;
390
+ enableDirectoryBubbling;
391
+ constructor(options = {}) {
392
+ this.pathRegistry = new MCPPathRegistry();
393
+ this.currentOS = platform();
394
+ this.debug = util.debuglog("ls-mcp");
395
+ this.directoryBubbleService = new DirectoryBubbleService();
396
+ this.versionDetectionService = new MCPVersionDetectionService();
397
+ this.enableDirectoryBubbling = options.enableDirectoryBubbling ?? false;
398
+ }
399
+ /**
400
+ * Get MCP configuration files for a specific AI application on the current OS
401
+ */
402
+ getConfigFilesPerApp(appName) {
403
+ try {
404
+ return this.pathRegistry.getPathsForApp(this.currentOS, appName);
405
+ } catch (error) {
406
+ throw new Error(`Failed to get config files for app '${appName}': ${error instanceof Error ? error.message : "Unknown error"}`, { cause: error });
407
+ }
408
+ }
409
+ /**
410
+ * Get MCP configuration files for all AI applications on the current OS
411
+ */
412
+ getAllConfigFiles() {
413
+ try {
414
+ return this.pathRegistry.getPathsForOS(this.currentOS);
415
+ } catch (error) {
416
+ throw new Error(`Failed to get all config files: ${error instanceof Error ? error.message : "Unknown error"}`, { cause: error });
417
+ }
418
+ }
419
+ /**
420
+ * Get MCP servers configured for a specific AI application on the current OS
421
+ */
422
+ async getMCPServersPerApp(appName) {
423
+ try {
424
+ const appPaths = this.getConfigFilesPerApp(appName);
425
+ const allServers = [];
426
+ for (const filePath of appPaths) {
427
+ const servers = await this.parseConfigFileForServers(filePath.filePath);
428
+ allServers.push(...servers);
429
+ }
430
+ return allServers;
431
+ } catch (error) {
432
+ throw new Error(`Failed to get MCP servers for app '${appName}': ${error instanceof Error ? error.message : "Unknown error"}`, { cause: error });
433
+ }
434
+ }
435
+ /**
436
+ * Get MCP servers configured for all AI applications on the current OS
437
+ */
438
+ async getAllMCPServers() {
439
+ try {
440
+ const allApps = this.pathRegistry.getSupportedApps(this.currentOS);
441
+ const allServers = {};
442
+ for (const appName of allApps) try {
443
+ allServers[appName] = await this.getMCPServersPerApp(appName);
444
+ } catch (error) {
445
+ this.debug(`Failed to get servers for app '${appName}': ${error instanceof Error ? error.message : "Unknown error"}`);
446
+ allServers[appName] = [];
447
+ }
448
+ return allServers;
449
+ } catch (error) {
450
+ throw new Error(`Failed to get all MCP servers: ${error instanceof Error ? error.message : "Unknown error"}`, { cause: error });
451
+ }
452
+ }
453
+ /**
454
+ * Get metadata for all supported AI applications on the current OS
455
+ */
456
+ getSupportedApps() {
457
+ try {
458
+ const appNames = this.pathRegistry.getSupportedApps(this.currentOS);
459
+ const appPaths = this.pathRegistry.getPathsForOS(this.currentOS);
460
+ return appNames.map((appName) => ({
461
+ name: appName,
462
+ friendlyName: this.getFriendlyName(appName),
463
+ paths: appPaths[appName] || []
464
+ }));
465
+ } catch (error) {
466
+ throw new Error(`Failed to get supported apps: ${error instanceof Error ? error.message : "Unknown error"}`, { cause: error });
467
+ }
468
+ }
469
+ /**
470
+ * Get all supported operating systems
471
+ */
472
+ getSupportedOperatingSystems() {
473
+ return this.pathRegistry.getSupportedOperatingSystems();
474
+ }
475
+ /**
476
+ * Validate if a configuration file exists and is parsable
477
+ */
478
+ async validateConfigFile(filePath) {
479
+ try {
480
+ await fs.access(filePath);
481
+ return await this.createParser(filePath).isValidSyntax();
482
+ } catch {
483
+ return false;
484
+ }
485
+ }
486
+ /**
487
+ * Create a parser instance (can be overridden for testing)
488
+ */
489
+ createParser(filePath) {
490
+ return new MCPConfigParser(filePath);
491
+ }
492
+ /**
493
+ * Get MCP file groups with resolved paths and server information
494
+ */
495
+ async getMCPFileGroups() {
496
+ try {
497
+ const appPaths = this.getAllConfigFiles();
498
+ const mcpFilesPathsData = {};
499
+ for (const groupName of Object.keys(appPaths)) {
500
+ const paths = appPaths[groupName];
501
+ mcpFilesPathsData[groupName] = {
502
+ name: groupName,
503
+ friendlyName: this.getFriendlyName(groupName),
504
+ paths: [],
505
+ stats: { serversCount: 0 }
506
+ };
507
+ const uniqueFilePaths = /* @__PURE__ */ new Set();
508
+ let totalServersCount = 0;
509
+ for (const filePathData of paths) {
510
+ let resolvedPath = filePathData.filePath.replace("~", process.env.HOME || "");
511
+ let absolutePath = path.resolve(resolvedPath);
512
+ if (filePathData.type === "local" && this.enableDirectoryBubbling) try {
513
+ await fs.access(resolvedPath);
514
+ } catch {
515
+ const bubbledPath = await this.directoryBubbleService.findLocalConfigInParentDirectories(filePathData.filePath, process.cwd());
516
+ if (bubbledPath) {
517
+ resolvedPath = bubbledPath;
518
+ absolutePath = path.resolve(resolvedPath);
519
+ }
520
+ }
521
+ if (uniqueFilePaths.has(absolutePath)) continue;
522
+ uniqueFilePaths.add(absolutePath);
523
+ try {
524
+ await fs.access(resolvedPath);
525
+ const parser = this.createParser(resolvedPath);
526
+ const parsable = await parser.isValidSyntax();
527
+ filePathData.parsable = parsable;
528
+ if (parsable) {
529
+ const configData = await parser.parseConfigFile();
530
+ const servers = await this.convertToMCPServerInfo(configData.servers || {});
531
+ filePathData.servers = servers;
532
+ totalServersCount += servers.length;
533
+ }
534
+ mcpFilesPathsData[groupName].paths.push(filePathData);
535
+ } catch (error) {
536
+ this.debug(`Skipping file ${resolvedPath}: ${error instanceof Error ? error.message : "Unknown error"}`);
537
+ }
538
+ }
539
+ if (mcpFilesPathsData[groupName] && mcpFilesPathsData[groupName].stats) mcpFilesPathsData[groupName].stats.serversCount = totalServersCount;
540
+ }
541
+ return mcpFilesPathsData;
542
+ } catch (error) {
543
+ throw new Error(`Failed to get MCP file groups: ${error instanceof Error ? error.message : "Unknown error"}`, { cause: error });
544
+ }
545
+ }
546
+ /**
547
+ * Parse custom configuration files provided by the user
548
+ * This method processes files independently of standard app-based discovery
549
+ */
550
+ async parseCustomFiles(filePaths) {
551
+ try {
552
+ const mcpFilesPathsData = { custom: {
553
+ name: "custom",
554
+ friendlyName: "Custom Files",
555
+ paths: [],
556
+ stats: { serversCount: 0 }
557
+ } };
558
+ let totalServersCount = 0;
559
+ for (const filePath of filePaths) {
560
+ const resolvedPath = filePath.replace("~", process.env.HOME || "");
561
+ const absolutePath = path.resolve(resolvedPath);
562
+ try {
563
+ await fs.access(absolutePath);
564
+ const parser = this.createParser(absolutePath);
565
+ const parsable = await parser.isValidSyntax();
566
+ const filePathData = {
567
+ filePath: absolutePath,
568
+ type: "local",
569
+ parsable
570
+ };
571
+ if (parsable) {
572
+ const configData = await parser.parseConfigFile();
573
+ const servers = await this.convertToMCPServerInfo(configData.servers || {});
574
+ filePathData.servers = servers;
575
+ totalServersCount += servers.length;
576
+ } else {
577
+ this.debug(`File ${absolutePath} has invalid syntax`);
578
+ filePathData.servers = [];
579
+ }
580
+ mcpFilesPathsData.custom.paths.push(filePathData);
581
+ } catch (error) {
582
+ this.debug(`Skipping file ${absolutePath}: ${error instanceof Error ? error.message : "Unknown error"}`);
583
+ mcpFilesPathsData.custom.paths.push({
584
+ filePath: absolutePath,
585
+ type: "local",
586
+ parsable: false,
587
+ servers: []
588
+ });
589
+ }
590
+ }
591
+ if (mcpFilesPathsData.custom.stats) mcpFilesPathsData.custom.stats.serversCount = totalServersCount;
592
+ return mcpFilesPathsData;
593
+ } catch (error) {
594
+ throw new Error(`Failed to parse custom files: ${error instanceof Error ? error.message : "Unknown error"}`, { cause: error });
595
+ }
596
+ }
597
+ /**
598
+ * Register a custom app with custom paths for the current OS
599
+ */
600
+ registerCustomApp(appName, paths) {
601
+ try {
602
+ this.pathRegistry.registerCustomApp(this.currentOS, appName, paths);
603
+ } catch (error) {
604
+ throw new Error(`Failed to register custom app '${appName}': ${error instanceof Error ? error.message : "Unknown error"}`, { cause: error });
605
+ }
606
+ }
607
+ /**
608
+ * Parse a configuration file and return server information
609
+ */
610
+ async parseConfigFileForServers(filePath) {
611
+ try {
612
+ const configData = await this.createParser(filePath).parseConfigFile();
613
+ return await this.convertToMCPServerInfo(configData.servers || {});
614
+ } catch (error) {
615
+ this.debug(`Failed to parse config file ${filePath}: ${error instanceof Error ? error.message : "Unknown error"}`);
616
+ return [];
617
+ }
618
+ }
619
+ /**
620
+ * Convert parsed server configs to MCPServerInfo format
621
+ */
622
+ async convertToMCPServerInfo(servers) {
623
+ const serverInfos = [];
624
+ for (const [serverName, serverConfig] of Object.entries(servers)) if (serverConfig && typeof serverConfig === "object") {
625
+ let source;
626
+ if (serverConfig.url) source = extractHostname(serverConfig.url);
627
+ else source = serverConfig.command || "";
628
+ const versionInfo = this.versionDetectionService.analyzeServerVersion(serverConfig.command || "", Array.isArray(serverConfig.args) ? serverConfig.args : void 0);
629
+ serverInfos.push({
630
+ name: serverName,
631
+ command: serverConfig.command || "",
632
+ args: Array.isArray(serverConfig.args) ? serverConfig.args : void 0,
633
+ transport: serverConfig.type === "streamable-http" ? "http" : serverConfig.type,
634
+ type: serverConfig.type,
635
+ source,
636
+ env: serverConfig.env,
637
+ headers: serverConfig.headers,
638
+ status: "stopped",
639
+ versionInfo: versionInfo || void 0,
640
+ credentials: CredentialDetectionService.analyzeServerConfig({
641
+ env: serverConfig.env,
642
+ args: serverConfig.args,
643
+ headers: serverConfig.headers
644
+ })
645
+ });
646
+ }
647
+ return serverInfos;
648
+ }
649
+ /**
650
+ * Get friendly name for an app
651
+ */
652
+ getFriendlyName(appName) {
653
+ return {
654
+ claude: "Claude Desktop",
655
+ claude_code: "Claude Code",
656
+ cursor: "Cursor",
657
+ vscode: "VS Code",
658
+ cline: "Cline",
659
+ windsurf: "Windsurf",
660
+ roo: "Roo",
661
+ "intellij-github-copilot": "IntelliJ GitHub Copilot",
662
+ junie: "IntelliJ Junie",
663
+ zed: "Zed",
664
+ gemini: "Gemini CLI"
665
+ }[appName] || appName;
666
+ }
773
667
  };
774
-
775
668
  // src/services/mcp-server-manager-service.ts
776
- import path2 from "path";
777
- import { execSync } from "child_process";
778
- import { platform as platform2 } from "os";
779
669
  var MCPServerManagerService = class {
780
- static {
781
- __name(this, "MCPServerManagerService");
782
- }
783
- name;
784
- command;
785
- args;
786
- transport;
787
- source;
788
- env;
789
- running = false;
790
- constructor(serverConfig) {
791
- this.name = serverConfig.name;
792
- this.command = serverConfig.command;
793
- this.args = serverConfig.args || [];
794
- this.transport = serverConfig.transport || "stdio";
795
- if (serverConfig?.type && serverConfig.type === "sse") {
796
- this.transport = "sse";
797
- }
798
- if (serverConfig?.type && (serverConfig.type === "http" || serverConfig.type === "streamable-http")) {
799
- this.transport = "http";
800
- }
801
- if (serverConfig?.type && serverConfig.type === "stdio") {
802
- this.transport = "stdio";
803
- }
804
- if (serverConfig.url) {
805
- this.source = extractHostname(serverConfig.url);
806
- this.transport = "http";
807
- } else {
808
- const fullCommand = [serverConfig.command, ...serverConfig.args || []].join(" ");
809
- this.source = fullCommand;
810
- }
811
- this.env = serverConfig.env || {};
812
- }
813
- getName() {
814
- return this.name;
815
- }
816
- getCmd() {
817
- return this.command;
818
- }
819
- getArgs() {
820
- return this.args;
821
- }
822
- getTransport() {
823
- return this.transport;
824
- }
825
- getSource() {
826
- return this.source;
827
- }
828
- getEnv() {
829
- return this.env;
830
- }
831
- isRunning() {
832
- try {
833
- let psOutput;
834
- if (platform2() === "win32") {
835
- psOutput = execSync('powershell -Command "Get-CimInstance -ClassName Win32_Process | Select-Object ProcessId,Name,CommandLine,ParentProcessId | ConvertTo-Csv -NoTypeInformation"', {
836
- encoding: "utf8",
837
- timeout: 5e3
838
- });
839
- } else {
840
- psOutput = execSync("ps -eao pid,ppid,args", {
841
- encoding: "utf8",
842
- timeout: 5e3
843
- });
844
- }
845
- const processMap = /* @__PURE__ */ new Map();
846
- const processes = psOutput.trim().split("\n");
847
- for (const processLine of processes) {
848
- if (!processLine.trim()) continue;
849
- let pid;
850
- let ppid;
851
- let commandLine;
852
- if (platform2() === "win32") {
853
- if (processLine.startsWith('"ProcessId"') || processLine.startsWith("ProcessId")) continue;
854
- const parts = this.parseCSVLine(processLine);
855
- if (parts.length < 4) continue;
856
- pid = parts[0].trim() || "";
857
- commandLine = parts[2].trim() || "";
858
- ppid = parts[3].trim() || "";
859
- } else {
860
- const match = processLine.trim().match(/^\s*(\d+)\s+(\d+)\s+(.+)$/);
861
- if (!match) continue;
862
- pid = match[1].trim() || "";
863
- ppid = match[2].trim() || "";
864
- commandLine = match[3].trim() || "";
865
- }
866
- const commandTokens = this.parseCommandLine(commandLine);
867
- if (commandTokens.length > 0) {
868
- processMap.set(pid, { ppid, commandTokens });
869
- }
870
- }
871
- let mcpServerDetection;
872
- for (const [pid, processData] of processMap) {
873
- const commandMatchLinux = this.isCommandMatch(processData.commandTokens, pid, processData.ppid);
874
- let commandMatchWin32 = false;
875
- if (platform2() === "win32") {
876
- let commandTokensOnWin32 = processData.commandTokens;
877
- if (commandTokensOnWin32.length > 0 && commandTokensOnWin32[0].toLowerCase().startsWith("cmd")) {
878
- commandTokensOnWin32 = commandTokensOnWin32.slice(1);
879
- while (commandTokensOnWin32.length > 0 && commandTokensOnWin32[0].startsWith("/")) {
880
- commandTokensOnWin32 = commandTokensOnWin32.slice(1);
881
- }
882
- }
883
- commandMatchWin32 = this.isCommandMatch(commandTokensOnWin32, pid, processData.ppid);
884
- }
885
- const commandMatch = commandMatchLinux || commandMatchWin32;
886
- if (commandMatch) {
887
- mcpServerDetection = {
888
- pid,
889
- commandLine: processData.commandTokens.join(" "),
890
- ppid: processData.ppid
891
- };
892
- const parentProcess = processMap.get(processData.ppid);
893
- if (parentProcess) {
894
- const { estimatedVendor, estimatedProduct } = this.getVendorFromCommand(parentProcess.commandTokens) || {};
895
- if (estimatedProduct || estimatedVendor) {
896
- mcpServerDetection = {
897
- ...mcpServerDetection,
898
- parentCommandLine: parentProcess.commandTokens.join(" "),
899
- estimatedVendor,
900
- estimatedProduct
901
- };
902
- return mcpServerDetection;
903
- }
904
- }
905
- }
906
- }
907
- if (mcpServerDetection) {
908
- return mcpServerDetection;
909
- }
910
- return false;
911
- } catch (error) {
912
- return false;
913
- }
914
- }
915
- getVendorFromCommand(commandTokens) {
916
- const commandString = commandTokens.join(" ").toLowerCase();
917
- if (commandString.includes("claude.app")) {
918
- return {
919
- estimatedVendor: "anthropic",
920
- estimatedProduct: "claude-desktop"
921
- };
922
- }
923
- if (commandString.includes("claude")) {
924
- return {
925
- estimatedVendor: "anthropic",
926
- estimatedProduct: "claude-desktop"
927
- };
928
- }
929
- if (commandString.includes("cursor")) {
930
- return {
931
- estimatedVendor: "cursor",
932
- estimatedProduct: "cursor"
933
- };
934
- }
935
- if (commandString.includes("visual studio code") || commandString.includes("vscode")) {
936
- return {
937
- estimatedVendor: "vscode",
938
- estimatedProduct: "vscode"
939
- };
940
- }
941
- }
942
- isCommandMatch(commandTokens, pid, ppid) {
943
- if (commandTokens.length === 0) return false;
944
- const baseCommand = this.getBaseCommand(commandTokens[0]);
945
- const commandInConfig = this.getBaseCommand(this.command);
946
- if (commandInConfig === "uvx" && baseCommand === "uv") {
947
- return this.matchUvxProcess(commandTokens);
948
- }
949
- if (commandInConfig === "npx" && baseCommand === "npm") {
950
- return this.matchNpxProcess(commandTokens);
951
- }
952
- if (commandInConfig === "uv" && baseCommand === "uv") {
953
- return this.matchGenericArgsToArgs(commandTokens);
954
- }
955
- const commandConfigPythonBase = this.getBaseCommand(this.command);
956
- const commandAliasesPython = ["python3", "python", "python3.10", "python3.11", "python3.12", "cpython3", "cpython", "python3", "python2"];
957
- if (commandAliasesPython.includes(commandConfigPythonBase) && commandAliasesPython.includes(baseCommand)) {
958
- return this.matchGenericArgsToArgs(commandTokens);
959
- }
960
- const commandGenericBase = this.getBaseCommand(this.command);
961
- const commandGenericProcessBase = this.getBaseCommand(commandTokens[0]);
962
- if (commandGenericBase === commandGenericProcessBase) {
963
- return this.matchGenericArgsToArgs(commandTokens);
964
- }
965
- return false;
966
- }
967
- matchGenericArgsToArgs(commandTokens) {
968
- if (this.args.length === 0) {
969
- return commandTokens[0] === this.command;
970
- }
971
- if (commandTokens.length < 2) {
972
- return false;
973
- }
974
- const commandWithoutArgs = commandTokens.slice(1);
975
- for (let i = 0; i < this.args.length; i++) {
976
- if (i >= commandWithoutArgs.length) return false;
977
- const arg = this.args[i].toLowerCase();
978
- const token = commandWithoutArgs[i].toLowerCase();
979
- if (arg !== token && !token.includes(arg)) {
980
- return false;
981
- }
982
- }
983
- return true;
984
- }
985
- getBaseCommand(fullCommandPath) {
986
- let baseCommand = path2.basename(fullCommandPath);
987
- if (platform2() === "win32") {
988
- baseCommand = path2.basename(fullCommandPath, ".exe");
989
- }
990
- baseCommand = baseCommand.toLowerCase();
991
- return baseCommand;
992
- }
993
- /*
994
- example1:
995
- ```
996
- "command": "uvx",
997
- "args": ["--from", "mcp-alchemy==2025.5.2.210242", "--with", "oracledb",
998
- "--refresh-package", "mcp-alchemy", "mcp-alchemy"],
999
- ```
1000
-
1001
- example 2:
1002
- ```
1003
- "command": "uvx",
1004
- "args": [
1005
- "mcp-neo4j-memory@0.1.4",
1006
- "--db-url",
1007
- "neo4j+s://xxxx.databases.neo4j.io",
1008
- "--username",
1009
- "<your-username>",
1010
- "--password",
1011
- "<your-password>"
1012
- ]
1013
- ```
1014
-
1015
- example 3:
1016
- ```
1017
- "vefaas": {
1018
- "command": "uvx",
1019
- "args": [
1020
- "--from",
1021
- "git+https://github.com/volcengine/mcp-server#subdirectory=server/mcp_server_vefaas_function",
1022
- "mcp-server-vefaas-function"
1023
- ],
1024
- "env": {
1025
- "VOLC_ACCESSKEY": "xxx",
1026
- "VOLC_SECRETKEY": "xxx"
1027
- }
1028
- }
1029
- }
1030
- ```
1031
-
1032
- example 4:
1033
- ```
1034
- "time": {
1035
- "command": "uvx",
1036
- "args": ["mcp-server-time", "--local-timezone=America/New_York"]
1037
- }
1038
- ```
1039
- */
1040
- getUvxMcpServerNameFromArgs() {
1041
- if (this.args.length === 0) return void 0;
1042
- let mcpServerName;
1043
- if (this.args.length === 1) {
1044
- mcpServerName = this.args[0];
1045
- return mcpServerName;
1046
- }
1047
- for (let i = 0; i < this.args.length; i++) {
1048
- if (this.args[i] === "--from" && i + 1 < this.args.length) {
1049
- mcpServerName = this.args[i + 1];
1050
- return mcpServerName;
1051
- }
1052
- }
1053
- const firstArg = this.args[0];
1054
- if (firstArg.startsWith("-") || firstArg.startsWith("--")) {
1055
- const lastArg = this.args[this.args.length - 1];
1056
- mcpServerName = lastArg;
1057
- return mcpServerName;
1058
- }
1059
- mcpServerName = firstArg;
1060
- return mcpServerName;
1061
- }
1062
- matchUvxProcess(commandTokens) {
1063
- if (commandTokens.length === 0) return false;
1064
- const mcpServerName = this.getUvxMcpServerNameFromArgs();
1065
- if (!mcpServerName) return false;
1066
- return this.findMcpServerNameInProcessArguments(commandTokens, mcpServerName);
1067
- }
1068
- findMcpServerNameInProcessArguments(commandTokens, mcpServerName) {
1069
- for (let i = 0; i < commandTokens.length; i++) {
1070
- const token = commandTokens[i].toLowerCase();
1071
- const normalizedMcpServerName = mcpServerName.toLowerCase();
1072
- if (normalizedMcpServerName === token || token.includes(normalizedMcpServerName)) {
1073
- return true;
1074
- }
1075
- }
1076
- return false;
1077
- }
1078
- parseCSVLine(line) {
1079
- const result = [];
1080
- let current = "";
1081
- let inQuotes = false;
1082
- for (let i = 0; i < line.length; i++) {
1083
- const char = line[i];
1084
- if (char === '"') {
1085
- if (inQuotes && line[i + 1] === '"') {
1086
- current += '"';
1087
- i++;
1088
- } else {
1089
- inQuotes = !inQuotes;
1090
- }
1091
- } else if (char === "," && !inQuotes) {
1092
- result.push(current);
1093
- current = "";
1094
- } else {
1095
- current += char;
1096
- }
1097
- }
1098
- result.push(current);
1099
- return result;
1100
- }
1101
- parseCommandLine(commandLine) {
1102
- const tokens = [];
1103
- let current = "";
1104
- let inQuotes = false;
1105
- let quoteChar = "";
1106
- for (let i = 0; i < commandLine.length; i++) {
1107
- const char = commandLine[i];
1108
- if (!inQuotes && (char === '"' || char === "'")) {
1109
- inQuotes = true;
1110
- quoteChar = char;
1111
- } else if (inQuotes && char === quoteChar) {
1112
- inQuotes = false;
1113
- quoteChar = "";
1114
- } else if (!inQuotes && char === " ") {
1115
- if (current.trim()) {
1116
- tokens.push(current.trim());
1117
- current = "";
1118
- }
1119
- } else {
1120
- current += char;
1121
- }
1122
- }
1123
- if (current.trim()) {
1124
- tokens.push(current.trim());
1125
- }
1126
- return tokens;
1127
- }
1128
- /*
1129
- example to match:
1130
- ```
1131
- "command": "npx",
1132
- "args": [
1133
- "-y",
1134
- "@modelcontextprotocol/server-postgres",
1135
- "postgresql://localhost/mydb"
1136
- ]
1137
- }
1138
- ```
1139
-
1140
- with a process command like:
1141
- ```
1142
- npm exec @modelcontextprotocol/server-postgres postgresql://localhost/mydb
1143
- ```
1144
- */
1145
- matchNpxProcess(commandTokens) {
1146
- if (commandTokens.length < 3) return false;
1147
- if (commandTokens[1] !== "exec") return false;
1148
- let argsToMatch = [];
1149
- const yIndex = this.args.indexOf("-y");
1150
- if (yIndex !== -1 && yIndex + 1 < this.args.length) {
1151
- argsToMatch = this.args.slice(yIndex + 1);
1152
- } else {
1153
- argsToMatch = this.args;
1154
- }
1155
- if (commandTokens.length - 2 !== argsToMatch.length) {
1156
- return false;
1157
- }
1158
- for (let i = 0; i < argsToMatch.length; i++) {
1159
- const commandToken = commandTokens[i + 2].toLowerCase();
1160
- const expectedArg = argsToMatch[i].toLowerCase();
1161
- if (commandToken !== expectedArg) {
1162
- return false;
1163
- }
1164
- }
1165
- return true;
1166
- }
670
+ name;
671
+ command;
672
+ args;
673
+ transport;
674
+ source;
675
+ env;
676
+ running = false;
677
+ constructor(serverConfig) {
678
+ this.name = serverConfig.name;
679
+ this.command = serverConfig.command;
680
+ this.args = serverConfig.args || [];
681
+ this.transport = serverConfig.transport || "stdio";
682
+ if (serverConfig?.type && serverConfig.type === "sse") this.transport = "sse";
683
+ if (serverConfig?.type && (serverConfig.type === "http" || serverConfig.type === "streamable-http")) this.transport = "http";
684
+ if (serverConfig?.type && serverConfig.type === "stdio") this.transport = "stdio";
685
+ if (serverConfig.url) {
686
+ this.source = extractHostname(serverConfig.url);
687
+ this.transport = "http";
688
+ } else {
689
+ const fullCommand = [serverConfig.command, ...serverConfig.args || []].join(" ");
690
+ this.source = fullCommand;
691
+ }
692
+ this.env = serverConfig.env || {};
693
+ }
694
+ getName() {
695
+ return this.name;
696
+ }
697
+ getCmd() {
698
+ return this.command;
699
+ }
700
+ getArgs() {
701
+ return this.args;
702
+ }
703
+ getTransport() {
704
+ return this.transport;
705
+ }
706
+ getSource() {
707
+ return this.source;
708
+ }
709
+ getEnv() {
710
+ return this.env;
711
+ }
712
+ isRunning() {
713
+ try {
714
+ let psOutput;
715
+ if (platform() === "win32") psOutput = execSync("powershell -Command \"Get-CimInstance -ClassName Win32_Process | Select-Object ProcessId,Name,CommandLine,ParentProcessId | ConvertTo-Csv -NoTypeInformation\"", {
716
+ encoding: "utf8",
717
+ timeout: 5e3
718
+ });
719
+ else psOutput = execSync("ps -eao pid,ppid,args", {
720
+ encoding: "utf8",
721
+ timeout: 5e3
722
+ });
723
+ const processMap = /* @__PURE__ */ new Map();
724
+ const processes = psOutput.trim().split("\n");
725
+ for (const processLine of processes) {
726
+ if (!processLine.trim()) continue;
727
+ let pid;
728
+ let ppid;
729
+ let commandLine;
730
+ if (platform() === "win32") {
731
+ if (processLine.startsWith("\"ProcessId\"") || processLine.startsWith("ProcessId")) continue;
732
+ const parts = this.parseCSVLine(processLine);
733
+ if (parts.length < 4) continue;
734
+ pid = parts[0].trim() || "";
735
+ commandLine = parts[2].trim() || "";
736
+ ppid = parts[3].trim() || "";
737
+ } else {
738
+ const match = processLine.trim().match(/^\s*(\d+)\s+(\d+)\s+(.+)$/);
739
+ if (!match) continue;
740
+ pid = match[1].trim() || "";
741
+ ppid = match[2].trim() || "";
742
+ commandLine = match[3].trim() || "";
743
+ }
744
+ const commandTokens = this.parseCommandLine(commandLine);
745
+ if (commandTokens.length > 0) processMap.set(pid, {
746
+ ppid,
747
+ commandTokens
748
+ });
749
+ }
750
+ let mcpServerDetection;
751
+ for (const [pid, processData] of processMap) {
752
+ const commandMatchLinux = this.isCommandMatch(processData.commandTokens);
753
+ let commandMatchWin32 = false;
754
+ if (platform() === "win32") {
755
+ let commandTokensOnWin32 = processData.commandTokens;
756
+ if (commandTokensOnWin32.length > 0 && commandTokensOnWin32[0].toLowerCase().startsWith("cmd")) {
757
+ commandTokensOnWin32 = commandTokensOnWin32.slice(1);
758
+ while (commandTokensOnWin32.length > 0 && commandTokensOnWin32[0].startsWith("/")) commandTokensOnWin32 = commandTokensOnWin32.slice(1);
759
+ }
760
+ commandMatchWin32 = this.isCommandMatch(commandTokensOnWin32);
761
+ }
762
+ if (commandMatchLinux || commandMatchWin32) {
763
+ mcpServerDetection = {
764
+ pid,
765
+ commandLine: processData.commandTokens.join(" "),
766
+ ppid: processData.ppid
767
+ };
768
+ const parentProcess = processMap.get(processData.ppid);
769
+ if (parentProcess) {
770
+ const { estimatedVendor, estimatedProduct } = this.getVendorFromCommand(parentProcess.commandTokens) || {};
771
+ if (estimatedProduct || estimatedVendor) {
772
+ mcpServerDetection = {
773
+ ...mcpServerDetection,
774
+ parentCommandLine: parentProcess.commandTokens.join(" "),
775
+ estimatedVendor,
776
+ estimatedProduct
777
+ };
778
+ return mcpServerDetection;
779
+ }
780
+ }
781
+ }
782
+ }
783
+ if (mcpServerDetection) return mcpServerDetection;
784
+ return false;
785
+ } catch {
786
+ return false;
787
+ }
788
+ }
789
+ getVendorFromCommand(commandTokens) {
790
+ const commandString = commandTokens.join(" ").toLowerCase();
791
+ if (commandString.includes("claude.app")) return {
792
+ estimatedVendor: "anthropic",
793
+ estimatedProduct: "claude-desktop"
794
+ };
795
+ if (commandString.includes("claude")) return {
796
+ estimatedVendor: "anthropic",
797
+ estimatedProduct: "claude-desktop"
798
+ };
799
+ if (commandString.includes("cursor")) return {
800
+ estimatedVendor: "cursor",
801
+ estimatedProduct: "cursor"
802
+ };
803
+ if (commandString.includes("visual studio code") || commandString.includes("vscode")) return {
804
+ estimatedVendor: "vscode",
805
+ estimatedProduct: "vscode"
806
+ };
807
+ }
808
+ isCommandMatch(commandTokens) {
809
+ if (commandTokens.length === 0) return false;
810
+ const baseCommand = this.getBaseCommand(commandTokens[0]);
811
+ const commandInConfig = this.getBaseCommand(this.command);
812
+ if (commandInConfig === "uvx" && baseCommand === "uv") return this.matchUvxProcess(commandTokens);
813
+ if (commandInConfig === "npx" && baseCommand === "npm") return this.matchNpxProcess(commandTokens);
814
+ if (commandInConfig === "uv" && baseCommand === "uv") return this.matchGenericArgsToArgs(commandTokens);
815
+ const commandConfigPythonBase = this.getBaseCommand(this.command);
816
+ const commandAliasesPython = [
817
+ "python3",
818
+ "python",
819
+ "python3.10",
820
+ "python3.11",
821
+ "python3.12",
822
+ "cpython3",
823
+ "cpython",
824
+ "python3",
825
+ "python2"
826
+ ];
827
+ if (commandAliasesPython.includes(commandConfigPythonBase) && commandAliasesPython.includes(baseCommand)) return this.matchGenericArgsToArgs(commandTokens);
828
+ if (this.getBaseCommand(this.command) === this.getBaseCommand(commandTokens[0])) return this.matchGenericArgsToArgs(commandTokens);
829
+ return false;
830
+ }
831
+ matchGenericArgsToArgs(commandTokens) {
832
+ if (this.args.length === 0) return commandTokens[0] === this.command;
833
+ if (commandTokens.length < 2) return false;
834
+ const commandWithoutArgs = commandTokens.slice(1);
835
+ for (let i = 0; i < this.args.length; i++) {
836
+ if (i >= commandWithoutArgs.length) return false;
837
+ const arg = this.args[i].toLowerCase();
838
+ const token = commandWithoutArgs[i].toLowerCase();
839
+ if (arg !== token && !token.includes(arg)) return false;
840
+ }
841
+ return true;
842
+ }
843
+ getBaseCommand(fullCommandPath) {
844
+ let baseCommand = path.basename(fullCommandPath);
845
+ if (platform() === "win32") baseCommand = path.basename(fullCommandPath, ".exe");
846
+ baseCommand = baseCommand.toLowerCase();
847
+ return baseCommand;
848
+ }
849
+ getUvxMcpServerNameFromArgs() {
850
+ if (this.args.length === 0) return void 0;
851
+ let mcpServerName;
852
+ if (this.args.length === 1) {
853
+ mcpServerName = this.args[0];
854
+ return mcpServerName;
855
+ }
856
+ for (let i = 0; i < this.args.length; i++) if (this.args[i] === "--from" && i + 1 < this.args.length) {
857
+ mcpServerName = this.args[i + 1];
858
+ return mcpServerName;
859
+ }
860
+ const firstArg = this.args[0];
861
+ if (firstArg.startsWith("-") || firstArg.startsWith("--")) {
862
+ mcpServerName = this.args[this.args.length - 1];
863
+ return mcpServerName;
864
+ }
865
+ mcpServerName = firstArg;
866
+ return mcpServerName;
867
+ }
868
+ matchUvxProcess(commandTokens) {
869
+ if (commandTokens.length === 0) return false;
870
+ const mcpServerName = this.getUvxMcpServerNameFromArgs();
871
+ if (!mcpServerName) return false;
872
+ return this.findMcpServerNameInProcessArguments(commandTokens, mcpServerName);
873
+ }
874
+ findMcpServerNameInProcessArguments(commandTokens, mcpServerName) {
875
+ for (let i = 0; i < commandTokens.length; i++) {
876
+ const token = commandTokens[i].toLowerCase();
877
+ const normalizedMcpServerName = mcpServerName.toLowerCase();
878
+ if (normalizedMcpServerName === token || token.includes(normalizedMcpServerName)) return true;
879
+ }
880
+ return false;
881
+ }
882
+ parseCSVLine(line) {
883
+ const result = [];
884
+ let current = "";
885
+ let inQuotes = false;
886
+ for (let i = 0; i < line.length; i++) {
887
+ const char = line[i];
888
+ if (char === "\"") {
889
+ if (inQuotes && line[i + 1] === "\"") {
890
+ current += "\"";
891
+ i++;
892
+ } else inQuotes = !inQuotes;
893
+ } else if (char === "," && !inQuotes) {
894
+ result.push(current);
895
+ current = "";
896
+ } else current += char;
897
+ }
898
+ result.push(current);
899
+ return result;
900
+ }
901
+ parseCommandLine(commandLine) {
902
+ const tokens = [];
903
+ let current = "";
904
+ let inQuotes = false;
905
+ let quoteChar = "";
906
+ for (let i = 0; i < commandLine.length; i++) {
907
+ const char = commandLine[i];
908
+ if (!inQuotes && (char === "\"" || char === "'")) {
909
+ inQuotes = true;
910
+ quoteChar = char;
911
+ } else if (inQuotes && char === quoteChar) {
912
+ inQuotes = false;
913
+ quoteChar = "";
914
+ } else if (!inQuotes && char === " ") {
915
+ if (current.trim()) {
916
+ tokens.push(current.trim());
917
+ current = "";
918
+ }
919
+ } else current += char;
920
+ }
921
+ if (current.trim()) tokens.push(current.trim());
922
+ return tokens;
923
+ }
924
+ matchNpxProcess(commandTokens) {
925
+ if (commandTokens.length < 3) return false;
926
+ if (commandTokens[1] !== "exec") return false;
927
+ let argsToMatch;
928
+ const yIndex = this.args.indexOf("-y");
929
+ if (yIndex !== -1 && yIndex + 1 < this.args.length) argsToMatch = this.args.slice(yIndex + 1);
930
+ else argsToMatch = this.args;
931
+ if (commandTokens.length - 2 !== argsToMatch.length) return false;
932
+ for (let i = 0; i < argsToMatch.length; i++) if (commandTokens[i + 2].toLowerCase() !== argsToMatch[i].toLowerCase()) return false;
933
+ return true;
934
+ }
1167
935
  };
1168
-
1169
936
  // src/main.ts
1170
937
  var MCPFiles = class {
1171
- static {
1172
- __name(this, "MCPFiles");
1173
- }
1174
- mcpConfigService;
1175
- customFiles;
1176
- constructor(customFiles) {
1177
- this.mcpConfigService = new MCPConfigService({ enableDirectoryBubbling: true });
1178
- this.customFiles = customFiles;
1179
- }
1180
- /**
1181
- * Find and process all MCP configuration files
1182
- * If customFiles are provided, only those files are processed (replaces automatic discovery)
1183
- */
1184
- async findFiles() {
1185
- try {
1186
- if (this.customFiles && this.customFiles.length > 0) {
1187
- const mcpFilesPathsData2 = await this.mcpConfigService.parseCustomFiles(this.customFiles);
1188
- for (const groupName of Object.keys(mcpFilesPathsData2)) {
1189
- const group = mcpFilesPathsData2[groupName];
1190
- for (const filePathData of group.paths) {
1191
- if (filePathData.servers && filePathData.servers.length > 0) {
1192
- for (const server of filePathData.servers) {
1193
- const serverConfig = {
1194
- name: server.name,
1195
- command: server.command,
1196
- args: server.args,
1197
- transport: server.transport,
1198
- type: server.type,
1199
- env: server.env
1200
- };
1201
- const serverManager = new MCPServerManagerService(serverConfig);
1202
- const processDetection = serverManager.isRunning();
1203
- let isRunning = false;
1204
- if (processDetection) {
1205
- if (typeof processDetection === "object" && processDetection.estimatedProduct === group.name) {
1206
- isRunning = true;
1207
- }
1208
- }
1209
- server.status = isRunning ? "running" : "stopped";
1210
- }
1211
- }
1212
- }
1213
- }
1214
- return mcpFilesPathsData2;
1215
- }
1216
- const mcpFilesPathsData = await this.mcpConfigService.getMCPFileGroups();
1217
- for (const groupName of Object.keys(mcpFilesPathsData)) {
1218
- const group = mcpFilesPathsData[groupName];
1219
- for (const filePathData of group.paths) {
1220
- if (filePathData.servers && filePathData.servers.length > 0) {
1221
- for (const server of filePathData.servers) {
1222
- const serverConfig = {
1223
- name: server.name,
1224
- command: server.command,
1225
- args: server.args,
1226
- transport: server.transport,
1227
- // transport is always populated from type in the data layer
1228
- type: server.type,
1229
- env: server.env
1230
- };
1231
- const serverManager = new MCPServerManagerService(serverConfig);
1232
- const processDetection = serverManager.isRunning();
1233
- let isRunning = false;
1234
- if (processDetection) {
1235
- if (typeof processDetection === "object" && processDetection.estimatedProduct === group.name) {
1236
- isRunning = true;
1237
- }
1238
- }
1239
- server.status = isRunning ? "running" : "stopped";
1240
- }
1241
- }
1242
- }
1243
- }
1244
- return mcpFilesPathsData;
1245
- } catch (error) {
1246
- throw new Error(`Failed to find MCP files: ${error instanceof Error ? error.message : "Unknown error"}`);
1247
- }
1248
- }
1249
- /**
1250
- * Get MCP configuration service instance for advanced operations
1251
- */
1252
- getMCPConfigService() {
1253
- return this.mcpConfigService;
1254
- }
1255
- };
1256
- export {
1257
- MCPFiles
938
+ mcpConfigService;
939
+ customFiles;
940
+ constructor(customFiles) {
941
+ this.mcpConfigService = new MCPConfigService({ enableDirectoryBubbling: true });
942
+ this.customFiles = customFiles;
943
+ }
944
+ /**
945
+ * Find and process all MCP configuration files
946
+ * If customFiles are provided, only those files are processed (replaces automatic discovery)
947
+ */
948
+ async findFiles() {
949
+ try {
950
+ if (this.customFiles && this.customFiles.length > 0) {
951
+ const mcpFilesPathsData = await this.mcpConfigService.parseCustomFiles(this.customFiles);
952
+ for (const groupName of Object.keys(mcpFilesPathsData)) {
953
+ const group = mcpFilesPathsData[groupName];
954
+ for (const filePathData of group.paths) if (filePathData.servers && filePathData.servers.length > 0) for (const server of filePathData.servers) {
955
+ const processDetection = new MCPServerManagerService({
956
+ name: server.name,
957
+ command: server.command,
958
+ args: server.args,
959
+ transport: server.transport,
960
+ type: server.type,
961
+ env: server.env
962
+ }).isRunning();
963
+ let isRunning = false;
964
+ if (processDetection) {
965
+ if (typeof processDetection === "object" && processDetection.estimatedProduct === group.name) isRunning = true;
966
+ }
967
+ server.status = isRunning ? "running" : "stopped";
968
+ }
969
+ }
970
+ return mcpFilesPathsData;
971
+ }
972
+ const mcpFilesPathsData = await this.mcpConfigService.getMCPFileGroups();
973
+ for (const groupName of Object.keys(mcpFilesPathsData)) {
974
+ const group = mcpFilesPathsData[groupName];
975
+ for (const filePathData of group.paths) if (filePathData.servers && filePathData.servers.length > 0) for (const server of filePathData.servers) {
976
+ const processDetection = new MCPServerManagerService({
977
+ name: server.name,
978
+ command: server.command,
979
+ args: server.args,
980
+ transport: server.transport,
981
+ type: server.type,
982
+ env: server.env
983
+ }).isRunning();
984
+ let isRunning = false;
985
+ if (processDetection) {
986
+ if (typeof processDetection === "object" && processDetection.estimatedProduct === group.name) isRunning = true;
987
+ }
988
+ server.status = isRunning ? "running" : "stopped";
989
+ }
990
+ }
991
+ return mcpFilesPathsData;
992
+ } catch (error) {
993
+ throw new Error(`Failed to find MCP files: ${error instanceof Error ? error.message : "Unknown error"}`, { cause: error });
994
+ }
995
+ }
996
+ /**
997
+ * Get MCP configuration service instance for advanced operations
998
+ */
999
+ getMCPConfigService() {
1000
+ return this.mcpConfigService;
1001
+ }
1258
1002
  };
1003
+ export { MCPFiles };