ls-mcp 1.9.1 → 1.11.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.
@@ -1,95 +1,34 @@
1
- import fs from 'node:fs/promises'
2
- import { parse } from 'jsonc-parser'
1
+ import { MCPConfigParser } from './mcp-config-parser.js'
3
2
 
4
3
  export class MCPConfigLinterService {
5
- private filePath: string
6
- private fileContents: string | null = null
7
- private parsed: boolean = false
8
- private valid: boolean = false
9
- private fileContentsData: any | null = null
4
+ private parser: MCPConfigParser
10
5
 
11
6
  constructor (filePath: string) {
12
- this.filePath = filePath
7
+ this.parser = new MCPConfigParser(filePath)
13
8
  }
14
9
 
15
10
  async parseFile (): Promise<void> {
16
- if (this.parsed) {
17
- return
18
- }
19
- this.parsed = true
20
-
21
- const fileContent = await this.getFileContent()
22
-
23
- // @TODO this should also support YAML files and other formats
24
- try {
25
- this.fileContentsData = JSON.parse(fileContent)
26
- if (typeof this.fileContentsData === 'object') {
27
- this.valid = true
28
- return
29
- }
30
- } catch (e) {
31
- // ignore
32
- }
33
-
34
- try {
35
- this.fileContentsData = parse(fileContent)
36
- if (typeof this.fileContentsData === 'object') {
37
- this.valid = true
38
- }
39
- } catch (error) {
40
- // ignore
41
- }
11
+ // This method is kept for backward compatibility but now delegates to the parser
12
+ await this.parser.parseConfigFile()
42
13
  }
43
14
 
44
15
  async isValidSyntax (): Promise<boolean> {
45
- try {
46
- await this.parseFile()
47
- return this.valid
48
- } catch (error) {
49
- return false
50
- }
16
+ return await this.parser.isValidSyntax()
51
17
  }
52
18
 
53
19
  async countMCPServers (): Promise<number> {
54
- try {
55
- const mcpServers = await this.getMCPServers()
56
- return Object.keys(mcpServers).length
57
- } catch (error) {
58
- return 0
59
- }
20
+ return await this.parser.countMCPServers()
60
21
  }
61
22
 
62
23
  async getMCPServers (): Promise<Record<string, object>> {
63
- await this.parseFile()
64
-
65
- // VS Code uses `servers`
66
- if (this.fileContentsData?.servers) {
67
- return this.fileContentsData.servers
68
- }
69
-
70
- // VS Code global settings.json file uses `mcp` -> `servers`
71
- if (this.fileContentsData?.mcp?.servers) {
72
- return this.fileContentsData.mcp.servers
73
- }
74
-
75
- // Claude and Cursor use the `mcpServers` key
76
- if (this.fileContentsData?.mcpServers) {
77
- return this.fileContentsData.mcpServers
78
- }
79
-
80
- // Zed uses `context_servers` key
81
- if (this.fileContentsData?.context_servers) {
82
- return this.fileContentsData.context_servers
83
- }
84
-
85
- return {}
24
+ const configData = await this.parser.parseConfigFile()
25
+ return configData.servers
86
26
  }
87
27
 
88
28
  async getFileContent (): Promise<string> {
89
- if (this.fileContents) {
90
- return this.fileContents
91
- }
92
- this.fileContents = await fs.readFile(this.filePath, 'utf-8')
93
- return this.fileContents
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)
94
33
  }
95
34
  }
