@wincode/mcp 0.0.0-stage → 0.1.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.
@@ -0,0 +1,1455 @@
1
+ import type { AgentId } from "@wincode/agent-core";
2
+ import { isUndefined, omitUndefined } from "@wincode/utils";
3
+ import type { JsonObject } from "type-fest";
4
+ import {
5
+ createSdkMcpClient,
6
+ createSdkMcpClientDeps,
7
+ type McpClient,
8
+ type McpClientFactoryDeps,
9
+ type McpClientResourceContent,
10
+ type McpClientTool,
11
+ } from "./client";
12
+ import type {
13
+ McpConfigLoader,
14
+ McpConfigOrigin,
15
+ McpConfigResult,
16
+ ResolvedMcpServerConfig,
17
+ } from "./config";
18
+ import { type McpSnapshotId, toMcpSnapshotId } from "./identifiers";
19
+ import {
20
+ isJsonObject,
21
+ MAX_MCP_TOOL_COUNT,
22
+ type McpToolManifest,
23
+ type McpToolManifestEntry,
24
+ } from "./manifest";
25
+ import {
26
+ type McpNormalizedResult,
27
+ normalizeMcpResultWithArtifacts,
28
+ } from "./result";
29
+ import { sanitizeMessage } from "./sanitize";
30
+ import { qualifyMcpToolName } from "./tool-identity";
31
+
32
+ export type McpServerState =
33
+ | "disabled"
34
+ | "connecting"
35
+ | "connected"
36
+ | "degraded"
37
+ | "failed";
38
+
39
+ export type McpServerStatus = {
40
+ auth: "none" | "required" | "authenticated";
41
+ error?: string;
42
+ exposure: "direct" | "hidden";
43
+ name: string;
44
+ source?: McpConfigOrigin;
45
+ state: McpServerState;
46
+ toolCount: number;
47
+ transport: "local" | "remote";
48
+ };
49
+
50
+ export type McpSnapshotTool = {
51
+ client: McpClient;
52
+ description: string;
53
+ originalToolName: string;
54
+ serverName: string;
55
+ };
56
+
57
+ export type McpResourceSummary = Readonly<{
58
+ description?: string;
59
+ mimeType?: string;
60
+ name: string;
61
+ server: string;
62
+ uri: string;
63
+ }>;
64
+
65
+ export type McpResourceTemplateSummary = Readonly<{
66
+ description?: string;
67
+ mimeType?: string;
68
+ name: string;
69
+ server: string;
70
+ uriTemplate: string;
71
+ }>;
72
+
73
+ export type McpResourcePage = Readonly<{
74
+ errors?: readonly Readonly<{ message: string; server: string }>[];
75
+ nextCursor?: string;
76
+ nextCursorByServer?: Readonly<Record<string, string>>;
77
+ resources: readonly McpResourceSummary[];
78
+ }>;
79
+
80
+ export type McpResourceTemplatePage = Readonly<{
81
+ errors?: readonly Readonly<{ message: string; server: string }>[];
82
+ nextCursor?: string;
83
+ nextCursorByServer?: Readonly<Record<string, string>>;
84
+ resourceTemplates: readonly McpResourceTemplateSummary[];
85
+ }>;
86
+
87
+ export type McpResourceRead = Readonly<{
88
+ contents: readonly McpClientResourceContent[];
89
+ server: string;
90
+ }>;
91
+
92
+ export type McpCatalogSnapshot = {
93
+ agent: AgentId;
94
+ id: McpSnapshotId;
95
+ manifest: McpToolManifest;
96
+ tools: ReadonlyMap<string, McpSnapshotTool>;
97
+ };
98
+
99
+ export type McpOAuthRedirectReader = (callback: Promise<URL>) => Promise<URL>;
100
+
101
+ export type McpRegistry = {
102
+ close(): Promise<void>;
103
+ initialize(waitForConnections?: boolean): Promise<void>;
104
+ createSnapshot(
105
+ agent: AgentId,
106
+ trackLatest?: boolean
107
+ ): Promise<McpCatalogSnapshot>;
108
+ execute(
109
+ snapshot: McpCatalogSnapshot,
110
+ toolName: string,
111
+ input: unknown,
112
+ signal?: AbortSignal
113
+ ): Promise<McpNormalizedResult>;
114
+ listResources(
115
+ serverName?: string,
116
+ cursor?: string,
117
+ signal?: AbortSignal
118
+ ): Promise<McpResourcePage>;
119
+ listResourceTemplates(
120
+ serverName?: string,
121
+ cursor?: string,
122
+ signal?: AbortSignal
123
+ ): Promise<McpResourceTemplatePage>;
124
+ readResource(
125
+ serverName: string,
126
+ uri: string,
127
+ signal?: AbortSignal
128
+ ): Promise<McpResourceRead>;
129
+ releaseSnapshot?(snapshot: McpCatalogSnapshot): void;
130
+ getStatuses(): readonly McpServerStatus[];
131
+ login(
132
+ serverName: string,
133
+ readRedirectUrl?: McpOAuthRedirectReader
134
+ ): Promise<void>;
135
+ logout(serverName: string): Promise<void>;
136
+ reconnect(serverName: string): Promise<void>;
137
+ subscribe(listener: () => void): () => void;
138
+ toggle(serverName: string): Promise<void>;
139
+ };
140
+
141
+ export type McpRegistryDeps = Readonly<{
142
+ createClient?: (config: ResolvedMcpServerConfig) => McpClient;
143
+ createOAuthProvider?: McpClientFactoryDeps["createOAuthProvider"];
144
+ env?: Readonly<Record<string, string | undefined>>;
145
+ loadConfig: McpConfigLoader;
146
+ loginOAuth?: (
147
+ config: Extract<ResolvedMcpServerConfig, { type: "remote" }>,
148
+ readRedirectUrl?: McpOAuthRedirectReader
149
+ ) => Promise<void>;
150
+ logoutOAuth?: (
151
+ config: Extract<ResolvedMcpServerConfig, { type: "remote" }>
152
+ ) => Promise<void>;
153
+ workspace: string;
154
+ }>;
155
+
156
+ type McpPageResult<Page> =
157
+ | Readonly<{ entry: ServerEntry; error: string }>
158
+ | Readonly<{ entry: ServerEntry; page: Page }>;
159
+
160
+ type ServerEntry = {
161
+ client: McpClient | undefined;
162
+ config: ResolvedMcpServerConfig;
163
+ source: McpConfigOrigin | undefined;
164
+ error: string | undefined;
165
+ executionController: AbortController;
166
+ state: McpServerState;
167
+ tools: readonly McpClientTool[];
168
+ };
169
+
170
+ type McpPageCollection<Item> = Readonly<{
171
+ errors: readonly Readonly<{ message: string; server: string }>[] | undefined;
172
+ items: readonly Item[];
173
+ nextCursor: string | undefined;
174
+ nextCursorByServer: Readonly<Record<string, string>> | undefined;
175
+ }>;
176
+
177
+ const collectResourcePages = <Page, SourceItem, Item>(
178
+ pages: readonly McpPageResult<Page>[],
179
+ serverName: string | undefined,
180
+ pageData: (page: Page) => Readonly<{
181
+ items: readonly SourceItem[];
182
+ nextCursor: string | undefined;
183
+ }>,
184
+ summarize: (entry: ServerEntry, item: SourceItem) => Item
185
+ ): McpPageCollection<Item> => {
186
+ const items: Item[] = [];
187
+ const errors: { message: string; server: string }[] = [];
188
+ const nextCursorByServer: Record<string, string> = {};
189
+ let nextCursor: string | undefined;
190
+ for (const result of pages) {
191
+ if ("error" in result) {
192
+ errors.push({ server: result.entry.config.name, message: result.error });
193
+ continue;
194
+ }
195
+ const data = pageData(result.page);
196
+ for (const item of data.items) {
197
+ items.push(summarize(result.entry, item));
198
+ }
199
+ if (data.nextCursor !== undefined) {
200
+ nextCursorByServer[result.entry.config.name] = data.nextCursor;
201
+ if (serverName === result.entry.config.name) {
202
+ nextCursor = data.nextCursor;
203
+ }
204
+ }
205
+ }
206
+ return {
207
+ errors: errors.length === 0 ? undefined : errors,
208
+ items,
209
+ nextCursor,
210
+ nextCursorByServer:
211
+ Object.keys(nextCursorByServer).length === 0
212
+ ? undefined
213
+ : nextCursorByServer,
214
+ };
215
+ };
216
+
217
+ const outputError = (message: string): McpNormalizedResult => ({
218
+ content: [{ type: "text", text: message }],
219
+ isError: true,
220
+ owner: "registry",
221
+ truncated: false,
222
+ });
223
+
224
+ const toJsonObject = (value: Record<string, unknown>): JsonObject =>
225
+ isJsonObject(value) ? value : { type: "object" };
226
+
227
+ const requestedRemoteTools = (
228
+ config: ResolvedMcpServerConfig
229
+ ): readonly string[] => {
230
+ if (config.type !== "remote") {
231
+ return [];
232
+ }
233
+ const requested = new Set<string>();
234
+ for (const value of new URL(config.url).searchParams.getAll("tools")) {
235
+ for (const name of value.split(",")) {
236
+ const trimmed = name.trim();
237
+ if (trimmed.length > 0) {
238
+ requested.add(trimmed);
239
+ }
240
+ }
241
+ }
242
+ return [...requested];
243
+ };
244
+
245
+ const matchesToolPattern = (pattern: string, toolName: string): boolean => {
246
+ const parts = pattern.split("*");
247
+ let cursor = 0;
248
+ for (const [index, part] of parts.entries()) {
249
+ if (part.length === 0) {
250
+ continue;
251
+ }
252
+ const position = toolName.indexOf(part, cursor);
253
+ if (
254
+ position < 0 ||
255
+ (index === 0 && position !== 0) ||
256
+ (index === parts.length - 1 && position + part.length !== toolName.length)
257
+ ) {
258
+ return false;
259
+ }
260
+ cursor = position + part.length;
261
+ }
262
+ return true;
263
+ };
264
+
265
+ const exposureForTool = (
266
+ config: ResolvedMcpServerConfig,
267
+ toolName: string
268
+ ): "direct" | "hidden" => {
269
+ const rules = config.toolExposure;
270
+ if (rules === undefined) {
271
+ return config.exposure ?? "direct";
272
+ }
273
+ const exact = rules[toolName];
274
+ if (exact !== undefined) {
275
+ return exact;
276
+ }
277
+ for (const [pattern, exposure] of Object.entries(rules)) {
278
+ if (!pattern.includes("*")) {
279
+ continue;
280
+ }
281
+ if (matchesToolPattern(pattern, toolName)) {
282
+ return exposure;
283
+ }
284
+ }
285
+ return config.exposure ?? "direct";
286
+ };
287
+
288
+ const defaultSdkClientFactory = (
289
+ workspace: string,
290
+ env: Record<string, string | undefined>,
291
+ createOAuthProvider: McpClientFactoryDeps["createOAuthProvider"]
292
+ ): ((config: ResolvedMcpServerConfig) => McpClient) => {
293
+ let deps: McpClientFactoryDeps | undefined;
294
+ return (config) => {
295
+ if (isUndefined(deps)) {
296
+ const environment = Object.fromEntries(
297
+ Object.entries(env).filter(
298
+ (entry): entry is [string, string] => !isUndefined(entry[1])
299
+ )
300
+ );
301
+ deps = createSdkMcpClientDeps({
302
+ clientInfo: { name: "wincode-cli", version: "0.1.0" },
303
+ ...(createOAuthProvider === undefined ? {} : { createOAuthProvider }),
304
+ environment,
305
+ workspace,
306
+ });
307
+ }
308
+ return createSdkMcpClient(config, deps);
309
+ };
310
+ };
311
+
312
+ export function createMcpRegistry(input: McpRegistryDeps): McpRegistry {
313
+ const workspace = input.workspace;
314
+ const env = input.env === undefined ? { ...process.env } : { ...input.env };
315
+ const createClient =
316
+ input.createClient ??
317
+ defaultSdkClientFactory(workspace, env, input.createOAuthProvider);
318
+
319
+ const serverEntries = new Map<string, ServerEntry>();
320
+ const invalidStatuses = new Map<string, McpServerStatus>();
321
+ const listeners = new Set<() => void>();
322
+ const closeController = new AbortController();
323
+ let closed = false;
324
+ let initPromise: Promise<void> | undefined;
325
+ let initialConnectionsPromise: Promise<void> = Promise.resolve();
326
+ let initialConnectionsSettled = true;
327
+ let initialCatalogReadyPromise: Promise<void> = Promise.resolve();
328
+ let initialized = false;
329
+ let refreshPromise: Promise<void> | undefined;
330
+ const entryOperations = new Map<string, Promise<void>>();
331
+ const reconnects = new Map<string, Promise<void>>();
332
+ const toggles = new Map<string, Promise<void>>();
333
+ let latestSnapshotId: McpSnapshotId | undefined;
334
+ const activeSnapshotIds = new Set<McpSnapshotId>();
335
+ const untrackedSnapshotIds = new Set<McpSnapshotId>();
336
+ const snapshotReplacements = new Map<McpSnapshotId, McpCatalogSnapshot>();
337
+ let catalogGeneration = 0;
338
+ let snapshotCreated = false;
339
+
340
+ const emit = (): void => {
341
+ for (const listener of [...listeners]) {
342
+ listener();
343
+ }
344
+ };
345
+
346
+ const runEntryOperation = (
347
+ serverName: string,
348
+ operation: () => Promise<void>
349
+ ): Promise<void> => {
350
+ const previous = entryOperations.get(serverName) ?? Promise.resolve();
351
+ const run = previous.catch(() => undefined).then(operation);
352
+ entryOperations.set(serverName, run);
353
+ run.then(
354
+ () => {
355
+ if (entryOperations.get(serverName) === run) {
356
+ entryOperations.delete(serverName);
357
+ }
358
+ },
359
+ () => {
360
+ if (entryOperations.get(serverName) === run) {
361
+ entryOperations.delete(serverName);
362
+ }
363
+ }
364
+ );
365
+ return run;
366
+ };
367
+
368
+ const closeClient = async (entry: ServerEntry): Promise<void> => {
369
+ const client = entry.client;
370
+ if (isUndefined(client)) {
371
+ return;
372
+ }
373
+ entry.client = undefined;
374
+ try {
375
+ await client.close();
376
+ } catch {
377
+ // closing is best-effort; errors are sanitized upstream
378
+ }
379
+ };
380
+
381
+ const startupSignal = (entry: ServerEntry): AbortSignal =>
382
+ AbortSignal.any([
383
+ AbortSignal.timeout(entry.config.timeout.startup),
384
+ closeController.signal,
385
+ ]);
386
+
387
+ const catalogSignal = (entry: ServerEntry): AbortSignal =>
388
+ AbortSignal.any([
389
+ AbortSignal.timeout(entry.config.timeout.catalog),
390
+ closeController.signal,
391
+ ]);
392
+
393
+ const publishTools = (
394
+ entry: ServerEntry,
395
+ client: McpClient,
396
+ tools: readonly McpClientTool[]
397
+ ): void => {
398
+ if (entry.client !== client) {
399
+ return;
400
+ }
401
+ entry.tools = tools;
402
+ emit();
403
+ };
404
+
405
+ const listEntryTools = async (
406
+ entry: ServerEntry,
407
+ client: McpClient
408
+ ): Promise<readonly McpClientTool[]> => {
409
+ const tools = await client.listTools(catalogSignal(entry));
410
+ const available = new Set(tools.map((tool) => tool.name));
411
+ const hasMissingRequestedTool = requestedRemoteTools(entry.config).some(
412
+ (name) => !available.has(name)
413
+ );
414
+ if (hasMissingRequestedTool) {
415
+ throw new Error("MCP server did not expose all requested tools");
416
+ }
417
+ return tools;
418
+ };
419
+
420
+ const loadCurrentConfig = (refresh = false): Promise<McpConfigResult> =>
421
+ input.loadConfig({ env, refresh, workspace });
422
+
423
+ const resourceEntriesFor = (serverName?: string): ServerEntry[] => {
424
+ if (serverName === undefined) {
425
+ return [...serverEntries.values()].filter(
426
+ (entry) =>
427
+ entry.state === "connected" &&
428
+ (entry.config.exposure ?? "direct") === "direct"
429
+ );
430
+ }
431
+ const entry = serverEntries.get(serverName);
432
+ if (entry === undefined) {
433
+ throw new Error("MCP server is unavailable");
434
+ }
435
+ return [entry];
436
+ };
437
+
438
+ const requestResourcePages = async <Page>(
439
+ entries: readonly ServerEntry[],
440
+ cursor: string | undefined,
441
+ signal: AbortSignal | undefined,
442
+ unavailableMessage: string,
443
+ request: (
444
+ client: McpClient,
445
+ cursor: string | undefined,
446
+ signal: AbortSignal
447
+ ) => Promise<Page> | undefined
448
+ ): Promise<readonly McpPageResult<Page>[]> =>
449
+ Promise.all(
450
+ entries.map(async (entry) => {
451
+ const client = entry.client;
452
+ if (
453
+ entry.state !== "connected" ||
454
+ (entry.config.exposure ?? "direct") !== "direct" ||
455
+ client === undefined
456
+ ) {
457
+ return { entry, error: unavailableMessage };
458
+ }
459
+ const signals = [catalogSignal(entry)];
460
+ if (signal !== undefined) {
461
+ signals.push(signal);
462
+ }
463
+ const pageRequest = request(client, cursor, AbortSignal.any(signals));
464
+ if (pageRequest === undefined) {
465
+ return { entry, error: unavailableMessage };
466
+ }
467
+ try {
468
+ return { entry, page: await pageRequest };
469
+ } catch (error) {
470
+ return {
471
+ entry,
472
+ error: sanitizeMessage(
473
+ entry.config,
474
+ error,
475
+ "MCP resource request failed"
476
+ ),
477
+ };
478
+ }
479
+ })
480
+ );
481
+
482
+ const listResourcePage = async <Page, SourceItem, Item>(
483
+ serverName: string | undefined,
484
+ cursor: string | undefined,
485
+ signal: AbortSignal | undefined,
486
+ unavailableMessage: string,
487
+ request: (
488
+ client: McpClient,
489
+ cursor: string | undefined,
490
+ signal: AbortSignal
491
+ ) => Promise<Page> | undefined,
492
+ pageData: (page: Page) => Readonly<{
493
+ items: readonly SourceItem[];
494
+ nextCursor: string | undefined;
495
+ }>,
496
+ summarize: (entry: ServerEntry, item: SourceItem) => Item
497
+ ): Promise<McpPageCollection<Item>> => {
498
+ await init();
499
+ const pages = await requestResourcePages(
500
+ resourceEntriesFor(serverName),
501
+ serverName === undefined ? undefined : cursor,
502
+ signal,
503
+ unavailableMessage,
504
+ request
505
+ );
506
+ return collectResourcePages(pages, serverName, pageData, summarize);
507
+ };
508
+
509
+ const listResources = async (
510
+ serverName?: string,
511
+ cursor?: string,
512
+ signal?: AbortSignal
513
+ ): Promise<McpResourcePage> => {
514
+ const collected = await listResourcePage(
515
+ serverName,
516
+ cursor,
517
+ signal,
518
+ "MCP resources are unavailable",
519
+ (client, requestCursor, requestSignal) =>
520
+ client.listResources?.(requestCursor, requestSignal),
521
+ (page) => ({ items: page.resources, nextCursor: page.nextCursor }),
522
+ (entry, resource) => ({
523
+ name: resource.name,
524
+ server: entry.config.name,
525
+ uri: resource.uri,
526
+ ...omitUndefined({
527
+ description: resource.description,
528
+ mimeType: resource.mimeType,
529
+ }),
530
+ })
531
+ );
532
+ return {
533
+ resources: collected.items,
534
+ ...omitUndefined({
535
+ nextCursor: collected.nextCursor,
536
+ nextCursorByServer: collected.nextCursorByServer,
537
+ errors: collected.errors,
538
+ }),
539
+ };
540
+ };
541
+
542
+ const listResourceTemplates = async (
543
+ serverName?: string,
544
+ cursor?: string,
545
+ signal?: AbortSignal
546
+ ): Promise<McpResourceTemplatePage> => {
547
+ const collected = await listResourcePage(
548
+ serverName,
549
+ cursor,
550
+ signal,
551
+ "MCP resource templates are unavailable",
552
+ (client, requestCursor, requestSignal) =>
553
+ client.listResourceTemplates?.(requestCursor, requestSignal),
554
+ (page) => ({
555
+ items: page.resourceTemplates,
556
+ nextCursor: page.nextCursor,
557
+ }),
558
+ (entry, resource) => ({
559
+ name: resource.name,
560
+ server: entry.config.name,
561
+ uriTemplate: resource.uriTemplate,
562
+ ...omitUndefined({
563
+ description: resource.description,
564
+ mimeType: resource.mimeType,
565
+ }),
566
+ })
567
+ );
568
+ return {
569
+ resourceTemplates: collected.items,
570
+ ...omitUndefined({
571
+ nextCursor: collected.nextCursor,
572
+ nextCursorByServer: collected.nextCursorByServer,
573
+ errors: collected.errors,
574
+ }),
575
+ };
576
+ };
577
+
578
+ const readResource = async (
579
+ serverName: string,
580
+ uri: string,
581
+ signal?: AbortSignal
582
+ ): Promise<McpResourceRead> => {
583
+ await init();
584
+ const entry = serverEntries.get(serverName);
585
+ if (
586
+ isUndefined(entry) ||
587
+ entry.state !== "connected" ||
588
+ (entry.config.exposure ?? "direct") !== "direct" ||
589
+ isUndefined(entry.client?.readResource)
590
+ ) {
591
+ throw new Error("MCP resource is unavailable");
592
+ }
593
+ const signals = [catalogSignal(entry)];
594
+ if (signal !== undefined) {
595
+ signals.push(signal);
596
+ }
597
+ try {
598
+ return {
599
+ contents: await entry.client.readResource(
600
+ uri,
601
+ AbortSignal.any(signals)
602
+ ),
603
+ server: entry.config.name,
604
+ };
605
+ } catch (error) {
606
+ throw new Error(
607
+ sanitizeMessage(entry.config, error, "MCP resource request failed")
608
+ );
609
+ }
610
+ };
611
+
612
+ const refreshEntryConfig = async (
613
+ entry: ServerEntry,
614
+ serverName: string
615
+ ): Promise<boolean> => {
616
+ const configResult = await loadCurrentConfig(true);
617
+ const config = configResult.servers[serverName];
618
+ if (!isUndefined(config)) {
619
+ entry.config = config;
620
+ entry.source = configResult.serverSources?.[serverName];
621
+ return true;
622
+ }
623
+
624
+ const diagnostic = configResult.diagnostics.find(
625
+ (item) => item.serverName === serverName
626
+ );
627
+ catalogGeneration += 1;
628
+ activeSnapshotIds.clear();
629
+ untrackedSnapshotIds.clear();
630
+ entry.executionController.abort();
631
+ entry.executionController = new AbortController();
632
+ await closeClient(entry);
633
+ entry.error = sanitizeMessage(
634
+ entry.config,
635
+ diagnostic?.message ?? "MCP server configuration is missing or invalid",
636
+ "Invalid MCP server configuration"
637
+ );
638
+ entry.state = "failed";
639
+ entry.tools = [];
640
+ emit();
641
+ return false;
642
+ };
643
+
644
+ const connectEntry = async (entry: ServerEntry): Promise<void> => {
645
+ const client = entry.client ?? createClient(entry.config);
646
+ entry.client = client;
647
+ client.setToolsChangedListener((tools) =>
648
+ publishTools(entry, client, tools)
649
+ );
650
+ entry.state = "connecting";
651
+ entry.error = undefined;
652
+ try {
653
+ await client.connect(startupSignal(entry));
654
+ if (closed) {
655
+ await closeClient(entry);
656
+ return;
657
+ }
658
+ entry.tools = await listEntryTools(entry, client);
659
+ entry.state = "connected";
660
+ entry.error = undefined;
661
+ } catch (error) {
662
+ entry.state = "failed";
663
+ entry.tools = [];
664
+ entry.error = sanitizeMessage(
665
+ entry.config,
666
+ error,
667
+ "unknown MCP registry error"
668
+ );
669
+ await closeClient(entry);
670
+ } finally {
671
+ emit();
672
+ }
673
+ };
674
+
675
+ const doInit = async (): Promise<void> => {
676
+ const configResult = await loadCurrentConfig();
677
+ for (const [name, config] of Object.entries(configResult.servers)) {
678
+ serverEntries.set(name, {
679
+ client: undefined,
680
+ config,
681
+ source: configResult.serverSources?.[name],
682
+ error: undefined,
683
+ executionController: new AbortController(),
684
+ state: config.disabled ? "disabled" : "connecting",
685
+ tools: [],
686
+ });
687
+ }
688
+ for (const invalid of Object.values(configResult.invalidServers ?? {})) {
689
+ if (serverEntries.has(invalid.name)) {
690
+ continue;
691
+ }
692
+ invalidStatuses.set(invalid.name, {
693
+ auth: "none",
694
+ error: "Invalid MCP server configuration",
695
+ exposure: "direct",
696
+ name: invalid.name,
697
+ source: configResult.serverSources?.[invalid.name],
698
+ state: "failed",
699
+ toolCount: 0,
700
+ transport: invalid.transport,
701
+ });
702
+ }
703
+ emit();
704
+ const connects: Promise<void>[] = [];
705
+ for (const entry of serverEntries.values()) {
706
+ if (entry.state !== "disabled") {
707
+ connects.push(connectEntry(entry));
708
+ }
709
+ }
710
+ initialConnectionsSettled = false;
711
+ initialConnectionsPromise = Promise.allSettled(connects).then(() => {
712
+ initialConnectionsSettled = true;
713
+ });
714
+ // The deadline bounds the wait, it is not a lifetime. Racing against
715
+ // `Bun.sleep` left a live timer holding the event loop for its full
716
+ // duration whenever the connections settled first, so a process that had
717
+ // finished every connection still took ten more seconds to exit. The
718
+ // timer is cleared on whichever side wins.
719
+ const deadline = Promise.withResolvers<void>();
720
+ const deadlineTimer = setTimeout(() => deadline.resolve(), 10_000);
721
+ initialCatalogReadyPromise = Promise.race([
722
+ initialConnectionsPromise,
723
+ deadline.promise,
724
+ ]).finally(() => {
725
+ clearTimeout(deadlineTimer);
726
+ });
727
+ };
728
+
729
+ const init = (): Promise<void> => {
730
+ if (isUndefined(initPromise)) {
731
+ initPromise = doInit().then(() => {
732
+ initialized = true;
733
+ });
734
+ }
735
+ return initPromise;
736
+ };
737
+
738
+ const buildSnapshot = async (agent: AgentId): Promise<McpCatalogSnapshot> => {
739
+ type Candidate = {
740
+ client: McpClient;
741
+ config: ResolvedMcpServerConfig;
742
+ tool: McpClientTool;
743
+ };
744
+ const candidates: Candidate[] = [];
745
+ for (const entry of serverEntries.values()) {
746
+ if (isUndefined(entry.client) || entry.state !== "connected") {
747
+ continue;
748
+ }
749
+ for (const tool of entry.tools) {
750
+ if (exposureForTool(entry.config, tool.name) === "hidden") {
751
+ continue;
752
+ }
753
+ candidates.push({
754
+ client: entry.client,
755
+ config: entry.config,
756
+ tool,
757
+ });
758
+ }
759
+ }
760
+ candidates.sort((a, b) => {
761
+ const byServer = a.config.name.localeCompare(b.config.name);
762
+ if (byServer !== 0) {
763
+ return byServer;
764
+ }
765
+ return a.tool.name.localeCompare(b.tool.name);
766
+ });
767
+ const manifest: McpToolManifestEntry[] = [];
768
+ const tools = new Map<string, McpSnapshotTool>();
769
+ let visibleCount = 0;
770
+ for (const candidate of candidates) {
771
+ const name = await qualifyMcpToolName(
772
+ candidate.config.name,
773
+ candidate.tool.name
774
+ );
775
+ const description = candidate.tool.description ?? "";
776
+ tools.set(name, {
777
+ client: candidate.client,
778
+ description,
779
+ originalToolName: candidate.tool.name,
780
+ serverName: candidate.config.name,
781
+ });
782
+ if (visibleCount < MAX_MCP_TOOL_COUNT) {
783
+ manifest.push({
784
+ name,
785
+ description,
786
+ inputSchema: toJsonObject(candidate.tool.inputSchema),
787
+ });
788
+ visibleCount += 1;
789
+ }
790
+ }
791
+ return {
792
+ agent,
793
+ id: toMcpSnapshotId(crypto.randomUUID()),
794
+ manifest,
795
+ tools,
796
+ };
797
+ };
798
+
799
+ const retainSnapshot = (
800
+ snapshot: McpCatalogSnapshot,
801
+ trackLatest: boolean
802
+ ): void => {
803
+ activeSnapshotIds.add(snapshot.id);
804
+ if (!trackLatest) {
805
+ untrackedSnapshotIds.add(snapshot.id);
806
+ return;
807
+ }
808
+ if (!isUndefined(latestSnapshotId)) {
809
+ activeSnapshotIds.delete(latestSnapshotId);
810
+ }
811
+ latestSnapshotId = snapshot.id;
812
+ };
813
+
814
+ const releaseSnapshot = (snapshot: McpCatalogSnapshot): void => {
815
+ const replacement = snapshotReplacements.get(snapshot.id);
816
+ if (!isUndefined(replacement)) {
817
+ snapshotReplacements.delete(snapshot.id);
818
+ releaseSnapshot(replacement);
819
+ }
820
+ if (snapshot.id === latestSnapshotId) {
821
+ return;
822
+ }
823
+ activeSnapshotIds.delete(snapshot.id);
824
+ untrackedSnapshotIds.delete(snapshot.id);
825
+ };
826
+
827
+ const createSnapshot = async (
828
+ agent: AgentId,
829
+ trackLatest = true
830
+ ): Promise<McpCatalogSnapshot> => {
831
+ if (closed) {
832
+ const snapshot: McpCatalogSnapshot = {
833
+ agent,
834
+ id: toMcpSnapshotId(crypto.randomUUID()),
835
+ manifest: [],
836
+ tools: new Map(),
837
+ };
838
+ retainSnapshot(snapshot, trackLatest);
839
+ return snapshot;
840
+ }
841
+ await init();
842
+ await initialCatalogReadyPromise;
843
+ if (snapshotCreated) {
844
+ const retryableEntries = [...serverEntries.values()].filter(
845
+ (entry) =>
846
+ entry.state === "degraded" ||
847
+ (entry.state === "failed" &&
848
+ entry.error !== "Invalid MCP server configuration")
849
+ );
850
+ await Promise.allSettled(
851
+ retryableEntries.map((entry) =>
852
+ runEntryOperation(entry.config.name, async () => {
853
+ if (
854
+ entry.state === "degraded" ||
855
+ (entry.state === "failed" &&
856
+ entry.error !== "Invalid MCP server configuration")
857
+ ) {
858
+ await doReconnect(entry);
859
+ }
860
+ })
861
+ )
862
+ );
863
+ }
864
+ snapshotCreated = true;
865
+ while (!closed) {
866
+ const generation = catalogGeneration;
867
+ const snapshot = await buildSnapshot(agent);
868
+ if (generation === catalogGeneration) {
869
+ retainSnapshot(snapshot, trackLatest);
870
+ return snapshot;
871
+ }
872
+ }
873
+ return {
874
+ agent,
875
+ id: toMcpSnapshotId(crypto.randomUUID()),
876
+ manifest: [],
877
+ tools: new Map(),
878
+ };
879
+ };
880
+
881
+ const executionError = (
882
+ toolName: string,
883
+ timeout: AbortSignal,
884
+ callerSignal: AbortSignal | undefined,
885
+ config: ResolvedMcpServerConfig | undefined,
886
+ error: unknown
887
+ ): string => {
888
+ if (callerSignal?.aborted) {
889
+ return `MCP tool '${toolName}' was cancelled`;
890
+ }
891
+ if (timeout.aborted) {
892
+ return `MCP tool '${toolName}' timed out`;
893
+ }
894
+ if (closeController.signal.aborted) {
895
+ return "MCP registry is closing";
896
+ }
897
+ return sanitizeMessage(config, error, "unknown MCP registry error");
898
+ };
899
+
900
+ const resolveExecutableSnapshot = (
901
+ snapshot: McpCatalogSnapshot
902
+ ): McpCatalogSnapshot | undefined => {
903
+ let current = snapshot;
904
+ let replacement = snapshotReplacements.get(current.id);
905
+ while (!isUndefined(replacement)) {
906
+ current = replacement;
907
+ replacement = snapshotReplacements.get(current.id);
908
+ }
909
+ if (
910
+ !activeSnapshotIds.has(current.id) ||
911
+ (current.id !== latestSnapshotId && !untrackedSnapshotIds.has(current.id))
912
+ ) {
913
+ return;
914
+ }
915
+ return current;
916
+ };
917
+
918
+ const matchesCurrentToolContract = (
919
+ previousSnapshot: McpCatalogSnapshot,
920
+ refreshedSnapshot: McpCatalogSnapshot,
921
+ toolName: string,
922
+ previousTool: McpSnapshotTool
923
+ ): boolean => {
924
+ const refreshedTool = refreshedSnapshot.tools.get(toolName);
925
+ const previousContract = previousSnapshot.manifest.find(
926
+ (item) => item.name === toolName
927
+ );
928
+ const refreshedContract = refreshedSnapshot.manifest.find(
929
+ (item) => item.name === toolName
930
+ );
931
+ if (
932
+ isUndefined(refreshedTool) ||
933
+ refreshedTool.serverName !== previousTool.serverName ||
934
+ refreshedTool.originalToolName !== previousTool.originalToolName ||
935
+ isUndefined(previousContract) ||
936
+ isUndefined(refreshedContract)
937
+ ) {
938
+ return false;
939
+ }
940
+ return (
941
+ previousContract.description === refreshedContract.description &&
942
+ Bun.deepEquals(
943
+ previousContract.inputSchema,
944
+ refreshedContract.inputSchema,
945
+ true
946
+ )
947
+ );
948
+ };
949
+
950
+ const recoverDegradedServer = async (
951
+ snapshot: McpCatalogSnapshot,
952
+ toolName: string,
953
+ tool: McpSnapshotTool,
954
+ entry: ServerEntry
955
+ ): Promise<McpCatalogSnapshot | string> => {
956
+ // The failed call already returned an error. Recover before executing
957
+ // this new request, but never replay the operation that just failed.
958
+ let refreshedSnapshot: McpCatalogSnapshot;
959
+ try {
960
+ refreshedSnapshot = await createSnapshot(snapshot.agent, false);
961
+ } catch (error) {
962
+ return sanitizeMessage(entry.config, error, "MCP server recovery failed");
963
+ }
964
+ if (entry.state !== "connected" || isUndefined(entry.client)) {
965
+ releaseSnapshot(refreshedSnapshot);
966
+ return (
967
+ entry.error ??
968
+ `MCP server '${entry.config.name}' is not connected after reconnect`
969
+ );
970
+ }
971
+ if (
972
+ !matchesCurrentToolContract(snapshot, refreshedSnapshot, toolName, tool)
973
+ ) {
974
+ releaseSnapshot(refreshedSnapshot);
975
+ return `MCP tool '${toolName}' changed after reconnect; retry with a fresh Agent Turn`;
976
+ }
977
+ snapshotReplacements.set(snapshot.id, refreshedSnapshot);
978
+ return refreshedSnapshot;
979
+ };
980
+
981
+ const executeConnectedTool = async (
982
+ toolName: string,
983
+ tool: McpSnapshotTool,
984
+ entry: ServerEntry,
985
+ input: unknown,
986
+ signal?: AbortSignal
987
+ ): Promise<McpNormalizedResult> => {
988
+ const timeout = AbortSignal.timeout(entry.config.timeout.execution);
989
+ const signals: AbortSignal[] = [
990
+ timeout,
991
+ closeController.signal,
992
+ entry.executionController.signal,
993
+ ];
994
+ if (!isUndefined(signal)) {
995
+ signals.push(signal);
996
+ }
997
+ const combined = AbortSignal.any(signals);
998
+ try {
999
+ const raw = await tool.client.callTool(
1000
+ tool.originalToolName,
1001
+ input,
1002
+ combined
1003
+ );
1004
+ return await normalizeMcpResultWithArtifacts(raw);
1005
+ } catch (error) {
1006
+ const message = executionError(
1007
+ toolName,
1008
+ timeout,
1009
+ signal,
1010
+ entry.config,
1011
+ error
1012
+ );
1013
+ if (
1014
+ signal?.aborted !== true &&
1015
+ !closeController.signal.aborted &&
1016
+ entry.client === tool.client &&
1017
+ !entry.executionController.signal.aborted
1018
+ ) {
1019
+ await closeClient(entry);
1020
+ entry.state = "degraded";
1021
+ entry.tools = [];
1022
+ entry.error = message;
1023
+ emit();
1024
+ }
1025
+ return outputError(message);
1026
+ }
1027
+ };
1028
+
1029
+ const execute = async (
1030
+ snapshot: McpCatalogSnapshot,
1031
+ toolName: string,
1032
+ input: unknown,
1033
+ signal?: AbortSignal
1034
+ ): Promise<McpNormalizedResult> => {
1035
+ const executableSnapshot = resolveExecutableSnapshot(snapshot);
1036
+ if (isUndefined(executableSnapshot)) {
1037
+ return outputError("MCP tool snapshot is stale or not executable");
1038
+ }
1039
+ if (executableSnapshot !== snapshot) {
1040
+ return execute(executableSnapshot, toolName, input, signal);
1041
+ }
1042
+ const tool = snapshot.tools.get(toolName);
1043
+ if (isUndefined(tool)) {
1044
+ return outputError(`Unknown MCP tool '${toolName}'`);
1045
+ }
1046
+ const entry = serverEntries.get(tool.serverName);
1047
+ if (isUndefined(entry)) {
1048
+ return outputError(`MCP server '${tool.serverName}' is not enabled`);
1049
+ }
1050
+ if (entry.state === "degraded") {
1051
+ const recovered = await recoverDegradedServer(
1052
+ snapshot,
1053
+ toolName,
1054
+ tool,
1055
+ entry
1056
+ );
1057
+ if (typeof recovered === "string") {
1058
+ return outputError(recovered);
1059
+ }
1060
+ return execute(recovered, toolName, input, signal);
1061
+ }
1062
+ if (entry.state !== "connected" || entry.client !== tool.client) {
1063
+ return outputError(`MCP server '${tool.serverName}' is not enabled`);
1064
+ }
1065
+ return executeConnectedTool(toolName, tool, entry, input, signal);
1066
+ };
1067
+
1068
+ const doReconnect = async (entry: ServerEntry): Promise<void> => {
1069
+ catalogGeneration += 1;
1070
+ activeSnapshotIds.clear();
1071
+ untrackedSnapshotIds.clear();
1072
+ entry.executionController.abort();
1073
+ entry.executionController = new AbortController();
1074
+ await closeClient(entry);
1075
+ const client = createClient(entry.config);
1076
+ entry.client = client;
1077
+ client.setToolsChangedListener((tools) =>
1078
+ publishTools(entry, client, tools)
1079
+ );
1080
+ entry.state = "connecting";
1081
+ entry.error = undefined;
1082
+ try {
1083
+ await entry.client.connect(startupSignal(entry));
1084
+ entry.tools = await listEntryTools(entry, entry.client);
1085
+ entry.state = "connected";
1086
+ entry.error = undefined;
1087
+ } catch (error) {
1088
+ entry.state = "failed";
1089
+ entry.tools = [];
1090
+ entry.error = sanitizeMessage(
1091
+ entry.config,
1092
+ error,
1093
+ "unknown MCP registry error"
1094
+ );
1095
+ await closeClient(entry);
1096
+ }
1097
+ catalogGeneration += 1;
1098
+ activeSnapshotIds.clear();
1099
+ untrackedSnapshotIds.clear();
1100
+ emit();
1101
+ };
1102
+
1103
+ const deactivateEntry = async (
1104
+ entry: ServerEntry,
1105
+ state: "disabled" | "failed",
1106
+ error?: string
1107
+ ): Promise<void> => {
1108
+ catalogGeneration += 1;
1109
+ activeSnapshotIds.clear();
1110
+ untrackedSnapshotIds.clear();
1111
+ entry.executionController.abort();
1112
+ entry.executionController = new AbortController();
1113
+ await closeClient(entry);
1114
+ entry.error = error;
1115
+ entry.state = state;
1116
+ entry.tools = [];
1117
+ };
1118
+
1119
+ const refreshExistingEntry = async (
1120
+ entry: ServerEntry,
1121
+ configResult: McpConfigResult
1122
+ ): Promise<boolean> => {
1123
+ const config = configResult.servers[entry.config.name];
1124
+ if (isUndefined(config)) {
1125
+ await deactivateEntry(
1126
+ entry,
1127
+ "failed",
1128
+ "Invalid MCP server configuration"
1129
+ );
1130
+ return false;
1131
+ }
1132
+ const configChanged = !Bun.deepEquals(entry.config, config, true);
1133
+ entry.config = config;
1134
+ entry.source = configResult.serverSources?.[entry.config.name];
1135
+ if (config.disabled) {
1136
+ if (entry.state !== "disabled") {
1137
+ await deactivateEntry(entry, "disabled");
1138
+ }
1139
+ return false;
1140
+ }
1141
+ return (
1142
+ entry.state !== "disabled" &&
1143
+ (configChanged || entry.state === "failed" || entry.state === "degraded")
1144
+ );
1145
+ };
1146
+
1147
+ const addNewResolvedEntries = (
1148
+ configResult: McpConfigResult,
1149
+ reconnectEntries: ServerEntry[]
1150
+ ): void => {
1151
+ for (const [name, config] of Object.entries(configResult.servers)) {
1152
+ if (serverEntries.has(name)) {
1153
+ continue;
1154
+ }
1155
+ invalidStatuses.delete(name);
1156
+ const entry: ServerEntry = {
1157
+ client: undefined,
1158
+ config,
1159
+ source: configResult.serverSources?.[name],
1160
+ error: undefined,
1161
+ executionController: new AbortController(),
1162
+ state: config.disabled ? "disabled" : "connecting",
1163
+ tools: [],
1164
+ };
1165
+ serverEntries.set(name, entry);
1166
+ if (!config.disabled) {
1167
+ reconnectEntries.push(entry);
1168
+ }
1169
+ }
1170
+ };
1171
+
1172
+ const syncInvalidStatuses = (configResult: McpConfigResult): void => {
1173
+ for (const invalid of Object.values(configResult.invalidServers ?? {})) {
1174
+ if (serverEntries.has(invalid.name)) {
1175
+ continue;
1176
+ }
1177
+ invalidStatuses.set(invalid.name, {
1178
+ auth: "none",
1179
+ error: "Invalid MCP server configuration",
1180
+ exposure: "direct",
1181
+ name: invalid.name,
1182
+ source: configResult.serverSources?.[invalid.name],
1183
+ state: "failed",
1184
+ toolCount: 0,
1185
+ transport: invalid.transport,
1186
+ });
1187
+ }
1188
+ };
1189
+
1190
+ const doRefresh = async (): Promise<void> => {
1191
+ const configResult = await loadCurrentConfig(true);
1192
+ const reconnectEntries: ServerEntry[] = [];
1193
+ const operations: Promise<void>[] = [];
1194
+ for (const entry of serverEntries.values()) {
1195
+ operations.push(
1196
+ runEntryOperation(entry.config.name, async () => {
1197
+ if (await refreshExistingEntry(entry, configResult)) {
1198
+ await doReconnect(entry);
1199
+ }
1200
+ })
1201
+ );
1202
+ }
1203
+ addNewResolvedEntries(configResult, reconnectEntries);
1204
+ for (const entry of reconnectEntries) {
1205
+ operations.push(
1206
+ runEntryOperation(entry.config.name, () => doReconnect(entry))
1207
+ );
1208
+ }
1209
+ syncInvalidStatuses(configResult);
1210
+ await Promise.allSettled(operations);
1211
+ emit();
1212
+ };
1213
+
1214
+ const initialize = async (waitForConnections = true): Promise<void> => {
1215
+ if (!initialized) {
1216
+ await init();
1217
+ if (waitForConnections) {
1218
+ await initialConnectionsPromise;
1219
+ }
1220
+ return;
1221
+ }
1222
+ if (waitForConnections && !initialConnectionsSettled) {
1223
+ await initialConnectionsPromise;
1224
+ return;
1225
+ }
1226
+ if (!isUndefined(refreshPromise)) {
1227
+ await refreshPromise;
1228
+ return;
1229
+ }
1230
+ const refresh = doRefresh();
1231
+ refreshPromise = refresh;
1232
+ refresh.then(
1233
+ () => {
1234
+ refreshPromise = undefined;
1235
+ },
1236
+ () => {
1237
+ refreshPromise = undefined;
1238
+ }
1239
+ );
1240
+ await refresh;
1241
+ };
1242
+
1243
+ const reconnectInvalidEntry = async (serverName: string): Promise<void> => {
1244
+ const configResult = await loadCurrentConfig(true);
1245
+ const config = configResult.servers[serverName];
1246
+ if (isUndefined(config)) {
1247
+ emit();
1248
+ return;
1249
+ }
1250
+ if (serverEntries.has(serverName)) {
1251
+ return;
1252
+ }
1253
+ const entry: ServerEntry = {
1254
+ client: undefined,
1255
+ config,
1256
+ source: configResult.serverSources?.[serverName],
1257
+ error: undefined,
1258
+ executionController: new AbortController(),
1259
+ state: config.disabled ? "disabled" : "connecting",
1260
+ tools: [],
1261
+ };
1262
+ invalidStatuses.delete(serverName);
1263
+ serverEntries.set(serverName, entry);
1264
+ if (!config.disabled) {
1265
+ await connectEntry(entry);
1266
+ }
1267
+ emit();
1268
+ };
1269
+
1270
+ const reconnectExistingEntry = async (
1271
+ entry: ServerEntry,
1272
+ serverName: string
1273
+ ): Promise<void> => {
1274
+ if (!(await refreshEntryConfig(entry, serverName))) {
1275
+ return;
1276
+ }
1277
+ if (entry.config.disabled) {
1278
+ await deactivateEntry(entry, "disabled");
1279
+ return;
1280
+ }
1281
+ await doReconnect(entry);
1282
+ };
1283
+
1284
+ const reconnect = (serverName: string): Promise<void> => {
1285
+ const inFlight = reconnects.get(serverName);
1286
+ if (!isUndefined(inFlight)) {
1287
+ return inFlight;
1288
+ }
1289
+ const run = runEntryOperation(serverName, async () => {
1290
+ await init();
1291
+ const entry = serverEntries.get(serverName);
1292
+ if (isUndefined(entry)) {
1293
+ if (invalidStatuses.has(serverName)) {
1294
+ await reconnectInvalidEntry(serverName);
1295
+ }
1296
+ return;
1297
+ }
1298
+ if (entry.state === "disabled" || entry.state === "connecting") {
1299
+ return;
1300
+ }
1301
+ await reconnectExistingEntry(entry, serverName);
1302
+ });
1303
+ reconnects.set(serverName, run);
1304
+ run.then(
1305
+ () => {
1306
+ reconnects.delete(serverName);
1307
+ },
1308
+ () => {
1309
+ reconnects.delete(serverName);
1310
+ }
1311
+ );
1312
+ return run;
1313
+ };
1314
+
1315
+ const oauthConfigFor = (
1316
+ serverName: string
1317
+ ): Extract<ResolvedMcpServerConfig, { type: "remote" }> => {
1318
+ const config = serverEntries.get(serverName)?.config;
1319
+ if (
1320
+ config === undefined ||
1321
+ config.type !== "remote" ||
1322
+ config.auth !== "oauth"
1323
+ ) {
1324
+ throw new Error(`MCP Server '${serverName}' does not use OAuth.`);
1325
+ }
1326
+ return config;
1327
+ };
1328
+
1329
+ const login = async (
1330
+ serverName: string,
1331
+ readRedirectUrl?: McpOAuthRedirectReader
1332
+ ): Promise<void> => {
1333
+ await init();
1334
+ const config = oauthConfigFor(serverName);
1335
+ if (input.loginOAuth === undefined) {
1336
+ throw new Error("MCP OAuth login is unavailable.");
1337
+ }
1338
+ await input.loginOAuth(config, readRedirectUrl);
1339
+ await reconnect(serverName);
1340
+ };
1341
+
1342
+ const logout = async (serverName: string): Promise<void> => {
1343
+ await init();
1344
+ const config = oauthConfigFor(serverName);
1345
+ if (input.logoutOAuth === undefined) {
1346
+ throw new Error("MCP OAuth logout is unavailable.");
1347
+ }
1348
+ await input.logoutOAuth(config);
1349
+ await reconnect(serverName);
1350
+ };
1351
+
1352
+ const toggle = (serverName: string): Promise<void> => {
1353
+ const inFlight = toggles.get(serverName);
1354
+ if (!isUndefined(inFlight)) {
1355
+ return inFlight;
1356
+ }
1357
+ const run = runEntryOperation(serverName, async () => {
1358
+ await init();
1359
+ const entry = serverEntries.get(serverName);
1360
+ if (isUndefined(entry)) {
1361
+ return;
1362
+ }
1363
+ if (entry.state === "disabled") {
1364
+ if (!(await refreshEntryConfig(entry, serverName))) {
1365
+ return;
1366
+ }
1367
+ await doReconnect(entry);
1368
+ return;
1369
+ }
1370
+ catalogGeneration += 1;
1371
+ activeSnapshotIds.clear();
1372
+ untrackedSnapshotIds.clear();
1373
+ entry.executionController.abort();
1374
+ await closeClient(entry);
1375
+ entry.error = undefined;
1376
+ entry.state = "disabled";
1377
+ entry.tools = [];
1378
+ emit();
1379
+ });
1380
+ toggles.set(serverName, run);
1381
+ run.then(
1382
+ () => toggles.delete(serverName),
1383
+ () => toggles.delete(serverName)
1384
+ );
1385
+ return run;
1386
+ };
1387
+
1388
+ const authFor = (entry: ServerEntry): McpServerStatus["auth"] => {
1389
+ if (entry.config.type !== "remote" || entry.config.auth !== "oauth") {
1390
+ return "none";
1391
+ }
1392
+ if (entry.state === "connected") {
1393
+ return "authenticated";
1394
+ }
1395
+ return "required";
1396
+ };
1397
+
1398
+ const getStatuses = (): readonly McpServerStatus[] => [
1399
+ ...[...serverEntries.values()].map(
1400
+ (entry): McpServerStatus => ({
1401
+ auth: authFor(entry),
1402
+ error: entry.error,
1403
+ exposure: entry.config.exposure ?? "direct",
1404
+ name: entry.config.name,
1405
+ source: entry.source,
1406
+ state: entry.state,
1407
+ toolCount: entry.tools.length,
1408
+ transport: entry.config.type,
1409
+ })
1410
+ ),
1411
+ ...invalidStatuses.values(),
1412
+ ];
1413
+
1414
+ const subscribe = (listener: () => void): (() => void) => {
1415
+ listeners.add(listener);
1416
+ return () => {
1417
+ listeners.delete(listener);
1418
+ };
1419
+ };
1420
+
1421
+ const close = async (): Promise<void> => {
1422
+ if (closed) {
1423
+ return;
1424
+ }
1425
+ closed = true;
1426
+ closeController.abort();
1427
+ if (!isUndefined(initPromise)) {
1428
+ try {
1429
+ await initPromise;
1430
+ } catch {
1431
+ // init is best-effort; individual connect failures are already surfaced
1432
+ }
1433
+ }
1434
+ await Promise.allSettled([...serverEntries.values()].map(closeClient));
1435
+ snapshotReplacements.clear();
1436
+ listeners.clear();
1437
+ };
1438
+
1439
+ return {
1440
+ close,
1441
+ createSnapshot,
1442
+ execute,
1443
+ listResources,
1444
+ listResourceTemplates,
1445
+ readResource,
1446
+ releaseSnapshot,
1447
+ getStatuses,
1448
+ initialize,
1449
+ login,
1450
+ logout,
1451
+ reconnect,
1452
+ subscribe,
1453
+ toggle,
1454
+ };
1455
+ }