ls-mcp 1.13.2 → 1.14.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/bin/cli.ts CHANGED
@@ -20,14 +20,37 @@ interface MCPServerInfo {
20
20
  const args = process.argv.slice(2)
21
21
  const jsonOutput = args.includes('--json')
22
22
 
23
+ // Parse --files flag
24
+ let customFiles: string[] | undefined
25
+ const filesIndex = args.findIndex(arg => arg === '--files')
26
+ if (filesIndex !== -1 && filesIndex < args.length - 1) {
27
+ // Get all arguments after --files until we hit another flag or end of args
28
+ const fileArgs: string[] = []
29
+ for (let i = filesIndex + 1; i < args.length; i++) {
30
+ if (args[i].startsWith('--')) {
31
+ break
32
+ }
33
+ fileArgs.push(args[i])
34
+ }
35
+
36
+ // Support both comma-separated and space-separated file paths
37
+ customFiles = fileArgs.flatMap(arg =>
38
+ arg.includes(',') ? arg.split(',').map(f => f.trim()) : [arg.trim()]
39
+ ).filter(f => f.length > 0)
40
+ }
41
+
23
42
  async function init () {
24
43
  // Start the CLI with a new line for better readability (only in non-JSON mode)
25
44
  if (!jsonOutput) {
26
45
  console.log()
27
- console.log('[+] Detecting MCP Server configurations...')
46
+ if (customFiles && customFiles.length > 0) {
47
+ console.log('[+] Analyzing specified MCP configuration files...')
48
+ } else {
49
+ console.log('[+] Detecting MCP Server configurations...')
50
+ }
28
51
  }
29
52
 
30
- const mcpFilesManager = new MCPFiles()
53
+ const mcpFilesManager = new MCPFiles(customFiles)
31
54
  const mcpFilesList = await mcpFilesManager.findFiles()
32
55
 
33
56
  if (Object.keys(mcpFilesList).length === 0) {
package/src/main.ts CHANGED
@@ -4,17 +4,61 @@ import { type MCPFileGroupsResultRecord } from './types/mcp-config-service.types
4
4
 
5
5
  export class MCPFiles {
6
6
  private mcpConfigService: MCPConfigService
7
+ private customFiles?: string[]
7
8
 
8
- constructor () {
9
+ constructor (customFiles?: string[]) {
9
10
  // Enable directory bubbling for better DX when running from nested directories
10
11
  this.mcpConfigService = new MCPConfigService({ enableDirectoryBubbling: true })
12
+ this.customFiles = customFiles
11
13
  }
12
14
 
13
15
  /**
14
16
  * Find and process all MCP configuration files
17
+ * If customFiles are provided, only those files are processed (replaces automatic discovery)
15
18
  */
16
19
  async findFiles (): Promise<MCPFileGroupsResultRecord> {
17
20
  try {
21
+ // If custom files are specified, use them instead of automatic discovery
22
+ if (this.customFiles && this.customFiles.length > 0) {
23
+ const mcpFilesPathsData = await this.mcpConfigService.parseCustomFiles(this.customFiles)
24
+
25
+ // Process each group to add server status information
26
+ for (const groupName of Object.keys(mcpFilesPathsData)) {
27
+ const group = mcpFilesPathsData[groupName]
28
+
29
+ for (const filePathData of group.paths) {
30
+ if (filePathData.servers && filePathData.servers.length > 0) {
31
+ // Update server status for each server in this file
32
+ for (const server of filePathData.servers) {
33
+ const serverConfig = {
34
+ name: server.name,
35
+ command: server.command,
36
+ args: server.args,
37
+ transport: server.transport,
38
+ type: server.type,
39
+ env: server.env
40
+ }
41
+
42
+ const serverManager = new MCPServerManagerService(serverConfig)
43
+ const processDetection = serverManager.isRunning()
44
+
45
+ // Determine if the server is running
46
+ let isRunning = false
47
+ if (processDetection) {
48
+ if (typeof processDetection === 'object' && processDetection.estimatedProduct === group.name) {
49
+ isRunning = true
50
+ }
51
+ }
52
+
53
+ server.status = isRunning ? 'running' : 'stopped'
54
+ }
55
+ }
56
+ }
57
+ }
58
+
59
+ return mcpFilesPathsData
60
+ }
61
+
18
62
  // Get MCP file groups with basic server information
19
63
  const mcpFilesPathsData = await this.mcpConfigService.getMCPFileGroups()
20
64
 
@@ -2,10 +2,8 @@ import { platform } from 'node:os'
2
2
  import path from 'node:path'
3
3
  import fs from 'node:fs/promises'
4
4
  import util from 'node:util'
5
- import { MCPPathRegistry } from './mcp-path-registry.js'
6
- import { MCPConfigParser } from './mcp-config-parser.js'
5
+ import { MCPPathRegistry, MCPConfigParser, DirectoryBubbleService } from 'agent-files'
7
6
  import { CredentialDetectionService } from './credential-detection-service.js'
8
- import { DirectoryBubbleService } from './directory-bubble-service.js'
9
7
  import { MCPVersionDetectionService } from './mcp-version-detection-service.js'
10
8
  import { extractHostname } from '../utils/url-utils.js'
11
9
  import {
@@ -42,7 +40,7 @@ export class MCPConfigService {
42
40
  */
43
41
  getConfigFilesPerApp (appName: string): MCPFilePath[] {
44
42
  try {
45
- return this.pathRegistry.getPathsForApp(this.currentOS, appName)
43
+ return this.pathRegistry.getPathsForApp(this.currentOS, appName) as MCPFilePath[]
46
44
  } catch (error) {
47
45
  throw new Error(`Failed to get config files for app '${appName}': ${error instanceof Error ? error.message : 'Unknown error'}`)
48
46
  }
@@ -53,7 +51,7 @@ export class MCPConfigService {
53
51
  */
54
52
  getAllConfigFiles (): MCPAppPathsRecord {
55
53
  try {
56
- return this.pathRegistry.getPathsForOS(this.currentOS)
54
+ return this.pathRegistry.getPathsForOS(this.currentOS) as MCPAppPathsRecord
57
55
  } catch (error) {
58
56
  throw new Error(`Failed to get all config files: ${error instanceof Error ? error.message : 'Unknown error'}`)
59
57
  }
@@ -113,7 +111,7 @@ export class MCPConfigService {
113
111
  return appNames.map(appName => ({
114
112
  name: appName,
115
113
  friendlyName: this.getFriendlyName(appName),
116
- paths: appPaths[appName] || []
114
+ paths: (appPaths as MCPAppPathsRecord)[appName] || []
117
115
  }))
118
116
  } catch (error) {
119
117
  throw new Error(`Failed to get supported apps: ${error instanceof Error ? error.message : 'Unknown error'}`)
@@ -155,7 +153,8 @@ export class MCPConfigService {
155
153
  const appPaths = this.getAllConfigFiles()
156
154
  const mcpFilesPathsData: MCPFileGroupsResultRecord = {}
157
155
 
158
- for (const [groupName, paths] of Object.entries(appPaths)) {
156
+ for (const groupName of Object.keys(appPaths)) {
157
+ const paths = appPaths[groupName]
159
158
  mcpFilesPathsData[groupName] = {
160
159
  name: groupName,
161
160
  friendlyName: this.getFriendlyName(groupName),
@@ -226,6 +225,75 @@ export class MCPConfigService {
226
225
  }
227
226
  }
228
227
 
228
+ /**
229
+ * Parse custom configuration files provided by the user
230
+ * This method processes files independently of standard app-based discovery
231
+ */
232
+ async parseCustomFiles (filePaths: string[]): Promise<MCPFileGroupsResultRecord> {
233
+ try {
234
+ const mcpFilesPathsData: MCPFileGroupsResultRecord = {
235
+ custom: {
236
+ name: 'custom',
237
+ friendlyName: 'Custom Files',
238
+ paths: [],
239
+ stats: { serversCount: 0 }
240
+ }
241
+ }
242
+
243
+ let totalServersCount = 0
244
+
245
+ for (const filePath of filePaths) {
246
+ const resolvedPath = filePath.replace('~', process.env.HOME || '')
247
+ const absolutePath = path.resolve(resolvedPath)
248
+
249
+ try {
250
+ // Check if file exists
251
+ await fs.access(absolutePath)
252
+
253
+ const parser = this.createParser(absolutePath)
254
+ const parsable = await parser.isValidSyntax()
255
+
256
+ const filePathData: MCPFilePath = {
257
+ filePath: absolutePath,
258
+ type: 'local',
259
+ parsable
260
+ }
261
+
262
+ if (parsable) {
263
+ const configData = await parser.parseConfigFile()
264
+ const servers = await this.convertToMCPServerInfo(configData.servers || {})
265
+ filePathData.servers = servers
266
+ totalServersCount += servers.length
267
+ } else {
268
+ this.debug(`File ${absolutePath} has invalid syntax`)
269
+ filePathData.servers = []
270
+ }
271
+
272
+ mcpFilesPathsData.custom.paths.push(filePathData)
273
+ } catch (error) {
274
+ // File does not exist or is not accessible
275
+ this.debug(`Skipping file ${absolutePath}: ${error instanceof Error ? error.message : 'Unknown error'}`)
276
+
277
+ // Still add to paths with parsable=false to show user it was attempted
278
+ mcpFilesPathsData.custom.paths.push({
279
+ filePath: absolutePath,
280
+ type: 'local',
281
+ parsable: false,
282
+ servers: []
283
+ })
284
+ }
285
+ }
286
+
287
+ if (mcpFilesPathsData.custom.stats) {
288
+ mcpFilesPathsData.custom.stats.serversCount = totalServersCount
289
+ }
290
+
291
+ return mcpFilesPathsData
292
+ } catch (error) {
293
+ throw new Error(`Failed to parse custom files: ${error instanceof Error ? error.message : 'Unknown error'}`)
294
+ }
295
+ }
296
+
229
297
  /**
230
298
  * Register a custom app with custom paths for the current OS
231
299
  */
@@ -1,20 +1,4 @@
1
- export interface MCPConfigData {
2
- raw: any
3
- parsed: boolean
4
- valid: boolean
5
- servers: Record<string, MCPServerConfig>
6
- }
7
-
8
- export interface MCPServerConfig {
9
- name: string
10
- command: string
11
- args?: string[]
12
- transport?: 'stdio' | 'sse' | 'http'
13
- type?: 'sse' | 'http' | 'stdio' | 'streamable-http'
14
- url?: string
15
- env?: Record<string, string>
16
- headers?: Record<string, string>
17
- }
1
+ import type { MCPFilePath as AgentFilePath } from 'agent-files'
18
2
 
19
3
  export interface MCPAppMetadata {
20
4
  name: string
@@ -22,9 +6,7 @@ export interface MCPAppMetadata {
22
6
  paths: MCPFilePath[]
23
7
  }
24
8
 
25
- export interface MCPFilePath {
26
- filePath: string
27
- type: 'local' | 'global'
9
+ export interface MCPFilePath extends AgentFilePath {
28
10
  parsable?: boolean
29
11
  servers?: MCPServerInfo[]
30
12
  }
@@ -1,82 +0,0 @@
1
- import path from 'node:path'
2
- import fs from 'node:fs/promises'
3
- import { homedir } from 'node:os'
4
-
5
- export class DirectoryBubbleService {
6
- /**
7
- * Find a local MCP config file by bubbling up the directory tree
8
- * @param localPath - The relative path to search for (e.g., '.vscode/mcp.json')
9
- * @param startDir - The directory to start searching from
10
- * @returns The absolute path to the found config file, or null if not found
11
- */
12
- async findLocalConfigInParentDirectories (
13
- localPath: string,
14
- startDir: string
15
- ): Promise<string | null> {
16
- try {
17
- let currentDir = path.resolve(startDir)
18
- const homeDir = homedir()
19
- const rootDir = '/'
20
- let iterationCount = 0
21
- const maxIterations = 100 // Safety limit to prevent infinite loops
22
-
23
- // Check the start directory first
24
- const startDirResult = await this.checkDirectoryForConfig(currentDir, localPath)
25
- if (startDirResult) {
26
- return path.join(currentDir, localPath)
27
- }
28
-
29
- // Bubble up directory tree until we reach home directory or root
30
- while (currentDir !== homeDir && currentDir !== rootDir && iterationCount < maxIterations) {
31
- const parentDir = this.getParentDirectory(currentDir)
32
- if (!parentDir || parentDir === currentDir) {
33
- break
34
- }
35
-
36
- // Additional safety check: ensure we're actually moving up the tree
37
- if (parentDir === currentDir || parentDir.length >= currentDir.length) {
38
- break
39
- }
40
-
41
- currentDir = parentDir
42
- iterationCount++
43
-
44
- const found = await this.checkDirectoryForConfig(currentDir, localPath)
45
- if (found) {
46
- return path.join(currentDir, localPath)
47
- }
48
- }
49
-
50
- return null
51
- } catch (error) {
52
- // Silently catch errors as per requirements
53
- return null
54
- }
55
- }
56
-
57
- /**
58
- * Check if a config file exists in the specified directory
59
- * @param dir - The directory to check
60
- * @param configPath - The relative path to the config file
61
- * @returns True if the config file exists and is accessible
62
- */
63
- private async checkDirectoryForConfig (dir: string, configPath: string): Promise<boolean> {
64
- try {
65
- const fullPath = path.join(dir, configPath)
66
- await fs.access(fullPath)
67
- return true
68
- } catch (error) {
69
- return false
70
- }
71
- }
72
-
73
- /**
74
- * Get the parent directory of the specified directory
75
- * @param dir - The directory to get the parent of
76
- * @returns The parent directory path, or null if already at root
77
- */
78
- private getParentDirectory (dir: string): string | null {
79
- const parent = path.dirname(dir)
80
- return parent === dir ? null : parent
81
- }
82
- }
@@ -1,34 +0,0 @@
1
- import { MCPConfigParser } from './mcp-config-parser.js'
2
-
3
- export class MCPConfigLinterService {
4
- private parser: MCPConfigParser
5
-
6
- constructor (filePath: string) {
7
- this.parser = new MCPConfigParser(filePath)
8
- }
9
-
10
- async parseFile (): Promise<void> {
11
- // This method is kept for backward compatibility but now delegates to the parser
12
- await this.parser.parseConfigFile()
13
- }
14
-
15
- async isValidSyntax (): Promise<boolean> {
16
- return await this.parser.isValidSyntax()
17
- }
18
-
19
- async countMCPServers (): Promise<number> {
20
- return await this.parser.countMCPServers()
21
- }
22
-
23
- async getMCPServers (): Promise<Record<string, object>> {
24
- const configData = await this.parser.parseConfigFile()
25
- return configData.servers
26
- }
27
-
28
- async getFileContent (): Promise<string> {
29
- // This method is kept for backward compatibility but the parser handles file reading internally
30
- // We'll need to access the parser's internal file content
31
- const configData = await this.parser.parseConfigFile()
32
- return JSON.stringify(configData.raw, null, 2)
33
- }
34
- }
@@ -1,234 +0,0 @@
1
- import fs from 'node:fs/promises'
2
- import { parse } from 'jsonc-parser'
3
- import { type MCPConfigData, type MCPServerConfig } from '../types/mcp-config-service.types.js'
4
-
5
- export class MCPConfigParser {
6
- private filePath: string
7
- private fileContents: string | null = null
8
- private parsed: boolean = false
9
- private valid: boolean = false
10
- private fileContentsData: any | null = null
11
-
12
- constructor (filePath: string) {
13
- this.filePath = filePath
14
- }
15
-
16
- /**
17
- * Parse the configuration file and return structured data
18
- */
19
- async parseConfigFile (): Promise<MCPConfigData> {
20
- if (this.parsed) {
21
- return {
22
- raw: this.fileContentsData,
23
- parsed: this.parsed,
24
- valid: this.valid,
25
- servers: await this.extractMCPServers(this.fileContentsData)
26
- }
27
- }
28
-
29
- this.parsed = true
30
- const fileContent = await this.getFileContent()
31
-
32
- // Try parsing as standard JSON first
33
- try {
34
- this.fileContentsData = JSON.parse(fileContent)
35
- if (typeof this.fileContentsData === 'object') {
36
- this.valid = true
37
- }
38
- } catch (e) {
39
- // Ignore JSON parse errors, try JSONC next
40
- }
41
-
42
- // Try parsing as JSONC if standard JSON failed
43
- if (!this.valid) {
44
- try {
45
- this.fileContentsData = parse(fileContent)
46
- if (typeof this.fileContentsData === 'object') {
47
- this.valid = true
48
- }
49
- } catch (error) {
50
- // Ignore JSONC parse errors
51
- }
52
- }
53
-
54
- // @TODO: Add support for YAML and other formats in the future
55
-
56
- if (!this.valid) {
57
- throw new Error(`Failed to parse configuration file: ${this.filePath}`)
58
- }
59
-
60
- return {
61
- raw: this.fileContentsData,
62
- parsed: this.parsed,
63
- valid: this.valid,
64
- servers: await this.extractMCPServers(this.fileContentsData)
65
- }
66
- }
67
-
68
- /**
69
- * Extract MCP servers from parsed configuration data
70
- */
71
- async extractMCPServers (configData: any): Promise<Record<string, MCPServerConfig>> {
72
- if (!configData || typeof configData !== 'object') {
73
- return {}
74
- }
75
-
76
- // VS Code uses `servers`
77
- if (configData.servers && typeof configData.servers === 'object') {
78
- return this.normalizeServerConfigs(configData.servers)
79
- }
80
-
81
- // VS Code global settings.json file uses `mcp` -> `servers`
82
- if (configData.mcp?.servers && typeof configData.mcp.servers === 'object') {
83
- return this.normalizeServerConfigs(configData.mcp.servers)
84
- }
85
-
86
- // Claude and Cursor use the `mcpServers` key
87
- if (configData.mcpServers && typeof configData.mcpServers === 'object') {
88
- return this.normalizeServerConfigs(configData.mcpServers)
89
- }
90
-
91
- // Zed uses `context_servers` key
92
- if (configData.context_servers && typeof configData.context_servers === 'object') {
93
- return this.normalizeServerConfigs(configData.context_servers)
94
- }
95
-
96
- return {}
97
- }
98
-
99
- /**
100
- * Normalize server configurations to ensure consistent structure
101
- */
102
- private normalizeServerConfigs (servers: Record<string, any>): Record<string, MCPServerConfig> {
103
- const normalized: Record<string, MCPServerConfig> = {}
104
-
105
- for (const [serverName, serverConfig] of Object.entries(servers)) {
106
- if (serverConfig && typeof serverConfig === 'object') {
107
- const env = serverConfig.env && typeof serverConfig.env === 'object' ? serverConfig.env : undefined
108
-
109
- normalized[serverName] = {
110
- name: serverName,
111
- command: serverConfig.command || '',
112
- args: Array.isArray(serverConfig.args) ? serverConfig.args : undefined,
113
- type: this.validateType(serverConfig.type) ? serverConfig.type : this.inferTransportType(serverConfig),
114
- url: serverConfig.url,
115
- env
116
- }
117
- }
118
- }
119
-
120
- return normalized
121
- }
122
-
123
- /**
124
- * Validate type value
125
- */
126
- private validateType (type: any): type is 'sse' | 'http' | 'stdio' | 'streamable-http' {
127
- return ['sse', 'http', 'stdio', 'streamable-http'].includes(type)
128
- }
129
-
130
- /**
131
- * Infer transport type from server configuration when type field is not explicitly set
132
- */
133
- private inferTransportType (serverConfig: any): 'sse' | 'http' | 'stdio' | undefined {
134
- // Rule 1: If URL is present, infer HTTP transport
135
- if (serverConfig.url && typeof serverConfig.url === 'string') {
136
- return 'http'
137
- }
138
-
139
- // Rule 2-4: Search through args array for transport indicators
140
- if (Array.isArray(serverConfig.args)) {
141
- const argsString = serverConfig.args.join(' ').toLowerCase()
142
-
143
- // Check for stdio indicators
144
- if (argsString.includes('stdio')) {
145
- return 'stdio'
146
- }
147
-
148
- // Check for HTTP indicators
149
- if (argsString.includes('http')) {
150
- return 'http'
151
- }
152
-
153
- // Check for SSE indicators
154
- if (argsString.includes('sse')) {
155
- return 'sse'
156
- }
157
- }
158
-
159
- // Rule 5: Default to stdio if command is present but no other indicators found
160
- // This is a reasonable default since most MCP servers use stdio transport
161
- if (serverConfig.command && typeof serverConfig.command === 'string') {
162
- return 'stdio'
163
- }
164
-
165
- // No transport type could be inferred
166
- return undefined
167
- }
168
-
169
- /**
170
- * Validate server configuration
171
- */
172
- validateServerConfig (serverConfig: MCPServerConfig): boolean {
173
- if (!serverConfig || typeof serverConfig !== 'object') {
174
- return false
175
- }
176
-
177
- if (!serverConfig.name || typeof serverConfig.name !== 'string') {
178
- return false
179
- }
180
-
181
- if (!serverConfig.command || typeof serverConfig.command !== 'string') {
182
- return false
183
- }
184
-
185
- return true
186
- }
187
-
188
- /**
189
- * Get supported configuration keys that the parser recognizes
190
- */
191
- getSupportedConfigKeys (): string[] {
192
- return ['servers', 'mcp.servers', 'mcpServers', 'context_servers']
193
- }
194
-
195
- /**
196
- * Check if the configuration file has valid syntax
197
- */
198
- async isValidSyntax (): Promise<boolean> {
199
- try {
200
- const configData = await this.parseConfigFile()
201
- return configData.valid
202
- } catch (error) {
203
- return false
204
- }
205
- }
206
-
207
- /**
208
- * Count the number of MCP servers in the configuration
209
- */
210
- async countMCPServers (): Promise<number> {
211
- try {
212
- const configData = await this.parseConfigFile()
213
- return Object.keys(configData.servers).length
214
- } catch (error) {
215
- return 0
216
- }
217
- }
218
-
219
- /**
220
- * Get the raw file content
221
- */
222
- private async getFileContent (): Promise<string> {
223
- if (this.fileContents) {
224
- return this.fileContents
225
- }
226
-
227
- try {
228
- this.fileContents = await fs.readFile(this.filePath, 'utf-8')
229
- return this.fileContents
230
- } catch (error) {
231
- throw new Error(`Failed to read file: ${this.filePath}`)
232
- }
233
- }
234
- }