@njuptlzf/mcp-adapter 2.29.0-0.0.1

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.
Files changed (131) hide show
  1. package/CHANGELOG.md +1205 -0
  2. package/LICENSE +21 -0
  3. package/MAPPING.md +73 -0
  4. package/README.md +564 -0
  5. package/abort.ts +34 -0
  6. package/adapters/pi-renderer.ts +7 -0
  7. package/adapters/protocol-elicitation-forwarder.ts +164 -0
  8. package/adapters/protocol-sampling-forwarder.ts +108 -0
  9. package/adapters/universal-host.ts +213 -0
  10. package/agent-dir.ts +68 -0
  11. package/agent-plugin-loader.ts +377 -0
  12. package/app-bridge.bundle.js +67 -0
  13. package/banner.png +0 -0
  14. package/bin/mcp-server.ts +282 -0
  15. package/cli.js +392 -0
  16. package/commands.ts +735 -0
  17. package/config.ts +1284 -0
  18. package/consent-manager.ts +64 -0
  19. package/direct-tools.ts +619 -0
  20. package/dist/agent-dir.d.ts +10 -0
  21. package/dist/agent-dir.js +63 -0
  22. package/dist/agent-dir.js.map +1 -0
  23. package/dist/agent-plugin-loader.d.ts +8 -0
  24. package/dist/agent-plugin-loader.js +356 -0
  25. package/dist/agent-plugin-loader.js.map +1 -0
  26. package/dist/config.d.ts +123 -0
  27. package/dist/config.js +1087 -0
  28. package/dist/config.js.map +1 -0
  29. package/dist/metadata-cache.d.ts +19 -0
  30. package/dist/metadata-cache.js +319 -0
  31. package/dist/metadata-cache.js.map +1 -0
  32. package/dist/package-mcp-loader.d.ts +2 -0
  33. package/dist/package-mcp-loader.js +156 -0
  34. package/dist/package-mcp-loader.js.map +1 -0
  35. package/dist/resource-tools.d.ts +1 -0
  36. package/dist/resource-tools.js +15 -0
  37. package/dist/resource-tools.js.map +1 -0
  38. package/dist/types.d.ts +564 -0
  39. package/dist/types.js +287 -0
  40. package/dist/types.js.map +1 -0
  41. package/dist/ui-app-bridge-helpers.d.ts +6 -0
  42. package/dist/ui-app-bridge-helpers.js +37 -0
  43. package/dist/ui-app-bridge-helpers.js.map +1 -0
  44. package/dist/ui-stream-types.d.ts +104 -0
  45. package/dist/ui-stream-types.js +59 -0
  46. package/dist/ui-stream-types.js.map +1 -0
  47. package/dist/ui-tool-visibility.d.ts +4 -0
  48. package/dist/ui-tool-visibility.js +27 -0
  49. package/dist/ui-tool-visibility.js.map +1 -0
  50. package/dist/utils.d.ts +32 -0
  51. package/dist/utils.js +338 -0
  52. package/dist/utils.js.map +1 -0
  53. package/elicitation-handler.ts +348 -0
  54. package/error-signal.ts +21 -0
  55. package/errors.ts +223 -0
  56. package/failure-backoff.ts +23 -0
  57. package/glimpse-ui.ts +80 -0
  58. package/host-html-template.ts +461 -0
  59. package/index.ts +1291 -0
  60. package/init.ts +692 -0
  61. package/interfaces/agent-paths.ts +67 -0
  62. package/interfaces/host-types.ts +102 -0
  63. package/interfaces/sampling.ts +57 -0
  64. package/json-schema-validator.ts +69 -0
  65. package/lifecycle.ts +446 -0
  66. package/logger.ts +169 -0
  67. package/mcp-auth-flow.ts +1026 -0
  68. package/mcp-auth.ts +1000 -0
  69. package/mcp-bearer-store.ts +387 -0
  70. package/mcp-callback-server.ts +534 -0
  71. package/mcp-code.ts +360 -0
  72. package/mcp-keyring-helper.cjs +89 -0
  73. package/mcp-oauth-provider.ts +666 -0
  74. package/mcp-output-guard.ts +496 -0
  75. package/mcp-panel.ts +1044 -0
  76. package/mcp-probe.ts +201 -0
  77. package/mcp-references.ts +368 -0
  78. package/mcp-script-worker.mjs +130 -0
  79. package/mcp-server.mjs +2133 -0
  80. package/mcp-setup-panel.ts +667 -0
  81. package/mcp-status.ts +98 -0
  82. package/mcp-trace.ts +306 -0
  83. package/metadata-cache.ts +382 -0
  84. package/namespace-tools.ts +276 -0
  85. package/npx-resolver.ts +543 -0
  86. package/oauth-handler.ts +30 -0
  87. package/oauth.ts +48 -0
  88. package/onboarding-state.ts +76 -0
  89. package/package-mcp-loader.ts +168 -0
  90. package/package.json +225 -0
  91. package/panel-keys.ts +53 -0
  92. package/prompts.ts +353 -0
  93. package/proxy-modes.ts +1418 -0
  94. package/request-headers-command.ts +330 -0
  95. package/resource-tools.ts +17 -0
  96. package/runtime-owner.ts +91 -0
  97. package/sampling-handler.ts +284 -0
  98. package/search-ranking.ts +278 -0
  99. package/server-manager.ts +1318 -0
  100. package/session-recovery.ts +158 -0
  101. package/skills/README.md +64 -0
  102. package/skills/mcp-adapter/SKILL.md +332 -0
  103. package/skills/mcp-adapter/references/deploy-examples.md +259 -0
  104. package/skills/mcp-adapter/references/deploy.md +89 -0
  105. package/skills/mcp-adapter/references/generate.md +144 -0
  106. package/skills/mcp-adapter/references/resolver.md +105 -0
  107. package/skills/mcp-adapter/references/verify.md +157 -0
  108. package/skills/mcp-scripting/SKILL.md +38 -0
  109. package/skills/resolve-conflicts/SKILL.md +482 -0
  110. package/skills/resolve-conflicts/references/patterns.md +432 -0
  111. package/skills/resolve-conflicts/references/sample-plan.md +96 -0
  112. package/skills/resolve-conflicts/scripts/handle-deleted-modified.sh +183 -0
  113. package/skills/resolve-conflicts/scripts/validate-conflicts.sh +120 -0
  114. package/skills/upstream-merge/SKILL.md +486 -0
  115. package/skills/upstream-merge/references/pi-coupling-markers.md +129 -0
  116. package/skills/upstream-merge/references/special-cases.md +39 -0
  117. package/state.ts +60 -0
  118. package/tool-approval.ts +195 -0
  119. package/tool-metadata.ts +296 -0
  120. package/tool-registrar.ts +253 -0
  121. package/tool-result-renderer.ts +477 -0
  122. package/ts-shape.ts +149 -0
  123. package/types.ts +991 -0
  124. package/ui-app-bridge-helpers.ts +40 -0
  125. package/ui-resource-handler.ts +250 -0
  126. package/ui-server.ts +852 -0
  127. package/ui-session.ts +571 -0
  128. package/ui-stream-types.ts +89 -0
  129. package/ui-tool-visibility.ts +25 -0
  130. package/unix-socket-transport.ts +85 -0
  131. package/utils.ts +382 -0
