-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathclient.ts
1283 lines (1139 loc) · 36.7 KB
/
client.ts
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 } from "@modelcontextprotocol/sdk/client/stdio.js";
import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
import type { StructuredToolInterface } from "@langchain/core/tools";
import * as fs from "fs";
import * as path from "path";
import debug from "debug";
import { loadMcpTools } from "./tools.js";
// Read package name from package.json
let debugLog: debug.Debugger;
function getDebugLog() {
if (!debugLog) {
debugLog = debug("@langchain/mcp-adapters:client");
}
return debugLog;
}
/**
* Configuration for stdio transport connection
*/
export interface StdioConnection {
transport: "stdio";
command: string;
args: string[];
env?: Record<string, string>;
encoding?: string;
encodingErrorHandler?: "strict" | "ignore" | "replace";
/**
* Additional restart settings
*/
restart?: {
/**
* Whether to automatically restart the process if it exits
*/
enabled?: boolean;
/**
* Maximum number of restart attempts
*/
maxAttempts?: number;
/**
* Delay in milliseconds between restart attempts
*/
delayMs?: number;
};
}
/**
* Configuration for SSE transport connection
*/
export interface SSEConnection {
transport: "sse";
url: string;
headers?: Record<string, string>;
useNodeEventSource?: boolean;
/**
* Additional reconnection settings
*/
reconnect?: {
/**
* Whether to automatically reconnect if the connection is lost
*/
enabled?: boolean;
/**
* Maximum number of reconnection attempts
*/
maxAttempts?: number;
/**
* Delay in milliseconds between reconnection attempts
*/
delayMs?: number;
};
}
/**
* Union type for all transport connection types
*/
export type Connection = StdioConnection | SSEConnection;
/**
* MCP configuration file format
*/
export interface MCPConfig {
servers: Record<string, Connection>;
}
/**
* Error class for MCP client operations
*/
export class MCPClientError extends Error {
constructor(message: string, public readonly serverName?: string) {
super(message);
this.name = "MCPClientError";
}
}
/**
* Client for connecting to multiple MCP servers and loading LangChain-compatible tools.
*/
export class MultiServerMCPClient {
private clients: Map<string, Client> = new Map();
private serverNameToTools: Map<string, StructuredToolInterface[]> = new Map();
private connections?: Record<string, Connection>;
private cleanupFunctions: Array<() => Promise<void>> = [];
private transportInstances: Map<
string,
StdioClientTransport | SSEClientTransport
> = new Map();
/**
* Create a new MultiServerMCPClient.
*
* @param connections - Optional connections to initialize
*/
constructor(connections?: Record<string, Connection>) {
if (connections) {
this.connections = MultiServerMCPClient.processConnections(connections);
} else {
// Try to load from default mcp.json if no connections are provided
this.connections = MultiServerMCPClient.tryLoadDefaultConfig();
}
}
/**
* Try to load the default configuration file (mcp.json) from the root directory
*/
private static tryLoadDefaultConfig():
| Record<string, Connection>
| undefined {
const defaultConfigPath = path.join(process.cwd(), "mcp.json");
if (fs.existsSync(defaultConfigPath)) {
getDebugLog()(
`INFO: Found default configuration at ${defaultConfigPath}, loading automatically`
);
const config = MultiServerMCPClient.loadConfigFromFile(defaultConfigPath);
return MultiServerMCPClient.processConnections(config.servers);
} else {
getDebugLog()(`INFO: No default mcp.json found in root directory`);
// don't throw if there's no default config to load
return undefined;
}
}
/**
* Load a configuration from a file
*
* @param configPath - Path to the configuration file
* @returns The parsed configuration
*/
private static loadConfigFromFile(configPath: string): MCPConfig {
const configData = fs.readFileSync(configPath, "utf8");
const config = JSON.parse(configData);
// Validate that config has a servers property
if (!config || typeof config !== "object" || !("servers" in config)) {
getDebugLog()(
`ERROR: Invalid MCP configuration from ${configPath}: missing 'servers' property`
);
throw new MCPClientError(
`Invalid MCP configuration: missing 'servers' property`
);
}
// Process environment variables in the configuration
MultiServerMCPClient.processEnvVarsInConfig(
Object.fromEntries(
Object.entries(
config.servers as Record<string, StdioConnection>
).filter(([_, value]) => value.transport === "stdio")
)
);
return config;
}
/**
* Process environment variables in configuration
* Replaces ${ENV_VAR} with the actual environment variable value
*
* @param servers - The servers configuration object
*/
private static processEnvVarsInConfig(
servers: Record<string, StdioConnection>
): void {
for (const [serverName, config] of Object.entries(servers)) {
if (typeof config !== "object" || config === null) continue;
// Process env object if it exists
if (config.env && typeof config.env === "object") {
for (const [key, value] of Object.entries(config.env)) {
if (
typeof value === "string" &&
value.startsWith("${") &&
value.endsWith("}")
) {
const envVar = value.slice(2, -1);
const envValue = process.env[envVar];
if (envValue) {
config.env[key] = envValue;
} else {
getDebugLog()(
`WARN: Environment variable ${envVar} not found for server "${serverName}"`
);
}
}
}
}
// Process any other string properties recursively
MultiServerMCPClient.processEnvVarsRecursively(config);
}
}
/**
* Process environment variables recursively in an object
*
* @param obj - The object to process
*/
private static processEnvVarsRecursively<T extends object>(obj: T): void {
if (typeof obj !== "object" || obj === null) return;
for (const [key, value] of Object.entries(obj)) {
if (
typeof value === "string" &&
value.startsWith("${") &&
value.endsWith("}")
) {
const envVar = value.slice(2, -1);
const envValue = process.env[envVar];
if (envValue) {
// eslint-disable-next-line no-param-reassign
obj[key as keyof T] = envValue as T[keyof T];
}
} else if (typeof value === "object" && value !== null && key !== "env") {
// Skip env object as it's handled separately
MultiServerMCPClient.processEnvVarsRecursively(value);
}
}
}
/**
* Process connection configurations
*
* @param connections - Raw connection configurations
* @returns Processed connection configurations
*/
private static processConnections(
connections: Record<string, Partial<Connection>>
): Record<string, Connection> {
const processedConnections: Record<string, Connection> = {};
for (const [serverName, config] of Object.entries(connections)) {
if (typeof config !== "object" || config === null) {
getDebugLog()(
`WARN: Invalid configuration for server "${serverName}". Skipping.`
);
continue;
}
// Determine the connection type and process accordingly
if (MultiServerMCPClient.isStdioConnection(config)) {
processedConnections[serverName] =
MultiServerMCPClient.processStdioConfig(serverName, config);
} else if (MultiServerMCPClient.isSSEConnection(config)) {
processedConnections[serverName] =
MultiServerMCPClient.processSSEConfig(serverName, config);
} else {
throw new MCPClientError(
`Server "${serverName}" has invalid or unsupported configuration. Skipping.`
);
}
}
return processedConnections;
}
/**
* Check if a configuration is for a stdio connection
*/
private static isStdioConnection(config: unknown): config is StdioConnection {
// When transport is missing, default to stdio if it has command and args
// OR when transport is explicitly set to 'stdio'
return (
typeof config === "object" &&
config !== null &&
(!("transport" in config) || config.transport === "stdio") &&
"command" in config &&
(!("args" in config) || Array.isArray(config.args))
);
}
/**
* Check if a configuration is for an SSE connection
*/
private static isSSEConnection(config: unknown): config is SSEConnection {
// Only consider it an SSE connection if transport is explicitly set to 'sse'
return (
typeof config === "object" &&
config !== null &&
"transport" in config &&
config.transport === "sse" &&
"url" in config &&
typeof config.url === "string"
);
}
/**
* Process stdio connection configuration
*/
private static processStdioConfig(
serverName: string,
config: Partial<StdioConnection>
): StdioConnection {
if (!config.command || typeof config.command !== "string") {
throw new MCPClientError(
`Missing or invalid command for server "${serverName}"`
);
}
if (config.args !== undefined && !Array.isArray(config.args)) {
throw new MCPClientError(
`Invalid args for server "${serverName} - must be an array of strings`
);
}
if (
config.args !== undefined &&
!config.args.every((arg) => typeof arg === "string")
) {
throw new MCPClientError(
`Invalid args for server "${serverName} - must be an array of strings`
);
}
// Always set transport to 'stdio' regardless of whether it was in the original config
const stdioConfig: StdioConnection = {
transport: "stdio",
command: config.command,
args: config.args ?? [],
};
if (config.env && typeof config.env !== "object") {
throw new MCPClientError(
`Invalid env for server "${serverName} - must be an object of key-value pairs`
);
}
if (
config.env &&
typeof config.env === "object" &&
Array.isArray(config.env)
) {
throw new MCPClientError(
`Invalid env for server "${serverName} - must be an object of key-value pairs`
);
}
if (
config.env &&
typeof config.env === "object" &&
!Object.values(config.env).every((value) => typeof value === "string")
) {
throw new MCPClientError(
`Invalid env for server "${serverName} - must be an object of key-value pairs with string values`
);
}
// Add optional properties if they exist
if (config.env && typeof config.env === "object") {
stdioConfig.env = config.env;
}
if (config.encoding !== undefined && typeof config.encoding !== "string") {
throw new MCPClientError(
`Invalid encoding for server "${serverName} - must be a string`
);
}
if (typeof config.encoding === "string") {
stdioConfig.encoding = config.encoding;
}
if (
config.encodingErrorHandler !== undefined &&
!["strict", "ignore", "replace"].includes(config.encodingErrorHandler)
) {
throw new MCPClientError(
`Invalid encodingErrorHandler for server "${serverName} - must be one of: strict, ignore, replace`
);
}
if (
["strict", "ignore", "replace"].includes(
config.encodingErrorHandler ?? ""
)
) {
stdioConfig.encodingErrorHandler = config.encodingErrorHandler as
| "strict"
| "ignore"
| "replace";
}
// Add restart configuration if present
if (config.restart && typeof config.restart !== "object") {
throw new MCPClientError(
`Invalid restart for server "${serverName} - must be an object`
);
}
if (config.restart && typeof config.restart === "object") {
if (
config.restart.enabled !== undefined &&
typeof config.restart.enabled !== "boolean"
) {
throw new MCPClientError(
`Invalid restart.enabled for server "${serverName} - must be a boolean`
);
}
stdioConfig.restart = {
enabled: Boolean(config.restart.enabled),
};
if (
config.restart.maxAttempts !== undefined &&
typeof config.restart.maxAttempts !== "number"
) {
throw new MCPClientError(
`Invalid restart.maxAttempts for server "${serverName} - must be a number`
);
}
if (typeof config.restart.maxAttempts === "number") {
stdioConfig.restart.maxAttempts = config.restart.maxAttempts;
}
if (
config.restart.delayMs !== undefined &&
typeof config.restart.delayMs !== "number"
) {
throw new MCPClientError(
`Invalid restart.delayMs for server "${serverName} - must be a number`
);
}
if (typeof config.restart.delayMs === "number") {
stdioConfig.restart.delayMs = config.restart.delayMs;
}
}
return stdioConfig;
}
/**
* Process SSE connection configuration
*/
private static processSSEConfig(
serverName: string,
config: SSEConnection
): SSEConnection {
if (!config.url || typeof config.url !== "string") {
throw new MCPClientError(
`Missing or invalid url for server "${serverName}"`
);
}
try {
const url = new URL(config.url);
if (!url.protocol.startsWith("http")) {
throw new MCPClientError(
`Invalid url for server "${serverName} - must be a valid HTTP or HTTPS URL`
);
}
} catch {
throw new MCPClientError(
`Invalid url for server "${serverName} - must be a valid URL`
);
}
if (!config.transport || config.transport !== "sse") {
throw new MCPClientError(
`Invalid transport for server "${serverName} - must be 'sse'`
);
}
const sseConfig: SSEConnection = {
transport: "sse",
url: config.url,
};
if (config.headers && typeof config.headers !== "object") {
throw new MCPClientError(
`Invalid headers for server "${serverName} - must be an object`
);
}
if (
config.headers &&
typeof config.headers === "object" &&
Array.isArray(config.headers)
) {
throw new MCPClientError(
`Invalid headers for server "${serverName} - must be an object of key-value pairs`
);
}
if (
config.headers &&
typeof config.headers === "object" &&
!Object.values(config.headers).every((value) => typeof value === "string")
) {
throw new MCPClientError(
`Invalid headers for server "${serverName} - must be an object of key-value pairs with string values`
);
}
// Add optional headers if they exist
if (config.headers && typeof config.headers === "object") {
sseConfig.headers = config.headers;
}
if (
config.useNodeEventSource !== undefined &&
typeof config.useNodeEventSource !== "boolean"
) {
throw new MCPClientError(
`Invalid useNodeEventSource for server "${serverName} - must be a boolean`
);
}
// Add optional useNodeEventSource flag if it exists
if (typeof config.useNodeEventSource === "boolean") {
sseConfig.useNodeEventSource = config.useNodeEventSource;
}
if (config.reconnect && typeof config.reconnect !== "object") {
throw new MCPClientError(
`Invalid reconnect for server "${serverName} - must be an object`
);
}
// Add reconnection configuration if present
if (config.reconnect && typeof config.reconnect === "object") {
if (
config.reconnect.enabled !== undefined &&
typeof config.reconnect.enabled !== "boolean"
) {
throw new MCPClientError(
`Invalid reconnect.enabled for server "${serverName} - must be a boolean`
);
}
sseConfig.reconnect = {
enabled: Boolean(config.reconnect.enabled),
};
if (
config.reconnect.maxAttempts !== undefined &&
typeof config.reconnect.maxAttempts !== "number"
) {
throw new MCPClientError(
`Invalid reconnect.maxAttempts for server "${serverName} - must be a number`
);
}
if (typeof config.reconnect.maxAttempts === "number") {
sseConfig.reconnect.maxAttempts = config.reconnect.maxAttempts;
}
if (
config.reconnect.delayMs !== undefined &&
typeof config.reconnect.delayMs !== "number"
) {
throw new MCPClientError(
`Invalid reconnect.delayMs for server "${serverName} - must be a number`
);
}
if (typeof config.reconnect.delayMs === "number") {
sseConfig.reconnect.delayMs = config.reconnect.delayMs;
}
}
return sseConfig;
}
/**
* Load a configuration from a JSON file.
*
* @param configPath - Path to the configuration file
* @returns A new MultiServerMCPClient
* @throws {MCPClientError} If the configuration file cannot be loaded or parsed
*/
static fromConfigFile(configPath: string): MultiServerMCPClient {
try {
const client = new MultiServerMCPClient();
const config = MultiServerMCPClient.loadConfigFromFile(configPath);
// Merge with existing connections if any
if (client.connections) {
client.connections = {
...client.connections,
...MultiServerMCPClient.processConnections(config.servers),
};
} else {
client.connections = MultiServerMCPClient.processConnections(
config.servers
);
}
getDebugLog()(`INFO: Loaded MCP configuration from ${configPath}`);
return client;
} catch (error) {
getDebugLog()(
`ERROR: Failed to load MCP configuration from ${configPath}: ${error}`
);
throw new MCPClientError(`Failed to load MCP configuration: ${error}`);
}
}
/**
* Initialize connections to all servers.
*
* @returns A map of server names to arrays of tools
* @throws {MCPClientError} If initialization fails
*/
async initializeConnections(): Promise<
Map<string, StructuredToolInterface[]>
> {
if (!this.connections || Object.keys(this.connections).length === 0) {
getDebugLog()(`WARN: No connections to initialize`);
return new Map();
}
for (const [serverName, connection] of Object.entries(this.connections)) {
getDebugLog()(
`INFO: Initializing connection to server "${serverName}"...`
);
if (connection.transport === "stdio") {
await this.initializeStdioConnection(serverName, connection);
} else if (connection.transport === "sse") {
await this.initializeSSEConnection(serverName, connection);
} else {
// This should never happen due to the validation in the constructor
throw new MCPClientError(
`Unsupported transport type for server "${serverName}"`,
serverName
);
}
}
return this.serverNameToTools;
}
/**
* Initialize a stdio connection
*/
private async initializeStdioConnection(
serverName: string,
connection: StdioConnection
): Promise<void> {
const { command, args, env, restart } = connection;
getDebugLog()(
`DEBUG: Creating stdio transport for server "${serverName}" with command: ${command} ${args.join(
" "
)}`
);
const transport = new StdioClientTransport({
command,
args,
env,
});
this.transportInstances.set(serverName, transport);
const client = new Client({
name: "langchain-mcp-adapter",
version: "0.1.0",
});
try {
await client.connect(transport);
// Set up auto-restart if configured
if (restart?.enabled) {
this.setupStdioRestart(serverName, transport, connection, restart);
}
} catch (error) {
throw new MCPClientError(
`Failed to connect to stdio server "${serverName}": ${error}`,
serverName
);
}
this.clients.set(serverName, client);
const cleanup = async () => {
getDebugLog()(
`DEBUG: Closing stdio transport for server "${serverName}"`
);
await transport.close();
};
this.cleanupFunctions.push(cleanup);
// Load tools for this server
await this.loadToolsForServer(serverName, client);
}
/**
* Set up stdio restart handling
*/
private setupStdioRestart(
serverName: string,
transport: StdioClientTransport,
connection: StdioConnection,
restart: NonNullable<StdioConnection["restart"]>
): void {
const originalOnClose = transport.onclose;
// eslint-disable-next-line no-param-reassign, @typescript-eslint/no-misused-promises
transport.onclose = async () => {
if (originalOnClose) {
await originalOnClose();
}
// Only attempt restart if we haven't cleaned up
if (this.clients.has(serverName)) {
getDebugLog()(
`INFO: Process for server "${serverName}" exited, attempting to restart...`
);
await this.attemptReconnect(
serverName,
connection,
restart.maxAttempts,
restart.delayMs
);
}
};
}
/**
* Initialize an SSE connection
*/
private async initializeSSEConnection(
serverName: string,
connection: SSEConnection
): Promise<void> {
const { url, headers, useNodeEventSource, reconnect } = connection;
getDebugLog()(
`DEBUG: Creating SSE transport for server "${serverName}" with URL: ${url}`
);
try {
const transport = await this.createSSETransport(
serverName,
url,
headers,
useNodeEventSource
);
this.transportInstances.set(serverName, transport);
const client = new Client({
name: "langchain-mcp-adapter",
version: "0.1.0",
});
try {
await client.connect(transport);
// Set up auto-reconnect if configured
if (reconnect?.enabled) {
this.setupSSEReconnect(serverName, transport, connection, reconnect);
}
} catch (error) {
throw new MCPClientError(
`Failed to connect to SSE server "${serverName}": ${error}`,
serverName
);
}
this.clients.set(serverName, client);
const cleanup = async () => {
getDebugLog()(
`DEBUG: Closing SSE transport for server "${serverName}"`
);
await transport.close();
};
this.cleanupFunctions.push(cleanup);
// Load tools for this server
await this.loadToolsForServer(serverName, client);
} catch (error) {
throw new MCPClientError(
`Failed to create SSE transport for server "${serverName}": ${error}`,
serverName
);
}
}
/**
* Create an SSE transport with appropriate EventSource implementation
*/
private async createSSETransport(
serverName: string,
url: string,
headers?: Record<string, string>,
useNodeEventSource?: boolean
): Promise<SSEClientTransport> {
if (!headers) {
// Simple case - no headers, use default transport
return new SSEClientTransport(new URL(url));
}
getDebugLog()(
`DEBUG: Using custom headers for SSE transport to server "${serverName}"`
);
// If useNodeEventSource is true, try Node.js implementations
if (useNodeEventSource) {
return await this.createNodeEventSourceTransport(
serverName,
url,
headers
);
}
// For browser environments, use the basic requestInit approach
getDebugLog()(
`DEBUG: Using browser EventSource for server "${serverName}". Headers may not be applied correctly.`
);
getDebugLog()(
`DEBUG: For better headers support in browsers, consider using a custom SSE implementation.`
);
return new SSEClientTransport(new URL(url), {
requestInit: { headers },
});
}
/**
* Create an EventSource transport for Node.js environments
*/
private async createNodeEventSourceTransport(
serverName: string,
url: string,
headers: Record<string, string>
): Promise<SSEClientTransport> {
// First try to use extended-eventsource which has better headers support
try {
const ExtendedEventSourceModule = await import("extended-eventsource");
const ExtendedEventSource = ExtendedEventSourceModule.EventSource;
getDebugLog()(
`DEBUG: Using Extended EventSource for server "${serverName}"`
);
getDebugLog()(
`DEBUG: Setting headers for Extended EventSource: ${JSON.stringify(
headers
)}`
);
// Override the global EventSource with the extended implementation
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(globalThis as any).EventSource = ExtendedEventSource;
// For Extended EventSource, create the SSE transport
return new SSEClientTransport(new URL(url), {
// Pass empty options for test compatibility
eventSourceInit: {},
requestInit: {},
});
} catch (extendedError) {
// Fall back to standard eventsource if extended-eventsource is not available
getDebugLog()(
`DEBUG: Extended EventSource not available, falling back to standard EventSource: ${extendedError}`
);
try {
// Dynamically import the eventsource package
// eslint-disable-next-line import/no-extraneous-dependencies
const EventSourceModule = await import("eventsource");
const EventSource =
"default" in EventSourceModule
? EventSourceModule.default
: EventSourceModule.EventSource;
getDebugLog()(
`DEBUG: Using Node.js EventSource for server "${serverName}"`
);
getDebugLog()(
`DEBUG: Setting headers for EventSource: ${JSON.stringify(headers)}`
);
// Override the global EventSource with the Node.js implementation
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(globalThis as any).EventSource = EventSource;
// Create transport with headers correctly configured for Node.js EventSource
return new SSEClientTransport(new URL(url), {
// Pass the headers to both eventSourceInit and requestInit for compatibility
requestInit: { headers },
});
} catch (nodeError) {
getDebugLog()(
`WARN: Failed to load EventSource packages for server "${serverName}". Headers may not be applied to SSE connection: ${nodeError}`
);
// Last resort fallback
return new SSEClientTransport(new URL(url), {
requestInit: { headers },
});
}
}
}
/**
* Set up SSE reconnect handling
*/
private setupSSEReconnect(
serverName: string,
transport: SSEClientTransport,
connection: SSEConnection,
reconnect: NonNullable<SSEConnection["reconnect"]>
): void {
const originalOnClose = transport.onclose;
// eslint-disable-next-line @typescript-eslint/no-misused-promises, no-param-reassign
transport.onclose = async () => {
if (originalOnClose) {
await originalOnClose();
}
// Only attempt reconnect if we haven't cleaned up
if (this.clients.has(serverName)) {
getDebugLog()(
`INFO: SSE connection for server "${serverName}" closed, attempting to reconnect...`
);
await this.attemptReconnect(
serverName,
connection,
reconnect.maxAttempts,
reconnect.delayMs
);
}
};
}
/**
* Load tools for a specific server
*/
private async loadToolsForServer(
serverName: string,
client: Client
): Promise<void> {
try {
getDebugLog()(`DEBUG: Loading tools for server "${serverName}"...`);
const tools = await loadMcpTools(serverName, client);
this.serverNameToTools.set(serverName, tools);
getDebugLog()(
`INFO: Successfully loaded ${tools.length} tools from server "${serverName}"`
);
} catch (error) {
throw new MCPClientError(
`Failed to load tools from server "${serverName}": ${error}`
);
}
}
/**
* Attempt to reconnect to a server after a connection failure.
*
* @param serverName - The name of the server to reconnect to
* @param connection - The connection configuration
* @param maxAttempts - Maximum number of reconnection attempts
* @param delayMs - Delay in milliseconds between reconnection attempts
* @private
*/
private async attemptReconnect(
serverName: string,
connection: Connection,
maxAttempts = 3,
delayMs = 1000
): Promise<void> {
let connected = false;
let attempts = 0;
// Clean up previous connection resources
this.cleanupServerResources(serverName);
while (
!connected &&