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