ls-mcp 1.1.0 → 1.3.0

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/src/main.ts CHANGED
@@ -1,34 +1,130 @@
1
1
  import fs from 'node:fs/promises'
2
- import path from 'node:path'
2
+ import { MCPConfigLinterService } from './services/mcp-config-linter-service.ts'
3
+ import { MCPServerManagerService } from './services/mcp-server-manager-service.ts'
3
4
 
4
- export class MCPFiles {
5
+ interface MCPServerInfo {
6
+ name: string
7
+ command: string
8
+ args?: string[]
9
+ transport?: 'stdio' | 'sse',
10
+ env?: Record<string, string>
11
+ status?: 'running' | 'stopped'
12
+ }
13
+
14
+ interface MCPFilePath {
15
+ filePath: string
16
+ type: 'local' | 'global'
17
+ parsable?: boolean
18
+ servers?: MCPServerInfo[]
19
+ }
20
+
21
+ interface MCPFileGroups {
22
+ name: string
23
+ friendlyName: string
24
+ paths: MCPFilePath[]
25
+ stats?: {
26
+ serversCount?: number
27
+ }
28
+ }
5
29
 
6
- private mcpFilePaths: string[] = [
7
-
8
- '~/Library/Application Support/Claude/claude_desktop_config.json',
9
- '.cursor/mcp.json',
10
- '~/.cursor/mcp.json',
30
+ interface MCPFileGroupsResult {
31
+ name: string
32
+ friendlyName: string
33
+ paths: MCPFilePath[]
34
+ stats: {
35
+ serversCount?: number
36
+ }
37
+ }
11
38
 
12
- ]
39
+ type MCPFilePathGroupsRecord = Record<string, MCPFileGroups>
40
+ type MCPFileGroupsResultRecord = Record<string, MCPFileGroupsResult>
13
41
 
14
- constructor(mcpFilePaths?: string[]) {
15
- if (mcpFilePaths) {
16
- this.mcpFilePaths = mcpFilePaths
42
+ export class MCPFiles {
43
+ private mcpFilePathGroups: MCPFilePathGroupsRecord = {
44
+ claude: {
45
+ name: 'claude-desktop',
46
+ friendlyName: 'Claude Desktop',
47
+ paths: [
48
+ { filePath: '~/Library/Application Support/Claude/claude_desktop_config.json', type: 'global' },
49
+ ]
50
+ },
51
+ cursor: {
52
+ name: 'cursor',
53
+ friendlyName: 'Cursor',
54
+ paths: [
55
+ { filePath: '~/.cursor/mcp.json', type: 'global' },
56
+ { filePath: '.cursor/mcp.json', type: 'local' },
57
+ ]
17
58
  }
18
59
  }
19
60
 
20
- async findFiles(): Promise<string[]> {
21
- const files: string[] = []
22
- for (const path of this.mcpFilePaths) {
23
- try {
24
- const resolvedPath = path.replace('~', process.env.HOME || '')
25
- await fs.access(resolvedPath)
26
- files.push(resolvedPath)
27
- } catch (error) {
28
- // File does not exist, continue to next
61
+ constructor (mcpFilePathGroups?: MCPFilePathGroupsRecord) {
62
+ this.mcpFilePathGroups = mcpFilePathGroups || this.mcpFilePathGroups
63
+ }
64
+
65
+ async findFiles (): Promise<MCPFileGroupsResultRecord> {
66
+ const mcpFilesPathsData: MCPFileGroupsResultRecord = {}
67
+
68
+ for (const groupName of Object.keys(this.mcpFilePathGroups)) {
69
+ const clientsGroup = this.mcpFilePathGroups[groupName]
70
+ mcpFilesPathsData[groupName] = {
71
+ name: clientsGroup.name,
72
+ friendlyName: clientsGroup.friendlyName,
73
+ paths: [],
74
+ stats: {}
75
+ }
76
+
77
+ for (const filePathData of clientsGroup.paths) {
78
+ const resolvedPath: string = filePathData.filePath.replace('~', process.env.HOME || '')
79
+ try {
80
+ await fs.access(resolvedPath)
81
+
82
+ const MCPConfigLinter = new MCPConfigLinterService(resolvedPath)
83
+ const parsable = await MCPConfigLinter.isValidSyntax()
84
+ filePathData.parsable = parsable
85
+
86
+ const mcpServersData: MCPServerInfo[] = []
87
+ const mcpServersFromConfig = await MCPConfigLinter.getMCPServers()
88
+ // let's iterate over the mcpServer Record and access the server objects
89
+ for (const serverName of Object.keys(mcpServersFromConfig)) {
90
+ const serverConfigRaw = mcpServersFromConfig[serverName] as any
91
+ const serverConfig = {
92
+ name: serverName,
93
+ command: serverConfigRaw.command || '',
94
+ args: serverConfigRaw.args,
95
+ transport: serverConfigRaw.transport,
96
+ env: serverConfigRaw.env
97
+ }
98
+ const MCPServerManager = new MCPServerManagerService(serverConfig)
99
+
100
+ const mcpServerProcessDetection = MCPServerManager.isRunning()
101
+ let mcpServerProcess = false
102
+ if (mcpServerProcessDetection) {
103
+ if (typeof mcpServerProcessDetection === 'object' && mcpServerProcessDetection.estimatedProduct === clientsGroup.name) {
104
+ mcpServerProcess = true
105
+ }
106
+ }
107
+
108
+ mcpServersData.push({
109
+ name: MCPServerManager.getName(),
110
+ command: MCPServerManager.getCmd(),
111
+ args: MCPServerManager.getArgs(),
112
+ transport: MCPServerManager.getTransport(),
113
+ env: MCPServerManager.getEnv(),
114
+ status: mcpServerProcess ? 'running' : 'stopped'
115
+ })
116
+ }
117
+
118
+ filePathData.servers = mcpServersData
119
+
120
+ mcpFilesPathsData[groupName]['stats']['serversCount'] = await MCPConfigLinter.countMCPServers()
121
+ mcpFilesPathsData[groupName].paths.push(filePathData)
122
+ } catch (error) {
123
+ // File does not exist, continue to next
124
+ }
29
125
  }
30
126
  }
31
- return files
127
+
128
+ return mcpFilesPathsData
32
129
  }
33
130
  }
34
-
@@ -0,0 +1,43 @@
1
+ import fs from 'node:fs/promises'
2
+
3
+ export class MCPConfigLinterService {
4
+ private filePath: string
5
+ private fileContents: string | null = null
6
+
7
+ constructor (filePath: string) {
8
+ this.filePath = filePath
9
+ }
10
+
11
+ async isValidSyntax (): Promise<boolean> {
12
+ // @TODO this should also support YAML files and other formats
13
+ try {
14
+ const fileContent = await this.getFileContent()
15
+ JSON.parse(fileContent)
16
+ return true
17
+ } catch (error) {
18
+ return false
19
+ }
20
+ }
21
+
22
+ async countMCPServers (): Promise<number> {
23
+ const mcpServers = await this.getMCPServers()
24
+ return Object.keys(mcpServers).length
25
+ }
26
+
27
+ async getMCPServers (): Promise<Record<string, object>> {
28
+ const fileContentRaw = await this.getFileContent()
29
+ const fileContentsData = JSON.parse(fileContentRaw)
30
+
31
+ const mcpServers = fileContentsData?.mcpServers
32
+
33
+ return mcpServers
34
+ }
35
+
36
+ async getFileContent (): Promise<string> {
37
+ if (this.fileContents) {
38
+ return this.fileContents
39
+ }
40
+ this.fileContents = await fs.readFile(this.filePath, 'utf-8')
41
+ return this.fileContents
42
+ }
43
+ }
@@ -0,0 +1,460 @@
1
+ import { execSync } from 'node:child_process'
2
+ import { platform } from 'node:os'
3
+
4
+ interface MCPServerConfig {
5
+ name: string
6
+ command: string
7
+ args?: string[]
8
+ transport?: 'stdio' | 'sse'
9
+ env?: Record<string, string>
10
+ }
11
+
12
+ interface MatchedProcess {
13
+ pid: string
14
+ commandLine: string
15
+ ppid?: string
16
+ parentCommandLine?: string
17
+ estimatedVendor?: string
18
+ estimatedProduct?: string
19
+ }
20
+
21
+ export class MCPServerManagerService {
22
+ private name: string
23
+ private command: string
24
+ private args: string[]
25
+ private transport?: 'stdio' | 'sse'
26
+ private env?: Record<string, string>
27
+ private running: boolean = false
28
+
29
+ constructor (serverConfig: MCPServerConfig) {
30
+ this.name = serverConfig.name
31
+ this.command = serverConfig.command
32
+ this.args = serverConfig.args || []
33
+ this.transport = serverConfig.transport || 'stdio'
34
+ this.env = serverConfig.env || {}
35
+ }
36
+
37
+ getName (): string {
38
+ return this.name
39
+ }
40
+
41
+ getCmd (): string {
42
+ return this.command
43
+ }
44
+
45
+ getArgs (): string[] {
46
+ return this.args
47
+ }
48
+
49
+ getTransport (): 'stdio' | 'sse' | undefined {
50
+ return this.transport
51
+ }
52
+
53
+ getEnv (): Record<string, string> | undefined {
54
+ return this.env
55
+ }
56
+
57
+ isRunning (): boolean | MatchedProcess {
58
+ try {
59
+ let psOutput: string
60
+
61
+ if (platform() === 'win32') {
62
+ // Windows: Use wmic to get process info
63
+ psOutput = execSync('wmic process get ProcessId,ParentProcessId,CommandLine /format:csv', {
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: Node,CommandLine,ParentProcessId,ProcessId
87
+ const parts = processLine.split(',')
88
+ if (parts.length < 4) continue
89
+ commandLine = parts[1] || ''
90
+ ppid = parts[2] || ''
91
+ pid = parts[3] || ''
92
+ } else {
93
+ // Parse Unix ps output: PID PPID COMMAND
94
+ const match = processLine.trim().match(/^\s*(\d+)\s+(\d+)\s+(.+)$/)
95
+ if (!match) continue
96
+ pid = match[1]
97
+ ppid = match[2]
98
+ commandLine = match[3]
99
+ }
100
+
101
+ // Parse command line and store in map
102
+ const commandTokens = this.parseCommandLine(commandLine)
103
+ if (commandTokens.length > 0) {
104
+ processMap.set(pid, { ppid, commandTokens })
105
+ }
106
+ }
107
+
108
+ // Then iterate the map to check for matches
109
+ let mcpServerDetection: MatchedProcess | undefined
110
+ for (const [pid, processData] of processMap) {
111
+ if (this.isCommandMatch(processData.commandTokens, pid, processData.ppid)) {
112
+ mcpServerDetection = {
113
+ pid,
114
+ commandLine: processData.commandTokens.join(' '),
115
+ ppid: processData.ppid,
116
+ }
117
+
118
+ // if we matched the command let's extract the parent command information
119
+ const parentProcess = processMap.get(processData.ppid)
120
+ if (parentProcess) {
121
+ const { estimatedVendor, estimatedProduct } = this.getVendorFromCommand(parentProcess.commandTokens) || {}
122
+
123
+ if (estimatedProduct || estimatedVendor) {
124
+ mcpServerDetection = {
125
+ ...mcpServerDetection,
126
+ parentCommandLine: parentProcess.commandTokens.join(' '),
127
+ estimatedVendor,
128
+ estimatedProduct
129
+ }
130
+
131
+ return mcpServerDetection
132
+ }
133
+ }
134
+ }
135
+ }
136
+
137
+ if (mcpServerDetection) {
138
+ return mcpServerDetection
139
+ }
140
+
141
+ return false
142
+ } catch (error) {
143
+ return false
144
+ }
145
+ }
146
+
147
+ private getVendorFromCommand (commandTokens: string[]): { estimatedVendor: string, estimatedProduct: string } | undefined {
148
+ // match based on known vendor patterns in the command string
149
+ const commandString = commandTokens.join(' ').toLowerCase()
150
+ if (commandString.includes('claude.app')) {
151
+ return {
152
+ estimatedVendor: 'anthropic',
153
+ estimatedProduct: 'claude-desktop'
154
+ }
155
+ }
156
+
157
+ if (commandString.includes('claude')) {
158
+ return {
159
+ estimatedVendor: 'anthropic',
160
+ estimatedProduct: 'claude-desktop'
161
+ }
162
+ }
163
+ }
164
+
165
+ private isCommandMatch (commandTokens: string[], pid: string, ppid: string): boolean {
166
+ // If no command tokens, cannot match
167
+ if (commandTokens.length === 0) return false
168
+
169
+ // Extracts the base command from the full command path of the process output list
170
+ // e.g. "/usr/homebrew/bin/uv" extracted to "uv"
171
+ const baseCommand = this.getBaseCommand(commandTokens[0])
172
+
173
+ // Map configured command to actual process command for uvx case
174
+ if (this.command === 'uvx' && baseCommand === 'uv') {
175
+ return this.matchUvxProcess(commandTokens)
176
+ }
177
+
178
+ // Map configured command to actual process command for npx case
179
+ if (this.command === 'npx' && baseCommand === 'npm') {
180
+ return this.matchNpxProcess(commandTokens)
181
+ }
182
+
183
+ /*
184
+ example config:
185
+ "test_server_2": {
186
+ "command": "uv",
187
+ "args": [
188
+ "--directory",
189
+ "/Users/lirantal/projects/repos/example-python-mcp-server",
190
+ "run",
191
+ "test-server.py"
192
+ ]
193
+ },
194
+ */
195
+ if (this.command === 'uv' && baseCommand === 'uv') {
196
+ return this.matchGenericArgsToArgs(commandTokens)
197
+ }
198
+
199
+ // Python Generic commands matching
200
+ /*
201
+ example config:
202
+ "test_server": {
203
+ "command": "/Users/lirantal/projects/repos/example-python-mcp-server/.venv/bin/python",
204
+ "args": [
205
+ "/Users/lirantal/projects/repos/example-python-mcp-server/test-server.py"
206
+ ]
207
+ }
208
+ */
209
+ const commandConfigPythonBase: string = this.getBaseCommand(this.command)
210
+ const commandAliasesPython = ['python3', 'python', 'python3.10', 'python3.11', 'python3.12', 'cpython3', 'cpython', 'python3', 'python2']
211
+ if (commandAliasesPython.includes(commandConfigPythonBase) && commandAliasesPython.includes(baseCommand)) {
212
+ return this.matchGenericArgsToArgs(commandTokens)
213
+ }
214
+
215
+ // Match generic commands with their args, one to one
216
+ // this matches commands like `node`
217
+ const commandGenericBase: string = this.getBaseCommand(this.command)
218
+ const commandGenericProcessBase: string = this.getBaseCommand(commandTokens[0])
219
+ if (commandGenericBase === commandGenericProcessBase) {
220
+ return this.matchGenericArgsToArgs(commandTokens)
221
+ }
222
+
223
+ return false
224
+ }
225
+
226
+ private matchGenericArgsToArgs (commandTokens: string[]): boolean {
227
+ if (this.args.length === 0) {
228
+ // If no args configured, we just check if the command matches
229
+ return commandTokens[0] === this.command
230
+ }
231
+
232
+ if (commandTokens.length < 2) {
233
+ // If there are no command tokens or only the command itself, we cannot match
234
+ return false
235
+ }
236
+
237
+ // Remove the command from the command tokens
238
+ const commandWithoutArgs = commandTokens.slice(1)
239
+
240
+ for (let i = 0; i < this.args.length; i++) {
241
+ // If we reach the end of command tokens, we cannot match
242
+ if (i >= commandWithoutArgs.length) return false
243
+
244
+ const arg = this.args[i]
245
+ const token = commandWithoutArgs[i]
246
+
247
+ // Check if the argument matches the command token
248
+ if (arg !== token && !token.includes(arg)) {
249
+ return false
250
+ }
251
+ }
252
+
253
+ // If we reached here, we matched all arguments
254
+ return true
255
+ }
256
+
257
+ // @TODO refactor this to use path.basename or similar
258
+ // to extract the base command from the full command path
259
+ private getBaseCommand (fullCommandPath: string): string {
260
+ // Extract base command name from full path
261
+ const parts = fullCommandPath.split(/[/\\]/)
262
+ return parts[parts.length - 1]
263
+ }
264
+
265
+ /*
266
+ example1:
267
+ ```
268
+ "command": "uvx",
269
+ "args": ["--from", "mcp-alchemy==2025.5.2.210242", "--with", "oracledb",
270
+ "--refresh-package", "mcp-alchemy", "mcp-alchemy"],
271
+ ```
272
+
273
+ example 2:
274
+ ```
275
+ "command": "uvx",
276
+ "args": [
277
+ "mcp-neo4j-memory@0.1.4",
278
+ "--db-url",
279
+ "neo4j+s://xxxx.databases.neo4j.io",
280
+ "--username",
281
+ "<your-username>",
282
+ "--password",
283
+ "<your-password>"
284
+ ]
285
+ ```
286
+
287
+ example 3:
288
+ ```
289
+ "vefaas": {
290
+ "command": "uvx",
291
+ "args": [
292
+ "--from",
293
+ "git+https://github.com/volcengine/mcp-server#subdirectory=server/mcp_server_vefaas_function",
294
+ "mcp-server-vefaas-function"
295
+ ],
296
+ "env": {
297
+ "VOLC_ACCESSKEY": "xxx",
298
+ "VOLC_SECRETKEY": "xxx"
299
+ }
300
+ }
301
+ }
302
+ ```
303
+
304
+ example 4:
305
+ ```
306
+ "time": {
307
+ "command": "uvx",
308
+ "args": ["mcp-server-time", "--local-timezone=America/New_York"]
309
+ }
310
+ ```
311
+ */
312
+ private getUvxMcpServerNameFromArgs (): string | undefined {
313
+ if (this.args.length === 0) return undefined
314
+
315
+ let mcpServerName
316
+
317
+ // If total args is 1 we know it is the MCP server name
318
+ if (this.args.length === 1) {
319
+ mcpServerName = this.args[0]
320
+ return mcpServerName
321
+ }
322
+
323
+ // Extract the MCP server name from --from flag if it exists
324
+ for (let i = 0; i < this.args.length; i++) {
325
+ if (this.args[i] === '--from' && i + 1 < this.args.length) {
326
+ mcpServerName = this.args[i + 1]
327
+ return mcpServerName
328
+ }
329
+ }
330
+
331
+ // If no use of --from flag, we try to extract the MCP server name from the last argument
332
+ const firstArg = this.args[0]
333
+ if (firstArg.startsWith('-') || firstArg.startsWith('--')) {
334
+ // If the first argument is a flag, take the last argument as the MCP server name
335
+ const lastArg = this.args[this.args.length - 1]
336
+ mcpServerName = lastArg
337
+ return mcpServerName
338
+ }
339
+
340
+ // If the first argument is not a flag, take it as the MCP server name
341
+ mcpServerName = firstArg
342
+ return mcpServerName
343
+ }
344
+
345
+ private matchUvxProcess (commandTokens: string[]): boolean {
346
+ if (commandTokens.length === 0) return false
347
+
348
+ // We already matched the base command as "uv" for uvx
349
+ // Let's get the MCP server name from the args in command configuration
350
+ const mcpServerName = this.getUvxMcpServerNameFromArgs()
351
+ if (!mcpServerName) return false
352
+
353
+ // Check if the command tokens contain the MCP server name
354
+ // const expectedArgs = [mcpServerName, ...this.args]
355
+ return this.findMcpServerNameInProcessArguments(commandTokens, mcpServerName)
356
+ }
357
+
358
+ private findMcpServerNameInProcessArguments (commandTokens: string[], mcpServerName: string): boolean {
359
+ // Check if the command tokens contain the MCP server name
360
+ for (let i = 0; i < commandTokens.length; i++) {
361
+ const token = commandTokens[i]
362
+ if (mcpServerName === token || token.includes(mcpServerName)) {
363
+ // If we find the MCP server name in the command tokens, we consider it a match
364
+ return true
365
+ }
366
+ }
367
+ return false
368
+ }
369
+
370
+ private parseCommandLine (commandLine: string): string[] {
371
+ const tokens: string[] = []
372
+ let current = ''
373
+ let inQuotes = false
374
+ let quoteChar = ''
375
+
376
+ for (let i = 0; i < commandLine.length; i++) {
377
+ const char = commandLine[i]
378
+
379
+ if (!inQuotes && (char === '"' || char === "'")) {
380
+ inQuotes = true
381
+ quoteChar = char
382
+ } else if (inQuotes && char === quoteChar) {
383
+ inQuotes = false
384
+ quoteChar = ''
385
+ } else if (!inQuotes && char === ' ') {
386
+ if (current.trim()) {
387
+ tokens.push(current.trim())
388
+ current = ''
389
+ }
390
+ } else {
391
+ current += char
392
+ }
393
+ }
394
+
395
+ if (current.trim()) {
396
+ tokens.push(current.trim())
397
+ }
398
+
399
+ return tokens
400
+ }
401
+
402
+ /*
403
+ example to match:
404
+ ```
405
+ "command": "npx",
406
+ "args": [
407
+ "-y",
408
+ "@modelcontextprotocol/server-postgres",
409
+ "postgresql://localhost/mydb"
410
+ ]
411
+ }
412
+ ```
413
+
414
+ with a process command like:
415
+ ```
416
+ npm exec @modelcontextprotocol/server-postgres postgresql://localhost/mydb
417
+ ```
418
+ */
419
+ private matchNpxProcess (commandTokens: string[]): boolean {
420
+ // npx command pattern: npm exec <package> [args...]
421
+ // Expected command tokens: ["npm", "exec", package_name, ...args]
422
+
423
+ if (commandTokens.length < 3) return false
424
+
425
+ // Check if it's the expected npm exec pattern
426
+ if (commandTokens[1] !== 'exec') return false
427
+
428
+ let argsToMatch: string[] = []
429
+ const yIndex = this.args.indexOf('-y')
430
+
431
+ if (yIndex !== -1 && yIndex + 1 < this.args.length) {
432
+ // Case 1: -y flag is present, extract args after it
433
+ argsToMatch = this.args.slice(yIndex + 1)
434
+ } else {
435
+ // Case 2: No -y flag, match all args directly
436
+ argsToMatch = this.args
437
+ }
438
+
439
+ // Match the args after "npm exec" with the extracted args from config
440
+ // commandTokens: ["npm", "exec", package_name, ...additional_args]
441
+ // argsToMatch: [package_name, ...additional_args]
442
+
443
+ if (commandTokens.length - 2 !== argsToMatch.length) {
444
+ // Length mismatch between process args and config args
445
+ return false
446
+ }
447
+
448
+ // Compare each argument starting from position 2 in commandTokens
449
+ for (let i = 0; i < argsToMatch.length; i++) {
450
+ const commandToken = commandTokens[i + 2] // Start from index 2 (after "npm exec")
451
+ const expectedArg = argsToMatch[i]
452
+
453
+ if (commandToken !== expectedArg) {
454
+ return false
455
+ }
456
+ }
457
+
458
+ return true
459
+ }
460
+ }