@@ -0,0 +1,1318 @@
1
+ import { mkdirSync, statSync } from "node:fs";
2
+ import { isDeepStrictEqual } from "node:util";
3
+ import {
4
+ Client,
5
+ SdkError,
6
+ SdkErrorCode,
7
+ SdkHttpError,
8
+ SSEClientTransport,
9
+ StreamableHTTPClientTransport,
10
+ UnauthorizedError,
11
+ type GetPromptResult,
12
+ type ListToolsResult,
13
+ type ReadResourceResult,
14
+ type CacheableRequestOptions,
15
+ type RequestOptions,
16
+ type UrlElicitationRequiredError,
17
+ type VersionNegotiationOptions,
18
+ } from "@modelcontextprotocol/client";
19
+ import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
20
+ import { UnixSocketClientTransport } from "./unix-socket-transport.ts";
21
+ import { probeMcpEndpoint } from "./mcp-probe.ts";
22
+ import {
23
+ isServerDisabled,
24
+ type McpTool,
25
+ type McpResource,
26
+ type McpPrompt,
27
+ type ServerDefinition,
28
+ type ServerStreamResultPatchNotification,
29
+ type Transport,
30
+ type McpTraceSettings,
31
+ SERVER_STREAM_RESULT_PATCH_METHOD,
32
+ serverStreamResultPatchNotificationSchema,
33
+ } from "./types.ts";
34
+ import { resolveNpxBinary } from "./npx-resolver.ts";
35
+ import { createJsonSchemaValidator } from "./json-schema-validator.ts";
36
+ import { logger } from "./logger.ts";
37
+ import { McpOAuthProvider } from "./mcp-oauth-provider.ts";
38
+ import { extractOAuthConfig, supportsOAuth, type McpOAuthRuntime } from "./mcp-auth-flow.ts";
39
+ import { invalidateAuthEntryCache, type AuthStorageOptions } from "./mcp-auth.ts";
40
+ import { getBearerTokenForUrl } from "./mcp-bearer-store.ts";
41
+ import { registerSamplingHandler, type ServerSamplingConfig } from "./sampling-handler.ts";
42
+ import {
43
+ handleUrlElicitation,
44
+ registerElicitationHandler,
45
+ type ServerElicitationConfig,
46
+ } from "./elicitation-handler.ts";
47
+ import {
48
+ interpolateEnvVars,
49
+ resolveBearerToken,
50
+ resolveCommandSecret,
51
+ resolveCommandSecretsRecord,
52
+ resolveConfigPath,
53
+ resolveServerUrl,
54
+ } from "./utils.ts";
55
+ import { abortable, throwIfAborted } from "./abort.ts";
56
+ import { combineAbortSignals } from "./runtime-owner.ts";
57
+ import {
58
+ createMcpTraceWriter,
59
+ isMcpTraceEnabled,
60
+ McpTraceWriter,
61
+ type McpTraceObserver,
62
+ traceTransportKind,
63
+ wrapTransportWithMcpTrace,
64
+ } from "./mcp-trace.ts";
65
+ import { createRequestHeadersCommandFetch } from "./request-headers-command.ts";
66
+
67
+ const MAX_CAPTURED_STDERR_BYTES = 8 * 1024;
68
+ const MAX_CAPTURED_STDERR_LINES = 3;
69
+ const abortCleanupPromises = new WeakMap<object, Promise<void>>();
70
+
71
+ type HttpAuthProviderState =
72
+ | { status: "disabled" }
73
+ | { status: "implicit-deferred" }
74
+ | { status: "explicit"; provider: McpOAuthProvider }
75
+ | { status: "implicit-challenged"; provider: McpOAuthProvider };
76
+
77
+ function isUnauthorizedHttpError(error: unknown): boolean {
78
+ return error instanceof UnauthorizedError || (error instanceof SdkHttpError && error.status === 401);
79
+ }
80
+
81
+ function shouldFallbackToSse(error: unknown, definition: ServerDefinition): boolean {
82
+ if (definition.protocolVersion === "2026-07-28") return false;
83
+ return error instanceof SdkHttpError && [404, 405, 406, 415].includes(error.status);
84
+ }
85
+
86
+ function resolveVersionNegotiation(definition: ServerDefinition): VersionNegotiationOptions | undefined {
87
+ switch (definition.protocolVersion) {
88
+ case undefined:
89
+ case "legacy":
90
+ return undefined;
91
+ case "auto":
92
+ return { mode: "auto" };
93
+ case "2026-07-28":
94
+ return { mode: { pin: "2026-07-28" } };
95
+ default:
96
+ throw new Error(`Invalid MCP protocolVersion: ${String(definition.protocolVersion)}`);
97
+ }
98
+ }
99
+
100
+ function boundedStderrChunk(chunk: Buffer | string): Buffer {
101
+ if (Buffer.isBuffer(chunk)) {
102
+ const start = Math.max(0, chunk.byteLength - MAX_CAPTURED_STDERR_BYTES);
103
+ return Buffer.from(chunk.subarray(start));
104
+ }
105
+
106
+ // Limit string conversion before encoding; Buffer.from(largeString) would
107
+ // otherwise allocate the entire stderr event before applying the cap.
108
+ const suffix = chunk.length > MAX_CAPTURED_STDERR_BYTES
109
+ ? chunk.slice(-MAX_CAPTURED_STDERR_BYTES)
110
+ : chunk;
111
+ const bytes = Buffer.from(suffix, "utf8");
112
+ return bytes.byteLength > MAX_CAPTURED_STDERR_BYTES
113
+ ? Buffer.from(bytes.subarray(bytes.byteLength - MAX_CAPTURED_STDERR_BYTES))
114
+ : bytes;
115
+ }
116
+
117
+ function appendStderrTail(tail: Buffer, chunk: Buffer | string): Buffer {
118
+ const bytes = boundedStderrChunk(chunk);
119
+ if (bytes.length === 0) return tail;
120
+ if (tail.length === 0) return bytes;
121
+ const combined = Buffer.concat([tail, bytes]);
122
+ return combined.length > MAX_CAPTURED_STDERR_BYTES
123
+ ? Buffer.from(combined.subarray(combined.length - MAX_CAPTURED_STDERR_BYTES))
124
+ : combined;
125
+ }
126
+
127
+ export interface ServerConnection {
128
+ client: Client;
129
+ transport: Transport;
130
+ definition: ServerDefinition;
131
+ tools: McpTool[];
132
+ /** Cache hints from the server's aggregated tools/list result. */
133
+ toolListHints?: Partial<Pick<ListToolsResult, "ttlMs" | "cacheScope">> | undefined;
134
+ /** Monotonic guard against older refresh responses replacing newer notifications. */
135
+ toolsRevision?: number;
136
+ resources: McpResource[];
137
+ prompts: McpPrompt[];
138
+ /** True when prompts were advertised but prompts/list failed. */
139
+ promptDiscoveryFailed?: boolean;
140
+ instructions?: string;
141
+ lastUsedAt: number;
142
+ inFlight: number;
143
+ status: "connected" | "closed" | "needs-auth";
144
+ /** True once this needs-auth episode discarded the cached credential. */
145
+ credentialsInvalidated?: boolean;
146
+ }
147
+
148
+
149
+ type UiStreamListener = (serverName: string, notification: ServerStreamResultPatchNotification["params"]) => void;
150
+ type MetadataListChangedListener = (serverName: string, reason: string) => void;
151
+
152
+ export type ToolRefreshResult = "updated" | "unchanged" | "superseded" | "refresh-timeout";
153
+
154
+ type ToolListCacheHints = Partial<Pick<ListToolsResult, "ttlMs" | "cacheScope">>;
155
+ type ToolListResult = { tools: McpTool[]; hints?: ToolListCacheHints };
156
+
157
+ const KEEP_ALIVE_REFRESH_TIMEOUT_MS = 5_000;
158
+
159
+ export function isTransientHttpConnectError(error: unknown): boolean {
160
+ let current: unknown = error;
161
+ while (current instanceof Error) {
162
+ if (current instanceof SdkHttpError && current.status === 503) return true;
163
+ current = current.cause;
164
+ }
165
+ return false;
166
+ }
167
+
168
+ export class McpServerManager {
169
+ private connections = new Map<string, ServerConnection>();
170
+ private connectPromises = new Map<string, Promise<ServerConnection>>();
171
+ private reconnectPromises = new Map<string, Promise<ServerConnection>>();
172
+ private uiStreamListeners = new Map<string, UiStreamListener>();
173
+ private samplingConfig: ServerSamplingConfig | undefined;
174
+ private metadataListChangedListener: MetadataListChangedListener | undefined;
175
+ private pendingMetadataPublications = new Map<
176
+ string,
177
+ { connection: ServerConnection; reason: string }
178
+ >();
179
+ private elicitationConfig: ServerElicitationConfig | undefined;
180
+ private authStorageOptions: AuthStorageOptions = {};
181
+ private oauthRuntime: McpOAuthRuntime | undefined;
182
+ private acceptedUrlElicitations = new Map<string, Set<string>>();
183
+ private defaultRequestTimeoutMs: number | undefined;
184
+ private runtimeSignal: AbortSignal | undefined;
185
+ private closePromises = new Map<string, Promise<void>>();
186
+ private closeGenerations = new Map<string, number>();
187
+ private connectAttempts = new Map<string, AbortController>();
188
+ private traceSettings: McpTraceSettings | undefined;
189
+ private traceWriter: McpTraceWriter | undefined;
190
+ private stopped = false;
191
+
192
+ /** Default cwd for stdio servers without an explicit config `cwd`. */
193
+ constructor(private readonly defaultCwd?: string) {}
194
+
195
+ setSamplingConfig(config: ServerSamplingConfig | undefined): void {
196
+ this.samplingConfig = config;
197
+ }
198
+
199
+ setMetadataListChangedListener(listener: MetadataListChangedListener | undefined): void {
200
+ this.metadataListChangedListener = listener;
201
+ }
202
+
203
+ publishMetadataChanged(
204
+ name: string,
205
+ expectedConnection: ServerConnection,
206
+ reason: string,
207
+ ): boolean {
208
+ const current = this.connections.get(name);
209
+ if (current !== expectedConnection || current.status !== "connected") return false;
210
+ try {
211
+ this.metadataListChangedListener?.(name, reason);
212
+ this.pendingMetadataPublications.delete(name);
213
+ return true;
214
+ } catch (error) {
215
+ this.pendingMetadataPublications.set(name, { connection: expectedConnection, reason });
216
+ const message = error instanceof Error ? error.message : String(error);
217
+ logger.debug(`MCP: metadata publication failed for ${name}; queued for retry: ${message}`);
218
+ return false;
219
+ }
220
+ }
221
+
222
+ setElicitationConfig(config: ServerElicitationConfig | undefined): void {
223
+ this.elicitationConfig = config;
224
+ }
225
+
226
+ setRuntimeSignal(signal: AbortSignal | undefined): void {
227
+ this.runtimeSignal = signal;
228
+ }
229
+
230
+ setDefaultRequestTimeoutMs(timeoutMs: number | undefined): void {
231
+ this.defaultRequestTimeoutMs = normalizeRequestTimeoutMs(timeoutMs);
232
+ }
233
+
234
+ setTraceConfig(settings: McpTraceSettings | undefined): void {
235
+ this.traceSettings = settings;
236
+ }
237
+
238
+ setAuthStorageOptions(options: AuthStorageOptions): void {
239
+ this.authStorageOptions = options;
240
+ }
241
+
242
+ setOAuthRuntime(runtime: McpOAuthRuntime): void {
243
+ this.oauthRuntime = runtime;
244
+ }
245
+
246
+ getRequestOptions(name: string, signal?: AbortSignal): RequestOptions | undefined {
247
+ const connection = this.connections.get(name);
248
+ return this.buildRequestOptions(connection?.definition, signal);
249
+ }
250
+
251
+ private getResolvedRequestTimeoutMs(definition?: ServerDefinition): number | undefined {
252
+ if (definition?.requestTimeoutMs !== undefined) {
253
+ return normalizeRequestTimeoutMs(definition.requestTimeoutMs);
254
+ }
255
+ return this.defaultRequestTimeoutMs;
256
+ }
257
+
258
+ private buildRequestOptions(
259
+ definition?: ServerDefinition,
260
+ signal?: AbortSignal,
261
+ ): RequestOptions | undefined {
262
+ const timeout = this.getResolvedRequestTimeoutMs(definition);
263
+ const ownedSignal = combineAbortSignals(this.runtimeSignal, signal);
264
+
265
+ if (!ownedSignal && timeout === undefined) {
266
+ return undefined;
267
+ }
268
+
269
+ return {
270
+ ...(ownedSignal ? { signal: ownedSignal } : {}),
271
+ ...(timeout !== undefined ? { timeout } : {}),
272
+ };
273
+ }
274
+
275
+ async connect(name: string, definition: ServerDefinition, signal?: AbortSignal): Promise<ServerConnection> {
276
+ if (isServerDisabled(definition)) throw new Error(`MCP server "${name}" is disabled`);
277
+ if (this.stopped) throw new Error("MCP server manager is closed");
278
+ const ownedSignal = combineAbortSignals(this.runtimeSignal, signal);
279
+ throwIfAborted(ownedSignal);
280
+ const closing = this.closePromises.get(name);
281
+ if (closing) await abortable(closing, ownedSignal);
282
+ throwIfAborted(ownedSignal);
283
+
284
+ // Dedupe concurrent connection attempts.
285
+ if (this.connectPromises.has(name)) {
286
+ return abortable(this.connectPromises.get(name)!, ownedSignal);
287
+ }
288
+
289
+ const existing = this.connections.get(name);
290
+ if (existing?.status === "connected") {
291
+ existing.lastUsedAt = Date.now();
292
+ return existing;
293
+ }
294
+
295
+ const credentialsInvalidated = existing?.status === "needs-auth"
296
+ && existing.credentialsInvalidated === true;
297
+ const generation = this.closeGenerations.get(name) ?? 0;
298
+ const attemptController = new AbortController();
299
+ const attemptSignal = combineAbortSignals(ownedSignal, attemptController.signal);
300
+ const connectionAttempt = this.createConnection(name, definition, attemptSignal, ownedSignal, credentialsInvalidated);
301
+ const promise = definition.url
302
+ ? connectionAttempt.catch(async error => { throw await this.enrichHttpConnectionError(definition, error); })
303
+ : connectionAttempt;
304
+ this.connectPromises.set(name, promise);
305
+ this.connectAttempts.set(name, attemptController);
306
+
307
+ try {
308
+ const connection = await promise;
309
+ if (attemptController.signal.aborted || (this.closeGenerations.get(name) ?? 0) !== generation) {
310
+ await this.disposeConnection(connection);
311
+ throwIfAborted(attemptSignal);
312
+ throw new Error(`MCP connection for ${name} was closed while connecting`);
313
+ }
314
+ this.connections.set(name, connection);
315
+ return connection;
316
+ } finally {
317
+ if (this.connectPromises.get(name) === promise) this.connectPromises.delete(name);
318
+ if (this.connectAttempts.get(name) === attemptController) this.connectAttempts.delete(name);
319
+ }
320
+ }
321
+
322
+ /**
323
+ * Reconnect a server whose connection was proven stale (e.g. by a 404
324
+ * "session no longer exists" response). Single-flight per server name —
325
+ * concurrent callers that raced to the same failure share one reconnect —
326
+ * and identity-guarded: `staleConnection` is only torn down if it is
327
+ * still the manager's current connection for `name`. If a concurrent
328
+ * reconnect (or an unrelated connect()) already replaced it with a fresh
329
+ * connection, that fresh connection is returned untouched.
330
+ */
331
+ async reconnect(
332
+ name: string,
333
+ definition: ServerDefinition,
334
+ staleConnection: ServerConnection,
335
+ signal?: AbortSignal,
336
+ ): Promise<ServerConnection> {
337
+ if (isServerDisabled(definition)) throw new Error(`MCP server "${name}" is disabled`);
338
+ if (this.stopped) throw new Error("MCP server manager is closed");
339
+ const ownedSignal = combineAbortSignals(this.runtimeSignal, signal);
340
+ throwIfAborted(ownedSignal);
341
+ const inFlight = this.reconnectPromises.get(name);
342
+ if (inFlight) {
343
+ return abortable(inFlight, ownedSignal);
344
+ }
345
+
346
+ const promise = this.doReconnect(name, definition, staleConnection, ownedSignal).finally(() => {
347
+ if (this.reconnectPromises.get(name) === promise) {
348
+ this.reconnectPromises.delete(name);
349
+ }
350
+ });
351
+ this.reconnectPromises.set(name, promise);
352
+ return abortable(promise, ownedSignal);
353
+ }
354
+
355
+ /**
356
+ * Fetch the authoritative tool catalog for a connection that still appears
357
+ * connected. The SDK response cache is explicitly bypassed so this request
358
+ * also proves the remote Streamable HTTP session is usable. Results are
359
+ * identity-guarded: a late response from a replaced connection is ignored.
360
+ */
361
+ async refreshTools(
362
+ name: string,
363
+ expectedConnection: ServerConnection,
364
+ signal?: AbortSignal,
365
+ ): Promise<ToolRefreshResult> {
366
+ if (this.stopped) throw new Error("MCP server manager is closed");
367
+ const ownedSignal = combineAbortSignals(this.runtimeSignal, signal);
368
+ throwIfAborted(ownedSignal);
369
+
370
+ const current = this.connections.get(name);
371
+ if (current !== expectedConnection || current.status !== "connected") {
372
+ return "superseded";
373
+ }
374
+
375
+ const requestOptions = this.buildRequestOptions(expectedConnection.definition, signal);
376
+ const timeout = Math.min(requestOptions?.timeout ?? KEEP_ALIVE_REFRESH_TIMEOUT_MS, KEEP_ALIVE_REFRESH_TIMEOUT_MS);
377
+ const healthOptions = {
378
+ ...requestOptions,
379
+ timeout,
380
+ };
381
+ if (!expectedConnection.client.getServerCapabilities?.()?.tools) {
382
+ await expectedConnection.client.ping(healthOptions);
383
+ throwIfAborted(ownedSignal);
384
+ if (this.connections.get(name) !== expectedConnection || expectedConnection.status !== "connected") {
385
+ return "superseded";
386
+ }
387
+ this.retryPendingMetadataPublication(name, expectedConnection);
388
+ return "unchanged";
389
+ }
390
+
391
+ const toolsRevision = expectedConnection.toolsRevision ?? 0;
392
+ const refreshSignal = combineAbortSignals(healthOptions.signal, AbortSignal.timeout(timeout));
393
+ let toolResult: ToolListResult;
394
+ try {
395
+ toolResult = await this.fetchAllTools(expectedConnection.client, {
396
+ ...healthOptions,
397
+ ...(refreshSignal ? { signal: refreshSignal } : {}),
398
+ cacheMode: "refresh",
399
+ });
400
+ } catch (error) {
401
+ throwIfAborted(ownedSignal);
402
+ if (this.connections.get(name) !== expectedConnection || expectedConnection.status !== "connected") {
403
+ return "superseded";
404
+ }
405
+ if (error instanceof SdkError && error.code === SdkErrorCode.RequestTimeout) {
406
+ return "refresh-timeout";
407
+ }
408
+ throw error;
409
+ }
410
+ throwIfAborted(ownedSignal);
411
+
412
+ if (this.connections.get(name) !== expectedConnection || expectedConnection.status !== "connected") {
413
+ return "superseded";
414
+ }
415
+ if ((expectedConnection.toolsRevision ?? 0) !== toolsRevision) {
416
+ return "superseded";
417
+ }
418
+
419
+ if (
420
+ isDeepStrictEqual(expectedConnection.tools, toolResult.tools) &&
421
+ isDeepStrictEqual(expectedConnection.toolListHints, toolResult.hints)
422
+ ) {
423
+ this.retryPendingMetadataPublication(name, expectedConnection);
424
+ return "unchanged";
425
+ }
426
+
427
+ const previousTools = expectedConnection.tools;
428
+ const previousToolListHints = expectedConnection.toolListHints;
429
+ expectedConnection.tools = toolResult.tools;
430
+ expectedConnection.toolListHints = toolResult.hints;
431
+ expectedConnection.toolsRevision = toolsRevision + 1;
432
+ try {
433
+ await this.metadataListChangedListener?.(name, "keep-alive-refresh");
434
+ this.pendingMetadataPublications.delete(name);
435
+ } catch (error) {
436
+ if (
437
+ this.connections.get(name) === expectedConnection &&
438
+ expectedConnection.tools === toolResult.tools &&
439
+ expectedConnection.toolListHints === toolResult.hints
440
+ ) {
441
+ expectedConnection.tools = previousTools;
442
+ expectedConnection.toolListHints = previousToolListHints;
443
+ expectedConnection.toolsRevision = toolsRevision;
444
+ }
445
+ throw error;
446
+ }
447
+ return "updated";
448
+ }
449
+
450
+ private retryPendingMetadataPublication(name: string, connection: ServerConnection): void {
451
+ const pendingPublication = this.pendingMetadataPublications.get(name);
452
+ if (pendingPublication?.connection !== connection) return;
453
+ this.metadataListChangedListener?.(name, pendingPublication.reason);
454
+ if (this.pendingMetadataPublications.get(name) === pendingPublication) {
455
+ this.pendingMetadataPublications.delete(name);
456
+ }
457
+ }
458
+
459
+ private async doReconnect(
460
+ name: string,
461
+ definition: ServerDefinition,
462
+ staleConnection: ServerConnection,
463
+ signal?: AbortSignal,
464
+ ): Promise<ServerConnection> {
465
+ throwIfAborted(signal);
466
+ const current = this.connections.get(name);
467
+
468
+ // Never tear down a connection we didn't prove stale: if the map no
469
+ // longer holds the connection we were asked to replace, someone else
470
+ // already reconnected (or connected) first.
471
+ if (current !== staleConnection) {
472
+ return current ?? this.connect(name, definition, signal);
473
+ }
474
+
475
+ const staleInFlight = staleConnection.inFlight;
476
+ await this.close(name);
477
+ const fresh = await this.connect(name, definition, signal);
478
+ fresh.inFlight = Math.max(fresh.inFlight, staleInFlight);
479
+ return fresh;
480
+ }
481
+
482
+ private async createConnection(
483
+ name: string,
484
+ definition: ServerDefinition,
485
+ signal?: AbortSignal,
486
+ requestSignal?: AbortSignal,
487
+ credentialsInvalidated = false,
488
+ ): Promise<ServerConnection> {
489
+ throwIfAborted(signal);
490
+
491
+ const tracingEnabled = isMcpTraceEnabled(definition, this.traceSettings);
492
+ const traceWriter = tracingEnabled
493
+ ? (this.traceWriter ??= createMcpTraceWriter(this.defaultCwd, this.traceSettings ?? {}))
494
+ : undefined;
495
+ const traceObserver: McpTraceObserver | undefined = traceWriter
496
+ ? { record: event => traceWriter.write(event) }
497
+ : undefined;
498
+
499
+ let client: Client;
500
+ let transport: Transport;
501
+ let clientConnected = false;
502
+ let invalidated = credentialsInvalidated;
503
+ let transportAlreadyTraced = false;
504
+ let stderrTail: Buffer<ArrayBufferLike> = Buffer.alloc(0);
505
+ const configuredTransports = [definition.command, definition.url, definition.socket]
506
+ .filter(value => typeof value === "string" && value.length > 0);
507
+ if (configuredTransports.length !== 1) {
508
+ throw new Error(`Server ${name} must configure exactly one of command, url, or socket`);
509
+ }
510
+
511
+ const requestOptions = this.buildRequestOptions(definition, requestSignal);
512
+
513
+ if (definition.command) {
514
+ client = this.createClient(name, definition);
515
+ let command = definition.command;
516
+ let args = (definition.args ?? []).map((argument) => interpolateEnvVars(argument));
517
+ const cwd = resolveConfigPath(definition.cwd) ?? this.defaultCwd;
518
+ if (cwd !== undefined) {
519
+ const cwdStats = statSync(cwd, { throwIfNoEntry: false });
520
+ if (!cwdStats) throw new Error(`MCP server "${name}" configured cwd does not exist: "${cwd}"`);
521
+ if (!cwdStats.isDirectory()) throw new Error(`MCP server "${name}" configured cwd is not a directory: "${cwd}"`);
522
+ }
523
+
524
+ if (command === "npx" || command === "npm") {
525
+ const resolved = await resolveNpxBinary(command, args, signal);
526
+ if (resolved) {
527
+ command = resolved.isJs ? "node" : resolved.binPath;
528
+ args = resolved.isJs ? [resolved.binPath, ...resolved.extraArgs] : resolved.extraArgs;
529
+ logger.debug(`${name} resolved to ${resolved.binPath} (skipping npm parent)`);
530
+ }
531
+ }
532
+ throwIfAborted(signal);
533
+
534
+ if (definition.pluginDataDir) mkdirSync(definition.pluginDataDir, { recursive: true });
535
+ const stdioTransport = new StdioClientTransport({
536
+ command,
537
+ args,
538
+ env: resolveEnv(definition.env, name, definition.literalEnv === true),
539
+ ...(cwd !== undefined ? { cwd } : {}),
540
+ stderr: definition.debug ? "inherit" : "pipe",
541
+ });
542
+ // Keep non-debug child diagnostics available for connection failures without
543
+ // retaining an unbounded stream or changing the existing debug behavior.
544
+ if (stdioTransport.stderr) {
545
+ stdioTransport.stderr.on("data", (chunk: Buffer | string) => {
546
+ stderrTail = appendStderrTail(stderrTail, chunk);
547
+ });
548
+ }
549
+ transport = stdioTransport;
550
+ } else if (definition.url) {
551
+ const httpConnection = await this.connectHttpClient(
552
+ definition,
553
+ name,
554
+ requestOptions,
555
+ signal,
556
+ traceObserver,
557
+ invalidated,
558
+ );
559
+ client = httpConnection.client;
560
+ transport = httpConnection.transport;
561
+ invalidated = httpConnection.credentialsInvalidated;
562
+ if (httpConnection.status === "needs-auth") {
563
+ return {
564
+ client,
565
+ transport,
566
+ definition,
567
+ tools: [],
568
+ resources: [],
569
+ prompts: [],
570
+ lastUsedAt: Date.now(),
571
+ inFlight: 0,
572
+ status: "needs-auth",
573
+ credentialsInvalidated: invalidated,
574
+ };
575
+ }
576
+ clientConnected = true;
577
+ transportAlreadyTraced = traceObserver !== undefined;
578
+ } else {
579
+ client = this.createClient(name, definition);
580
+ transport = new UnixSocketClientTransport(resolveConfigPath(definition.socket!)!);
581
+ }
582
+
583
+ if (traceObserver && !transportAlreadyTraced) {
584
+ const traceTransportKindValue = traceTransportKind(definition, transport);
585
+ transport = wrapTransportWithMcpTrace(transport, name, traceTransportKindValue, traceObserver);
586
+ }
587
+
588
+ try {
589
+ throwIfAborted(signal);
590
+ if (!clientConnected) {
591
+ await this.connectClientWithAbort(client, transport, requestOptions, signal);
592
+ }
593
+ this.attachAdapterNotificationHandlers(name, client);
594
+
595
+ const instructions = client.getInstructions?.();
596
+ const connection: ServerConnection = {
597
+ client,
598
+ transport,
599
+ definition,
600
+ tools: [],
601
+ toolsRevision: 0,
602
+ resources: [],
603
+ prompts: [],
604
+ ...(instructions !== undefined ? { instructions } : {}),
605
+ lastUsedAt: Date.now(),
606
+ inFlight: 0,
607
+ status: "connected",
608
+ };
609
+
610
+ // Reflect the SDK's own close signal in connection status, guarded by
611
+ // identity so a stale connection's late close can never clobber a fresh
612
+ // connection. The SDK client owns the transport callbacks.
613
+ client.onclose = () => {
614
+ if (this.connections.get(name) === connection) {
615
+ connection.status = "closed";
616
+ }
617
+ };
618
+
619
+ // Discover tools, resources, and prompts. Resource and prompt listing is
620
+ // optional: only servers advertising the capability are queried.
621
+ const [toolResult, resources, promptResult] = await Promise.all([
622
+ this.fetchAllTools(client, requestOptions),
623
+ this.fetchAllResources(client, requestOptions),
624
+ this.fetchAllPrompts(client, requestOptions),
625
+ ]);
626
+ connection.tools = toolResult.tools;
627
+ connection.toolListHints = toolResult.hints;
628
+ connection.resources = resources;
629
+ connection.prompts = promptResult.prompts;
630
+ connection.promptDiscoveryFailed = promptResult.failed;
631
+
632
+ return connection;
633
+ } catch (error) {
634
+ // If connectClientWithAbort closed the transport, await that exact close.
635
+ // Otherwise the SDK client owns its transport and performs cleanup once.
636
+ const abortCleanup = abortCleanupPromises.get(transport);
637
+ const abortCleanupFailed = error instanceof AggregateError && error.message === "MCP connection abort cleanup failed";
638
+ const cleanupResults = abortCleanupFailed
639
+ ? []
640
+ : await Promise.allSettled([
641
+ abortCleanup ?? Promise.resolve().then(() => client.close()),
642
+ ]);
643
+ const cleanupFailures = cleanupResults.flatMap(result => result.status === "rejected" ? [result.reason] : []);
644
+ let reportedError: unknown = error;
645
+ if (cleanupFailures.length > 0) {
646
+ reportedError = new AggregateError([error, ...cleanupFailures], "MCP connection setup failed");
647
+ }
648
+
649
+ // A cleanup failure remains a setup failure rather than being hidden
650
+ // behind needs-auth.
651
+ if (isUnauthorizedHttpError(error) && supportsOAuth(definition) && cleanupFailures.length === 0) {
652
+ if (!invalidated) {
653
+ invalidateAuthEntryCache(name);
654
+ invalidated = true;
655
+ }
656
+ return {
657
+ client,
658
+ transport,
659
+ definition,
660
+ tools: [],
661
+ resources: [],
662
+ prompts: [],
663
+ lastUsedAt: Date.now(),
664
+ inFlight: 0,
665
+ status: "needs-auth",
666
+ credentialsInvalidated: invalidated,
667
+ };
668
+ }
669
+
670
+ if (stderrTail.length > 0) {
671
+ const stderrText = stderrTail.toString("utf8").trim();
672
+ const lines = stderrText.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
673
+ if (lines.length > 0) {
674
+ const baseMessage = reportedError instanceof Error ? reportedError.message : String(reportedError);
675
+ const detail = lines.slice(-MAX_CAPTURED_STDERR_LINES).join(" — ");
676
+ throw new Error(`${baseMessage} (${detail})`, { cause: reportedError });
677
+ }
678
+ }
679
+ throw reportedError;
680
+ }
681
+ }
682
+
683
+ private async enrichHttpConnectionError(definition: ServerDefinition, error: unknown): Promise<Error> {
684
+ const originalMessage = error instanceof Error ? error.message : String(error);
685
+ if (isTransientHttpConnectError(error)) {
686
+ return new Error(`${originalMessage} — endpoint is temporarily unavailable (HTTP 503)`, { cause: error });
687
+ }
688
+ try {
689
+ const probe = await probeMcpEndpoint(resolveServerUrl(definition)!);
690
+ return new Error(`${originalMessage} — probe: ${probe.classification}`, { cause: error });
691
+ } catch {
692
+ return error instanceof Error ? error : new Error(originalMessage);
693
+ }
694
+ }
695
+
696
+ private async connectClientWithAbort(
697
+ client: Client,
698
+ transport: Transport,
699
+ requestOptions?: RequestOptions,
700
+ signal?: AbortSignal,
701
+ ): Promise<void> {
702
+ throwIfAborted(signal);
703
+ let abortCleanup: Promise<void> | undefined;
704
+ const closeTransport = () => {
705
+ abortCleanup = Promise.resolve().then(() => transport.close());
706
+ abortCleanupPromises.set(transport, abortCleanup);
707
+ };
708
+ signal?.addEventListener("abort", closeTransport, { once: true });
709
+ try {
710
+ await abortable(client.connect(transport, requestOptions), signal);
711
+ await abortCleanup;
712
+ } catch (error) {
713
+ if (abortCleanup) {
714
+ try {
715
+ await abortCleanup;
716
+ } catch (cleanupError) {
717
+ throw new AggregateError([error, cleanupError], "MCP connection abort cleanup failed");
718
+ }
719
+ }
720
+ throw error;
721
+ } finally {
722
+ signal?.removeEventListener("abort", closeTransport);
723
+ }
724
+ }
725
+
726
+ private buildClientCapabilities() {
727
+ return {
728
+ ...(this.samplingConfig ? { sampling: {} } : {}),
729
+ ...(this.elicitationConfig
730
+ ? {
731
+ elicitation: {
732
+ form: {},
733
+ ...(this.elicitationConfig.allowUrl ? { url: {} } : {}),
734
+ },
735
+ }
736
+ : {}),
737
+ };
738
+ }
739
+
740
+ private createClient(serverName: string, definition: ServerDefinition): Client {
741
+ const capabilities = this.buildClientCapabilities();
742
+ const versionNegotiation = resolveVersionNegotiation(definition);
743
+ let client: Client;
744
+ client = new Client(
745
+ { name: `pi-mcp-${serverName}`, version: "1.0.0" },
746
+ {
747
+ jsonSchemaValidator: createJsonSchemaValidator(),
748
+ ...(versionNegotiation ? { versionNegotiation } : {}),
749
+ ...(Object.keys(capabilities).length > 0 ? { capabilities } : {}),
750
+ listChanged: {
751
+ tools: {
752
+ onChanged: (error: Error | null, tools: McpTool[] | null) => {
753
+ this.handleToolsListChanged(serverName, client, error, tools);
754
+ },
755
+ },
756
+ resources: {
757
+ onChanged: (error: Error | null, resources: McpResource[] | null) => {
758
+ this.handleResourcesListChanged(serverName, client, error, resources);
759
+ },
760
+ },
761
+ prompts: {
762
+ onChanged: (error: Error | null, prompts: McpPrompt[] | null) => {
763
+ this.handlePromptsListChanged(serverName, client, error, prompts);
764
+ },
765
+ },
766
+ },
767
+ },
768
+ );
769
+ if (this.samplingConfig) {
770
+ registerSamplingHandler(client, { ...this.samplingConfig, serverName });
771
+ }
772
+ if (this.elicitationConfig) {
773
+ registerElicitationHandler(client, {
774
+ ...this.elicitationConfig,
775
+ serverName,
776
+ onUrlAccepted: elicitationId => this.rememberUrlElicitation(serverName, elicitationId),
777
+ });
778
+ if (this.elicitationConfig.allowUrl) {
779
+ client.setNotificationHandler("notifications/elicitation/complete", notification => {
780
+ if (this.runtimeSignal?.aborted) return;
781
+ const accepted = this.acceptedUrlElicitations.get(serverName);
782
+ if (!accepted?.delete(notification.params.elicitationId)) return;
783
+ this.elicitationConfig?.ui.notify(
784
+ `MCP browser interaction for ${serverName} completed. You can retry the tool now.`,
785
+ "info",
786
+ );
787
+ });
788
+ }
789
+ }
790
+ return client;
791
+ }
792
+
793
+ private handleToolsListChanged(
794
+ serverName: string,
795
+ client: Client,
796
+ error: Error | null,
797
+ tools: McpTool[] | null,
798
+ ): void {
799
+ if (error) {
800
+ logger.debug(`MCP: tools/list_changed refresh failed for ${serverName}: ${error.message}`);
801
+ return;
802
+ }
803
+ if (!tools) return;
804
+ const connection = this.connections.get(serverName);
805
+ if (!connection || connection.client !== client || connection.status !== "connected") return;
806
+ connection.tools = tools;
807
+ connection.toolsRevision = (connection.toolsRevision ?? 0) + 1;
808
+ this.metadataListChangedListener?.(serverName, "tools-list-changed");
809
+ this.pendingMetadataPublications.delete(serverName);
810
+ }
811
+
812
+ private handlePromptsListChanged(
813
+ serverName: string,
814
+ client: Client,
815
+ error: Error | null,
816
+ prompts: McpPrompt[] | null,
817
+ ): void {
818
+ if (error) {
819
+ logger.debug(`MCP: prompts/list_changed refresh failed for ${serverName}: ${error.message}`);
820
+ return;
821
+ }
822
+ if (!prompts) return;
823
+ const connection = this.connections.get(serverName);
824
+ if (!connection || connection.client !== client || connection.status !== "connected") return;
825
+ connection.prompts = prompts;
826
+ connection.promptDiscoveryFailed = false;
827
+ this.metadataListChangedListener?.(serverName, "prompts-list-changed");
828
+ this.pendingMetadataPublications.delete(serverName);
829
+ }
830
+
831
+ private handleResourcesListChanged(
832
+ serverName: string,
833
+ client: Client,
834
+ error: Error | null,
835
+ resources: McpResource[] | null,
836
+ ): void {
837
+ if (error) {
838
+ logger.debug(`MCP: resources/list_changed refresh failed for ${serverName}: ${error.message}`);
839
+ return;
840
+ }
841
+ if (!resources) return;
842
+ const connection = this.connections.get(serverName);
843
+ if (!connection || connection.client !== client || connection.status !== "connected") return;
844
+ connection.resources = resources;
845
+ this.metadataListChangedListener?.(serverName, "resources-list-changed");
846
+ this.pendingMetadataPublications.delete(serverName);
847
+ }
848
+
849
+ async handleUrlElicitationRequired(
850
+ serverName: string,
851
+ error: UrlElicitationRequiredError,
852
+ ): Promise<"accept" | "decline" | "cancel"> {
853
+ if (this.runtimeSignal?.aborted || !this.elicitationConfig?.allowUrl) return "cancel";
854
+ for (const params of error.elicitations) {
855
+ const result = await handleUrlElicitation({
856
+ ...this.elicitationConfig,
857
+ serverName,
858
+ onUrlAccepted: elicitationId => this.rememberUrlElicitation(serverName, elicitationId),
859
+ }, params);
860
+ if (result.action !== "accept") return result.action;
861
+ }
862
+ return "accept";
863
+ }
864
+
865
+ private rememberUrlElicitation(serverName: string, elicitationId: string): void {
866
+ if (this.runtimeSignal?.aborted) return;
867
+ let accepted = this.acceptedUrlElicitations.get(serverName);
868
+ if (!accepted) {
869
+ accepted = new Set();
870
+ this.acceptedUrlElicitations.set(serverName, accepted);
871
+ }
872
+ accepted.add(elicitationId);
873
+ }
874
+
875
+ private async connectHttpClient(
876
+ definition: ServerDefinition,
877
+ serverName: string,
878
+ requestOptions: RequestOptions | undefined,
879
+ signal?: AbortSignal,
880
+ traceObserver?: McpTraceObserver,
881
+ credentialsInvalidated = false,
882
+ ): Promise<{ client: Client; transport: Transport; status: "connected" | "needs-auth"; credentialsInvalidated: boolean }> {
883
+ throwIfAborted(signal);
884
+ const serverUrl = resolveServerUrl(definition)!;
885
+ const url = new URL(serverUrl);
886
+
887
+ // Resolve secret commands only for this connection attempt, without
888
+ // mutating the persisted configuration.
889
+ const hasCommandHeader = Object.values(definition.headers ?? {})
890
+ .some(value => value.startsWith("!") && !value.startsWith("!!"));
891
+ const headers = resolveCommandSecretsRecord(
892
+ definition.headers,
893
+ key => `MCP server "${serverName}" HTTP header "${key}"`,
894
+ ) ?? {};
895
+
896
+ // Resolve bearer auth before creating requestInit so every attempted
897
+ // transport receives the same headers.
898
+ const commandBearer = definition.bearerToken?.startsWith("!") && !definition.bearerToken.startsWith("!!")
899
+ ? definition.bearerToken
900
+ : undefined;
901
+ if (definition.auth === "bearer") {
902
+ const token = commandBearer
903
+ ? resolveCommandSecret(commandBearer, `MCP server "${serverName}" HTTP bearer token`)
904
+ : resolveBearerToken(definition)
905
+ ?? (definition.bearerToken === undefined && definition.bearerTokenEnv === undefined && definition.bearerTokenStore === true
906
+ ? getBearerTokenForUrl(serverName, serverUrl)
907
+ : undefined);
908
+ if (token) headers["Authorization"] = `Bearer ${token}`;
909
+ }
910
+
911
+ if (hasCommandHeader || commandBearer) {
912
+ try {
913
+ new Headers(headers);
914
+ } catch {
915
+ throw new Error(`Failed to resolve MCP server "${serverName}" HTTP command secret: command returned an invalid header value`);
916
+ }
917
+ }
918
+
919
+ const requestInit = Object.keys(headers).length > 0 ? { headers } : undefined;
920
+ const requestFetch = definition.requestHeadersCommand
921
+ ? createRequestHeadersCommandFetch(definition.requestHeadersCommand)
922
+ : undefined;
923
+ const createAuthProvider = (): McpOAuthProvider => new McpOAuthProvider(
924
+ serverName,
925
+ serverUrl,
926
+ extractOAuthConfig(definition),
927
+ { onRedirect: async () => {} },
928
+ this.authStorageOptions,
929
+ this.oauthRuntime?.signal,
930
+ );
931
+
932
+ // Explicit OAuth checks secure storage immediately. Implicit OAuth defers
933
+ // provider construction until the server proves authentication is needed.
934
+ let authState: HttpAuthProviderState = supportsOAuth(definition)
935
+ ? definition.auth === undefined
936
+ ? { status: "implicit-deferred" }
937
+ : { status: "explicit", provider: createAuthProvider() }
938
+ : { status: "disabled" };
939
+
940
+ const attempt = async (
941
+ kind: "streamable-http" | "sse",
942
+ ): Promise<
943
+ | { status: "connected"; client: Client; transport: Transport }
944
+ | { status: "failed"; client: Client; transport: Transport; error: unknown }
945
+ > => {
946
+ const authProvider = "provider" in authState ? authState.provider : undefined;
947
+ const transportOptions = {
948
+ ...(requestInit !== undefined ? { requestInit } : {}),
949
+ ...(requestFetch !== undefined ? { fetch: requestFetch } : {}),
950
+ ...(authProvider !== undefined ? { authProvider } : {}),
951
+ ...(authProvider !== undefined
952
+ && definition.oauth !== false
953
+ && definition.oauth?.skipIssuerMetadataValidation === true
954
+ ? { skipIssuerMetadataValidation: true }
955
+ : {}),
956
+ };
957
+ const baseTransport: Transport = kind === "streamable-http"
958
+ ? new StreamableHTTPClientTransport(url, transportOptions)
959
+ : new SSEClientTransport(url, transportOptions);
960
+ const transport = traceObserver
961
+ ? wrapTransportWithMcpTrace(baseTransport, serverName, kind, traceObserver)
962
+ : baseTransport;
963
+ const client = this.createClient(serverName, definition);
964
+
965
+ try {
966
+ await this.connectClientWithAbort(client, transport, requestOptions, signal);
967
+ return { status: "connected", client, transport };
968
+ } catch (error) {
969
+ const abortCleanupFailed = error instanceof AggregateError
970
+ && error.message === "MCP connection abort cleanup failed";
971
+ if (!abortCleanupFailed) {
972
+ try {
973
+ await (abortCleanupPromises.get(transport) ?? client.close());
974
+ } catch (cleanupError) {
975
+ throw new AggregateError([error, cleanupError], "MCP HTTP connection cleanup failed");
976
+ }
977
+ }
978
+ return { status: "failed", client, transport, error };
979
+ }
980
+ };
981
+
982
+ // Connect the real client once. Retry Streamable HTTP only for an implicit
983
+ // OAuth challenge; use SSE only for definitive endpoint incompatibility.
984
+ // Agent Plugins set httpTransport, and their declared transport is used without fallback.
985
+ let kind: "streamable-http" | "sse" = definition.httpTransport ?? "streamable-http";
986
+ let invalidated = credentialsInvalidated;
987
+ for (;;) {
988
+ const result = await attempt(kind);
989
+ if (result.status === "connected") return { ...result, credentialsInvalidated: invalidated };
990
+ if (result.error instanceof AggregateError
991
+ && result.error.message === "MCP connection abort cleanup failed") {
992
+ throw result.error;
993
+ }
994
+ if (signal?.aborted) throwIfAborted(signal);
995
+
996
+ if (authState.status === "implicit-deferred" && isUnauthorizedHttpError(result.error)) {
997
+ authState = { status: "implicit-challenged", provider: createAuthProvider() };
998
+ continue;
999
+ }
1000
+ if (isUnauthorizedHttpError(result.error)) {
1001
+ if (supportsOAuth(definition)) {
1002
+ if (!invalidated) {
1003
+ invalidateAuthEntryCache(serverName);
1004
+ invalidated = true;
1005
+ }
1006
+ return {
1007
+ client: result.client,
1008
+ transport: result.transport,
1009
+ status: "needs-auth",
1010
+ credentialsInvalidated: invalidated,
1011
+ };
1012
+ }
1013
+ throw result.error;
1014
+ }
1015
+
1016
+ if (definition.httpTransport === undefined && kind === "streamable-http" && shouldFallbackToSse(result.error, definition)) {
1017
+ kind = "sse";
1018
+ continue;
1019
+ }
1020
+ throw result.error;
1021
+ }
1022
+ }
1023
+
1024
+ private async fetchAllTools(client: Client, requestOptions?: CacheableRequestOptions): Promise<ToolListResult> {
1025
+ const allTools: McpTool[] = [];
1026
+ let cursor: string | undefined;
1027
+ let hints: ToolListCacheHints | undefined;
1028
+ let firstPage = true;
1029
+
1030
+ do {
1031
+ const result = await client.listTools(cursor ? { cursor } : undefined, requestOptions);
1032
+ if (firstPage) {
1033
+ const ttlMs = typeof result.ttlMs === "number" && Number.isSafeInteger(result.ttlMs) && result.ttlMs >= 0
1034
+ ? result.ttlMs
1035
+ : undefined;
1036
+ const cacheScope = result.cacheScope === "public" || result.cacheScope === "private"
1037
+ ? result.cacheScope
1038
+ : undefined;
1039
+ if (ttlMs !== undefined || cacheScope !== undefined) {
1040
+ hints = {
1041
+ ...(ttlMs !== undefined ? { ttlMs } : {}),
1042
+ ...(cacheScope !== undefined ? { cacheScope } : {}),
1043
+ };
1044
+ }
1045
+ firstPage = false;
1046
+ }
1047
+ allTools.push(...(result.tools ?? []));
1048
+ cursor = result.nextCursor;
1049
+ } while (cursor);
1050
+
1051
+ return { tools: allTools, ...(hints !== undefined ? { hints } : {}) };
1052
+ }
1053
+
1054
+ private async fetchAllPrompts(
1055
+ client: Client,
1056
+ requestOptions?: RequestOptions,
1057
+ ): Promise<{ prompts: McpPrompt[]; failed: boolean }> {
1058
+ const capabilities = client.getServerCapabilities?.();
1059
+ if (!capabilities?.prompts) return { prompts: [], failed: false };
1060
+
1061
+ try {
1062
+ const prompts: McpPrompt[] = [];
1063
+ let cursor: string | undefined;
1064
+ do {
1065
+ const result = await client.listPrompts(cursor ? { cursor } : undefined, requestOptions);
1066
+ prompts.push(...(result.prompts ?? []));
1067
+ cursor = result.nextCursor;
1068
+ } while (cursor);
1069
+ return { prompts, failed: false };
1070
+ } catch (error) {
1071
+ if (requestOptions?.signal?.aborted) throwIfAborted(requestOptions.signal);
1072
+ if (isUnauthorizedHttpError(error)) throw error;
1073
+ const message = error instanceof Error ? error.message : String(error);
1074
+ logger.debug(`MCP: prompts/list failed: ${message}`);
1075
+ return { prompts: [], failed: true };
1076
+ }
1077
+ }
1078
+
1079
+ private async fetchAllResources(client: Client, requestOptions?: RequestOptions): Promise<McpResource[]> {
1080
+ const capabilities = client.getServerCapabilities?.();
1081
+ if (!capabilities?.resources) return [];
1082
+
1083
+ try {
1084
+ const allResources: McpResource[] = [];
1085
+ let cursor: string | undefined;
1086
+
1087
+ do {
1088
+ const result = await client.listResources(cursor ? { cursor } : undefined, requestOptions);
1089
+ allResources.push(...(result.resources ?? []));
1090
+ cursor = result.nextCursor;
1091
+ } while (cursor);
1092
+
1093
+ return allResources;
1094
+ } catch (error) {
1095
+ if (requestOptions?.signal?.aborted) {
1096
+ throwIfAborted(requestOptions.signal);
1097
+ }
1098
+ if (isUnauthorizedHttpError(error)) throw error;
1099
+ // The server advertises resources but the listing failed
1100
+ return [];
1101
+ }
1102
+ }
1103
+
1104
+ private attachAdapterNotificationHandlers(serverName: string, client: Client): void {
1105
+ client.setNotificationHandler(
1106
+ SERVER_STREAM_RESULT_PATCH_METHOD,
1107
+ { params: serverStreamResultPatchNotificationSchema.shape.params },
1108
+ params => {
1109
+ const listener = this.uiStreamListeners.get(params.streamToken);
1110
+ if (!listener) return;
1111
+ listener(serverName, params);
1112
+ },
1113
+ );
1114
+ }
1115
+
1116
+ registerUiStreamListener(streamToken: string, listener: UiStreamListener): void {
1117
+ this.uiStreamListeners.set(streamToken, listener);
1118
+ }
1119
+
1120
+ removeUiStreamListener(streamToken: string): void {
1121
+ this.uiStreamListeners.delete(streamToken);
1122
+ }
1123
+
1124
+ async getPrompt(
1125
+ name: string,
1126
+ promptName: string,
1127
+ args?: Record<string, string>,
1128
+ signal?: AbortSignal,
1129
+ ): Promise<GetPromptResult> {
1130
+ const connection = this.connections.get(name);
1131
+ if (!connection || connection.status !== "connected") {
1132
+ throw new Error(`Server "${name}" is not connected`);
1133
+ }
1134
+ try {
1135
+ this.touch(name);
1136
+ this.incrementInFlight(name);
1137
+ return await connection.client.getPrompt(
1138
+ { name: promptName, ...(args ? { arguments: args } : {}) },
1139
+ this.getRequestOptions(name, signal),
1140
+ );
1141
+ } finally {
1142
+ this.decrementInFlight(name);
1143
+ this.touch(name);
1144
+ }
1145
+ }
1146
+
1147
+ async readResource(name: string, uri: string, signal?: AbortSignal): Promise<ReadResourceResult> {
1148
+ if (isServerDisabled(this.connections.get(name)?.definition)) {
1149
+ throw new Error(`MCP server "${name}" is disabled`);
1150
+ }
1151
+ const connection = this.connections.get(name);
1152
+ if (!connection || connection.status !== "connected") {
1153
+ throw new Error(`Server "${name}" is not connected`);
1154
+ }
1155
+
1156
+ try {
1157
+ this.touch(name);
1158
+ this.incrementInFlight(name);
1159
+ return await connection.client.readResource({ uri }, this.getRequestOptions(name, signal));
1160
+ } finally {
1161
+ this.decrementInFlight(name);
1162
+ this.touch(name);
1163
+ }
1164
+ }
1165
+
1166
+ async close(name: string): Promise<void> {
1167
+ this.closeGenerations.set(name, (this.closeGenerations.get(name) ?? 0) + 1);
1168
+ this.connectAttempts.get(name)?.abort(new Error(`MCP connection ${name} was closed`));
1169
+ this.pendingMetadataPublications.delete(name);
1170
+
1171
+ const connection = this.connections.get(name);
1172
+ if (!connection) {
1173
+ const pendingClose = this.closePromises.get(name);
1174
+ if (pendingClose) {
1175
+ await pendingClose;
1176
+ return;
1177
+ }
1178
+ const pendingConnect = this.connectPromises.get(name);
1179
+ if (pendingConnect) {
1180
+ try {
1181
+ await pendingConnect;
1182
+ } catch (error) {
1183
+ if (this.containsCleanupFailure(error)) throw error;
1184
+ }
1185
+ }
1186
+ return;
1187
+ }
1188
+
1189
+ // Delete before awaiting SDK cleanup so a replacement cannot be removed by
1190
+ // an old close operation finishing later.
1191
+ connection.status = "closed";
1192
+ this.connections.delete(name);
1193
+ this.acceptedUrlElicitations.delete(name);
1194
+ const closing = this.disposeConnection(connection).finally(() => {
1195
+ if (this.closePromises.get(name) === closing) this.closePromises.delete(name);
1196
+ });
1197
+ this.closePromises.set(name, closing);
1198
+ return closing;
1199
+ }
1200
+
1201
+ private async disposeConnection(connection: ServerConnection): Promise<void> {
1202
+ const results = await Promise.allSettled([
1203
+ // Only client.close() is needed; the client owns the transport and will close it internally.
1204
+ Promise.resolve().then(() => connection.client.close()),
1205
+ this.traceWriter?.flush() ?? Promise.resolve(),
1206
+ ]);
1207
+ const failures = results.flatMap(result => result.status === "rejected" ? [result.reason] : []);
1208
+ if (failures.length > 0) throw new AggregateError(failures, "MCP connection cleanup failed");
1209
+ }
1210
+
1211
+ async closeAll(): Promise<void> {
1212
+ this.stopped = true;
1213
+ const names = new Set([...this.connections.keys(), ...this.connectPromises.keys()]);
1214
+ for (const name of names) {
1215
+ this.closeGenerations.set(name, (this.closeGenerations.get(name) ?? 0) + 1);
1216
+ this.connectAttempts.get(name)?.abort(new Error(`MCP connection ${name} was closed`));
1217
+ }
1218
+
1219
+ const pendingConnects = [...this.connectPromises.values()];
1220
+ const currentNames = [...this.connections.keys()];
1221
+ const pendingResults = await Promise.allSettled(pendingConnects);
1222
+ const results = await Promise.allSettled(currentNames.map(name => this.close(name)));
1223
+
1224
+ // A connect that resolved during the first close snapshot is still fenced;
1225
+ // close any handle that was already inserted before its attempt settled.
1226
+ const lateNames = [...this.connections.keys()];
1227
+ const lateResults = await Promise.allSettled(lateNames.map(name => this.close(name)));
1228
+ const failures = [...pendingResults, ...results, ...lateResults]
1229
+ .flatMap(result => result.status === "rejected" ? [result.reason] : [])
1230
+ .filter(error => this.containsCleanupFailure(error));
1231
+ this.uiStreamListeners.clear();
1232
+ this.acceptedUrlElicitations.clear();
1233
+ this.pendingMetadataPublications.clear();
1234
+ this.samplingConfig = undefined;
1235
+ this.elicitationConfig = undefined;
1236
+ await this.traceWriter?.flush();
1237
+ if (failures.length > 0) throw new AggregateError(failures, "MCP manager cleanup failed");
1238
+ }
1239
+
1240
+ private containsCleanupFailure(error: unknown): boolean {
1241
+ const pending: unknown[] = [error];
1242
+ const seen = new Set<unknown>();
1243
+ while (pending.length > 0) {
1244
+ const current = pending.pop();
1245
+ if (!(current instanceof Error) || seen.has(current)) continue;
1246
+ seen.add(current);
1247
+ if (current instanceof AggregateError) {
1248
+ if (/cleanup failed|setup failed/.test(current.message)) return true;
1249
+ pending.push(...current.errors);
1250
+ }
1251
+ if (current.cause !== undefined) pending.push(current.cause);
1252
+ }
1253
+ return false;
1254
+ }
1255
+
1256
+ isConnecting(name: string): boolean {
1257
+ return this.connectPromises.has(name);
1258
+ }
1259
+
1260
+ getConnection(name: string): ServerConnection | undefined {
1261
+ return this.connections.get(name);
1262
+ }
1263
+
1264
+ getAllConnections(): Map<string, ServerConnection> {
1265
+ return new Map(this.connections);
1266
+ }
1267
+
1268
+ touch(name: string): void {
1269
+ const connection = this.connections.get(name);
1270
+ if (connection) {
1271
+ connection.lastUsedAt = Date.now();
1272
+ }
1273
+ }
1274
+
1275
+ incrementInFlight(name: string): void {
1276
+ const connection = this.connections.get(name);
1277
+ if (connection) {
1278
+ connection.inFlight = (connection.inFlight ?? 0) + 1;
1279
+ }
1280
+ }
1281
+
1282
+ decrementInFlight(name: string): void {
1283
+ const connection = this.connections.get(name);
1284
+ if (connection && connection.inFlight) {
1285
+ connection.inFlight--;
1286
+ }
1287
+ }
1288
+
1289
+ isIdle(name: string, timeoutMs: number): boolean {
1290
+ const connection = this.connections.get(name);
1291
+ if (!connection || connection.status !== "connected") return false;
1292
+ if (connection.inFlight > 0) return false;
1293
+ return (Date.now() - connection.lastUsedAt) > timeoutMs;
1294
+ }
1295
+ }
1296
+
1297
+ /**
1298
+ * Resolve environment variables with interpolation.
1299
+ */
1300
+ function resolveEnv(env: Record<string, string> | undefined, serverName: string, literalEnv = false): Record<string, string> {
1301
+ const resolved: Record<string, string> = {};
1302
+ for (const [key, value] of Object.entries(process.env)) {
1303
+ if (value !== undefined) resolved[key] = value;
1304
+ }
1305
+ if (literalEnv) return env ? { ...resolved, ...env } : resolved;
1306
+
1307
+ const overrides = resolveCommandSecretsRecord(
1308
+ env,
1309
+ key => `MCP server "${serverName}" stdio env "${key}"`,
1310
+ );
1311
+ return overrides ? { ...resolved, ...overrides } : resolved;
1312
+ }
1313
+
1314
+ function normalizeRequestTimeoutMs(timeoutMs: number | undefined): number | undefined {
1315
+ return typeof timeoutMs === "number" && Number.isFinite(timeoutMs) && timeoutMs > 0
1316
+ ? timeoutMs
1317
+ : undefined;
1318
+ }