@duckmind/dm-windows-x64 0.63.4 → 0.63.9

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