-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Expand file tree
/
Copy pathMcpHub.ts
More file actions
1866 lines (1644 loc) · 61.4 KB
/
McpHub.ts
File metadata and controls
1866 lines (1644 loc) · 61.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { Client } from "@modelcontextprotocol/sdk/client/index.js"
import { StdioClientTransport, getDefaultEnvironment } from "@modelcontextprotocol/sdk/client/stdio.js"
import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js"
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"
import ReconnectingEventSource from "reconnecting-eventsource"
import {
CallToolResultSchema,
ListResourcesResultSchema,
ListResourceTemplatesResultSchema,
ListToolsResultSchema,
ReadResourceResultSchema,
} from "@modelcontextprotocol/sdk/types.js"
import chokidar, { FSWatcher } from "chokidar"
import delay from "delay"
import deepEqual from "fast-deep-equal"
import * as fs from "fs/promises"
import * as path from "path"
import * as vscode from "vscode"
import { z } from "zod"
import { t } from "../../i18n"
import { ClineProvider } from "../../core/webview/ClineProvider"
import { GlobalFileNames } from "../../shared/globalFileNames"
import {
McpResource,
McpResourceResponse,
McpResourceTemplate,
McpServer,
McpTool,
McpToolCallResponse,
} from "../../shared/mcp"
import { fileExistsAtPath } from "../../utils/fs"
import { arePathsEqual } from "../../utils/path"
import { injectVariables } from "../../utils/config"
import { NotificationService } from "./kilocode/NotificationService"
// Discriminated union for connection states
export type ConnectedMcpConnection = {
type: "connected"
server: McpServer
client: Client
transport: StdioClientTransport | SSEClientTransport | StreamableHTTPClientTransport
}
export type DisconnectedMcpConnection = {
type: "disconnected"
server: McpServer
client: null
transport: null
}
export type McpConnection = ConnectedMcpConnection | DisconnectedMcpConnection
// Enum for disable reasons
export enum DisableReason {
MCP_DISABLED = "mcpDisabled",
SERVER_DISABLED = "serverDisabled",
}
// Base configuration schema for common settings
const BaseConfigSchema = z.object({
disabled: z.boolean().optional(),
timeout: z.number().min(1).max(3600).optional().default(60),
alwaysAllow: z.array(z.string()).default([]),
watchPaths: z.array(z.string()).optional(), // paths to watch for changes and restart server
disabledTools: z.array(z.string()).default([]),
})
// Custom error messages for better user feedback
const typeErrorMessage = "Server type must be 'stdio', 'sse', or 'streamable-http'"
const stdioFieldsErrorMessage =
"For 'stdio' type servers, you must provide a 'command' field and can optionally include 'args' and 'env'"
const sseFieldsErrorMessage =
"For 'sse' type servers, you must provide a 'url' field and can optionally include 'headers'"
const streamableHttpFieldsErrorMessage =
"For 'streamable-http' type servers, you must provide a 'url' field and can optionally include 'headers'"
const mixedFieldsErrorMessage =
"Cannot mix 'stdio' and ('sse' or 'streamable-http') fields. For 'stdio' use 'command', 'args', and 'env'. For 'sse'/'streamable-http' use 'url' and 'headers'"
const missingFieldsErrorMessage =
"Server configuration must include either 'command' (for stdio) or 'url' (for sse/streamable-http) and a corresponding 'type' if 'url' is used."
// Helper function to create a refined schema with better error messages
const createServerTypeSchema = () => {
return z.union([
// Stdio config (has command field)
BaseConfigSchema.extend({
type: z.enum(["stdio"]).optional(),
command: z.string().min(1, "Command cannot be empty"),
args: z.array(z.string()).optional(),
cwd: z.string().default(() => vscode.workspace.workspaceFolders?.at(0)?.uri.fsPath ?? process.cwd()),
env: z.record(z.string()).optional(),
// Ensure no SSE fields are present
url: z.undefined().optional(),
headers: z.undefined().optional(),
})
.transform((data) => ({
...data,
type: "stdio" as const,
}))
.refine((data) => data.type === undefined || data.type === "stdio", { message: typeErrorMessage }),
// SSE config (has url field)
BaseConfigSchema.extend({
type: z.enum(["sse"]).optional(),
url: z.string().url("URL must be a valid URL format"),
headers: z.record(z.string()).optional(),
// Ensure no stdio fields are present
command: z.undefined().optional(),
args: z.undefined().optional(),
env: z.undefined().optional(),
})
.transform((data) => ({
...data,
type: "sse" as const,
}))
.refine((data) => data.type === undefined || data.type === "sse", { message: typeErrorMessage }),
// StreamableHTTP config (has url field)
BaseConfigSchema.extend({
type: z.enum(["streamable-http"]).optional(),
url: z.string().url("URL must be a valid URL format"),
headers: z.record(z.string()).optional(),
// Ensure no stdio fields are present
command: z.undefined().optional(),
args: z.undefined().optional(),
env: z.undefined().optional(),
})
.transform((data) => ({
...data,
type: "streamable-http" as const,
}))
.refine((data) => data.type === undefined || data.type === "streamable-http", {
message: typeErrorMessage,
}),
])
}
// Server configuration schema with automatic type inference and validation
export const ServerConfigSchema = createServerTypeSchema()
// Settings schema
const McpSettingsSchema = z.object({
mcpServers: z.record(ServerConfigSchema),
})
export class McpHub {
private providerRef: WeakRef<ClineProvider>
private disposables: vscode.Disposable[] = []
private settingsWatcher?: vscode.FileSystemWatcher
private fileWatchers: Map<string, FSWatcher[]> = new Map()
private projectMcpWatcher?: vscode.FileSystemWatcher
private isDisposed: boolean = false
connections: McpConnection[] = []
isConnecting: boolean = false
readonly kiloNotificationService = new NotificationService()
private refCount: number = 0 // Reference counter for active clients
private configChangeDebounceTimers: Map<string, NodeJS.Timeout> = new Map()
constructor(provider: ClineProvider) {
this.providerRef = new WeakRef(provider)
this.watchMcpSettingsFile()
this.watchProjectMcpFile().catch(console.error)
this.setupWorkspaceFoldersWatcher()
this.initializeGlobalMcpServers()
this.initializeProjectMcpServers()
}
/**
* Registers a client (e.g., ClineProvider) using this hub.
* Increments the reference count.
*/
public registerClient(): void {
this.refCount++
// console.log(`McpHub: Client registered. Ref count: ${this.refCount}`)
}
/**
* Unregisters a client. Decrements the reference count.
* If the count reaches zero, disposes the hub.
*/
public async unregisterClient(): Promise<void> {
this.refCount--
// console.log(`McpHub: Client unregistered. Ref count: ${this.refCount}`)
if (this.refCount <= 0) {
console.log("McpHub: Last client unregistered. Disposing hub.")
await this.dispose()
}
}
/**
* Validates and normalizes server configuration
* @param config The server configuration to validate
* @param serverName Optional server name for error messages
* @returns The validated configuration
* @throws Error if the configuration is invalid
*/
private validateServerConfig(config: any, serverName?: string): z.infer<typeof ServerConfigSchema> {
// Detect configuration issues before validation
const hasStdioFields = config.command !== undefined
const hasUrlFields = config.url !== undefined // Covers sse and streamable-http
// Check for mixed fields (stdio vs url-based)
if (hasStdioFields && hasUrlFields) {
throw new Error(mixedFieldsErrorMessage)
}
// Infer type for stdio if not provided
if (!config.type && hasStdioFields) {
config.type = "stdio"
}
// For url-based configs, type must be provided by the user
if (hasUrlFields && !config.type) {
throw new Error("Configuration with 'url' must explicitly specify 'type' as 'sse' or 'streamable-http'.")
}
// Validate type if provided
if (config.type && !["stdio", "sse", "streamable-http"].includes(config.type)) {
throw new Error(typeErrorMessage)
}
// Check for type/field mismatch
if (config.type === "stdio" && !hasStdioFields) {
throw new Error(stdioFieldsErrorMessage)
}
if (config.type === "sse" && !hasUrlFields) {
throw new Error(sseFieldsErrorMessage)
}
if (config.type === "streamable-http" && !hasUrlFields) {
throw new Error(streamableHttpFieldsErrorMessage)
}
// If neither command nor url is present (type alone is not enough)
if (!hasStdioFields && !hasUrlFields) {
throw new Error(missingFieldsErrorMessage)
}
// Validate the config against the schema
try {
return ServerConfigSchema.parse(config)
} catch (validationError) {
if (validationError instanceof z.ZodError) {
// Extract and format validation errors
const errorMessages = validationError.errors
.map((err) => `${err.path.join(".")}: ${err.message}`)
.join("; ")
throw new Error(
serverName
? `Invalid configuration for server "${serverName}": ${errorMessages}`
: `Invalid server configuration: ${errorMessages}`,
)
}
throw validationError
}
}
/**
* Formats and displays error messages to the user
* @param message The error message prefix
* @param error The error object
*/
private showErrorMessage(message: string, error: unknown): void {
console.error(`${message}:`, error)
}
public setupWorkspaceFoldersWatcher(): void {
// Skip if test environment is detected
if (process.env.NODE_ENV === "test") {
return
}
this.disposables.push(
vscode.workspace.onDidChangeWorkspaceFolders(async () => {
await this.updateProjectMcpServers()
await this.watchProjectMcpFile()
}),
)
}
/**
* Debounced wrapper for handling config file changes
*/
private debounceConfigChange(filePath: string, source: "global" | "project"): void {
const key = `${source}-${filePath}`
// Clear existing timer if any
const existingTimer = this.configChangeDebounceTimers.get(key)
if (existingTimer) {
clearTimeout(existingTimer)
}
// Set new timer
const timer = setTimeout(async () => {
this.configChangeDebounceTimers.delete(key)
await this.handleConfigFileChange(filePath, source)
}, 500) // 500ms debounce
this.configChangeDebounceTimers.set(key, timer)
}
private async handleConfigFileChange(filePath: string, source: "global" | "project"): Promise<void> {
try {
const content = await fs.readFile(filePath, "utf-8")
let config: any
try {
config = JSON.parse(content)
} catch (parseError) {
const errorMessage = t("mcp:errors.invalid_settings_syntax")
console.error(errorMessage, parseError)
vscode.window.showErrorMessage(errorMessage)
return
}
const result = McpSettingsSchema.safeParse(config)
if (!result.success) {
const errorMessages = result.error.errors
.map((err) => `${err.path.join(".")}: ${err.message}`)
.join("\n")
vscode.window.showErrorMessage(t("mcp:errors.invalid_settings_validation", { errorMessages }))
return
}
await this.updateServerConnections(result.data.mcpServers || {}, source)
} catch (error) {
// Check if the error is because the file doesn't exist
if (error.code === "ENOENT" && source === "project") {
// File was deleted, clean up project MCP servers
await this.cleanupProjectMcpServers()
await this.notifyWebviewOfServerChanges()
vscode.window.showInformationMessage(t("mcp:info.project_config_deleted"))
} else {
this.showErrorMessage(t("mcp:errors.failed_update_project"), error)
}
}
}
private async watchProjectMcpFile(): Promise<void> {
// Skip if test environment is detected or VSCode APIs are not available
if (process.env.NODE_ENV === "test" || !vscode.workspace.createFileSystemWatcher) {
return
}
// Clean up existing project MCP watcher if it exists
if (this.projectMcpWatcher) {
this.projectMcpWatcher.dispose()
this.projectMcpWatcher = undefined
}
if (!vscode.workspace.workspaceFolders?.length) {
return
}
const workspaceFolder = vscode.workspace.workspaceFolders[0]
const projectMcpPattern = new vscode.RelativePattern(workspaceFolder, ".kilocode/mcp.json")
// Create a file system watcher for the project MCP file pattern
this.projectMcpWatcher = vscode.workspace.createFileSystemWatcher(projectMcpPattern)
// Watch for file changes
const changeDisposable = this.projectMcpWatcher.onDidChange((uri) => {
this.debounceConfigChange(uri.fsPath, "project")
})
// Watch for file creation
const createDisposable = this.projectMcpWatcher.onDidCreate((uri) => {
this.debounceConfigChange(uri.fsPath, "project")
})
// Watch for file deletion
const deleteDisposable = this.projectMcpWatcher.onDidDelete(async () => {
// Clean up all project MCP servers when the file is deleted
await this.cleanupProjectMcpServers()
await this.notifyWebviewOfServerChanges()
vscode.window.showInformationMessage(t("mcp:info.project_config_deleted"))
})
this.disposables.push(
vscode.Disposable.from(changeDisposable, createDisposable, deleteDisposable, this.projectMcpWatcher),
)
}
private async updateProjectMcpServers(): Promise<void> {
try {
const projectMcpPath = await this.getProjectMcpPath()
if (!projectMcpPath) return
const content = await fs.readFile(projectMcpPath, "utf-8")
let config: any
try {
config = JSON.parse(content)
} catch (parseError) {
const errorMessage = t("mcp:errors.invalid_settings_syntax")
console.error(errorMessage, parseError)
vscode.window.showErrorMessage(errorMessage)
return
}
// Validate configuration structure
const result = McpSettingsSchema.safeParse(config)
if (result.success) {
await this.updateServerConnections(result.data.mcpServers || {}, "project")
} else {
// Format validation errors for better user feedback
const errorMessages = result.error.errors
.map((err) => `${err.path.join(".")}: ${err.message}`)
.join("\n")
console.error("Invalid project MCP settings format:", errorMessages)
vscode.window.showErrorMessage(t("mcp:errors.invalid_settings_validation", { errorMessages }))
}
} catch (error) {
this.showErrorMessage(t("mcp:errors.failed_update_project"), error)
}
}
private async cleanupProjectMcpServers(): Promise<void> {
// Disconnect and remove all project MCP servers
const projectConnections = this.connections.filter((conn) => conn.server.source === "project")
for (const conn of projectConnections) {
await this.deleteConnection(conn.server.name, "project")
}
// Clear project servers from the connections list
await this.updateServerConnections({}, "project", false)
}
getServers(): McpServer[] {
// Only return enabled servers
return this.connections.filter((conn) => !conn.server.disabled).map((conn) => conn.server)
}
getAllServers(): McpServer[] {
// Return all servers regardless of state
return this.connections.map((conn) => conn.server)
}
async getMcpServersPath(): Promise<string> {
const provider = this.providerRef.deref()
if (!provider) {
throw new Error("Provider not available")
}
const mcpServersPath = await provider.ensureMcpServersDirectoryExists()
return mcpServersPath
}
async getMcpSettingsFilePath(): Promise<string> {
const provider = this.providerRef.deref()
if (!provider) {
throw new Error("Provider not available")
}
const mcpSettingsFilePath = path.join(
await provider.ensureSettingsDirectoryExists(),
GlobalFileNames.mcpSettings,
)
const fileExists = await fileExistsAtPath(mcpSettingsFilePath)
if (!fileExists) {
await fs.writeFile(
mcpSettingsFilePath,
`{
"mcpServers": {
}
}`,
)
}
return mcpSettingsFilePath
}
private async watchMcpSettingsFile(): Promise<void> {
// Skip if test environment is detected or VSCode APIs are not available
if (process.env.NODE_ENV === "test" || !vscode.workspace.createFileSystemWatcher) {
return
}
// Clean up existing settings watcher if it exists
if (this.settingsWatcher) {
this.settingsWatcher.dispose()
this.settingsWatcher = undefined
}
const settingsPath = await this.getMcpSettingsFilePath()
const settingsUri = vscode.Uri.file(settingsPath)
const settingsPattern = new vscode.RelativePattern(path.dirname(settingsPath), path.basename(settingsPath))
// Create a file system watcher for the global MCP settings file
this.settingsWatcher = vscode.workspace.createFileSystemWatcher(settingsPattern)
// Watch for file changes
const changeDisposable = this.settingsWatcher.onDidChange((uri) => {
if (arePathsEqual(uri.fsPath, settingsPath)) {
this.debounceConfigChange(settingsPath, "global")
}
})
// Watch for file creation
const createDisposable = this.settingsWatcher.onDidCreate((uri) => {
if (arePathsEqual(uri.fsPath, settingsPath)) {
this.debounceConfigChange(settingsPath, "global")
}
})
this.disposables.push(vscode.Disposable.from(changeDisposable, createDisposable, this.settingsWatcher))
}
private async initializeMcpServers(source: "global" | "project"): Promise<void> {
try {
const configPath =
source === "global" ? await this.getMcpSettingsFilePath() : await this.getProjectMcpPath()
if (!configPath) {
return
}
const content = await fs.readFile(configPath, "utf-8")
const config = JSON.parse(content)
const result = McpSettingsSchema.safeParse(config)
if (result.success) {
// Pass all servers including disabled ones - they'll be handled in updateServerConnections
await this.updateServerConnections(result.data.mcpServers || {}, source, false)
} else {
const errorMessages = result.error.errors
.map((err) => `${err.path.join(".")}: ${err.message}`)
.join("\n")
console.error(`Invalid ${source} MCP settings format:`, errorMessages)
vscode.window.showErrorMessage(t("mcp:errors.invalid_settings_validation", { errorMessages }))
if (source === "global") {
// Still try to connect with the raw config, but show warnings
try {
await this.updateServerConnections(config.mcpServers || {}, source, false)
} catch (error) {
this.showErrorMessage(`Failed to initialize ${source} MCP servers with raw config`, error)
}
}
}
} catch (error) {
if (error instanceof SyntaxError) {
const errorMessage = t("mcp:errors.invalid_settings_syntax")
console.error(errorMessage, error)
vscode.window.showErrorMessage(errorMessage)
} else {
this.showErrorMessage(`Failed to initialize ${source} MCP servers`, error)
}
}
}
private async initializeGlobalMcpServers(): Promise<void> {
await this.initializeMcpServers("global")
}
// Get project-level MCP configuration path
private async getProjectMcpPath(): Promise<string | null> {
if (!vscode.workspace.workspaceFolders?.length) {
return null
}
const workspaceFolder = vscode.workspace.workspaceFolders[0]
// kilocode_change
// First, we try the standard location: .kilocode/mcp.json
// If not found, fall back to .mcp.json in the project root
const projectMcpDir = path.join(workspaceFolder.uri.fsPath, ".kilocode")
const projectMcpPath = path.join(projectMcpDir, "mcp.json")
try {
await fs.access(projectMcpPath)
return projectMcpPath
} catch {
// If not found in .kilocode/, fall back to .mcp.json in root directory
const rootMcpPath = path.join(workspaceFolder.uri.fsPath, ".mcp.json")
try {
await fs.access(rootMcpPath)
return rootMcpPath
} catch {
return null
}
}
}
// Initialize project-level MCP servers
private async initializeProjectMcpServers(): Promise<void> {
await this.initializeMcpServers("project")
}
/**
* Creates a placeholder connection for disabled servers or when MCP is globally disabled
* @param name The server name
* @param config The server configuration
* @param source The source of the server (global or project)
* @param reason The reason for creating a placeholder (mcpDisabled or serverDisabled)
* @returns A placeholder DisconnectedMcpConnection object
*/
private createPlaceholderConnection(
name: string,
config: z.infer<typeof ServerConfigSchema>,
source: "global" | "project",
reason: DisableReason,
): DisconnectedMcpConnection {
return {
type: "disconnected",
server: {
name,
config: JSON.stringify(config),
status: "disconnected",
disabled: reason === DisableReason.SERVER_DISABLED ? true : config.disabled,
source,
projectPath: source === "project" ? vscode.workspace.workspaceFolders?.[0]?.uri.fsPath : undefined,
errorHistory: [],
},
client: null,
transport: null,
}
}
/**
* Checks if MCP is globally enabled
* @returns Promise<boolean> indicating if MCP is enabled
*/
private async isMcpEnabled(): Promise<boolean> {
const provider = this.providerRef.deref()
if (!provider) {
return true // Default to enabled if provider is not available
}
const state = await provider.getState()
return state.mcpEnabled ?? true
}
private async connectToServer(
name: string,
config: z.infer<typeof ServerConfigSchema>,
source: "global" | "project" = "global",
): Promise<void> {
// Remove existing connection if it exists with the same source
await this.deleteConnection(name, source)
// Check if MCP is globally enabled
const mcpEnabled = await this.isMcpEnabled()
if (!mcpEnabled) {
// Still create a connection object to track the server, but don't actually connect
const connection = this.createPlaceholderConnection(name, config, source, DisableReason.MCP_DISABLED)
this.connections.push(connection)
return
}
// Skip connecting to disabled servers
if (config.disabled) {
// Still create a connection object to track the server, but don't actually connect
const connection = this.createPlaceholderConnection(name, config, source, DisableReason.SERVER_DISABLED)
this.connections.push(connection)
return
}
// Set up file watchers for enabled servers
this.setupFileWatcher(name, config, source)
try {
const client = new Client(
{
name: "Kilo Code",
version: this.providerRef.deref()?.context.extension?.packageJSON?.version ?? "1.0.0",
},
{
capabilities: {},
},
)
let transport: StdioClientTransport | SSEClientTransport | StreamableHTTPClientTransport
// Inject variables to the config (environment, magic variables,...)
const configInjected = (await injectVariables(config, {
env: process.env,
workspaceFolder: vscode.workspace.workspaceFolders?.[0]?.uri.fsPath ?? "",
})) as typeof config
if (configInjected.type === "stdio") {
// On Windows, wrap commands with cmd.exe to handle non-exe executables like npx.ps1
// This is necessary for node version managers (fnm, nvm-windows, volta) that implement
// commands as PowerShell scripts rather than executables.
// Note: This adds a small overhead as commands go through an additional shell layer.
const isWindows = process.platform === "win32"
// Check if command is already cmd.exe to avoid double-wrapping
const isAlreadyWrapped =
configInjected.command.toLowerCase() === "cmd.exe" || configInjected.command.toLowerCase() === "cmd"
const command = isWindows && !isAlreadyWrapped ? "cmd.exe" : configInjected.command
const args =
isWindows && !isAlreadyWrapped
? ["/c", configInjected.command, ...(configInjected.args || [])]
: configInjected.args
transport = new StdioClientTransport({
command,
args,
cwd: configInjected.cwd,
env: {
...getDefaultEnvironment(),
...(configInjected.env || {}),
},
stderr: "pipe",
})
// Set up stdio specific error handling
transport.onerror = async (error) => {
console.error(`Transport error for "${name}":`, error)
const connection = this.findConnection(name, source)
if (connection) {
connection.server.status = "disconnected"
this.appendErrorMessage(connection, error instanceof Error ? error.message : `${error}`)
}
await this.notifyWebviewOfServerChanges()
}
transport.onclose = async () => {
const connection = this.findConnection(name, source)
if (connection) {
connection.server.status = "disconnected"
}
await this.notifyWebviewOfServerChanges()
}
// transport.stderr is only available after the process has been started. However we can't start it separately from the .connect() call because it also starts the transport. And we can't place this after the connect call since we need to capture the stderr stream before the connection is established, in order to capture errors during the connection process.
// As a workaround, we start the transport ourselves, and then monkey-patch the start method to no-op so that .connect() doesn't try to start it again.
await transport.start()
const stderrStream = transport.stderr
if (stderrStream) {
stderrStream.on("data", async (data: Buffer) => {
const output = data.toString()
// Check if output contains INFO level log
const isInfoLog = /INFO/i.test(output)
if (isInfoLog) {
// Log normal informational messages
console.log(`Server "${name}" info:`, output)
} else {
// Treat as error log
console.error(`Server "${name}" stderr:`, output)
const connection = this.findConnection(name, source)
if (connection) {
this.appendErrorMessage(connection, output)
if (connection.server.status === "disconnected") {
await this.notifyWebviewOfServerChanges()
}
}
}
})
} else {
console.error(`No stderr stream for ${name}`)
}
} else if (configInjected.type === "streamable-http") {
// Streamable HTTP connection
transport = new StreamableHTTPClientTransport(new URL(configInjected.url), {
requestInit: {
headers: configInjected.headers,
},
})
// Set up Streamable HTTP specific error handling
transport.onerror = async (error) => {
console.error(`Transport error for "${name}" (streamable-http):`, error)
const connection = this.findConnection(name, source)
if (connection) {
connection.server.status = "disconnected"
this.appendErrorMessage(connection, error instanceof Error ? error.message : `${error}`)
}
await this.notifyWebviewOfServerChanges()
}
transport.onclose = async () => {
const connection = this.findConnection(name, source)
if (connection) {
connection.server.status = "disconnected"
}
await this.notifyWebviewOfServerChanges()
}
} else if (configInjected.type === "sse") {
// SSE connection
const sseOptions = {
requestInit: {
headers: configInjected.headers,
},
}
// Configure ReconnectingEventSource options
const reconnectingEventSourceOptions = {
max_retry_time: 5000, // Maximum retry time in milliseconds
withCredentials: configInjected.headers?.["Authorization"] ? true : false, // Enable credentials if Authorization header exists
fetch: (url: string | URL, init: RequestInit) => {
const headers = new Headers({ ...(init?.headers || {}), ...(configInjected.headers || {}) })
return fetch(url, {
...init,
headers,
})
},
}
global.EventSource = ReconnectingEventSource
transport = new SSEClientTransport(new URL(configInjected.url), {
...sseOptions,
eventSourceInit: reconnectingEventSourceOptions,
})
// Set up SSE specific error handling
transport.onerror = async (error) => {
console.error(`Transport error for "${name}":`, error)
const connection = this.findConnection(name, source)
if (connection) {
connection.server.status = "disconnected"
this.appendErrorMessage(connection, error instanceof Error ? error.message : `${error}`)
}
await this.notifyWebviewOfServerChanges()
}
transport.onclose = async () => {
const connection = this.findConnection(name, source)
if (connection) {
connection.server.status = "disconnected"
}
await this.notifyWebviewOfServerChanges()
}
} else {
// Should not happen if validateServerConfig is correct
throw new Error(`Unsupported MCP server type: ${(configInjected as any).type}`)
}
// Only override transport.start for stdio transports that have already been started
if (configInjected.type === "stdio") {
transport.start = async () => {}
}
// Create a connected connection
const connection: ConnectedMcpConnection = {
type: "connected",
server: {
name,
config: JSON.stringify(configInjected),
status: "connecting",
disabled: configInjected.disabled,
source,
projectPath: source === "project" ? vscode.workspace.workspaceFolders?.[0]?.uri.fsPath : undefined,
errorHistory: [],
},
client,
transport,
}
this.connections.push(connection)
// Connect (this will automatically start the transport)
await client.connect(transport)
connection.server.status = "connected"
connection.server.error = ""
connection.server.instructions = client.getInstructions()
this.kiloNotificationService.connect(name, connection.client)
// Initial fetch of tools and resources
connection.server.tools = await this.fetchToolsList(name, source)
connection.server.resources = await this.fetchResourcesList(name, source)
connection.server.resourceTemplates = await this.fetchResourceTemplatesList(name, source)
} catch (error) {
// Update status with error
const connection = this.findConnection(name, source)
if (connection) {
connection.server.status = "disconnected"
this.appendErrorMessage(connection, error instanceof Error ? error.message : `${error}`)
}
throw error
}
}
private appendErrorMessage(connection: McpConnection, error: string, level: "error" | "warn" | "info" = "error") {
const MAX_ERROR_LENGTH = 1000
const truncatedError =
error.length > MAX_ERROR_LENGTH
? `${error.substring(0, MAX_ERROR_LENGTH)}...(error message truncated)`
: error
// Add to error history
if (!connection.server.errorHistory) {
connection.server.errorHistory = []
}
connection.server.errorHistory.push({
message: truncatedError,
timestamp: Date.now(),
level,
})
// Keep only the last 100 errors
if (connection.server.errorHistory.length > 100) {
connection.server.errorHistory = connection.server.errorHistory.slice(-100)
}
// Update current error display
connection.server.error = truncatedError
}
/**
* Helper method to find a connection by server name and source
* @param serverName The name of the server to find
* @param source Optional source to filter by (global or project)
* @returns The matching connection or undefined if not found
*/
private findConnection(serverName: string, source?: "global" | "project"): McpConnection | undefined {
// If source is specified, only find servers with that source
if (source !== undefined) {
return this.connections.find((conn) => conn.server.name === serverName && conn.server.source === source)
}
// If no source is specified, first look for project servers, then global servers
// This ensures that when servers have the same name, project servers are prioritized
const projectConn = this.connections.find(
(conn) => conn.server.name === serverName && conn.server.source === "project",
)
if (projectConn) return projectConn
// If no project server is found, look for global servers
return this.connections.find(
(conn) => conn.server.name === serverName && (conn.server.source === "global" || !conn.server.source),
)
}
private async fetchToolsList(serverName: string, source?: "global" | "project"): Promise<McpTool[]> {
try {
// Use the helper method to find the connection
const connection = this.findConnection(serverName, source)
if (!connection || connection.type !== "connected") {
return []
}
const response = await connection.client.request({ method: "tools/list" }, ListToolsResultSchema)
// Determine the actual source of the server
const actualSource = connection.server.source || "global"
let configPath: string
let alwaysAllowConfig: string[] = []
let disabledToolsList: string[] = []
// Read from the appropriate config file based on the actual source
try {
let serverConfigData: Record<string, any> = {}
if (actualSource === "project") {
// Get project MCP config path
const projectMcpPath = await this.getProjectMcpPath()
if (projectMcpPath) {
configPath = projectMcpPath
const content = await fs.readFile(configPath, "utf-8")
serverConfigData = JSON.parse(content)
}
} else {
// Get global MCP settings path
configPath = await this.getMcpSettingsFilePath()
const content = await fs.readFile(configPath, "utf-8")
serverConfigData = JSON.parse(content)
}
if (serverConfigData) {
alwaysAllowConfig = serverConfigData.mcpServers?.[serverName]?.alwaysAllow || []
disabledToolsList = serverConfigData.mcpServers?.[serverName]?.disabledTools || []
}
} catch (error) {
console.error(`Failed to read tool configuration for ${serverName}:`, error)
// Continue with empty configs
}
// Mark tools as always allowed and enabled for prompt based on settings
const tools = (response?.tools || []).map((tool) => ({
...tool,
alwaysAllow: alwaysAllowConfig.includes(tool.name),
enabledForPrompt: !disabledToolsList.includes(tool.name),
}))
return tools
} catch (error) {
console.error(`Failed to fetch tools for ${serverName}:`, error)
return []
}
}
private async fetchResourcesList(serverName: string, source?: "global" | "project"): Promise<McpResource[]> {
try {
const connection = this.findConnection(serverName, source)
if (!connection || connection.type !== "connected") {
return []
}
const response = await connection.client.request({ method: "resources/list" }, ListResourcesResultSchema)
return response?.resources || []
} catch (error) {
// console.error(`Failed to fetch resources for ${serverName}:`, error)
return []
}
}
private async fetchResourceTemplatesList(
serverName: string,
source?: "global" | "project",
): Promise<McpResourceTemplate[]> {
try {
const connection = this.findConnection(serverName, source)
if (!connection || connection.type !== "connected") {