ls-mcp 1.2.0 → 1.3.1

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.
@@ -1,3 +1,6 @@
1
+ import { execSync } from 'node:child_process'
2
+ import { platform } from 'node:os'
3
+
1
4
  interface MCPServerConfig {
2
5
  name: string
3
6
  command: string
@@ -6,13 +9,21 @@ interface MCPServerConfig {
6
9
  env?: Record<string, string>
7
10
  }
8
11
 
12
+ interface MatchedProcess {
13
+ pid: string
14
+ commandLine: string
15
+ ppid?: string
16
+ parentCommandLine?: string
17
+ estimatedVendor?: string
18
+ estimatedProduct?: string
19
+ }
20
+
9
21
  export class MCPServerManagerService {
10
22
  private name: string
11
23
  private command: string
12
24
  private args: string[]
13
25
  private transport?: 'stdio' | 'sse'
14
26
  private env?: Record<string, string>
15
-
16
27
  private running: boolean = false
17
28
 
18
29
  constructor (serverConfig: MCPServerConfig) {
@@ -43,7 +54,440 @@ export class MCPServerManagerService {
43
54
  return this.env
44
55
  }
45
56
 
46
- isRunning (): boolean {
47
- return this.running
57
+ isRunning (): boolean | MatchedProcess {
58
+ try {
59
+ let psOutput: string
60
+
61
+ if (platform() === 'win32') {
62
+ // Windows: Use PowerShell Get-CimInstance to get process info
63
+ psOutput = execSync('powershell -Command "Get-CimInstance -ClassName Win32_Process | Select-Object ProcessId,Name,CommandLine,ParentProcessId | ConvertTo-Csv -NoTypeInformation"', {
64
+ encoding: 'utf8',
65
+ timeout: 5000
66
+ })
67
+ } else {
68
+ // Unix/Linux/macOS: Use ps command with pid, ppid, and args
69
+ psOutput = execSync('ps -eao pid,ppid,args', {
70
+ encoding: 'utf8',
71
+ timeout: 5000
72
+ })
73
+ }
74
+
75
+ const processMap = new Map<string, { ppid: string, commandTokens: string[] }>()
76
+ const processes = psOutput.trim().split('\n')
77
+
78
+ for (const processLine of processes) {
79
+ if (!processLine.trim()) continue
80
+
81
+ let pid: string
82
+ let ppid: string
83
+ let commandLine: string
84
+
85
+ if (platform() === 'win32') {
86
+ // Parse Windows CSV format: ProcessId,Name,CommandLine,ParentProcessId
87
+ // Skip header line
88
+ if (processLine.startsWith('"ProcessId"') || processLine.startsWith('ProcessId')) continue
89
+
90
+ const parts = this.parseCSVLine(processLine)
91
+ if (parts.length < 4) continue
92
+ pid = parts[0] || ''
93
+ // Skip Name (parts[1])
94
+ commandLine = parts[2] || ''
95
+ ppid = parts[3] || ''
96
+ } else {
97
+ // Parse Unix ps output: PID PPID COMMAND
98
+ const match = processLine.trim().match(/^\s*(\d+)\s+(\d+)\s+(.+)$/)
99
+ if (!match) continue
100
+ pid = match[1]
101
+ ppid = match[2]
102
+ commandLine = match[3]
103
+ }
104
+
105
+ // Parse command line and store in map
106
+ const commandTokens = this.parseCommandLine(commandLine)
107
+ if (commandTokens.length > 0) {
108
+ processMap.set(pid, { ppid, commandTokens })
109
+ }
110
+ }
111
+
112
+ // Then iterate the map to check for matches
113
+ let mcpServerDetection: MatchedProcess | undefined
114
+ for (const [pid, processData] of processMap) {
115
+ if (this.isCommandMatch(processData.commandTokens, pid, processData.ppid)) {
116
+ mcpServerDetection = {
117
+ pid,
118
+ commandLine: processData.commandTokens.join(' '),
119
+ ppid: processData.ppid,
120
+ }
121
+
122
+ // if we matched the command let's extract the parent command information
123
+ const parentProcess = processMap.get(processData.ppid)
124
+ if (parentProcess) {
125
+ const { estimatedVendor, estimatedProduct } = this.getVendorFromCommand(parentProcess.commandTokens) || {}
126
+
127
+ if (estimatedProduct || estimatedVendor) {
128
+ mcpServerDetection = {
129
+ ...mcpServerDetection,
130
+ parentCommandLine: parentProcess.commandTokens.join(' '),
131
+ estimatedVendor,
132
+ estimatedProduct
133
+ }
134
+
135
+ return mcpServerDetection
136
+ }
137
+ }
138
+ }
139
+ }
140
+
141
+ if (mcpServerDetection) {
142
+ return mcpServerDetection
143
+ }
144
+
145
+ return false
146
+ } catch (error) {
147
+ return false
148
+ }
149
+ }
150
+
151
+ private getVendorFromCommand (commandTokens: string[]): { estimatedVendor: string, estimatedProduct: string } | undefined {
152
+ // match based on known vendor patterns in the command string
153
+ const commandString = commandTokens.join(' ').toLowerCase()
154
+ if (commandString.includes('claude.app')) {
155
+ return {
156
+ estimatedVendor: 'anthropic',
157
+ estimatedProduct: 'claude-desktop'
158
+ }
159
+ }
160
+
161
+ if (commandString.includes('claude')) {
162
+ return {
163
+ estimatedVendor: 'anthropic',
164
+ estimatedProduct: 'claude-desktop'
165
+ }
166
+ }
167
+ }
168
+
169
+ private isCommandMatch (commandTokens: string[], pid: string, ppid: string): boolean {
170
+ // If no command tokens, cannot match
171
+ if (commandTokens.length === 0) return false
172
+
173
+ // Extracts the base command from the full command path of the process output list
174
+ // e.g. "/usr/homebrew/bin/uv" extracted to "uv"
175
+ const baseCommand = this.getBaseCommand(commandTokens[0])
176
+
177
+ // Map configured command to actual process command for uvx case
178
+ if (this.command === 'uvx' && baseCommand === 'uv') {
179
+ return this.matchUvxProcess(commandTokens)
180
+ }
181
+
182
+ // Map configured command to actual process command for npx case
183
+ if (this.command === 'npx' && baseCommand === 'npm') {
184
+ return this.matchNpxProcess(commandTokens)
185
+ }
186
+
187
+ /*
188
+ example config:
189
+ "test_server_2": {
190
+ "command": "uv",
191
+ "args": [
192
+ "--directory",
193
+ "/Users/lirantal/projects/repos/example-python-mcp-server",
194
+ "run",
195
+ "test-server.py"
196
+ ]
197
+ },
198
+ */
199
+ if (this.command === 'uv' && baseCommand === 'uv') {
200
+ return this.matchGenericArgsToArgs(commandTokens)
201
+ }
202
+
203
+ // Python Generic commands matching
204
+ /*
205
+ example config:
206
+ "test_server": {
207
+ "command": "/Users/lirantal/projects/repos/example-python-mcp-server/.venv/bin/python",
208
+ "args": [
209
+ "/Users/lirantal/projects/repos/example-python-mcp-server/test-server.py"
210
+ ]
211
+ }
212
+ */
213
+ const commandConfigPythonBase: string = this.getBaseCommand(this.command)
214
+ const commandAliasesPython = ['python3', 'python', 'python3.10', 'python3.11', 'python3.12', 'cpython3', 'cpython', 'python3', 'python2']
215
+ if (commandAliasesPython.includes(commandConfigPythonBase) && commandAliasesPython.includes(baseCommand)) {
216
+ return this.matchGenericArgsToArgs(commandTokens)
217
+ }
218
+
219
+ // Match generic commands with their args, one to one
220
+ // this matches commands like `node`
221
+ const commandGenericBase: string = this.getBaseCommand(this.command)
222
+ const commandGenericProcessBase: string = this.getBaseCommand(commandTokens[0])
223
+ if (commandGenericBase === commandGenericProcessBase) {
224
+ return this.matchGenericArgsToArgs(commandTokens)
225
+ }
226
+
227
+ return false
228
+ }
229
+
230
+ private matchGenericArgsToArgs (commandTokens: string[]): boolean {
231
+ if (this.args.length === 0) {
232
+ // If no args configured, we just check if the command matches
233
+ return commandTokens[0] === this.command
234
+ }
235
+
236
+ if (commandTokens.length < 2) {
237
+ // If there are no command tokens or only the command itself, we cannot match
238
+ return false
239
+ }
240
+
241
+ // Remove the command from the command tokens
242
+ const commandWithoutArgs = commandTokens.slice(1)
243
+
244
+ for (let i = 0; i < this.args.length; i++) {
245
+ // If we reach the end of command tokens, we cannot match
246
+ if (i >= commandWithoutArgs.length) return false
247
+
248
+ const arg = this.args[i]
249
+ const token = commandWithoutArgs[i]
250
+
251
+ // Check if the argument matches the command token
252
+ if (arg !== token && !token.includes(arg)) {
253
+ return false
254
+ }
255
+ }
256
+
257
+ // If we reached here, we matched all arguments
258
+ return true
259
+ }
260
+
261
+ // @TODO refactor this to use path.basename or similar
262
+ // to extract the base command from the full command path
263
+ private getBaseCommand (fullCommandPath: string): string {
264
+ // Extract base command name from full path
265
+ const parts = fullCommandPath.split(/[/\\]/)
266
+ return parts[parts.length - 1]
267
+ }
268
+
269
+ /*
270
+ example1:
271
+ ```
272
+ "command": "uvx",
273
+ "args": ["--from", "mcp-alchemy==2025.5.2.210242", "--with", "oracledb",
274
+ "--refresh-package", "mcp-alchemy", "mcp-alchemy"],
275
+ ```
276
+
277
+ example 2:
278
+ ```
279
+ "command": "uvx",
280
+ "args": [
281
+ "mcp-neo4j-memory@0.1.4",
282
+ "--db-url",
283
+ "neo4j+s://xxxx.databases.neo4j.io",
284
+ "--username",
285
+ "<your-username>",
286
+ "--password",
287
+ "<your-password>"
288
+ ]
289
+ ```
290
+
291
+ example 3:
292
+ ```
293
+ "vefaas": {
294
+ "command": "uvx",
295
+ "args": [
296
+ "--from",
297
+ "git+https://github.com/volcengine/mcp-server#subdirectory=server/mcp_server_vefaas_function",
298
+ "mcp-server-vefaas-function"
299
+ ],
300
+ "env": {
301
+ "VOLC_ACCESSKEY": "xxx",
302
+ "VOLC_SECRETKEY": "xxx"
303
+ }
304
+ }
305
+ }
306
+ ```
307
+
308
+ example 4:
309
+ ```
310
+ "time": {
311
+ "command": "uvx",
312
+ "args": ["mcp-server-time", "--local-timezone=America/New_York"]
313
+ }
314
+ ```
315
+ */
316
+ private getUvxMcpServerNameFromArgs (): string | undefined {
317
+ if (this.args.length === 0) return undefined
318
+
319
+ let mcpServerName
320
+
321
+ // If total args is 1 we know it is the MCP server name
322
+ if (this.args.length === 1) {
323
+ mcpServerName = this.args[0]
324
+ return mcpServerName
325
+ }
326
+
327
+ // Extract the MCP server name from --from flag if it exists
328
+ for (let i = 0; i < this.args.length; i++) {
329
+ if (this.args[i] === '--from' && i + 1 < this.args.length) {
330
+ mcpServerName = this.args[i + 1]
331
+ return mcpServerName
332
+ }
333
+ }
334
+
335
+ // If no use of --from flag, we try to extract the MCP server name from the last argument
336
+ const firstArg = this.args[0]
337
+ if (firstArg.startsWith('-') || firstArg.startsWith('--')) {
338
+ // If the first argument is a flag, take the last argument as the MCP server name
339
+ const lastArg = this.args[this.args.length - 1]
340
+ mcpServerName = lastArg
341
+ return mcpServerName
342
+ }
343
+
344
+ // If the first argument is not a flag, take it as the MCP server name
345
+ mcpServerName = firstArg
346
+ return mcpServerName
347
+ }
348
+
349
+ private matchUvxProcess (commandTokens: string[]): boolean {
350
+ if (commandTokens.length === 0) return false
351
+
352
+ // We already matched the base command as "uv" for uvx
353
+ // Let's get the MCP server name from the args in command configuration
354
+ const mcpServerName = this.getUvxMcpServerNameFromArgs()
355
+ if (!mcpServerName) return false
356
+
357
+ // Check if the command tokens contain the MCP server name
358
+ // const expectedArgs = [mcpServerName, ...this.args]
359
+ return this.findMcpServerNameInProcessArguments(commandTokens, mcpServerName)
360
+ }
361
+
362
+ private findMcpServerNameInProcessArguments (commandTokens: string[], mcpServerName: string): boolean {
363
+ // Check if the command tokens contain the MCP server name
364
+ for (let i = 0; i < commandTokens.length; i++) {
365
+ const token = commandTokens[i]
366
+ if (mcpServerName === token || token.includes(mcpServerName)) {
367
+ // If we find the MCP server name in the command tokens, we consider it a match
368
+ return true
369
+ }
370
+ }
371
+ return false
372
+ }
373
+
374
+ private parseCSVLine (line: string): string[] {
375
+ const result: string[] = []
376
+ let current = ''
377
+ let inQuotes = false
378
+
379
+ for (let i = 0; i < line.length; i++) {
380
+ const char = line[i]
381
+
382
+ if (char === '"') {
383
+ if (inQuotes && line[i + 1] === '"') {
384
+ // Escaped quote
385
+ current += '"'
386
+ i++ // Skip next quote
387
+ } else {
388
+ // Toggle quote state
389
+ inQuotes = !inQuotes
390
+ }
391
+ } else if (char === ',' && !inQuotes) {
392
+ result.push(current)
393
+ current = ''
394
+ } else {
395
+ current += char
396
+ }
397
+ }
398
+
399
+ result.push(current)
400
+ return result
401
+ }
402
+
403
+ private parseCommandLine (commandLine: string): string[] {
404
+ const tokens: string[] = []
405
+ let current = ''
406
+ let inQuotes = false
407
+ let quoteChar = ''
408
+
409
+ for (let i = 0; i < commandLine.length; i++) {
410
+ const char = commandLine[i]
411
+
412
+ if (!inQuotes && (char === '"' || char === "'")) {
413
+ inQuotes = true
414
+ quoteChar = char
415
+ } else if (inQuotes && char === quoteChar) {
416
+ inQuotes = false
417
+ quoteChar = ''
418
+ } else if (!inQuotes && char === ' ') {
419
+ if (current.trim()) {
420
+ tokens.push(current.trim())
421
+ current = ''
422
+ }
423
+ } else {
424
+ current += char
425
+ }
426
+ }
427
+
428
+ if (current.trim()) {
429
+ tokens.push(current.trim())
430
+ }
431
+
432
+ return tokens
433
+ }
434
+
435
+ /*
436
+ example to match:
437
+ ```
438
+ "command": "npx",
439
+ "args": [
440
+ "-y",
441
+ "@modelcontextprotocol/server-postgres",
442
+ "postgresql://localhost/mydb"
443
+ ]
444
+ }
445
+ ```
446
+
447
+ with a process command like:
448
+ ```
449
+ npm exec @modelcontextprotocol/server-postgres postgresql://localhost/mydb
450
+ ```
451
+ */
452
+ private matchNpxProcess (commandTokens: string[]): boolean {
453
+ // npx command pattern: npm exec <package> [args...]
454
+ // Expected command tokens: ["npm", "exec", package_name, ...args]
455
+
456
+ if (commandTokens.length < 3) return false
457
+
458
+ // Check if it's the expected npm exec pattern
459
+ if (commandTokens[1] !== 'exec') return false
460
+
461
+ let argsToMatch: string[] = []
462
+ const yIndex = this.args.indexOf('-y')
463
+
464
+ if (yIndex !== -1 && yIndex + 1 < this.args.length) {
465
+ // Case 1: -y flag is present, extract args after it
466
+ argsToMatch = this.args.slice(yIndex + 1)
467
+ } else {
468
+ // Case 2: No -y flag, match all args directly
469
+ argsToMatch = this.args
470
+ }
471
+
472
+ // Match the args after "npm exec" with the extracted args from config
473
+ // commandTokens: ["npm", "exec", package_name, ...additional_args]
474
+ // argsToMatch: [package_name, ...additional_args]
475
+
476
+ if (commandTokens.length - 2 !== argsToMatch.length) {
477
+ // Length mismatch between process args and config args
478
+ return false
479
+ }
480
+
481
+ // Compare each argument starting from position 2 in commandTokens
482
+ for (let i = 0; i < argsToMatch.length; i++) {
483
+ const commandToken = commandTokens[i + 2] // Start from index 2 (after "npm exec")
484
+ const expectedArg = argsToMatch[i]
485
+
486
+ if (commandToken !== expectedArg) {
487
+ return false
488
+ }
489
+ }
490
+
491
+ return true
48
492
  }
49
493
  }
@@ -27,28 +27,49 @@ export class RenderService {
27
27
  static printMcpServers (data: any[]) {
28
28
  if (data.length === 0) return
29
29
 
30
- // const headers = ['STATUS', 'NAME', 'TRANSPORT', 'VERSION', 'TOOLS', 'RESOURCES']
31
- // const keys = ['status', 'name', 'transport', 'version', 'tools', 'resources']
32
30
  const headers = ['STATUS', 'NAME', 'TRANSPORT']
33
31
  const keys = ['status', 'name', 'transport']
34
- const centerColumns = [0, 2, 4, 5] // STATUS, TOOLS, RESOURCES column indices
32
+ const centerColumns = [0, 2] // STATUS and TRANSPORT column indices
35
33
  const leftPadding = ' ' // 6 characters
36
34
 
37
- // Calculate column widths
35
+ // Calculate column widths accounting for styled text
38
36
  const columnWidths = headers.map((header, index) => {
39
- const dataWidth = Math.max(...data.map(row => String(row[keys[index]]).length))
40
- return Math.max(header.length, dataWidth)
37
+ const headerWidth = this.getVisibleLength(ColumnNameComponent(header))
38
+ const dataWidth = Math.max(...data.map(row => {
39
+ let text = String(row[keys[index]])
40
+
41
+ // Apply the same transformations used in rendering
42
+ if (keys[index] === 'transport') {
43
+ text = TransportComponent(text)
44
+ }
45
+ if (keys[index] === 'status') {
46
+ text = MCPServerStatusComponent(text)
47
+ }
48
+ if (keys[index] === 'name') {
49
+ text = MCPServerNameComponent(text)
50
+ }
51
+
52
+ return this.getVisibleLength(text)
53
+ }))
54
+ return Math.max(headerWidth, dataWidth)
41
55
  })
42
56
 
43
57
  // Helper function to center text in a given width
44
58
  const centerText = (text: string, width: number): string => {
45
- // Calculate visible length by removing ANSI escape codes
46
- const padding = width - this.getVisibleLength(text)
59
+ const visibleLength = this.getVisibleLength(text)
60
+ const padding = width - visibleLength
47
61
  const leftPad = Math.floor(padding / 2)
48
62
  const rightPad = padding - leftPad
49
63
  return ' '.repeat(leftPad) + text + ' '.repeat(rightPad)
50
64
  }
51
65
 
66
+ // Helper function to pad text to the right
67
+ const padRight = (text: string, width: number): string => {
68
+ const visibleLength = this.getVisibleLength(text)
69
+ const padding = Math.max(0, width - visibleLength)
70
+ return text + ' '.repeat(padding)
71
+ }
72
+
52
73
  // Calculate total table width for separator line
53
74
  const totalWidth = columnWidths.reduce((sum, width) => sum + width, 0) + (columnWidths.length - 1) * 2
54
75
  const separator = '─'.repeat(totalWidth)
@@ -62,35 +83,34 @@ export class RenderService {
62
83
  if (centerColumns.includes(index)) {
63
84
  return centerText(headerText, columnWidths[index])
64
85
  }
65
- // Calculate visible length by removing ANSI escape codes
66
- const padding = columnWidths[index] - this.getVisibleLength(headerText)
67
- return headerText + ' '.repeat(Math.max(0, padding))
86
+ return padRight(headerText, columnWidths[index])
68
87
  }).join(' ')
69
88
  console.log(leftPadding + headerRow)
70
89
 
71
- // Print bottom separator
90
+ // Print separator
72
91
  console.log(leftPadding + separator)
73
92
 
74
93
  // Print data rows
75
94
  for (const row of data) {
76
95
  const dataRow = keys.map((key, index) => {
77
96
  let text = String(row[key])
97
+
98
+ // Apply styling transformations
78
99
  if (key === 'transport') {
79
100
  text = TransportComponent(text)
80
101
  }
81
-
82
102
  if (key === 'status') {
83
103
  text = MCPServerStatusComponent(text)
84
104
  }
85
-
86
105
  if (key === 'name') {
87
106
  text = MCPServerNameComponent(text)
88
107
  }
89
108
 
109
+ // Apply alignment
90
110
  if (centerColumns.includes(index)) {
91
111
  return centerText(text, columnWidths[index])
92
112
  }
93
- return text.padEnd(columnWidths[index])
113
+ return padRight(text, columnWidths[index])
94
114
  }).join(' ')
95
115
  console.log(leftPadding + dataRow)
96
116
  }
@@ -177,11 +197,16 @@ export class RenderService {
177
197
  const filledWidth = Math.round(progress * width)
178
198
  const emptyWidth = width - filledWidth
179
199
 
180
- const colorRunning = count > 0 ? 'greenBright' : 'red'
181
- const colorEmpty = count > 0 ? 'green' : 'red'
200
+ let filled: string
201
+ let empty: string
182
202
 
183
- const filled = styleText([colorRunning], '█'.repeat(filledWidth))
184
- const empty = styleText([colorEmpty], '░'.repeat(emptyWidth))
203
+ if (count > 0) {
204
+ filled = styleText(['greenBright'], '█'.repeat(filledWidth))
205
+ empty = styleText(['green'], '░'.repeat(emptyWidth))
206
+ } else {
207
+ filled = '█'.repeat(filledWidth)
208
+ empty = '░'.repeat(emptyWidth)
209
+ }
185
210
 
186
211
  return `${filled}${empty} ${count} / ${total} ${label}`
187
212
  }