@@ -0,0 +1,234 @@
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
+ }
@@ -0,0 +1,304 @@
1
+ import { platform } from 'node:os'
2
+ import path from 'node:path'
3
+ import fs from 'node:fs/promises'
4
+ import util from 'node:util'
5
+ import { MCPPathRegistry } from './mcp-path-registry.js'
6
+ import { MCPConfigParser } from './mcp-config-parser.js'
7
+ import { CredentialDetectionService } from './credential-detection-service.js'
8
+ import { DirectoryBubbleService } from './directory-bubble-service.js'
9
+ import { extractHostname } from '../utils/url-utils.js'
10
+ import {
11
+ type MCPAppPathsRecord,
12
+ type MCPFilePath,
13
+ type MCPServerInfo,
14
+ type MCPAppMetadata,
15
+ type MCPFileGroupsResultRecord
16
+ } from '../types/mcp-config-service.types.js'
17
+
18
+ export interface MCPConfigServiceOptions {
19
+ enableDirectoryBubbling?: boolean
20
+ }
21
+
22
+ export class MCPConfigService {
23
+ private pathRegistry: MCPPathRegistry
24
+ private currentOS: string
25
+ private debug: util.DebugLogger
26
+ private directoryBubbleService: DirectoryBubbleService
27
+ private enableDirectoryBubbling: boolean
28
+
29
+ constructor (options: MCPConfigServiceOptions = {}) {
30
+ this.pathRegistry = new MCPPathRegistry()
31
+ this.currentOS = platform()
32
+ this.debug = util.debuglog('ls-mcp')
33
+ this.directoryBubbleService = new DirectoryBubbleService()
34
+ this.enableDirectoryBubbling = options.enableDirectoryBubbling ?? false
35
+ }
36
+
37
+ /**
38
+ * Get MCP configuration files for a specific AI application on the current OS
39
+ */
40
+ getConfigFilesPerApp (appName: string): MCPFilePath[] {
41
+ try {
42
+ return this.pathRegistry.getPathsForApp(this.currentOS, appName)
43
+ } catch (error) {
44
+ throw new Error(`Failed to get config files for app '${appName}': ${error instanceof Error ? error.message : 'Unknown error'}`)
45
+ }
46
+ }
47
+
48
+ /**
49
+ * Get MCP configuration files for all AI applications on the current OS
50
+ */
51
+ getAllConfigFiles (): MCPAppPathsRecord {
52
+ try {
53
+ return this.pathRegistry.getPathsForOS(this.currentOS)
54
+ } catch (error) {
55
+ throw new Error(`Failed to get all config files: ${error instanceof Error ? error.message : 'Unknown error'}`)
56
+ }
57
+ }
58
+
59
+ /**
60
+ * Get MCP servers configured for a specific AI application on the current OS
61
+ */
62
+ async getMCPServersPerApp (appName: string): Promise<MCPServerInfo[]> {
63
+ try {
64
+ const appPaths = this.getConfigFilesPerApp(appName)
65
+ const allServers: MCPServerInfo[] = []
66
+
67
+ for (const filePath of appPaths) {
68
+ const servers = await this.parseConfigFileForServers(filePath.filePath)
69
+ allServers.push(...servers)
70
+ }
71
+
72
+ return allServers
73
+ } catch (error) {
74
+ throw new Error(`Failed to get MCP servers for app '${appName}': ${error instanceof Error ? error.message : 'Unknown error'}`)
75
+ }
76
+ }
77
+
78
+ /**
79
+ * Get MCP servers configured for all AI applications on the current OS
80
+ */
81
+ async getAllMCPServers (): Promise<Record<string, MCPServerInfo[]>> {
82
+ try {
83
+ const allApps = this.pathRegistry.getSupportedApps(this.currentOS)
84
+ const allServers: Record<string, MCPServerInfo[]> = {}
85
+
86
+ for (const appName of allApps) {
87
+ try {
88
+ allServers[appName] = await this.getMCPServersPerApp(appName)
89
+ } catch (error) {
90
+ // Log error but continue with other apps
91
+ this.debug(`Failed to get servers for app '${appName}': ${error instanceof Error ? error.message : 'Unknown error'}`)
92
+ allServers[appName] = []
93
+ }
94
+ }
95
+
96
+ return allServers
97
+ } catch (error) {
98
+ throw new Error(`Failed to get all MCP servers: ${error instanceof Error ? error.message : 'Unknown error'}`)
99
+ }
100
+ }
101
+
102
+ /**
103
+ * Get metadata for all supported AI applications on the current OS
104
+ */
105
+ getSupportedApps (): MCPAppMetadata[] {
106
+ try {
107
+ const appNames = this.pathRegistry.getSupportedApps(this.currentOS)
108
+ const appPaths = this.pathRegistry.getPathsForOS(this.currentOS)
109
+
110
+ return appNames.map(appName => ({
111
+ name: appName,
112
+ friendlyName: this.getFriendlyName(appName),
113
+ paths: appPaths[appName] || []
114
+ }))
115
+ } catch (error) {
116
+ throw new Error(`Failed to get supported apps: ${error instanceof Error ? error.message : 'Unknown error'}`)
117
+ }
118
+ }
119
+
120
+ /**
121
+ * Get all supported operating systems
122
+ */
123
+ getSupportedOperatingSystems (): string[] {
124
+ return this.pathRegistry.getSupportedOperatingSystems()
125
+ }
126
+
127
+ /**
128
+ * Validate if a configuration file exists and is parsable
129
+ */
130
+ async validateConfigFile (filePath: string): Promise<boolean> {
131
+ try {
132
+ await fs.access(filePath)
133
+ const parser = this.createParser(filePath)
134
+ return await parser.isValidSyntax()
135
+ } catch (error) {
136
+ return false
137
+ }
138
+ }
139
+
140
+ /**
141
+ * Create a parser instance (can be overridden for testing)
142
+ */
143
+ protected createParser (filePath: string): MCPConfigParser {
144
+ return new MCPConfigParser(filePath)
145
+ }
146
+
147
+ /**
148
+ * Get MCP file groups with resolved paths and server information
149
+ */
150
+ async getMCPFileGroups (): Promise<MCPFileGroupsResultRecord> {
151
+ try {
152
+ const appPaths = this.getAllConfigFiles()
153
+ const mcpFilesPathsData: MCPFileGroupsResultRecord = {}
154
+
155
+ for (const [groupName, paths] of Object.entries(appPaths)) {
156
+ mcpFilesPathsData[groupName] = {
157
+ name: groupName,
158
+ friendlyName: this.getFriendlyName(groupName),
159
+ paths: [],
160
+ stats: { serversCount: 0 }
161
+ }
162
+
163
+ const uniqueFilePaths = new Set<string>()
164
+ let totalServersCount = 0
165
+
166
+ for (const filePathData of paths) {
167
+ let resolvedPath = filePathData.filePath.replace('~', process.env.HOME || '')
168
+ let absolutePath = path.resolve(resolvedPath)
169
+
170
+ // For local paths, try to bubble up if not found in current directory and if enabled
171
+ if (filePathData.type === 'local' && this.enableDirectoryBubbling) {
172
+ try {
173
+ await fs.access(resolvedPath)
174
+ // File exists in current directory, no need to bubble up
175
+ } catch (error) {
176
+ // File not found in current directory, try to bubble up
177
+ const bubbledPath = await this.directoryBubbleService.findLocalConfigInParentDirectories(
178
+ filePathData.filePath,
179
+ process.cwd()
180
+ )
181
+
182
+ if (bubbledPath) {
183
+ resolvedPath = bubbledPath
184
+ absolutePath = path.resolve(resolvedPath)
185
+ }
186
+ }
187
+ }
188
+
189
+ if (uniqueFilePaths.has(absolutePath)) {
190
+ continue
191
+ }
192
+ uniqueFilePaths.add(absolutePath)
193
+
194
+ try {
195
+ await fs.access(resolvedPath)
196
+
197
+ const parser = this.createParser(resolvedPath)
198
+ const parsable = await parser.isValidSyntax()
199
+ filePathData.parsable = parsable
200
+
201
+ if (parsable) {
202
+ const configData = await parser.parseConfigFile()
203
+ const servers = await this.convertToMCPServerInfo(configData.servers || {})
204
+ filePathData.servers = servers
205
+ totalServersCount += servers.length
206
+ }
207
+
208
+ mcpFilesPathsData[groupName].paths.push(filePathData)
209
+ } catch (error) {
210
+ // File does not exist or is not accessible, continue to next
211
+ this.debug(`Skipping file ${resolvedPath}: ${error instanceof Error ? error.message : 'Unknown error'}`)
212
+ }
213
+ }
214
+
215
+ if (mcpFilesPathsData[groupName] && mcpFilesPathsData[groupName].stats) {
216
+ mcpFilesPathsData[groupName].stats.serversCount = totalServersCount
217
+ }
218
+ }
219
+
220
+ return mcpFilesPathsData
221
+ } catch (error) {
222
+ throw new Error(`Failed to get MCP file groups: ${error instanceof Error ? error.message : 'Unknown error'}`)
223
+ }
224
+ }
225
+
226
+ /**
227
+ * Register a custom app with custom paths for the current OS
228
+ */
229
+ registerCustomApp (appName: string, paths: MCPFilePath[]): void {
230
+ try {
231
+ this.pathRegistry.registerCustomApp(this.currentOS, appName, paths)
232
+ } catch (error) {
233
+ throw new Error(`Failed to register custom app '${appName}': ${error instanceof Error ? error.message : 'Unknown error'}`)
234
+ }
235
+ }
236
+
237
+ /**
238
+ * Parse a configuration file and return server information
239
+ */
240
+ private async parseConfigFileForServers (filePath: string): Promise<MCPServerInfo[]> {
241
+ try {
242
+ const parser = this.createParser(filePath)
243
+ const configData = await parser.parseConfigFile()
244
+ return await this.convertToMCPServerInfo(configData.servers || {})
245
+ } catch (error) {
246
+ this.debug(`Failed to parse config file ${filePath}: ${error instanceof Error ? error.message : 'Unknown error'}`)
247
+ return []
248
+ }
249
+ }
250
+
251
+ /**
252
+ * Convert parsed server configs to MCPServerInfo format
253
+ */
254
+ private async convertToMCPServerInfo (servers: Record<string, any>): Promise<MCPServerInfo[]> {
255
+ const serverInfos: MCPServerInfo[] = []
256
+
257
+ for (const [serverName, serverConfig] of Object.entries(servers)) {
258
+ if (serverConfig && typeof serverConfig === 'object') {
259
+ // Determine the source: extract hostname from URL or use command
260
+ let source: string
261
+ if (serverConfig.url) {
262
+ source = extractHostname(serverConfig.url)
263
+ } else {
264
+ source = serverConfig.command || ''
265
+ }
266
+
267
+ serverInfos.push({
268
+ name: serverName,
269
+ command: serverConfig.command || '',
270
+ args: Array.isArray(serverConfig.args) ? serverConfig.args : undefined,
271
+ transport: serverConfig.type === 'streamable-http' ? 'http' : serverConfig.type, // Map streamable-http to http
272
+ type: serverConfig.type,
273
+ source,
274
+ env: serverConfig.env,
275
+ status: 'stopped', // Default status, will be updated by server manager
276
+ credentials: CredentialDetectionService.analyzeEnvironmentVariables(serverConfig.env)
277
+ })
278
+ }
279
+ }
280
+
281
+ return serverInfos
282
+ }
283
+
284
+ /**
285
+ * Get friendly name for an app
286
+ */
287
+ private getFriendlyName (appName: string): string {
288
+ const friendlyNames: Record<string, string> = {
289
+ claude: 'Claude Desktop',
290
+ claude_code: 'Claude Code',
291
+ cursor: 'Cursor',
292
+ vscode: 'VS Code',
293
+ cline: 'Cline',
294
+ windsurf: 'Windsurf',
295
+ roo: 'Roo',
296
+ 'intellij-github-copilot': 'IntelliJ GitHub Copilot',
297
+ junie: 'IntelliJ Junie',
298
+ zed: 'Zed',
299
+ gemini: 'Gemini CLI'
300
+ }
301
+
302
+ return friendlyNames[appName] || appName
303
+ }
304
+ }