@herbertgao/pi-extensions 2026.9.11 → 2026.9.13
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.
- package/README.md +4 -4
- package/THIRD_PARTY_NOTICES.md +1 -1
- package/node_modules/@herbertgao/pi-cc-extensions/package.json +1 -1
- package/node_modules/@herbertgao/pi-subagents/CHANGELOG.md +8 -0
- package/node_modules/@herbertgao/pi-subagents/package.json +1 -1
- package/node_modules/@herbertgao/pi-subagents/src/agent-manager.ts +5 -4
- package/node_modules/@herbertgao/pi-subagents/src/mention-clone.ts +39 -16
- package/node_modules/@juicesharp/rpiv-ask-user-question/package.json +2 -2
- package/node_modules/@narumitw/pi-btw/README.md +21 -4
- package/node_modules/@narumitw/pi-btw/dist/index.ts +1668 -958
- package/node_modules/@narumitw/pi-btw/dist/index.ts.map +4 -4
- package/node_modules/@narumitw/pi-btw/docs/workflows.md +10 -2
- package/node_modules/@narumitw/pi-btw/package.json +1 -1
- package/node_modules/@narumitw/pi-btw/src/btw.ts +17 -79
- package/node_modules/@narumitw/pi-btw/src/conversation-context.ts +74 -0
- package/node_modules/@narumitw/pi-btw/src/fullscreen-ui.ts +196 -7
- package/node_modules/@narumitw/pi-btw/src/main-thread-updates.ts +40 -0
- package/node_modules/@narumitw/pi-btw/src/menu.ts +34 -2
- package/node_modules/@narumitw/pi-btw/src/settings.ts +49 -0
- package/node_modules/@narumitw/pi-btw/src/transcript-pager.ts +9 -1
- package/node_modules/@narumitw/pi-btw/src/workspace-layout.ts +559 -0
- package/node_modules/pi-mcp-adapter/CHANGELOG.md +62 -0
- package/node_modules/pi-mcp-adapter/README.md +75 -7
- package/node_modules/pi-mcp-adapter/bearer-command-resolver.ts +193 -0
- package/node_modules/pi-mcp-adapter/cli.js +56 -5
- package/node_modules/pi-mcp-adapter/commands.ts +96 -5
- package/node_modules/pi-mcp-adapter/config.ts +73 -6
- package/node_modules/pi-mcp-adapter/direct-tool-surface.ts +22 -28
- package/node_modules/pi-mcp-adapter/direct-tools.ts +13 -5
- package/node_modules/pi-mcp-adapter/dist/abort.d.ts +2 -0
- package/node_modules/pi-mcp-adapter/dist/abort.js +36 -0
- package/node_modules/pi-mcp-adapter/dist/abort.js.map +1 -0
- package/node_modules/pi-mcp-adapter/dist/bearer-command-resolver.d.ts +6 -0
- package/node_modules/pi-mcp-adapter/dist/bearer-command-resolver.js +194 -0
- package/node_modules/pi-mcp-adapter/dist/bearer-command-resolver.js.map +1 -0
- package/node_modules/pi-mcp-adapter/dist/config.d.ts +5 -0
- package/node_modules/pi-mcp-adapter/dist/config.js +75 -6
- package/node_modules/pi-mcp-adapter/dist/config.js.map +1 -1
- package/node_modules/pi-mcp-adapter/dist/consent-manager.d.ts +18 -0
- package/node_modules/pi-mcp-adapter/dist/consent-manager.js +88 -0
- package/node_modules/pi-mcp-adapter/dist/consent-manager.js.map +1 -0
- package/node_modules/pi-mcp-adapter/dist/elicitation-handler.d.ts +17 -0
- package/node_modules/pi-mcp-adapter/dist/elicitation-handler.js +316 -0
- package/node_modules/pi-mcp-adapter/dist/elicitation-handler.js.map +1 -0
- package/node_modules/pi-mcp-adapter/dist/errors.d.ts +131 -0
- package/node_modules/pi-mcp-adapter/dist/errors.js +278 -0
- package/node_modules/pi-mcp-adapter/dist/errors.js.map +1 -0
- package/node_modules/pi-mcp-adapter/dist/http-ca.d.ts +8 -0
- package/node_modules/pi-mcp-adapter/dist/http-ca.js +88 -0
- package/node_modules/pi-mcp-adapter/dist/http-ca.js.map +1 -0
- package/node_modules/pi-mcp-adapter/dist/jev-client.d.ts +15 -0
- package/node_modules/pi-mcp-adapter/dist/jev-client.js +340 -0
- package/node_modules/pi-mcp-adapter/dist/jev-client.js.map +1 -0
- package/node_modules/pi-mcp-adapter/dist/jev-contracts.d.ts +77 -0
- package/node_modules/pi-mcp-adapter/dist/jev-contracts.js +2 -0
- package/node_modules/pi-mcp-adapter/dist/jev-contracts.js.map +1 -0
- package/node_modules/pi-mcp-adapter/dist/jev-key-store.d.ts +22 -0
- package/node_modules/pi-mcp-adapter/dist/jev-key-store.js +85 -0
- package/node_modules/pi-mcp-adapter/dist/jev-key-store.js.map +1 -0
- package/node_modules/pi-mcp-adapter/dist/json-schema-validator.d.ts +2 -0
- package/node_modules/pi-mcp-adapter/dist/json-schema-validator.js +55 -0
- package/node_modules/pi-mcp-adapter/dist/json-schema-validator.js.map +1 -0
- package/node_modules/pi-mcp-adapter/dist/lifecycle.d.ts +56 -0
- package/node_modules/pi-mcp-adapter/dist/lifecycle.js +410 -0
- package/node_modules/pi-mcp-adapter/dist/lifecycle.js.map +1 -0
- package/node_modules/pi-mcp-adapter/dist/logger.d.ts +51 -0
- package/node_modules/pi-mcp-adapter/dist/logger.js +131 -0
- package/node_modules/pi-mcp-adapter/dist/logger.js.map +1 -0
- package/node_modules/pi-mcp-adapter/dist/mcp-auth-fetch.d.ts +26 -0
- package/node_modules/pi-mcp-adapter/dist/mcp-auth-fetch.js +103 -0
- package/node_modules/pi-mcp-adapter/dist/mcp-auth-fetch.js.map +1 -0
- package/node_modules/pi-mcp-adapter/dist/mcp-auth-flow.d.ts +118 -0
- package/node_modules/pi-mcp-adapter/dist/mcp-auth-flow.js +1098 -0
- package/node_modules/pi-mcp-adapter/dist/mcp-auth-flow.js.map +1 -0
- package/node_modules/pi-mcp-adapter/dist/mcp-auth.d.ts +168 -0
- package/node_modules/pi-mcp-adapter/dist/mcp-auth.js +1117 -0
- package/node_modules/pi-mcp-adapter/dist/mcp-auth.js.map +1 -0
- package/node_modules/pi-mcp-adapter/dist/mcp-bearer-store.js +7 -140
- package/node_modules/pi-mcp-adapter/dist/mcp-bearer-store.js.map +1 -1
- package/node_modules/pi-mcp-adapter/dist/mcp-callback-server.d.ts +53 -0
- package/node_modules/pi-mcp-adapter/dist/mcp-callback-server.js +441 -0
- package/node_modules/pi-mcp-adapter/dist/mcp-callback-server.js.map +1 -0
- package/node_modules/pi-mcp-adapter/dist/mcp-oauth-provider.d.ts +148 -0
- package/node_modules/pi-mcp-adapter/dist/mcp-oauth-provider.js +689 -0
- package/node_modules/pi-mcp-adapter/dist/mcp-oauth-provider.js.map +1 -0
- package/node_modules/pi-mcp-adapter/dist/mcp-probe.d.ts +6 -0
- package/node_modules/pi-mcp-adapter/dist/mcp-probe.js +166 -0
- package/node_modules/pi-mcp-adapter/dist/mcp-probe.js.map +1 -0
- package/node_modules/pi-mcp-adapter/dist/mcp-tasks.d.ts +102 -0
- package/node_modules/pi-mcp-adapter/dist/mcp-tasks.js +369 -0
- package/node_modules/pi-mcp-adapter/dist/mcp-tasks.js.map +1 -0
- package/node_modules/pi-mcp-adapter/dist/mcp-trace.d.ts +95 -0
- package/node_modules/pi-mcp-adapter/dist/mcp-trace.js +242 -0
- package/node_modules/pi-mcp-adapter/dist/mcp-trace.js.map +1 -0
- package/node_modules/pi-mcp-adapter/dist/metadata-cache.js +2 -11
- package/node_modules/pi-mcp-adapter/dist/metadata-cache.js.map +1 -1
- package/node_modules/pi-mcp-adapter/dist/npx-resolver.d.ts +6 -0
- package/node_modules/pi-mcp-adapter/dist/npx-resolver.js +505 -0
- package/node_modules/pi-mcp-adapter/dist/npx-resolver.js.map +1 -0
- package/node_modules/pi-mcp-adapter/dist/request-headers-command.d.ts +10 -0
- package/node_modules/pi-mcp-adapter/dist/request-headers-command.js +312 -0
- package/node_modules/pi-mcp-adapter/dist/request-headers-command.js.map +1 -0
- package/node_modules/pi-mcp-adapter/dist/runtime-owner.d.ts +13 -0
- package/node_modules/pi-mcp-adapter/dist/runtime-owner.js +97 -0
- package/node_modules/pi-mcp-adapter/dist/runtime-owner.js.map +1 -0
- package/node_modules/pi-mcp-adapter/dist/sampling-handler.d.ts +17 -0
- package/node_modules/pi-mcp-adapter/dist/sampling-handler.js +203 -0
- package/node_modules/pi-mcp-adapter/dist/sampling-handler.js.map +1 -0
- package/node_modules/pi-mcp-adapter/dist/secure-keyring.d.ts +11 -0
- package/node_modules/pi-mcp-adapter/dist/secure-keyring.js +172 -0
- package/node_modules/pi-mcp-adapter/dist/secure-keyring.js.map +1 -0
- package/node_modules/pi-mcp-adapter/dist/server-manager.d.ts +157 -0
- package/node_modules/pi-mcp-adapter/dist/server-manager.js +1743 -0
- package/node_modules/pi-mcp-adapter/dist/server-manager.js.map +1 -0
- package/node_modules/pi-mcp-adapter/dist/session-approvals.d.ts +34 -0
- package/node_modules/pi-mcp-adapter/dist/session-approvals.js +140 -0
- package/node_modules/pi-mcp-adapter/dist/session-approvals.js.map +1 -0
- package/node_modules/pi-mcp-adapter/dist/session-recovery.d.ts +26 -0
- package/node_modules/pi-mcp-adapter/dist/session-recovery.js +142 -0
- package/node_modules/pi-mcp-adapter/dist/session-recovery.js.map +1 -0
- package/node_modules/pi-mcp-adapter/dist/state.d.ts +73 -0
- package/node_modules/pi-mcp-adapter/dist/state.js +2 -0
- package/node_modules/pi-mcp-adapter/dist/state.js.map +1 -0
- package/node_modules/pi-mcp-adapter/dist/types.d.ts +36 -0
- package/node_modules/pi-mcp-adapter/dist/types.js +18 -0
- package/node_modules/pi-mcp-adapter/dist/types.js.map +1 -1
- package/node_modules/pi-mcp-adapter/dist/ui-resource-handler.d.ts +17 -0
- package/node_modules/pi-mcp-adapter/dist/ui-resource-handler.js +219 -0
- package/node_modules/pi-mcp-adapter/dist/ui-resource-handler.js.map +1 -0
- package/node_modules/pi-mcp-adapter/dist/unix-socket-transport.d.ts +15 -0
- package/node_modules/pi-mcp-adapter/dist/unix-socket-transport.js +85 -0
- package/node_modules/pi-mcp-adapter/dist/unix-socket-transport.js.map +1 -0
- package/node_modules/pi-mcp-adapter/dist/utils.d.ts +1 -0
- package/node_modules/pi-mcp-adapter/dist/utils.js +13 -0
- package/node_modules/pi-mcp-adapter/dist/utils.js.map +1 -1
- package/node_modules/pi-mcp-adapter/elicitation-handler.ts +29 -19
- package/node_modules/pi-mcp-adapter/examples/jev-accessibility-loop.mjs +85 -0
- package/node_modules/pi-mcp-adapter/examples/jev-semantic-filter.mjs +34 -0
- package/node_modules/pi-mcp-adapter/index.ts +129 -6
- package/node_modules/pi-mcp-adapter/init.ts +6 -19
- package/node_modules/pi-mcp-adapter/jev-client.ts +273 -0
- package/node_modules/pi-mcp-adapter/jev-contracts.ts +53 -0
- package/node_modules/pi-mcp-adapter/jev-key-store.ts +79 -0
- package/node_modules/pi-mcp-adapter/lifecycle.ts +14 -3
- package/node_modules/pi-mcp-adapter/mcp-bearer-store.ts +7 -142
- package/node_modules/pi-mcp-adapter/mcp-code.ts +119 -11
- package/node_modules/pi-mcp-adapter/mcp-output-guard.ts +4 -0
- package/node_modules/pi-mcp-adapter/mcp-references.ts +5 -3
- package/node_modules/pi-mcp-adapter/mcp-script-worker.mjs +5 -0
- package/node_modules/pi-mcp-adapter/mcp-tasks.ts +467 -0
- package/node_modules/pi-mcp-adapter/metadata-cache.ts +2 -13
- package/node_modules/pi-mcp-adapter/namespace-tools.ts +1 -1
- package/node_modules/pi-mcp-adapter/package.json +17 -9
- package/node_modules/pi-mcp-adapter/proxy-modes.ts +319 -166
- package/node_modules/pi-mcp-adapter/request-headers-command.ts +6 -3
- package/node_modules/pi-mcp-adapter/search-ranking.ts +38 -7
- package/node_modules/pi-mcp-adapter/secure-keyring.ts +170 -0
- package/node_modules/pi-mcp-adapter/semantic-search.ts +186 -0
- package/node_modules/pi-mcp-adapter/server-manager.ts +293 -50
- package/node_modules/pi-mcp-adapter/session-approvals.ts +14 -0
- package/node_modules/pi-mcp-adapter/skills/mcp-scripting/SKILL.md +2 -0
- package/node_modules/pi-mcp-adapter/state.ts +3 -1
- package/node_modules/pi-mcp-adapter/tool-approval.ts +26 -4
- package/node_modules/pi-mcp-adapter/tool-metadata.ts +6 -14
- package/node_modules/pi-mcp-adapter/tool-registrar.ts +8 -6
- package/node_modules/pi-mcp-adapter/tool-result-renderer.ts +4 -1
- package/node_modules/pi-mcp-adapter/types.ts +53 -0
- package/node_modules/pi-mcp-adapter/ui-server.ts +17 -9
- package/node_modules/pi-mcp-adapter/utils.ts +16 -0
- package/node_modules/pi-multi-account/CHANGELOG.md +23 -0
- package/node_modules/pi-multi-account/README.md +38 -11
- package/node_modules/pi-multi-account/index.ts +371 -96
- package/node_modules/pi-multi-account/package.json +5 -4
- package/node_modules/pi-multi-account/provider-payload-stream.ts +36 -28
- package/node_modules/pi-multi-account/usage.ts +31 -2
- package/node_modules/pi-typesafe/README.md +3 -1
- package/node_modules/pi-typesafe/dist/auth.d.ts +10 -3
- package/node_modules/pi-typesafe/dist/auth.js +13 -7
- package/node_modules/pi-typesafe/dist/backends.d.ts +31 -0
- package/node_modules/pi-typesafe/dist/backends.js +33 -0
- package/node_modules/pi-typesafe/dist/client.d.ts +3 -9
- package/node_modules/pi-typesafe/dist/client.js +63 -39
- package/node_modules/pi-typesafe/dist/credentials.d.ts +11 -5
- package/node_modules/pi-typesafe/dist/credentials.js +15 -8
- package/node_modules/pi-typesafe/dist/extension.js +4 -1
- package/node_modules/pi-typesafe/dist/index.d.ts +1 -1
- package/node_modules/pi-typesafe/dist/index.js +1 -1
- package/node_modules/pi-typesafe/dist/login.d.ts +13 -7
- package/node_modules/pi-typesafe/dist/login.js +17 -8
- package/node_modules/pi-typesafe/dist/schema.js +19 -13
- package/node_modules/pi-typesafe/package.json +1 -1
- package/package.json +11 -10
|
@@ -0,0 +1,1743 @@
|
|
|
1
|
+
import { mkdirSync, statSync } from "node:fs";
|
|
2
|
+
import { BlockList, isIP } from "node:net";
|
|
3
|
+
import { isDeepStrictEqual } from "node:util";
|
|
4
|
+
import { Client, SdkError, SdkErrorCode, SdkHttpError, SseError, SSEClientTransport, StreamableHTTPClientTransport, UnauthorizedError, } from "@modelcontextprotocol/client";
|
|
5
|
+
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
|
|
6
|
+
import { UnixSocketClientTransport } from "./unix-socket-transport.js";
|
|
7
|
+
import { probeMcpEndpoint } from "./mcp-probe.js";
|
|
8
|
+
import { isServerDisabled, SERVER_STREAM_RESULT_PATCH_METHOD, serverStreamResultPatchNotificationSchema, } from "./types.js";
|
|
9
|
+
import { resolveNpxBinary } from "./npx-resolver.js";
|
|
10
|
+
import { createJsonSchemaValidator } from "./json-schema-validator.js";
|
|
11
|
+
import { logger } from "./logger.js";
|
|
12
|
+
import { RESOURCE_MIME_TYPE } from "./ui-app-bridge-helpers.js";
|
|
13
|
+
import { isBuiltInAgentPlugin } from "./agent-plugin-provenance.js";
|
|
14
|
+
import { McpOAuthProvider } from "./mcp-oauth-provider.js";
|
|
15
|
+
import { extractOAuthConfig, supportsOAuth } from "./mcp-auth-flow.js";
|
|
16
|
+
import { captureOAuthAuthority, inspectAuthForUrl, invalidateAuthEntryCache, } from "./mcp-auth.js";
|
|
17
|
+
import { getBearerTokenForUrl } from "./mcp-bearer-store.js";
|
|
18
|
+
import { handleSamplingRequest, registerSamplingHandler } from "./sampling-handler.js";
|
|
19
|
+
import { handleElicitationRequest, handleUrlElicitation, registerElicitationHandler, } from "./elicitation-handler.js";
|
|
20
|
+
import { attachTaskSession } from "./mcp-tasks.js";
|
|
21
|
+
import { interpolateEnvVars, resolveBearerToken, resolveCommandSecretsRecord, resolveConfigPath, resolveServerUrl, } from "./utils.js";
|
|
22
|
+
import { abortable, throwIfAborted } from "./abort.js";
|
|
23
|
+
import { combineAbortSignals } from "./runtime-owner.js";
|
|
24
|
+
import { createMcpTraceWriter, isMcpTraceEnabled, traceTransportKind, wrapTransportWithMcpTrace, } from "./mcp-trace.js";
|
|
25
|
+
import { createOAuthFetch, resolveOAuthHeaders } from "./mcp-auth-fetch.js";
|
|
26
|
+
import { createRequestHeadersCommandFetch } from "./request-headers-command.js";
|
|
27
|
+
import { createCaFetch, validateCaFile } from "./http-ca.js";
|
|
28
|
+
import { BearerCommandResolver } from "./bearer-command-resolver.js";
|
|
29
|
+
const MAX_CAPTURED_STDERR_BYTES = 8 * 1024;
|
|
30
|
+
const MAX_CAPTURED_STDERR_LINES = 3;
|
|
31
|
+
const abortCleanupPromises = new WeakMap();
|
|
32
|
+
function isLiteralLocalAddress(url) {
|
|
33
|
+
const hostname = new URL(url).hostname.replace(/^\[|\]$/g, "");
|
|
34
|
+
const family = isIP(hostname);
|
|
35
|
+
if (!family)
|
|
36
|
+
return false;
|
|
37
|
+
const local = new BlockList();
|
|
38
|
+
local.addSubnet("10.0.0.0", 8);
|
|
39
|
+
local.addSubnet("172.16.0.0", 12);
|
|
40
|
+
local.addSubnet("192.168.0.0", 16);
|
|
41
|
+
local.addSubnet("169.254.0.0", 16);
|
|
42
|
+
local.addSubnet("fc00::", 7, "ipv6");
|
|
43
|
+
local.addSubnet("fe80::", 10, "ipv6");
|
|
44
|
+
return local.check(hostname, family === 6 ? "ipv6" : "ipv4");
|
|
45
|
+
}
|
|
46
|
+
function localNetworkFailureCodes(error, seen = new Set()) {
|
|
47
|
+
if (typeof error !== "object" || error === null || seen.has(error))
|
|
48
|
+
return [];
|
|
49
|
+
seen.add(error);
|
|
50
|
+
const codes = [];
|
|
51
|
+
if ("code" in error && typeof error.code === "string"
|
|
52
|
+
&& ["EHOSTUNREACH", "ENETUNREACH", "EACCES"].includes(error.code)) {
|
|
53
|
+
codes.push(error.code);
|
|
54
|
+
}
|
|
55
|
+
if ("cause" in error)
|
|
56
|
+
codes.push(...localNetworkFailureCodes(error.cause, seen));
|
|
57
|
+
if (error instanceof AggregateError) {
|
|
58
|
+
for (const nested of error.errors)
|
|
59
|
+
codes.push(...localNetworkFailureCodes(nested, seen));
|
|
60
|
+
}
|
|
61
|
+
return [...new Set(codes)];
|
|
62
|
+
}
|
|
63
|
+
export function isUnauthorizedHttpError(error) {
|
|
64
|
+
return error instanceof UnauthorizedError
|
|
65
|
+
|| (error instanceof SdkHttpError && error.status === 401)
|
|
66
|
+
// Some pinned-SDK transport paths emit this plain Error when bearer
|
|
67
|
+
// request headers are used without an OAuth authProvider.
|
|
68
|
+
|| (error instanceof Error && /^Error POSTing to endpoint \(HTTP 401\):/.test(error.message));
|
|
69
|
+
}
|
|
70
|
+
function shouldFallbackToSse(error, definition) {
|
|
71
|
+
if (definition.protocolVersion === "2026-07-28")
|
|
72
|
+
return false;
|
|
73
|
+
return error instanceof SdkHttpError && [404, 405, 406, 415].includes(error.status);
|
|
74
|
+
}
|
|
75
|
+
function resolveVersionNegotiation(definition) {
|
|
76
|
+
switch (definition.protocolVersion) {
|
|
77
|
+
case undefined:
|
|
78
|
+
case "legacy":
|
|
79
|
+
return undefined;
|
|
80
|
+
case "auto":
|
|
81
|
+
return { mode: "auto" };
|
|
82
|
+
case "2026-07-28":
|
|
83
|
+
return { mode: { pin: "2026-07-28" } };
|
|
84
|
+
default:
|
|
85
|
+
throw new Error(`Invalid MCP protocolVersion: ${String(definition.protocolVersion)}`);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
function boundedStderrChunk(chunk) {
|
|
89
|
+
if (Buffer.isBuffer(chunk)) {
|
|
90
|
+
const start = Math.max(0, chunk.byteLength - MAX_CAPTURED_STDERR_BYTES);
|
|
91
|
+
return Buffer.from(chunk.subarray(start));
|
|
92
|
+
}
|
|
93
|
+
// Limit string conversion before encoding; Buffer.from(largeString) would
|
|
94
|
+
// otherwise allocate the entire stderr event before applying the cap.
|
|
95
|
+
const suffix = chunk.length > MAX_CAPTURED_STDERR_BYTES
|
|
96
|
+
? chunk.slice(-MAX_CAPTURED_STDERR_BYTES)
|
|
97
|
+
: chunk;
|
|
98
|
+
const bytes = Buffer.from(suffix, "utf8");
|
|
99
|
+
return bytes.byteLength > MAX_CAPTURED_STDERR_BYTES
|
|
100
|
+
? Buffer.from(bytes.subarray(bytes.byteLength - MAX_CAPTURED_STDERR_BYTES))
|
|
101
|
+
: bytes;
|
|
102
|
+
}
|
|
103
|
+
function appendStderrTail(tail, chunk) {
|
|
104
|
+
const bytes = boundedStderrChunk(chunk);
|
|
105
|
+
if (bytes.length === 0)
|
|
106
|
+
return tail;
|
|
107
|
+
if (tail.length === 0)
|
|
108
|
+
return bytes;
|
|
109
|
+
const combined = Buffer.concat([tail, bytes]);
|
|
110
|
+
return combined.length > MAX_CAPTURED_STDERR_BYTES
|
|
111
|
+
? Buffer.from(combined.subarray(combined.length - MAX_CAPTURED_STDERR_BYTES))
|
|
112
|
+
: combined;
|
|
113
|
+
}
|
|
114
|
+
const KEEP_ALIVE_REFRESH_TIMEOUT_MS = 5_000;
|
|
115
|
+
const LISTEN_RETRY_DELAY_MS = 5_000;
|
|
116
|
+
const RECENT_RESOURCE_TTL_MS = 10 * 60_000;
|
|
117
|
+
const MAX_RESOURCE_SUBSCRIPTIONS = 32;
|
|
118
|
+
export function isTransientHttpConnectError(error) {
|
|
119
|
+
let current = error;
|
|
120
|
+
while (current instanceof Error) {
|
|
121
|
+
if (current instanceof SdkHttpError && current.status === 503)
|
|
122
|
+
return true;
|
|
123
|
+
current = current.cause;
|
|
124
|
+
}
|
|
125
|
+
return false;
|
|
126
|
+
}
|
|
127
|
+
/** Wrap a FetchLike so each request re-resolves the bearer token via the resolver. */
|
|
128
|
+
function createBearerCommandFetch(resolver, delegate) {
|
|
129
|
+
const innerFetch = delegate
|
|
130
|
+
? (input, init) => delegate(input, init)
|
|
131
|
+
: (input, init) => globalThis.fetch(input, init);
|
|
132
|
+
return async (input, init) => {
|
|
133
|
+
const request = new Request(input, init);
|
|
134
|
+
const token = await resolver.resolve(request.signal);
|
|
135
|
+
const headers = new Headers(request.headers);
|
|
136
|
+
headers.set("Authorization", `Bearer ${token}`);
|
|
137
|
+
// Composed runtime fetches accept Request despite the SDK's narrower type.
|
|
138
|
+
return innerFetch(new Request(request, { headers }));
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
export class McpServerManager {
|
|
142
|
+
defaultCwd;
|
|
143
|
+
connections = new Map();
|
|
144
|
+
connectPromises = new Map();
|
|
145
|
+
connectOAuthAuthorities = new Map();
|
|
146
|
+
reconnectPromises = new Map();
|
|
147
|
+
reconnectOAuthAuthorities = new Map();
|
|
148
|
+
reconnectAttempts = new Map();
|
|
149
|
+
uiStreamListeners = new Map();
|
|
150
|
+
samplingConfig;
|
|
151
|
+
metadataListChangedListener;
|
|
152
|
+
listenStateChangedListener;
|
|
153
|
+
resourceUpdatedListeners = new Map();
|
|
154
|
+
pendingMetadataPublications = new Map();
|
|
155
|
+
elicitationConfig;
|
|
156
|
+
authStorageOptions = {};
|
|
157
|
+
oauthRuntime;
|
|
158
|
+
acceptedUrlElicitations = new Map();
|
|
159
|
+
defaultRequestTimeoutMs;
|
|
160
|
+
runtimeSignal;
|
|
161
|
+
closePromises = new Map();
|
|
162
|
+
closeGenerations = new Map();
|
|
163
|
+
connectAttempts = new Map();
|
|
164
|
+
traceSettings;
|
|
165
|
+
traceWriter;
|
|
166
|
+
stopped = false;
|
|
167
|
+
/** Default cwd for stdio servers without an explicit config `cwd`. */
|
|
168
|
+
constructor(defaultCwd) {
|
|
169
|
+
this.defaultCwd = defaultCwd;
|
|
170
|
+
}
|
|
171
|
+
setSamplingConfig(config) {
|
|
172
|
+
this.samplingConfig = config;
|
|
173
|
+
}
|
|
174
|
+
setMetadataListChangedListener(listener) {
|
|
175
|
+
this.metadataListChangedListener = listener;
|
|
176
|
+
}
|
|
177
|
+
setListenStateChangedListener(listener) {
|
|
178
|
+
this.listenStateChangedListener = listener;
|
|
179
|
+
}
|
|
180
|
+
publishMetadataChanged(name, expectedConnection, reason) {
|
|
181
|
+
const current = this.connections.get(name);
|
|
182
|
+
if (current !== expectedConnection || current.status !== "connected")
|
|
183
|
+
return false;
|
|
184
|
+
try {
|
|
185
|
+
this.metadataListChangedListener?.(name, reason);
|
|
186
|
+
this.pendingMetadataPublications.delete(name);
|
|
187
|
+
return true;
|
|
188
|
+
}
|
|
189
|
+
catch (error) {
|
|
190
|
+
this.pendingMetadataPublications.set(name, { connection: expectedConnection, reason });
|
|
191
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
192
|
+
logger.debug(`MCP: metadata publication failed for ${name}; queued for retry: ${message}`);
|
|
193
|
+
return false;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
setElicitationConfig(config) {
|
|
197
|
+
this.elicitationConfig = config;
|
|
198
|
+
}
|
|
199
|
+
setRuntimeSignal(signal) {
|
|
200
|
+
this.runtimeSignal = signal;
|
|
201
|
+
}
|
|
202
|
+
setDefaultRequestTimeoutMs(timeoutMs) {
|
|
203
|
+
this.defaultRequestTimeoutMs = normalizeRequestTimeoutMs(timeoutMs);
|
|
204
|
+
}
|
|
205
|
+
setTraceConfig(settings) {
|
|
206
|
+
this.traceSettings = settings;
|
|
207
|
+
}
|
|
208
|
+
setAuthStorageOptions(options) {
|
|
209
|
+
this.authStorageOptions = options;
|
|
210
|
+
}
|
|
211
|
+
setOAuthRuntime(runtime) {
|
|
212
|
+
this.oauthRuntime = runtime;
|
|
213
|
+
}
|
|
214
|
+
getRequestOptions(name, signal) {
|
|
215
|
+
const connection = this.connections.get(name);
|
|
216
|
+
return this.buildRequestOptions(connection?.definition, signal);
|
|
217
|
+
}
|
|
218
|
+
getResolvedRequestTimeoutMs(definition) {
|
|
219
|
+
if (definition?.requestTimeoutMs !== undefined) {
|
|
220
|
+
return normalizeRequestTimeoutMs(definition.requestTimeoutMs);
|
|
221
|
+
}
|
|
222
|
+
return this.defaultRequestTimeoutMs;
|
|
223
|
+
}
|
|
224
|
+
buildRequestOptions(definition, signal) {
|
|
225
|
+
const timeout = this.getResolvedRequestTimeoutMs(definition);
|
|
226
|
+
const ownedSignal = combineAbortSignals(this.runtimeSignal, signal);
|
|
227
|
+
if (!ownedSignal && timeout === undefined) {
|
|
228
|
+
return undefined;
|
|
229
|
+
}
|
|
230
|
+
return {
|
|
231
|
+
...(ownedSignal ? { signal: ownedSignal } : {}),
|
|
232
|
+
...(timeout !== undefined ? { timeout } : {}),
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
arbitrateConnectionAttempt(name, oauthAuthority, promises, authorities, attempts) {
|
|
236
|
+
const existingPromise = promises.get(name);
|
|
237
|
+
if (!existingPromise)
|
|
238
|
+
return undefined;
|
|
239
|
+
const existingAuthority = authorities.get(name);
|
|
240
|
+
let reusable = oauthAuthority === undefined && existingAuthority === undefined;
|
|
241
|
+
if (oauthAuthority && existingAuthority) {
|
|
242
|
+
try {
|
|
243
|
+
existingAuthority();
|
|
244
|
+
reusable = true;
|
|
245
|
+
}
|
|
246
|
+
catch {
|
|
247
|
+
reusable = false;
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
if (reusable)
|
|
251
|
+
return existingPromise;
|
|
252
|
+
const replacedAttempt = attempts.get(name);
|
|
253
|
+
replacedAttempt?.abort(new Error(`MCP connection ${name} was replaced`));
|
|
254
|
+
if (attempts.get(name) === replacedAttempt)
|
|
255
|
+
attempts.delete(name);
|
|
256
|
+
if (promises.get(name) === existingPromise)
|
|
257
|
+
promises.delete(name);
|
|
258
|
+
if (authorities.get(name) === existingAuthority)
|
|
259
|
+
authorities.delete(name);
|
|
260
|
+
return undefined;
|
|
261
|
+
}
|
|
262
|
+
async connect(name, definition, signal) {
|
|
263
|
+
validateCaFile(definition);
|
|
264
|
+
if (isServerDisabled(definition))
|
|
265
|
+
throw new Error(`MCP server "${name}" is disabled`);
|
|
266
|
+
if (this.stopped)
|
|
267
|
+
throw new Error("MCP server manager is closed");
|
|
268
|
+
const ownedSignal = combineAbortSignals(this.runtimeSignal, signal);
|
|
269
|
+
throwIfAborted(ownedSignal);
|
|
270
|
+
const oauthAuthority = definition.url && supportsOAuth(definition)
|
|
271
|
+
? captureOAuthAuthority(name, false)
|
|
272
|
+
: undefined;
|
|
273
|
+
const closing = this.closePromises.get(name);
|
|
274
|
+
if (closing)
|
|
275
|
+
await abortable(closing, ownedSignal);
|
|
276
|
+
throwIfAborted(ownedSignal);
|
|
277
|
+
// Dedupe concurrent connection attempts.
|
|
278
|
+
const existingConnect = this.arbitrateConnectionAttempt(name, oauthAuthority, this.connectPromises, this.connectOAuthAuthorities, this.connectAttempts);
|
|
279
|
+
if (existingConnect)
|
|
280
|
+
return abortable(existingConnect, ownedSignal);
|
|
281
|
+
const existing = this.connections.get(name);
|
|
282
|
+
if (existing?.status === "connected") {
|
|
283
|
+
existing.lastUsedAt = Date.now();
|
|
284
|
+
return existing;
|
|
285
|
+
}
|
|
286
|
+
// A needs-auth route can be retried through either public path. Share an
|
|
287
|
+
// authority-compatible reconnect candidate instead of creating a second
|
|
288
|
+
// owner for the same server.
|
|
289
|
+
const existingReconnect = this.arbitrateConnectionAttempt(name, oauthAuthority, this.reconnectPromises, this.reconnectOAuthAuthorities, this.reconnectAttempts);
|
|
290
|
+
if (existingReconnect)
|
|
291
|
+
return abortable(existingReconnect, ownedSignal);
|
|
292
|
+
const credentialsInvalidated = existing?.status === "needs-auth"
|
|
293
|
+
&& existing.credentialsInvalidated === true;
|
|
294
|
+
const generation = this.closeGenerations.get(name) ?? 0;
|
|
295
|
+
const attemptController = new AbortController();
|
|
296
|
+
const attemptSignal = combineAbortSignals(ownedSignal, attemptController.signal);
|
|
297
|
+
const connectionAttempt = this.createConnection(name, definition, attemptSignal, ownedSignal, credentialsInvalidated, oauthAuthority, attemptController);
|
|
298
|
+
const promise = definition.url
|
|
299
|
+
? connectionAttempt.catch(async (error) => { throw await this.enrichHttpConnectionError(definition, error); })
|
|
300
|
+
: connectionAttempt;
|
|
301
|
+
this.connectPromises.set(name, promise);
|
|
302
|
+
if (oauthAuthority)
|
|
303
|
+
this.connectOAuthAuthorities.set(name, oauthAuthority);
|
|
304
|
+
this.connectAttempts.set(name, attemptController);
|
|
305
|
+
try {
|
|
306
|
+
const connection = await promise;
|
|
307
|
+
if (attemptController.signal.aborted || (this.closeGenerations.get(name) ?? 0) !== generation) {
|
|
308
|
+
await this.disposeConnection(connection);
|
|
309
|
+
throwIfAborted(attemptSignal);
|
|
310
|
+
throw new Error(`MCP connection for ${name} was closed while connecting`);
|
|
311
|
+
}
|
|
312
|
+
this.connections.set(name, connection);
|
|
313
|
+
this.watchListenSubscription(name, connection, connection.listenSubscription);
|
|
314
|
+
if ([...this.resourceUpdatedListeners.values()].some(registration => registration.serverName === name)) {
|
|
315
|
+
void this.ensureListen(name, connection);
|
|
316
|
+
}
|
|
317
|
+
return connection;
|
|
318
|
+
}
|
|
319
|
+
finally {
|
|
320
|
+
if (this.connectPromises.get(name) === promise)
|
|
321
|
+
this.connectPromises.delete(name);
|
|
322
|
+
if (this.connectOAuthAuthorities.get(name) === oauthAuthority) {
|
|
323
|
+
this.connectOAuthAuthorities.delete(name);
|
|
324
|
+
}
|
|
325
|
+
if (this.connectAttempts.get(name) === attemptController)
|
|
326
|
+
this.connectAttempts.delete(name);
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
/**
|
|
330
|
+
* Reconnect a server whose connection was proven stale (e.g. by a 404
|
|
331
|
+
* "session no longer exists" response). Single-flight per server name —
|
|
332
|
+
* concurrent callers that raced to the same failure share one reconnect —
|
|
333
|
+
* and identity-guarded: `staleConnection` is only torn down if it is
|
|
334
|
+
* still the manager's current connection for `name`. If a concurrent
|
|
335
|
+
* reconnect (or an unrelated connect()) already replaced it with a fresh
|
|
336
|
+
* connection, that fresh connection is returned untouched.
|
|
337
|
+
*/
|
|
338
|
+
async reconnect(name, definition, staleConnection, signal) {
|
|
339
|
+
validateCaFile(definition);
|
|
340
|
+
if (isServerDisabled(definition))
|
|
341
|
+
throw new Error(`MCP server "${name}" is disabled`);
|
|
342
|
+
if (this.stopped)
|
|
343
|
+
throw new Error("MCP server manager is closed");
|
|
344
|
+
const ownedSignal = combineAbortSignals(this.runtimeSignal, signal);
|
|
345
|
+
throwIfAborted(ownedSignal);
|
|
346
|
+
const oauthAuthority = definition.url && supportsOAuth(definition)
|
|
347
|
+
? captureOAuthAuthority(name, false)
|
|
348
|
+
: undefined;
|
|
349
|
+
// connect() and reconnect() are interchangeable retry entry points for a
|
|
350
|
+
// published needs-auth route. They must not create competing OAuth owners.
|
|
351
|
+
const existingConnect = this.arbitrateConnectionAttempt(name, oauthAuthority, this.connectPromises, this.connectOAuthAuthorities, this.connectAttempts);
|
|
352
|
+
if (existingConnect)
|
|
353
|
+
return abortable(existingConnect, ownedSignal);
|
|
354
|
+
const inFlight = this.arbitrateConnectionAttempt(name, oauthAuthority, this.reconnectPromises, this.reconnectOAuthAuthorities, this.reconnectAttempts);
|
|
355
|
+
if (inFlight)
|
|
356
|
+
return abortable(inFlight, ownedSignal);
|
|
357
|
+
const attemptController = new AbortController();
|
|
358
|
+
const attemptSignal = combineAbortSignals(ownedSignal, attemptController.signal);
|
|
359
|
+
const promise = this.doReconnect(name, definition, staleConnection, attemptSignal, oauthAuthority, attemptController)
|
|
360
|
+
.catch(error => {
|
|
361
|
+
if (attemptController.signal.aborted && !this.containsCleanupFailure(error)) {
|
|
362
|
+
throw new Error(`MCP connection for ${name} was closed while reconnecting`, { cause: error });
|
|
363
|
+
}
|
|
364
|
+
throw error;
|
|
365
|
+
})
|
|
366
|
+
.finally(() => {
|
|
367
|
+
if (this.reconnectPromises.get(name) === promise) {
|
|
368
|
+
this.reconnectPromises.delete(name);
|
|
369
|
+
}
|
|
370
|
+
if (this.reconnectAttempts.get(name) === attemptController) {
|
|
371
|
+
this.reconnectAttempts.delete(name);
|
|
372
|
+
}
|
|
373
|
+
if (this.reconnectOAuthAuthorities.get(name) === oauthAuthority) {
|
|
374
|
+
this.reconnectOAuthAuthorities.delete(name);
|
|
375
|
+
}
|
|
376
|
+
});
|
|
377
|
+
this.reconnectPromises.set(name, promise);
|
|
378
|
+
if (oauthAuthority)
|
|
379
|
+
this.reconnectOAuthAuthorities.set(name, oauthAuthority);
|
|
380
|
+
this.reconnectAttempts.set(name, attemptController);
|
|
381
|
+
return abortable(promise, ownedSignal);
|
|
382
|
+
}
|
|
383
|
+
/**
|
|
384
|
+
* Fetch the authoritative tool catalog for a connection that still appears
|
|
385
|
+
* connected. The SDK response cache is explicitly bypassed so this request
|
|
386
|
+
* also proves the remote Streamable HTTP session is usable. Results are
|
|
387
|
+
* identity-guarded: a late response from a replaced connection is ignored.
|
|
388
|
+
*/
|
|
389
|
+
async refreshTools(name, expectedConnection, signal) {
|
|
390
|
+
if (this.stopped)
|
|
391
|
+
throw new Error("MCP server manager is closed");
|
|
392
|
+
const ownedSignal = combineAbortSignals(this.runtimeSignal, signal);
|
|
393
|
+
throwIfAborted(ownedSignal);
|
|
394
|
+
const current = this.connections.get(name);
|
|
395
|
+
if (current !== expectedConnection || current.status !== "connected") {
|
|
396
|
+
return "superseded";
|
|
397
|
+
}
|
|
398
|
+
await this.ensureListen(name, expectedConnection);
|
|
399
|
+
const requestOptions = this.buildRequestOptions(expectedConnection.definition, signal);
|
|
400
|
+
const timeout = Math.min(requestOptions?.timeout ?? KEEP_ALIVE_REFRESH_TIMEOUT_MS, KEEP_ALIVE_REFRESH_TIMEOUT_MS);
|
|
401
|
+
const healthOptions = {
|
|
402
|
+
...requestOptions,
|
|
403
|
+
timeout,
|
|
404
|
+
};
|
|
405
|
+
if (!expectedConnection.client.getServerCapabilities?.()?.tools) {
|
|
406
|
+
await expectedConnection.client.ping(healthOptions);
|
|
407
|
+
throwIfAborted(ownedSignal);
|
|
408
|
+
if (this.connections.get(name) !== expectedConnection || expectedConnection.status !== "connected") {
|
|
409
|
+
return "superseded";
|
|
410
|
+
}
|
|
411
|
+
this.retryPendingMetadataPublication(name, expectedConnection);
|
|
412
|
+
return "unchanged";
|
|
413
|
+
}
|
|
414
|
+
const toolsRevision = expectedConnection.toolsRevision ?? 0;
|
|
415
|
+
const refreshSignal = combineAbortSignals(healthOptions.signal, AbortSignal.timeout(timeout));
|
|
416
|
+
let toolResult;
|
|
417
|
+
try {
|
|
418
|
+
toolResult = await this.fetchAllTools(expectedConnection.client, {
|
|
419
|
+
...healthOptions,
|
|
420
|
+
...(refreshSignal ? { signal: refreshSignal } : {}),
|
|
421
|
+
cacheMode: "refresh",
|
|
422
|
+
});
|
|
423
|
+
}
|
|
424
|
+
catch (error) {
|
|
425
|
+
throwIfAborted(ownedSignal);
|
|
426
|
+
if (this.connections.get(name) !== expectedConnection || expectedConnection.status !== "connected") {
|
|
427
|
+
return "superseded";
|
|
428
|
+
}
|
|
429
|
+
if (error instanceof SdkError && error.code === SdkErrorCode.RequestTimeout) {
|
|
430
|
+
return "refresh-timeout";
|
|
431
|
+
}
|
|
432
|
+
throw error;
|
|
433
|
+
}
|
|
434
|
+
throwIfAborted(ownedSignal);
|
|
435
|
+
if (this.connections.get(name) !== expectedConnection || expectedConnection.status !== "connected") {
|
|
436
|
+
return "superseded";
|
|
437
|
+
}
|
|
438
|
+
if ((expectedConnection.toolsRevision ?? 0) !== toolsRevision) {
|
|
439
|
+
return "superseded";
|
|
440
|
+
}
|
|
441
|
+
if (isDeepStrictEqual(expectedConnection.tools, toolResult.tools) &&
|
|
442
|
+
isDeepStrictEqual(expectedConnection.toolListHints, toolResult.hints)) {
|
|
443
|
+
this.retryPendingMetadataPublication(name, expectedConnection);
|
|
444
|
+
return "unchanged";
|
|
445
|
+
}
|
|
446
|
+
const previousTools = expectedConnection.tools;
|
|
447
|
+
const previousToolListHints = expectedConnection.toolListHints;
|
|
448
|
+
expectedConnection.tools = toolResult.tools;
|
|
449
|
+
expectedConnection.toolListHints = toolResult.hints;
|
|
450
|
+
expectedConnection.toolsRevision = toolsRevision + 1;
|
|
451
|
+
try {
|
|
452
|
+
await this.metadataListChangedListener?.(name, "keep-alive-refresh");
|
|
453
|
+
this.pendingMetadataPublications.delete(name);
|
|
454
|
+
}
|
|
455
|
+
catch (error) {
|
|
456
|
+
if (this.connections.get(name) === expectedConnection &&
|
|
457
|
+
expectedConnection.tools === toolResult.tools &&
|
|
458
|
+
expectedConnection.toolListHints === toolResult.hints) {
|
|
459
|
+
expectedConnection.tools = previousTools;
|
|
460
|
+
expectedConnection.toolListHints = previousToolListHints;
|
|
461
|
+
expectedConnection.toolsRevision = toolsRevision;
|
|
462
|
+
}
|
|
463
|
+
throw error;
|
|
464
|
+
}
|
|
465
|
+
return "updated";
|
|
466
|
+
}
|
|
467
|
+
retryPendingMetadataPublication(name, connection) {
|
|
468
|
+
const pendingPublication = this.pendingMetadataPublications.get(name);
|
|
469
|
+
if (pendingPublication?.connection !== connection)
|
|
470
|
+
return;
|
|
471
|
+
this.metadataListChangedListener?.(name, pendingPublication.reason);
|
|
472
|
+
if (this.pendingMetadataPublications.get(name) === pendingPublication) {
|
|
473
|
+
this.pendingMetadataPublications.delete(name);
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
setListenState(name, connection, state) {
|
|
477
|
+
if (connection.listenState === state)
|
|
478
|
+
return;
|
|
479
|
+
connection.listenState = state;
|
|
480
|
+
if (this.connections.get(name) === connection) {
|
|
481
|
+
try {
|
|
482
|
+
this.listenStateChangedListener?.(name, state);
|
|
483
|
+
}
|
|
484
|
+
catch {
|
|
485
|
+
// Status consumers must not interrupt listen lifecycle recovery.
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
catalogListenFilter(connection) {
|
|
490
|
+
const capabilities = connection.client.getServerCapabilities?.();
|
|
491
|
+
return {
|
|
492
|
+
...(capabilities?.tools?.listChanged ? { toolsListChanged: true } : {}),
|
|
493
|
+
...(capabilities?.prompts?.listChanged ? { promptsListChanged: true } : {}),
|
|
494
|
+
...(capabilities?.resources?.listChanged ? { resourcesListChanged: true } : {}),
|
|
495
|
+
};
|
|
496
|
+
}
|
|
497
|
+
currentListenFilter(name, connection) {
|
|
498
|
+
const now = Date.now();
|
|
499
|
+
const recent = connection.recentResourceUris;
|
|
500
|
+
if (recent) {
|
|
501
|
+
for (const [uri, touchedAt] of recent) {
|
|
502
|
+
if (now - touchedAt > RECENT_RESOURCE_TTL_MS)
|
|
503
|
+
recent.delete(uri);
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
const openResourceUris = [...new Set([...this.resourceUpdatedListeners.values()]
|
|
507
|
+
.filter(registration => registration.serverName === name)
|
|
508
|
+
.map(registration => registration.uri))].slice(-MAX_RESOURCE_SUBSCRIPTIONS);
|
|
509
|
+
const openSet = new Set(openResourceUris);
|
|
510
|
+
const recentSlots = MAX_RESOURCE_SUBSCRIPTIONS - openResourceUris.length;
|
|
511
|
+
const recentResourceUris = recentSlots > 0
|
|
512
|
+
? [...(recent?.keys() ?? [])].filter(uri => !openSet.has(uri)).slice(-recentSlots)
|
|
513
|
+
: [];
|
|
514
|
+
const resourceSubscriptions = [...openResourceUris, ...recentResourceUris];
|
|
515
|
+
return {
|
|
516
|
+
...this.catalogListenFilter(connection),
|
|
517
|
+
...(resourceSubscriptions.length > 0 ? { resourceSubscriptions } : {}),
|
|
518
|
+
};
|
|
519
|
+
}
|
|
520
|
+
watchListenSubscription(name, connection, subscription) {
|
|
521
|
+
if (!subscription)
|
|
522
|
+
return;
|
|
523
|
+
void subscription.closed.then(cause => {
|
|
524
|
+
if (this.stopped ||
|
|
525
|
+
this.connections.get(name) !== connection ||
|
|
526
|
+
connection.status !== "connected" ||
|
|
527
|
+
connection.listenSubscription !== subscription)
|
|
528
|
+
return;
|
|
529
|
+
if (cause === "remote") {
|
|
530
|
+
const staleUris = connection.listenFilter?.resourceSubscriptions ?? [];
|
|
531
|
+
if (staleUris.length > 0)
|
|
532
|
+
connection.resourceReadRefreshUris = new Set(staleUris);
|
|
533
|
+
connection.listenCatalogStale = true;
|
|
534
|
+
connection.listenRetryAfter = Date.now();
|
|
535
|
+
this.setListenState(name, connection, "dropped");
|
|
536
|
+
}
|
|
537
|
+
else if (cause === "graceful" || connection.listenState !== "re-establishing") {
|
|
538
|
+
connection.listenStopped = true;
|
|
539
|
+
this.setListenState(name, connection, "not-listening");
|
|
540
|
+
}
|
|
541
|
+
});
|
|
542
|
+
}
|
|
543
|
+
/** Quietly repairs a modern catalog listen at an existing activity boundary. */
|
|
544
|
+
async ensureListen(name, expectedConnection) {
|
|
545
|
+
if (this.stopped ||
|
|
546
|
+
this.connections.get(name) !== expectedConnection ||
|
|
547
|
+
expectedConnection.status !== "connected" ||
|
|
548
|
+
expectedConnection.listenStopped ||
|
|
549
|
+
expectedConnection.client.getProtocolEra?.() !== "modern")
|
|
550
|
+
return;
|
|
551
|
+
const filter = this.currentListenFilter(name, expectedConnection);
|
|
552
|
+
if (Object.keys(filter).length === 0) {
|
|
553
|
+
this.setListenState(name, expectedConnection, "not-listening");
|
|
554
|
+
return;
|
|
555
|
+
}
|
|
556
|
+
if (expectedConnection.listenPromise) {
|
|
557
|
+
await expectedConnection.listenPromise;
|
|
558
|
+
return this.ensureListen(name, expectedConnection);
|
|
559
|
+
}
|
|
560
|
+
if ((expectedConnection.listenRetryAfter ?? 0) > Date.now())
|
|
561
|
+
return;
|
|
562
|
+
const sameFilter = isDeepStrictEqual(expectedConnection.listenFilter, filter);
|
|
563
|
+
if (expectedConnection.listenState === "active" && sameFilter) {
|
|
564
|
+
if (!expectedConnection.listenCatalogStale)
|
|
565
|
+
return;
|
|
566
|
+
const attempt = (async () => {
|
|
567
|
+
this.setListenState(name, expectedConnection, "re-establishing");
|
|
568
|
+
const confirmed = await this.reconcileCatalogAfterListen(name, expectedConnection, this.buildRequestOptions(expectedConnection.definition));
|
|
569
|
+
if (!confirmed)
|
|
570
|
+
expectedConnection.listenRetryAfter = Date.now() + LISTEN_RETRY_DELAY_MS;
|
|
571
|
+
this.setListenState(name, expectedConnection, "active");
|
|
572
|
+
})().finally(() => {
|
|
573
|
+
if (expectedConnection.listenPromise === attempt)
|
|
574
|
+
delete expectedConnection.listenPromise;
|
|
575
|
+
});
|
|
576
|
+
expectedConnection.listenPromise = attempt;
|
|
577
|
+
return attempt;
|
|
578
|
+
}
|
|
579
|
+
const attempt = (async () => {
|
|
580
|
+
const recoverDroppedListen = expectedConnection.listenState === "dropped";
|
|
581
|
+
this.setListenState(name, expectedConnection, "re-establishing");
|
|
582
|
+
const previous = expectedConnection.listenSubscription;
|
|
583
|
+
if (previous)
|
|
584
|
+
await previous.close().catch(() => { });
|
|
585
|
+
if (this.connections.get(name) !== expectedConnection || expectedConnection.status !== "connected")
|
|
586
|
+
return;
|
|
587
|
+
try {
|
|
588
|
+
const requestOptions = this.buildRequestOptions(expectedConnection.definition);
|
|
589
|
+
const subscription = await expectedConnection.client.listen(filter, {
|
|
590
|
+
...requestOptions,
|
|
591
|
+
timeout: Math.min(requestOptions?.timeout ?? KEEP_ALIVE_REFRESH_TIMEOUT_MS, KEEP_ALIVE_REFRESH_TIMEOUT_MS),
|
|
592
|
+
});
|
|
593
|
+
if (this.connections.get(name) !== expectedConnection || expectedConnection.status !== "connected") {
|
|
594
|
+
await subscription.close().catch(() => { });
|
|
595
|
+
return;
|
|
596
|
+
}
|
|
597
|
+
expectedConnection.listenSubscription = subscription;
|
|
598
|
+
expectedConnection.listenFilter = filter;
|
|
599
|
+
delete expectedConnection.listenStopped;
|
|
600
|
+
delete expectedConnection.listenRetryAfter;
|
|
601
|
+
this.watchListenSubscription(name, expectedConnection, subscription);
|
|
602
|
+
const confirmed = recoverDroppedListen
|
|
603
|
+
? await this.reconcileCatalogAfterListen(name, expectedConnection, requestOptions)
|
|
604
|
+
: true;
|
|
605
|
+
if (!confirmed)
|
|
606
|
+
expectedConnection.listenRetryAfter = Date.now() + LISTEN_RETRY_DELAY_MS;
|
|
607
|
+
this.setListenState(name, expectedConnection, "active");
|
|
608
|
+
}
|
|
609
|
+
catch (error) {
|
|
610
|
+
if (this.connections.get(name) !== expectedConnection || expectedConnection.status !== "connected")
|
|
611
|
+
return;
|
|
612
|
+
if (expectedConnection.listenSubscription)
|
|
613
|
+
await expectedConnection.listenSubscription.close().catch(() => { });
|
|
614
|
+
expectedConnection.listenRetryAfter = Date.now() + LISTEN_RETRY_DELAY_MS;
|
|
615
|
+
this.setListenState(name, expectedConnection, "dropped");
|
|
616
|
+
logger.debug(`MCP: catalog listen repair failed for ${name}: ${error instanceof Error ? error.message : String(error)}`);
|
|
617
|
+
}
|
|
618
|
+
})().finally(() => {
|
|
619
|
+
if (expectedConnection.listenPromise === attempt)
|
|
620
|
+
delete expectedConnection.listenPromise;
|
|
621
|
+
});
|
|
622
|
+
expectedConnection.listenPromise = attempt;
|
|
623
|
+
return attempt;
|
|
624
|
+
}
|
|
625
|
+
async reconcileCatalogAfterListen(name, expectedConnection, requestOptions) {
|
|
626
|
+
const timeout = Math.min(requestOptions?.timeout ?? KEEP_ALIVE_REFRESH_TIMEOUT_MS, KEEP_ALIVE_REFRESH_TIMEOUT_MS);
|
|
627
|
+
const refreshSignal = combineAbortSignals(requestOptions?.signal, AbortSignal.timeout(timeout));
|
|
628
|
+
const refreshOptions = {
|
|
629
|
+
...requestOptions,
|
|
630
|
+
timeout,
|
|
631
|
+
cacheMode: "refresh",
|
|
632
|
+
...(refreshSignal ? { signal: refreshSignal } : {}),
|
|
633
|
+
};
|
|
634
|
+
const [toolResult, resources, promptResult] = await Promise.allSettled([
|
|
635
|
+
this.fetchAllTools(expectedConnection.client, refreshOptions),
|
|
636
|
+
this.fetchAllResources(expectedConnection.client, refreshOptions, true),
|
|
637
|
+
this.fetchAllPrompts(expectedConnection.client, refreshOptions),
|
|
638
|
+
]);
|
|
639
|
+
if (this.connections.get(name) !== expectedConnection || expectedConnection.status !== "connected")
|
|
640
|
+
return false;
|
|
641
|
+
const nextTools = toolResult.status === "fulfilled" ? toolResult.value : undefined;
|
|
642
|
+
const nextResources = resources.status === "fulfilled" ? resources.value : undefined;
|
|
643
|
+
const nextPrompts = promptResult.status === "fulfilled" && !promptResult.value.failed ? promptResult.value : undefined;
|
|
644
|
+
const confirmed = nextTools !== undefined && nextResources !== undefined && nextPrompts !== undefined;
|
|
645
|
+
const changed = (nextTools !== undefined && (!isDeepStrictEqual(expectedConnection.tools, nextTools.tools) ||
|
|
646
|
+
!isDeepStrictEqual(expectedConnection.toolListHints, nextTools.hints))) ||
|
|
647
|
+
(nextResources !== undefined && (!isDeepStrictEqual(expectedConnection.resources, nextResources.resources) ||
|
|
648
|
+
expectedConnection.resourceDiscoveryFailed !== nextResources.failed)) ||
|
|
649
|
+
(nextPrompts !== undefined && (!isDeepStrictEqual(expectedConnection.prompts, nextPrompts.prompts) ||
|
|
650
|
+
expectedConnection.promptDiscoveryFailed !== false));
|
|
651
|
+
if (!changed) {
|
|
652
|
+
this.retryPendingMetadataPublication(name, expectedConnection);
|
|
653
|
+
if (confirmed)
|
|
654
|
+
delete expectedConnection.listenCatalogStale;
|
|
655
|
+
else
|
|
656
|
+
expectedConnection.listenCatalogStale = true;
|
|
657
|
+
return confirmed;
|
|
658
|
+
}
|
|
659
|
+
if (nextTools !== undefined) {
|
|
660
|
+
expectedConnection.tools = nextTools.tools;
|
|
661
|
+
expectedConnection.toolListHints = nextTools.hints;
|
|
662
|
+
expectedConnection.toolsRevision = (expectedConnection.toolsRevision ?? 0) + 1;
|
|
663
|
+
}
|
|
664
|
+
if (nextResources !== undefined) {
|
|
665
|
+
expectedConnection.resources = nextResources.resources;
|
|
666
|
+
expectedConnection.resourceDiscoveryFailed = nextResources.failed;
|
|
667
|
+
}
|
|
668
|
+
if (nextPrompts !== undefined) {
|
|
669
|
+
expectedConnection.prompts = nextPrompts.prompts;
|
|
670
|
+
expectedConnection.promptDiscoveryFailed = false;
|
|
671
|
+
}
|
|
672
|
+
if (confirmed)
|
|
673
|
+
delete expectedConnection.listenCatalogStale;
|
|
674
|
+
else
|
|
675
|
+
expectedConnection.listenCatalogStale = true;
|
|
676
|
+
this.metadataListChangedListener?.(name, "listen-recovered");
|
|
677
|
+
this.pendingMetadataPublications.delete(name);
|
|
678
|
+
return confirmed;
|
|
679
|
+
}
|
|
680
|
+
async prepareResourceUse(name, uri, expectedConnection) {
|
|
681
|
+
if (this.connections.get(name) !== expectedConnection || expectedConnection.status !== "connected")
|
|
682
|
+
return false;
|
|
683
|
+
const refreshRead = expectedConnection.listenState === "dropped" ||
|
|
684
|
+
expectedConnection.listenState === "re-establishing" ||
|
|
685
|
+
expectedConnection.resourceReadRefreshUris?.has(uri) === true;
|
|
686
|
+
const recent = expectedConnection.recentResourceUris ?? new Map();
|
|
687
|
+
recent.delete(uri);
|
|
688
|
+
recent.set(uri, Date.now());
|
|
689
|
+
while (recent.size > MAX_RESOURCE_SUBSCRIPTIONS) {
|
|
690
|
+
const oldest = recent.keys().next().value;
|
|
691
|
+
if (oldest === undefined)
|
|
692
|
+
break;
|
|
693
|
+
recent.delete(oldest);
|
|
694
|
+
}
|
|
695
|
+
expectedConnection.recentResourceUris = recent;
|
|
696
|
+
await this.ensureListen(name, expectedConnection);
|
|
697
|
+
expectedConnection.resourceReadRefreshUris?.delete(uri);
|
|
698
|
+
return refreshRead;
|
|
699
|
+
}
|
|
700
|
+
registerResourceUpdatedListener(token, serverName, uri, listener) {
|
|
701
|
+
this.removeResourceUpdatedListener(token);
|
|
702
|
+
this.resourceUpdatedListeners.set(token, { serverName, uri, listener });
|
|
703
|
+
const connection = this.connections.get(serverName);
|
|
704
|
+
if (!connection || connection.status !== "connected")
|
|
705
|
+
return;
|
|
706
|
+
void this.prepareResourceUse(serverName, uri, connection);
|
|
707
|
+
}
|
|
708
|
+
removeResourceUpdatedListener(token) {
|
|
709
|
+
this.resourceUpdatedListeners.delete(token);
|
|
710
|
+
}
|
|
711
|
+
async doReconnect(name, definition, staleConnection, signal, oauthAuthority, attemptOwner) {
|
|
712
|
+
throwIfAborted(signal);
|
|
713
|
+
const current = this.connections.get(name);
|
|
714
|
+
// Never tear down a connection we didn't prove stale: if the map no
|
|
715
|
+
// longer holds the connection we were asked to replace, someone else
|
|
716
|
+
// already reconnected (or connected) first.
|
|
717
|
+
if (current !== staleConnection) {
|
|
718
|
+
return current ?? this.connect(name, definition, signal);
|
|
719
|
+
}
|
|
720
|
+
// Build the replacement privately. The current route remains usable until
|
|
721
|
+
// the candidate has completed its handshake and metadata discovery. A
|
|
722
|
+
// failed candidate therefore cannot remove or close the last good route.
|
|
723
|
+
const generation = this.closeGenerations.get(name) ?? 0;
|
|
724
|
+
const credentialsInvalidated = staleConnection.status === "needs-auth"
|
|
725
|
+
&& staleConnection.credentialsInvalidated === true;
|
|
726
|
+
const candidateAttempt = this.createConnection(name, definition, signal, signal, credentialsInvalidated, oauthAuthority, attemptOwner);
|
|
727
|
+
const fresh = definition.url
|
|
728
|
+
? await candidateAttempt.catch(async (error) => { throw await this.enrichHttpConnectionError(definition, error); })
|
|
729
|
+
: await candidateAttempt;
|
|
730
|
+
// An explicit close or a concurrent replacement supersedes this candidate.
|
|
731
|
+
// Dispose only the candidate we own; never close whichever route is now
|
|
732
|
+
// registered under the shared server name.
|
|
733
|
+
if (signal?.aborted
|
|
734
|
+
|| this.reconnectAttempts.get(name) !== attemptOwner
|
|
735
|
+
|| (this.closeGenerations.get(name) ?? 0) !== generation) {
|
|
736
|
+
await this.disposeConnection(fresh);
|
|
737
|
+
throwIfAborted(signal);
|
|
738
|
+
throw new Error(`MCP connection for ${name} was closed while reconnecting`);
|
|
739
|
+
}
|
|
740
|
+
const routeAtPublish = this.connections.get(name);
|
|
741
|
+
if (routeAtPublish !== staleConnection) {
|
|
742
|
+
await this.disposeConnection(fresh);
|
|
743
|
+
return routeAtPublish ?? this.connect(name, definition, signal);
|
|
744
|
+
}
|
|
745
|
+
fresh.inFlight = Math.max(fresh.inFlight, staleConnection.inFlight);
|
|
746
|
+
this.connections.set(name, fresh);
|
|
747
|
+
this.watchListenSubscription(name, fresh, fresh.listenSubscription);
|
|
748
|
+
if ([...this.resourceUpdatedListeners.values()].some(registration => registration.serverName === name)) {
|
|
749
|
+
void this.ensureListen(name, fresh);
|
|
750
|
+
}
|
|
751
|
+
// Publish first so calls route to the fresh image while the exact displaced
|
|
752
|
+
// child is terminated and reaped. Late close callbacks are identity-guarded.
|
|
753
|
+
staleConnection.status = "closed";
|
|
754
|
+
try {
|
|
755
|
+
await this.disposeConnection(staleConnection);
|
|
756
|
+
}
|
|
757
|
+
catch (error) {
|
|
758
|
+
const failures = error instanceof AggregateError ? error.errors : [error];
|
|
759
|
+
const details = failures
|
|
760
|
+
.map(failure => failure instanceof Error ? failure.message : String(failure))
|
|
761
|
+
.join("; ");
|
|
762
|
+
logger.debug(`MCP: stale connection cleanup failed for ${name}: ${details}`);
|
|
763
|
+
}
|
|
764
|
+
// Publication is not permission to return a route that close() disposed
|
|
765
|
+
// while stale cleanup was pending.
|
|
766
|
+
if ((this.closeGenerations.get(name) ?? 0) !== generation
|
|
767
|
+
|| this.connections.get(name) !== fresh
|
|
768
|
+
|| fresh.status === "closed") {
|
|
769
|
+
throw new Error(`MCP connection for ${name} was closed while reconnecting`);
|
|
770
|
+
}
|
|
771
|
+
return fresh;
|
|
772
|
+
}
|
|
773
|
+
async createConnection(name, definition, signal, requestSignal, credentialsInvalidated = false, oauthAuthority, attemptOwner) {
|
|
774
|
+
throwIfAborted(signal);
|
|
775
|
+
const tracingEnabled = isMcpTraceEnabled(definition, this.traceSettings);
|
|
776
|
+
const traceWriter = tracingEnabled
|
|
777
|
+
? (this.traceWriter ??= createMcpTraceWriter(this.defaultCwd, this.traceSettings ?? {}))
|
|
778
|
+
: undefined;
|
|
779
|
+
const traceObserver = traceWriter
|
|
780
|
+
? { record: event => traceWriter.write(event) }
|
|
781
|
+
: undefined;
|
|
782
|
+
let client;
|
|
783
|
+
let transport;
|
|
784
|
+
let clientConnected = false;
|
|
785
|
+
let invalidated = credentialsInvalidated;
|
|
786
|
+
let transportAlreadyTraced = false;
|
|
787
|
+
let stderrTail = Buffer.alloc(0);
|
|
788
|
+
const configuredTransports = [definition.command, definition.url, definition.socket]
|
|
789
|
+
.filter(value => typeof value === "string" && value.length > 0);
|
|
790
|
+
if (configuredTransports.length !== 1) {
|
|
791
|
+
throw new Error(`Server ${name} must configure exactly one of command, url, or socket`);
|
|
792
|
+
}
|
|
793
|
+
const requestOptions = this.buildRequestOptions(definition, requestSignal);
|
|
794
|
+
if (definition.command) {
|
|
795
|
+
client = this.createClient(name, definition);
|
|
796
|
+
let command = definition.command;
|
|
797
|
+
const literalArgs = isBuiltInAgentPlugin(definition, "args");
|
|
798
|
+
const literalCwd = isBuiltInAgentPlugin(definition, "cwd");
|
|
799
|
+
let args = literalArgs ? [...(definition.args ?? [])] : (definition.args ?? []).map((argument) => interpolateEnvVars(argument));
|
|
800
|
+
const cwd = (literalCwd ? definition.cwd : resolveConfigPath(definition.cwd)) ?? this.defaultCwd;
|
|
801
|
+
if (definition.pluginDataDir)
|
|
802
|
+
mkdirSync(definition.pluginDataDir, { recursive: true });
|
|
803
|
+
if (cwd !== undefined) {
|
|
804
|
+
const cwdStats = statSync(cwd, { throwIfNoEntry: false });
|
|
805
|
+
if (!cwdStats)
|
|
806
|
+
throw new Error(`MCP server "${name}" configured cwd does not exist: "${cwd}"`);
|
|
807
|
+
if (!cwdStats.isDirectory())
|
|
808
|
+
throw new Error(`MCP server "${name}" configured cwd is not a directory: "${cwd}"`);
|
|
809
|
+
}
|
|
810
|
+
if (command === "npx" || command === "npm") {
|
|
811
|
+
const resolved = await resolveNpxBinary(command, args, signal);
|
|
812
|
+
if (resolved) {
|
|
813
|
+
command = resolved.isJs ? "node" : resolved.binPath;
|
|
814
|
+
args = resolved.isJs ? [resolved.binPath, ...resolved.extraArgs] : resolved.extraArgs;
|
|
815
|
+
logger.debug(`${name} resolved to ${resolved.binPath} (skipping npm parent)`);
|
|
816
|
+
}
|
|
817
|
+
}
|
|
818
|
+
throwIfAborted(signal);
|
|
819
|
+
const stdioTransport = new StdioClientTransport({
|
|
820
|
+
command,
|
|
821
|
+
args,
|
|
822
|
+
env: resolveEnv(definition.env, name, isBuiltInAgentPlugin(definition, "env") || definition.literalEnv === true, definition.inheritEnv !== false),
|
|
823
|
+
...(cwd !== undefined ? { cwd } : {}),
|
|
824
|
+
stderr: definition.debug ? "inherit" : "pipe",
|
|
825
|
+
});
|
|
826
|
+
// Keep non-debug child diagnostics available for connection failures without
|
|
827
|
+
// retaining an unbounded stream or changing the existing debug behavior.
|
|
828
|
+
if (stdioTransport.stderr) {
|
|
829
|
+
stdioTransport.stderr.on("data", (chunk) => {
|
|
830
|
+
stderrTail = appendStderrTail(stderrTail, chunk);
|
|
831
|
+
});
|
|
832
|
+
}
|
|
833
|
+
transport = stdioTransport;
|
|
834
|
+
}
|
|
835
|
+
else if (definition.url) {
|
|
836
|
+
const httpConnection = await this.connectHttpClient(definition, name, requestOptions, signal, traceObserver, invalidated, oauthAuthority, attemptOwner);
|
|
837
|
+
client = httpConnection.client;
|
|
838
|
+
transport = httpConnection.transport;
|
|
839
|
+
invalidated = httpConnection.credentialsInvalidated;
|
|
840
|
+
if (httpConnection.status === "needs-auth") {
|
|
841
|
+
return {
|
|
842
|
+
client,
|
|
843
|
+
transport,
|
|
844
|
+
definition,
|
|
845
|
+
tools: [],
|
|
846
|
+
resources: [],
|
|
847
|
+
prompts: [],
|
|
848
|
+
lastUsedAt: Date.now(),
|
|
849
|
+
inFlight: 0,
|
|
850
|
+
status: "needs-auth",
|
|
851
|
+
listenState: "disconnected",
|
|
852
|
+
credentialsInvalidated: invalidated,
|
|
853
|
+
};
|
|
854
|
+
}
|
|
855
|
+
clientConnected = true;
|
|
856
|
+
transportAlreadyTraced = traceObserver !== undefined;
|
|
857
|
+
}
|
|
858
|
+
else {
|
|
859
|
+
client = this.createClient(name, definition);
|
|
860
|
+
transport = new UnixSocketClientTransport(resolveConfigPath(definition.socket));
|
|
861
|
+
}
|
|
862
|
+
if (traceObserver && !transportAlreadyTraced) {
|
|
863
|
+
const traceTransportKindValue = traceTransportKind(definition, transport);
|
|
864
|
+
transport = wrapTransportWithMcpTrace(transport, name, traceTransportKindValue, traceObserver);
|
|
865
|
+
}
|
|
866
|
+
try {
|
|
867
|
+
throwIfAborted(signal);
|
|
868
|
+
if (!clientConnected) {
|
|
869
|
+
await this.connectClientWithAbort(client, transport, requestOptions, signal);
|
|
870
|
+
}
|
|
871
|
+
this.attachAdapterNotificationHandlers(name, client);
|
|
872
|
+
const instructions = client.getInstructions?.();
|
|
873
|
+
const protocolEra = client.getProtocolEra?.();
|
|
874
|
+
const autoOpenedSubscription = client.autoOpenedSubscription;
|
|
875
|
+
const connection = {
|
|
876
|
+
client,
|
|
877
|
+
transport,
|
|
878
|
+
definition,
|
|
879
|
+
tools: [],
|
|
880
|
+
toolsRevision: 0,
|
|
881
|
+
resources: [],
|
|
882
|
+
prompts: [],
|
|
883
|
+
...(instructions !== undefined ? { instructions } : {}),
|
|
884
|
+
lastUsedAt: Date.now(),
|
|
885
|
+
inFlight: 0,
|
|
886
|
+
status: "connected",
|
|
887
|
+
listenState: protocolEra === "modern"
|
|
888
|
+
? autoOpenedSubscription
|
|
889
|
+
? "active"
|
|
890
|
+
: "not-listening"
|
|
891
|
+
: "legacy",
|
|
892
|
+
...(autoOpenedSubscription ? {
|
|
893
|
+
listenSubscription: autoOpenedSubscription,
|
|
894
|
+
} : {}),
|
|
895
|
+
};
|
|
896
|
+
if (autoOpenedSubscription)
|
|
897
|
+
connection.listenFilter = this.catalogListenFilter(connection);
|
|
898
|
+
// Reflect the SDK's own close signal in connection status, guarded by
|
|
899
|
+
// identity so a stale connection's late close can never clobber a fresh
|
|
900
|
+
// connection. The SDK client owns the transport callbacks.
|
|
901
|
+
client.onclose = () => {
|
|
902
|
+
if (connection.status === "closed")
|
|
903
|
+
return;
|
|
904
|
+
connection.status = "closed";
|
|
905
|
+
if (this.connections.get(name) !== connection)
|
|
906
|
+
return;
|
|
907
|
+
this.metadataListChangedListener?.(name, "remote-close");
|
|
908
|
+
};
|
|
909
|
+
// Discover tools, resources, and prompts. Resource and prompt listing is
|
|
910
|
+
// optional: only servers advertising the capability are queried.
|
|
911
|
+
const [toolResult, resources, promptResult] = await Promise.all([
|
|
912
|
+
this.fetchAllTools(client, requestOptions),
|
|
913
|
+
this.fetchAllResources(client, requestOptions),
|
|
914
|
+
this.fetchAllPrompts(client, requestOptions),
|
|
915
|
+
]);
|
|
916
|
+
if (connection.status !== "connected") {
|
|
917
|
+
throw new Error(`MCP connection for ${name} closed during metadata discovery`);
|
|
918
|
+
}
|
|
919
|
+
connection.tools = toolResult.tools;
|
|
920
|
+
connection.toolListHints = toolResult.hints;
|
|
921
|
+
connection.resources = resources.resources;
|
|
922
|
+
connection.resourceDiscoveryFailed = resources.failed;
|
|
923
|
+
connection.prompts = promptResult.prompts;
|
|
924
|
+
connection.promptDiscoveryFailed = promptResult.failed;
|
|
925
|
+
if (definition.tasks !== false) {
|
|
926
|
+
try {
|
|
927
|
+
const attachment = await attachTaskSession({
|
|
928
|
+
client,
|
|
929
|
+
serverName: name,
|
|
930
|
+
definition,
|
|
931
|
+
transport,
|
|
932
|
+
requestTimeoutMs: this.getResolvedRequestTimeoutMs(definition),
|
|
933
|
+
clientInfo: { name: `pi-mcp-${name}`, version: "1.0.0" },
|
|
934
|
+
clientCapabilities: this.buildClientCapabilities(),
|
|
935
|
+
...(this.elicitationConfig
|
|
936
|
+
? {
|
|
937
|
+
onElicitation: (request, signal) => handleElicitationRequest({
|
|
938
|
+
...this.elicitationConfig,
|
|
939
|
+
serverName: name,
|
|
940
|
+
onUrlAccepted: elicitationId => this.rememberUrlElicitation(name, elicitationId),
|
|
941
|
+
}, request, signal),
|
|
942
|
+
}
|
|
943
|
+
: {}),
|
|
944
|
+
...(this.samplingConfig
|
|
945
|
+
? {
|
|
946
|
+
onSampling: (request, signal) => handleSamplingRequest({
|
|
947
|
+
...this.samplingConfig,
|
|
948
|
+
serverName: name,
|
|
949
|
+
// Cancelling the task should also stop the local sampling run.
|
|
950
|
+
getSignal: () => combineAbortSignals(this.samplingConfig.getSignal(), signal),
|
|
951
|
+
}, request),
|
|
952
|
+
}
|
|
953
|
+
: {}),
|
|
954
|
+
});
|
|
955
|
+
if (attachment && connection.status === "connected") {
|
|
956
|
+
connection.taskSession = attachment.session;
|
|
957
|
+
connection.taskChannel = attachment.channel;
|
|
958
|
+
}
|
|
959
|
+
else if (attachment) {
|
|
960
|
+
attachment.channel.rejectAll("MCP connection closed");
|
|
961
|
+
await attachment.session.close().catch(() => { });
|
|
962
|
+
}
|
|
963
|
+
}
|
|
964
|
+
catch (error) {
|
|
965
|
+
logger.debug(`Task session attach failed for ${name}: ${String(error)}`);
|
|
966
|
+
}
|
|
967
|
+
}
|
|
968
|
+
return connection;
|
|
969
|
+
}
|
|
970
|
+
catch (error) {
|
|
971
|
+
// If connectClientWithAbort closed the transport, await that exact close.
|
|
972
|
+
// Otherwise the SDK client owns its transport and performs cleanup once.
|
|
973
|
+
const abortCleanup = abortCleanupPromises.get(transport);
|
|
974
|
+
const abortCleanupFailed = error instanceof AggregateError && error.message === "MCP connection abort cleanup failed";
|
|
975
|
+
const cleanupResults = abortCleanupFailed
|
|
976
|
+
? []
|
|
977
|
+
: await Promise.allSettled([
|
|
978
|
+
abortCleanup ?? Promise.resolve().then(() => client.close()),
|
|
979
|
+
]);
|
|
980
|
+
const cleanupFailures = cleanupResults.flatMap(result => result.status === "rejected" ? [result.reason] : []);
|
|
981
|
+
let reportedError = error;
|
|
982
|
+
if (cleanupFailures.length > 0) {
|
|
983
|
+
reportedError = new AggregateError([error, ...cleanupFailures], "MCP connection setup failed");
|
|
984
|
+
}
|
|
985
|
+
// A cleanup failure remains a setup failure rather than being hidden
|
|
986
|
+
// behind needs-auth.
|
|
987
|
+
if (isUnauthorizedHttpError(error) && supportsOAuth(definition) && cleanupFailures.length === 0) {
|
|
988
|
+
if (!invalidated) {
|
|
989
|
+
invalidateAuthEntryCache(name);
|
|
990
|
+
invalidated = true;
|
|
991
|
+
}
|
|
992
|
+
return {
|
|
993
|
+
client,
|
|
994
|
+
transport,
|
|
995
|
+
definition,
|
|
996
|
+
tools: [],
|
|
997
|
+
resources: [],
|
|
998
|
+
prompts: [],
|
|
999
|
+
lastUsedAt: Date.now(),
|
|
1000
|
+
inFlight: 0,
|
|
1001
|
+
status: "needs-auth",
|
|
1002
|
+
listenState: "disconnected",
|
|
1003
|
+
credentialsInvalidated: invalidated,
|
|
1004
|
+
};
|
|
1005
|
+
}
|
|
1006
|
+
if (stderrTail.length > 0) {
|
|
1007
|
+
const stderrText = stderrTail.toString("utf8").trim();
|
|
1008
|
+
const lines = stderrText.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
|
|
1009
|
+
if (lines.length > 0) {
|
|
1010
|
+
const baseMessage = reportedError instanceof Error ? reportedError.message : String(reportedError);
|
|
1011
|
+
const detail = lines.slice(-MAX_CAPTURED_STDERR_LINES).join(" — ");
|
|
1012
|
+
throw new Error(`${baseMessage} (${detail})`, { cause: reportedError });
|
|
1013
|
+
}
|
|
1014
|
+
}
|
|
1015
|
+
throw reportedError;
|
|
1016
|
+
}
|
|
1017
|
+
}
|
|
1018
|
+
async enrichHttpConnectionError(definition, error) {
|
|
1019
|
+
const originalMessage = error instanceof Error ? error.message : String(error);
|
|
1020
|
+
if (process.platform === "darwin") {
|
|
1021
|
+
const codes = localNetworkFailureCodes(error);
|
|
1022
|
+
if (codes.length > 0 && isLiteralLocalAddress(resolveServerUrl(definition))) {
|
|
1023
|
+
return new Error(`${originalMessage} — ${codes.join(", ")} — macOS Local Network Privacy may be blocking access. Check System Settings > Privacy & Security > Local Network for the app hosting Pi; enable access if listed and restart it. Try launching Pi from Terminal.app or SSH. Routing or firewall problems can also cause this error.`, { cause: error });
|
|
1024
|
+
}
|
|
1025
|
+
}
|
|
1026
|
+
if (isTransientHttpConnectError(error)) {
|
|
1027
|
+
return new Error(`${originalMessage} — endpoint is temporarily unavailable (HTTP 503)`, { cause: error });
|
|
1028
|
+
}
|
|
1029
|
+
try {
|
|
1030
|
+
const probe = await probeMcpEndpoint(resolveServerUrl(definition));
|
|
1031
|
+
return new Error(`${originalMessage} — probe: ${probe.classification}`, { cause: error });
|
|
1032
|
+
}
|
|
1033
|
+
catch {
|
|
1034
|
+
return error instanceof Error ? error : new Error(originalMessage);
|
|
1035
|
+
}
|
|
1036
|
+
}
|
|
1037
|
+
async connectClientWithAbort(client, transport, requestOptions, signal) {
|
|
1038
|
+
throwIfAborted(signal);
|
|
1039
|
+
let abortCleanup;
|
|
1040
|
+
const closeTransport = () => {
|
|
1041
|
+
abortCleanup = Promise.resolve().then(() => transport.close());
|
|
1042
|
+
abortCleanupPromises.set(transport, abortCleanup);
|
|
1043
|
+
};
|
|
1044
|
+
signal?.addEventListener("abort", closeTransport, { once: true });
|
|
1045
|
+
try {
|
|
1046
|
+
await abortable(client.connect(transport, requestOptions), signal);
|
|
1047
|
+
await abortCleanup;
|
|
1048
|
+
}
|
|
1049
|
+
catch (error) {
|
|
1050
|
+
if (abortCleanup) {
|
|
1051
|
+
try {
|
|
1052
|
+
await abortCleanup;
|
|
1053
|
+
}
|
|
1054
|
+
catch (cleanupError) {
|
|
1055
|
+
throw new AggregateError([error, cleanupError], "MCP connection abort cleanup failed");
|
|
1056
|
+
}
|
|
1057
|
+
}
|
|
1058
|
+
throw error;
|
|
1059
|
+
}
|
|
1060
|
+
finally {
|
|
1061
|
+
signal?.removeEventListener("abort", closeTransport);
|
|
1062
|
+
}
|
|
1063
|
+
}
|
|
1064
|
+
buildClientCapabilities() {
|
|
1065
|
+
return {
|
|
1066
|
+
extensions: {
|
|
1067
|
+
"io.modelcontextprotocol/ui": {
|
|
1068
|
+
mimeTypes: [RESOURCE_MIME_TYPE],
|
|
1069
|
+
},
|
|
1070
|
+
},
|
|
1071
|
+
...(this.samplingConfig ? { sampling: {} } : {}),
|
|
1072
|
+
...(this.elicitationConfig
|
|
1073
|
+
? {
|
|
1074
|
+
elicitation: {
|
|
1075
|
+
form: {},
|
|
1076
|
+
...(this.elicitationConfig.allowUrl ? { url: {} } : {}),
|
|
1077
|
+
},
|
|
1078
|
+
}
|
|
1079
|
+
: {}),
|
|
1080
|
+
};
|
|
1081
|
+
}
|
|
1082
|
+
createClient(serverName, definition) {
|
|
1083
|
+
const capabilities = this.buildClientCapabilities();
|
|
1084
|
+
const versionNegotiation = resolveVersionNegotiation(definition);
|
|
1085
|
+
let client;
|
|
1086
|
+
client = new Client({ name: `pi-mcp-${serverName}`, version: "1.0.0" }, {
|
|
1087
|
+
jsonSchemaValidator: createJsonSchemaValidator(),
|
|
1088
|
+
...(versionNegotiation ? { versionNegotiation } : {}),
|
|
1089
|
+
...(Object.keys(capabilities).length > 0 ? { capabilities } : {}),
|
|
1090
|
+
listChanged: {
|
|
1091
|
+
tools: {
|
|
1092
|
+
onChanged: (error, tools) => {
|
|
1093
|
+
this.handleToolsListChanged(serverName, client, error, tools);
|
|
1094
|
+
},
|
|
1095
|
+
},
|
|
1096
|
+
resources: {
|
|
1097
|
+
onChanged: (error, resources) => {
|
|
1098
|
+
this.handleResourcesListChanged(serverName, client, error, resources);
|
|
1099
|
+
},
|
|
1100
|
+
},
|
|
1101
|
+
prompts: {
|
|
1102
|
+
onChanged: (error, prompts) => {
|
|
1103
|
+
this.handlePromptsListChanged(serverName, client, error, prompts);
|
|
1104
|
+
},
|
|
1105
|
+
},
|
|
1106
|
+
},
|
|
1107
|
+
});
|
|
1108
|
+
if (this.samplingConfig) {
|
|
1109
|
+
registerSamplingHandler(client, { ...this.samplingConfig, serverName });
|
|
1110
|
+
}
|
|
1111
|
+
if (this.elicitationConfig) {
|
|
1112
|
+
registerElicitationHandler(client, {
|
|
1113
|
+
...this.elicitationConfig,
|
|
1114
|
+
serverName,
|
|
1115
|
+
onUrlAccepted: elicitationId => this.rememberUrlElicitation(serverName, elicitationId),
|
|
1116
|
+
});
|
|
1117
|
+
if (this.elicitationConfig.allowUrl) {
|
|
1118
|
+
client.setNotificationHandler("notifications/elicitation/complete", notification => {
|
|
1119
|
+
if (this.runtimeSignal?.aborted)
|
|
1120
|
+
return;
|
|
1121
|
+
const accepted = this.acceptedUrlElicitations.get(serverName);
|
|
1122
|
+
if (!accepted?.delete(notification.params.elicitationId))
|
|
1123
|
+
return;
|
|
1124
|
+
this.elicitationConfig?.ui.notify(`MCP browser interaction for ${serverName} completed. You can retry the tool now.`, "info");
|
|
1125
|
+
});
|
|
1126
|
+
}
|
|
1127
|
+
}
|
|
1128
|
+
return client;
|
|
1129
|
+
}
|
|
1130
|
+
handleToolsListChanged(serverName, client, error, tools) {
|
|
1131
|
+
if (error) {
|
|
1132
|
+
logger.debug(`MCP: tools/list_changed refresh failed for ${serverName}: ${error.message}`);
|
|
1133
|
+
return;
|
|
1134
|
+
}
|
|
1135
|
+
if (!tools)
|
|
1136
|
+
return;
|
|
1137
|
+
const connection = this.connections.get(serverName);
|
|
1138
|
+
if (!connection || connection.client !== client || connection.status !== "connected")
|
|
1139
|
+
return;
|
|
1140
|
+
connection.tools = tools;
|
|
1141
|
+
connection.toolsRevision = (connection.toolsRevision ?? 0) + 1;
|
|
1142
|
+
this.metadataListChangedListener?.(serverName, "tools-list-changed");
|
|
1143
|
+
this.pendingMetadataPublications.delete(serverName);
|
|
1144
|
+
}
|
|
1145
|
+
handlePromptsListChanged(serverName, client, error, prompts) {
|
|
1146
|
+
if (error) {
|
|
1147
|
+
logger.debug(`MCP: prompts/list_changed refresh failed for ${serverName}: ${error.message}`);
|
|
1148
|
+
return;
|
|
1149
|
+
}
|
|
1150
|
+
if (!prompts)
|
|
1151
|
+
return;
|
|
1152
|
+
const connection = this.connections.get(serverName);
|
|
1153
|
+
if (!connection || connection.client !== client || connection.status !== "connected")
|
|
1154
|
+
return;
|
|
1155
|
+
connection.prompts = prompts;
|
|
1156
|
+
connection.promptDiscoveryFailed = false;
|
|
1157
|
+
this.metadataListChangedListener?.(serverName, "prompts-list-changed");
|
|
1158
|
+
this.pendingMetadataPublications.delete(serverName);
|
|
1159
|
+
}
|
|
1160
|
+
handleResourcesListChanged(serverName, client, error, resources) {
|
|
1161
|
+
if (error) {
|
|
1162
|
+
logger.debug(`MCP: resources/list_changed refresh failed for ${serverName}: ${error.message}`);
|
|
1163
|
+
return;
|
|
1164
|
+
}
|
|
1165
|
+
if (!resources)
|
|
1166
|
+
return;
|
|
1167
|
+
const connection = this.connections.get(serverName);
|
|
1168
|
+
if (!connection || connection.client !== client || connection.status !== "connected")
|
|
1169
|
+
return;
|
|
1170
|
+
connection.resources = resources;
|
|
1171
|
+
connection.resourceDiscoveryFailed = false;
|
|
1172
|
+
this.metadataListChangedListener?.(serverName, "resources-list-changed");
|
|
1173
|
+
this.pendingMetadataPublications.delete(serverName);
|
|
1174
|
+
}
|
|
1175
|
+
async handleUrlElicitationRequired(serverName, error) {
|
|
1176
|
+
if (this.runtimeSignal?.aborted || !this.elicitationConfig?.allowUrl)
|
|
1177
|
+
return "cancel";
|
|
1178
|
+
for (const params of error.elicitations) {
|
|
1179
|
+
const result = await handleUrlElicitation({
|
|
1180
|
+
...this.elicitationConfig,
|
|
1181
|
+
serverName,
|
|
1182
|
+
onUrlAccepted: elicitationId => this.rememberUrlElicitation(serverName, elicitationId),
|
|
1183
|
+
}, params);
|
|
1184
|
+
if (result.action !== "accept")
|
|
1185
|
+
return result.action;
|
|
1186
|
+
}
|
|
1187
|
+
return "accept";
|
|
1188
|
+
}
|
|
1189
|
+
rememberUrlElicitation(serverName, elicitationId) {
|
|
1190
|
+
if (this.runtimeSignal?.aborted)
|
|
1191
|
+
return;
|
|
1192
|
+
let accepted = this.acceptedUrlElicitations.get(serverName);
|
|
1193
|
+
if (!accepted) {
|
|
1194
|
+
accepted = new Set();
|
|
1195
|
+
this.acceptedUrlElicitations.set(serverName, accepted);
|
|
1196
|
+
}
|
|
1197
|
+
accepted.add(elicitationId);
|
|
1198
|
+
}
|
|
1199
|
+
async connectHttpClient(definition, serverName, requestOptions, signal, traceObserver, credentialsInvalidated = false, oauthAuthority, attemptOwner) {
|
|
1200
|
+
throwIfAborted(signal);
|
|
1201
|
+
const serverUrl = resolveServerUrl(definition);
|
|
1202
|
+
const url = new URL(serverUrl);
|
|
1203
|
+
// Resolve secret commands only for this connection attempt, without
|
|
1204
|
+
// mutating the persisted configuration.
|
|
1205
|
+
const literalHeaders = isBuiltInAgentPlugin(definition, "headers");
|
|
1206
|
+
const hasCommandHeader = !literalHeaders && Object.values(definition.headers ?? {})
|
|
1207
|
+
.some(value => value.startsWith("!") && !value.startsWith("!!"));
|
|
1208
|
+
const oauthEnabled = supportsOAuth(definition);
|
|
1209
|
+
let headers;
|
|
1210
|
+
if (literalHeaders) {
|
|
1211
|
+
headers = { ...definition.headers };
|
|
1212
|
+
}
|
|
1213
|
+
else if (oauthEnabled) {
|
|
1214
|
+
headers = Object.fromEntries(resolveOAuthHeaders(definition.headers));
|
|
1215
|
+
}
|
|
1216
|
+
else {
|
|
1217
|
+
headers = resolveCommandSecretsRecord(definition.headers, key => `MCP server "${serverName}" HTTP header "${key}"`) ?? {};
|
|
1218
|
+
}
|
|
1219
|
+
// Resolve bearer auth before creating requestInit so every attempted
|
|
1220
|
+
// transport receives the same headers.
|
|
1221
|
+
const commandBearer = definition.bearerToken?.startsWith("!") && !definition.bearerToken.startsWith("!!")
|
|
1222
|
+
? definition.bearerToken
|
|
1223
|
+
: undefined;
|
|
1224
|
+
// Command-backed bearers resolve eagerly, then refresh through a TTL cache.
|
|
1225
|
+
let bearerCommandResolver;
|
|
1226
|
+
if (definition.auth === "bearer") {
|
|
1227
|
+
if (commandBearer) {
|
|
1228
|
+
bearerCommandResolver = new BearerCommandResolver(commandBearer, `MCP server "${serverName}" HTTP bearer token`);
|
|
1229
|
+
// Eager resolve so a broken command surfaces at connect time, not at
|
|
1230
|
+
// the first tool call.
|
|
1231
|
+
await bearerCommandResolver.resolve(signal);
|
|
1232
|
+
}
|
|
1233
|
+
else {
|
|
1234
|
+
const token = resolveBearerToken(definition)
|
|
1235
|
+
?? (definition.bearerToken === undefined && definition.bearerTokenEnv === undefined && definition.bearerTokenStore === true
|
|
1236
|
+
? getBearerTokenForUrl(serverName, serverUrl)
|
|
1237
|
+
: undefined);
|
|
1238
|
+
if (token)
|
|
1239
|
+
headers["Authorization"] = `Bearer ${token}`;
|
|
1240
|
+
}
|
|
1241
|
+
}
|
|
1242
|
+
if (hasCommandHeader || commandBearer) {
|
|
1243
|
+
try {
|
|
1244
|
+
new Headers(headers);
|
|
1245
|
+
}
|
|
1246
|
+
catch {
|
|
1247
|
+
throw new Error(`Failed to resolve MCP server "${serverName}" HTTP command secret: command returned an invalid header value`);
|
|
1248
|
+
}
|
|
1249
|
+
}
|
|
1250
|
+
// Do not give origin-bound headers to SDK requestInit: it reuses those
|
|
1251
|
+
// defaults for discovered OAuth endpoints, including other origins.
|
|
1252
|
+
const requestInit = !oauthEnabled && Object.keys(headers).length > 0 ? { headers } : undefined;
|
|
1253
|
+
const serviceHeaders = oauthEnabled ? new Headers(headers) : new Headers();
|
|
1254
|
+
let caFetch = createCaFetch(definition);
|
|
1255
|
+
try {
|
|
1256
|
+
const createAuthProvider = () => {
|
|
1257
|
+
const currentConnectAttempt = this.connectAttempts.get(serverName);
|
|
1258
|
+
const currentReconnectAttempt = this.reconnectAttempts.get(serverName);
|
|
1259
|
+
if ((currentConnectAttempt && currentConnectAttempt !== attemptOwner)
|
|
1260
|
+
|| (currentReconnectAttempt && currentReconnectAttempt !== attemptOwner)) {
|
|
1261
|
+
throw new Error(`MCP connection for ${serverName} was replaced while connecting`);
|
|
1262
|
+
}
|
|
1263
|
+
if (!oauthAuthority)
|
|
1264
|
+
throw new Error(`Missing OAuth authority for ${serverName}`);
|
|
1265
|
+
const provider = new McpOAuthProvider(serverName, serverUrl, extractOAuthConfig(definition), { onRedirect: async () => { } }, this.authStorageOptions, this.oauthRuntime?.signal, undefined, oauthAuthority);
|
|
1266
|
+
provider.setAuthFetch(createOAuthFetch(serverUrl, () => serviceHeaders, combineAbortSignals(this.oauthRuntime?.signal, signal), {
|
|
1267
|
+
...(caFetch ? { delegate: caFetch.fetch } : {}),
|
|
1268
|
+
}));
|
|
1269
|
+
return provider;
|
|
1270
|
+
};
|
|
1271
|
+
// Explicit OAuth checks secure storage immediately. Implicit OAuth keeps
|
|
1272
|
+
// anonymous servers provider-free unless URL-bound credentials are already
|
|
1273
|
+
// stored, so an unavailable credential store does not break anonymous use.
|
|
1274
|
+
let implicitStoredAuth;
|
|
1275
|
+
if (definition.auth === undefined && supportsOAuth(definition)) {
|
|
1276
|
+
try {
|
|
1277
|
+
implicitStoredAuth = inspectAuthForUrl(serverName, serverUrl, this.authStorageOptions);
|
|
1278
|
+
}
|
|
1279
|
+
catch {
|
|
1280
|
+
// Implicit preflight is opportunistic; malformed records must not block
|
|
1281
|
+
// an otherwise anonymous-capable server from connecting.
|
|
1282
|
+
}
|
|
1283
|
+
}
|
|
1284
|
+
const hasImplicitStoredTokens = implicitStoredAuth?.status === "present"
|
|
1285
|
+
&& implicitStoredAuth.entry.tokens !== undefined;
|
|
1286
|
+
if (hasImplicitStoredTokens)
|
|
1287
|
+
invalidateAuthEntryCache(serverName);
|
|
1288
|
+
let authState = supportsOAuth(definition)
|
|
1289
|
+
? definition.auth === undefined
|
|
1290
|
+
? hasImplicitStoredTokens
|
|
1291
|
+
? { status: "implicit-stored", provider: createAuthProvider() }
|
|
1292
|
+
: { status: "implicit-deferred" }
|
|
1293
|
+
: { status: "explicit", provider: createAuthProvider() }
|
|
1294
|
+
: { status: "disabled" };
|
|
1295
|
+
const commandFetch = definition.requestHeadersCommand
|
|
1296
|
+
? createRequestHeadersCommandFetch(definition.requestHeadersCommand, caFetch?.fetch)
|
|
1297
|
+
: caFetch?.fetch;
|
|
1298
|
+
// requestHeadersCommand stays last in the header chain.
|
|
1299
|
+
const bearerFetch = bearerCommandResolver
|
|
1300
|
+
? createBearerCommandFetch(bearerCommandResolver, commandFetch)
|
|
1301
|
+
: commandFetch;
|
|
1302
|
+
const requestFetch = oauthEnabled
|
|
1303
|
+
? createOAuthFetch(serverUrl, () => serviceHeaders, this.oauthRuntime?.signal, {
|
|
1304
|
+
// MCP streams outlive individual auth requests; retain SDK request deadlines.
|
|
1305
|
+
timeout: false,
|
|
1306
|
+
...(bearerFetch ? { delegate: bearerFetch } : {}),
|
|
1307
|
+
})
|
|
1308
|
+
: bearerFetch;
|
|
1309
|
+
const attempt = async (kind) => {
|
|
1310
|
+
const authProvider = "provider" in authState ? authState.provider : undefined;
|
|
1311
|
+
let sseFetchFailure;
|
|
1312
|
+
const transportFetch = kind === "sse" && process.platform === "darwin" && isLiteralLocalAddress(serverUrl)
|
|
1313
|
+
? async (input, init) => {
|
|
1314
|
+
try {
|
|
1315
|
+
return await (requestFetch ?? globalThis.fetch)(input, init);
|
|
1316
|
+
}
|
|
1317
|
+
catch (error) {
|
|
1318
|
+
// EventSource discards the fetch cause before the SDK creates SseError.
|
|
1319
|
+
if (localNetworkFailureCodes(error).length > 0)
|
|
1320
|
+
sseFetchFailure = error;
|
|
1321
|
+
throw error;
|
|
1322
|
+
}
|
|
1323
|
+
}
|
|
1324
|
+
: requestFetch;
|
|
1325
|
+
const transportOptions = {
|
|
1326
|
+
...(requestInit !== undefined ? { requestInit } : {}),
|
|
1327
|
+
...(transportFetch !== undefined ? { fetch: transportFetch } : {}),
|
|
1328
|
+
...(authProvider !== undefined ? { authProvider } : {}),
|
|
1329
|
+
...(authProvider !== undefined
|
|
1330
|
+
&& definition.oauth !== false
|
|
1331
|
+
&& definition.oauth?.skipIssuerMetadataValidation === true
|
|
1332
|
+
? { skipIssuerMetadataValidation: true }
|
|
1333
|
+
: {}),
|
|
1334
|
+
};
|
|
1335
|
+
const baseTransport = kind === "streamable-http"
|
|
1336
|
+
? new StreamableHTTPClientTransport(url, transportOptions)
|
|
1337
|
+
: new SSEClientTransport(url, transportOptions);
|
|
1338
|
+
const transport = traceObserver
|
|
1339
|
+
? wrapTransportWithMcpTrace(baseTransport, serverName, kind, traceObserver)
|
|
1340
|
+
: baseTransport;
|
|
1341
|
+
const client = this.createClient(serverName, definition);
|
|
1342
|
+
try {
|
|
1343
|
+
await this.connectClientWithAbort(client, transport, requestOptions, signal);
|
|
1344
|
+
return { status: "connected", client, transport };
|
|
1345
|
+
}
|
|
1346
|
+
catch (error) {
|
|
1347
|
+
if (error instanceof SseError && sseFetchFailure !== undefined) {
|
|
1348
|
+
error = new AggregateError([error, sseFetchFailure], error.message);
|
|
1349
|
+
}
|
|
1350
|
+
const abortCleanupFailed = error instanceof AggregateError
|
|
1351
|
+
&& error.message === "MCP connection abort cleanup failed";
|
|
1352
|
+
if (!abortCleanupFailed) {
|
|
1353
|
+
try {
|
|
1354
|
+
await (abortCleanupPromises.get(transport) ?? client.close());
|
|
1355
|
+
}
|
|
1356
|
+
catch (cleanupError) {
|
|
1357
|
+
throw new AggregateError([error, cleanupError], "MCP HTTP connection cleanup failed");
|
|
1358
|
+
}
|
|
1359
|
+
}
|
|
1360
|
+
return { status: "failed", client, transport, error };
|
|
1361
|
+
}
|
|
1362
|
+
};
|
|
1363
|
+
// Connect the real client once. Retry Streamable HTTP only for an implicit
|
|
1364
|
+
// OAuth challenge; use SSE only for definitive endpoint incompatibility.
|
|
1365
|
+
// Agent Plugins set httpTransport, and their declared transport is used without fallback.
|
|
1366
|
+
let kind = definition.httpTransport ?? "streamable-http";
|
|
1367
|
+
let invalidated = credentialsInvalidated;
|
|
1368
|
+
for (;;) {
|
|
1369
|
+
const result = await attempt(kind);
|
|
1370
|
+
if (result.status === "connected") {
|
|
1371
|
+
const ownedCa = caFetch;
|
|
1372
|
+
if (ownedCa) {
|
|
1373
|
+
const close = result.transport.close.bind(result.transport);
|
|
1374
|
+
const onclose = result.transport.onclose;
|
|
1375
|
+
result.transport.onclose = () => {
|
|
1376
|
+
void ownedCa.close().catch(error => {
|
|
1377
|
+
logger.debug(`MCP: CA dispatcher cleanup failed for ${serverName}: ${String(error)}`);
|
|
1378
|
+
});
|
|
1379
|
+
onclose?.();
|
|
1380
|
+
};
|
|
1381
|
+
result.transport.close = async () => {
|
|
1382
|
+
try {
|
|
1383
|
+
await close();
|
|
1384
|
+
}
|
|
1385
|
+
finally {
|
|
1386
|
+
await ownedCa.close();
|
|
1387
|
+
}
|
|
1388
|
+
};
|
|
1389
|
+
caFetch = undefined;
|
|
1390
|
+
}
|
|
1391
|
+
return { ...result, credentialsInvalidated: invalidated };
|
|
1392
|
+
}
|
|
1393
|
+
if (result.error instanceof AggregateError
|
|
1394
|
+
&& result.error.message === "MCP connection abort cleanup failed") {
|
|
1395
|
+
throw result.error;
|
|
1396
|
+
}
|
|
1397
|
+
if (signal?.aborted)
|
|
1398
|
+
throwIfAborted(signal);
|
|
1399
|
+
if (authState.status === "implicit-deferred" && isUnauthorizedHttpError(result.error)) {
|
|
1400
|
+
authState = { status: "implicit-challenged", provider: createAuthProvider() };
|
|
1401
|
+
continue;
|
|
1402
|
+
}
|
|
1403
|
+
if (isUnauthorizedHttpError(result.error)) {
|
|
1404
|
+
if (supportsOAuth(definition)) {
|
|
1405
|
+
if (!invalidated) {
|
|
1406
|
+
invalidateAuthEntryCache(serverName);
|
|
1407
|
+
invalidated = true;
|
|
1408
|
+
}
|
|
1409
|
+
return {
|
|
1410
|
+
client: result.client,
|
|
1411
|
+
transport: result.transport,
|
|
1412
|
+
status: "needs-auth",
|
|
1413
|
+
credentialsInvalidated: invalidated,
|
|
1414
|
+
};
|
|
1415
|
+
}
|
|
1416
|
+
throw result.error;
|
|
1417
|
+
}
|
|
1418
|
+
if (definition.httpTransport === undefined && kind === "streamable-http" && shouldFallbackToSse(result.error, definition)) {
|
|
1419
|
+
kind = "sse";
|
|
1420
|
+
continue;
|
|
1421
|
+
}
|
|
1422
|
+
throw result.error;
|
|
1423
|
+
}
|
|
1424
|
+
}
|
|
1425
|
+
finally {
|
|
1426
|
+
await caFetch?.close();
|
|
1427
|
+
}
|
|
1428
|
+
}
|
|
1429
|
+
async fetchAllTools(client, requestOptions) {
|
|
1430
|
+
const allTools = [];
|
|
1431
|
+
let cursor;
|
|
1432
|
+
let hints;
|
|
1433
|
+
let firstPage = true;
|
|
1434
|
+
do {
|
|
1435
|
+
const result = await client.listTools(cursor ? { cursor } : undefined, requestOptions);
|
|
1436
|
+
if (firstPage) {
|
|
1437
|
+
const ttlMs = typeof result.ttlMs === "number" && Number.isSafeInteger(result.ttlMs) && result.ttlMs >= 0
|
|
1438
|
+
? result.ttlMs
|
|
1439
|
+
: undefined;
|
|
1440
|
+
const cacheScope = result.cacheScope === "public" || result.cacheScope === "private"
|
|
1441
|
+
? result.cacheScope
|
|
1442
|
+
: undefined;
|
|
1443
|
+
if (ttlMs !== undefined || cacheScope !== undefined) {
|
|
1444
|
+
hints = {
|
|
1445
|
+
...(ttlMs !== undefined ? { ttlMs } : {}),
|
|
1446
|
+
...(cacheScope !== undefined ? { cacheScope } : {}),
|
|
1447
|
+
};
|
|
1448
|
+
}
|
|
1449
|
+
firstPage = false;
|
|
1450
|
+
}
|
|
1451
|
+
allTools.push(...(result.tools ?? []));
|
|
1452
|
+
cursor = result.nextCursor;
|
|
1453
|
+
} while (cursor);
|
|
1454
|
+
return { tools: allTools, ...(hints !== undefined ? { hints } : {}) };
|
|
1455
|
+
}
|
|
1456
|
+
async fetchAllPrompts(client, requestOptions) {
|
|
1457
|
+
const capabilities = client.getServerCapabilities?.();
|
|
1458
|
+
if (!capabilities?.prompts)
|
|
1459
|
+
return { prompts: [], failed: false };
|
|
1460
|
+
try {
|
|
1461
|
+
const prompts = [];
|
|
1462
|
+
let cursor;
|
|
1463
|
+
do {
|
|
1464
|
+
const result = await client.listPrompts(cursor ? { cursor } : undefined, requestOptions);
|
|
1465
|
+
prompts.push(...(result.prompts ?? []));
|
|
1466
|
+
cursor = result.nextCursor;
|
|
1467
|
+
} while (cursor);
|
|
1468
|
+
return { prompts, failed: false };
|
|
1469
|
+
}
|
|
1470
|
+
catch (error) {
|
|
1471
|
+
if (requestOptions?.signal?.aborted)
|
|
1472
|
+
throwIfAborted(requestOptions.signal);
|
|
1473
|
+
if (isUnauthorizedHttpError(error))
|
|
1474
|
+
throw error;
|
|
1475
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1476
|
+
logger.debug(`MCP: prompts/list failed: ${message}`);
|
|
1477
|
+
return { prompts: [], failed: true };
|
|
1478
|
+
}
|
|
1479
|
+
}
|
|
1480
|
+
async fetchAllResources(client, requestOptions, strict = false) {
|
|
1481
|
+
const capabilities = client.getServerCapabilities?.();
|
|
1482
|
+
if (!capabilities?.resources)
|
|
1483
|
+
return { resources: [], failed: false };
|
|
1484
|
+
try {
|
|
1485
|
+
const allResources = [];
|
|
1486
|
+
let cursor;
|
|
1487
|
+
do {
|
|
1488
|
+
const result = await client.listResources(cursor ? { cursor } : undefined, requestOptions);
|
|
1489
|
+
allResources.push(...(result.resources ?? []));
|
|
1490
|
+
cursor = result.nextCursor;
|
|
1491
|
+
} while (cursor);
|
|
1492
|
+
return { resources: allResources, failed: false };
|
|
1493
|
+
}
|
|
1494
|
+
catch (error) {
|
|
1495
|
+
if (requestOptions?.signal?.aborted) {
|
|
1496
|
+
throwIfAborted(requestOptions.signal);
|
|
1497
|
+
}
|
|
1498
|
+
if (isUnauthorizedHttpError(error))
|
|
1499
|
+
throw error;
|
|
1500
|
+
if (strict)
|
|
1501
|
+
throw error;
|
|
1502
|
+
// The server advertises resources but the listing failed
|
|
1503
|
+
return { resources: [], failed: true };
|
|
1504
|
+
}
|
|
1505
|
+
}
|
|
1506
|
+
attachAdapterNotificationHandlers(serverName, client) {
|
|
1507
|
+
client.setNotificationHandler("notifications/resources/updated", notification => {
|
|
1508
|
+
const uri = notification.params.uri;
|
|
1509
|
+
const connection = this.connections.get(serverName);
|
|
1510
|
+
if (!connection || connection.client !== client || connection.status !== "connected")
|
|
1511
|
+
return;
|
|
1512
|
+
for (const registration of this.resourceUpdatedListeners.values()) {
|
|
1513
|
+
if (registration.serverName === serverName && registration.uri === uri) {
|
|
1514
|
+
try {
|
|
1515
|
+
registration.listener(serverName, uri);
|
|
1516
|
+
}
|
|
1517
|
+
catch {
|
|
1518
|
+
// One UI listener must not block resource invalidation for others.
|
|
1519
|
+
}
|
|
1520
|
+
}
|
|
1521
|
+
}
|
|
1522
|
+
});
|
|
1523
|
+
client.setNotificationHandler(SERVER_STREAM_RESULT_PATCH_METHOD, { params: serverStreamResultPatchNotificationSchema.shape.params }, params => {
|
|
1524
|
+
const listener = this.uiStreamListeners.get(params.streamToken);
|
|
1525
|
+
if (!listener)
|
|
1526
|
+
return;
|
|
1527
|
+
listener(serverName, params);
|
|
1528
|
+
});
|
|
1529
|
+
}
|
|
1530
|
+
registerUiStreamListener(streamToken, listener) {
|
|
1531
|
+
this.uiStreamListeners.set(streamToken, listener);
|
|
1532
|
+
}
|
|
1533
|
+
removeUiStreamListener(streamToken) {
|
|
1534
|
+
this.uiStreamListeners.delete(streamToken);
|
|
1535
|
+
}
|
|
1536
|
+
async getPrompt(name, promptName, args, signal) {
|
|
1537
|
+
const connection = this.connections.get(name);
|
|
1538
|
+
if (!connection || connection.status !== "connected") {
|
|
1539
|
+
throw new Error(`Server "${name}" is not connected`);
|
|
1540
|
+
}
|
|
1541
|
+
try {
|
|
1542
|
+
this.touch(name);
|
|
1543
|
+
this.incrementInFlight(name);
|
|
1544
|
+
await this.ensureListen(name, connection);
|
|
1545
|
+
return await connection.client.getPrompt({ name: promptName, ...(args ? { arguments: args } : {}) }, this.getRequestOptions(name, signal));
|
|
1546
|
+
}
|
|
1547
|
+
finally {
|
|
1548
|
+
this.decrementInFlight(name);
|
|
1549
|
+
this.touch(name);
|
|
1550
|
+
}
|
|
1551
|
+
}
|
|
1552
|
+
async readResource(name, uri, signal) {
|
|
1553
|
+
if (isServerDisabled(this.connections.get(name)?.definition)) {
|
|
1554
|
+
throw new Error(`MCP server "${name}" is disabled`);
|
|
1555
|
+
}
|
|
1556
|
+
const connection = this.connections.get(name);
|
|
1557
|
+
if (!connection || connection.status !== "connected") {
|
|
1558
|
+
throw new Error(`Server "${name}" is not connected`);
|
|
1559
|
+
}
|
|
1560
|
+
try {
|
|
1561
|
+
this.touch(name);
|
|
1562
|
+
this.incrementInFlight(name);
|
|
1563
|
+
const refreshRead = await this.prepareResourceUse(name, uri, connection);
|
|
1564
|
+
const requestOptions = this.getRequestOptions(name, signal);
|
|
1565
|
+
return await connection.client.readResource({ uri }, refreshRead ? { ...requestOptions, cacheMode: "refresh" } : requestOptions);
|
|
1566
|
+
}
|
|
1567
|
+
finally {
|
|
1568
|
+
this.decrementInFlight(name);
|
|
1569
|
+
this.touch(name);
|
|
1570
|
+
}
|
|
1571
|
+
}
|
|
1572
|
+
async close(name) {
|
|
1573
|
+
this.closeGenerations.set(name, (this.closeGenerations.get(name) ?? 0) + 1);
|
|
1574
|
+
this.connectAttempts.get(name)?.abort(new Error(`MCP connection ${name} was closed`));
|
|
1575
|
+
this.reconnectAttempts.get(name)?.abort(new Error(`MCP connection ${name} was closed`));
|
|
1576
|
+
this.pendingMetadataPublications.delete(name);
|
|
1577
|
+
const pendingReconnect = this.reconnectPromises.get(name);
|
|
1578
|
+
const connection = this.connections.get(name);
|
|
1579
|
+
if (!connection) {
|
|
1580
|
+
const pendingClose = this.closePromises.get(name);
|
|
1581
|
+
if (pendingClose) {
|
|
1582
|
+
await pendingClose;
|
|
1583
|
+
return;
|
|
1584
|
+
}
|
|
1585
|
+
const pendingConnect = this.connectPromises.get(name);
|
|
1586
|
+
for (const pending of [pendingConnect, pendingReconnect]) {
|
|
1587
|
+
if (!pending)
|
|
1588
|
+
continue;
|
|
1589
|
+
try {
|
|
1590
|
+
await pending;
|
|
1591
|
+
}
|
|
1592
|
+
catch (error) {
|
|
1593
|
+
if (this.containsCleanupFailure(error))
|
|
1594
|
+
throw error;
|
|
1595
|
+
}
|
|
1596
|
+
}
|
|
1597
|
+
return;
|
|
1598
|
+
}
|
|
1599
|
+
// Delete before awaiting SDK cleanup so a replacement cannot be removed by
|
|
1600
|
+
// an old close operation finishing later.
|
|
1601
|
+
connection.status = "closed";
|
|
1602
|
+
this.connections.delete(name);
|
|
1603
|
+
this.acceptedUrlElicitations.delete(name);
|
|
1604
|
+
const closing = this.disposeConnection(connection).finally(() => {
|
|
1605
|
+
if (this.closePromises.get(name) === closing)
|
|
1606
|
+
this.closePromises.delete(name);
|
|
1607
|
+
});
|
|
1608
|
+
this.closePromises.set(name, closing);
|
|
1609
|
+
await closing;
|
|
1610
|
+
if (pendingReconnect) {
|
|
1611
|
+
try {
|
|
1612
|
+
await pendingReconnect;
|
|
1613
|
+
}
|
|
1614
|
+
catch (error) {
|
|
1615
|
+
if (this.containsCleanupFailure(error))
|
|
1616
|
+
throw error;
|
|
1617
|
+
}
|
|
1618
|
+
}
|
|
1619
|
+
}
|
|
1620
|
+
async disposeConnection(connection) {
|
|
1621
|
+
const results = await Promise.allSettled([
|
|
1622
|
+
// Release ext-tasks state first so its SDK adapter detaches before close.
|
|
1623
|
+
Promise.resolve().then(async () => {
|
|
1624
|
+
connection.taskChannel?.rejectAll("MCP connection closed");
|
|
1625
|
+
await connection.taskSession?.close();
|
|
1626
|
+
}).catch(() => { }),
|
|
1627
|
+
// Only client.close() is needed; the client owns the transport and will close it internally.
|
|
1628
|
+
Promise.resolve().then(() => connection.client.close()),
|
|
1629
|
+
this.traceWriter?.flush() ?? Promise.resolve(),
|
|
1630
|
+
]);
|
|
1631
|
+
const failures = results.flatMap(result => result.status === "rejected" ? [result.reason] : []);
|
|
1632
|
+
if (failures.length > 0)
|
|
1633
|
+
throw new AggregateError(failures, "MCP connection cleanup failed");
|
|
1634
|
+
}
|
|
1635
|
+
async closeAll() {
|
|
1636
|
+
this.stopped = true;
|
|
1637
|
+
const names = new Set([
|
|
1638
|
+
...this.connections.keys(),
|
|
1639
|
+
...this.connectPromises.keys(),
|
|
1640
|
+
...this.reconnectPromises.keys(),
|
|
1641
|
+
]);
|
|
1642
|
+
for (const name of names) {
|
|
1643
|
+
this.closeGenerations.set(name, (this.closeGenerations.get(name) ?? 0) + 1);
|
|
1644
|
+
this.connectAttempts.get(name)?.abort(new Error(`MCP connection ${name} was closed`));
|
|
1645
|
+
this.reconnectAttempts.get(name)?.abort(new Error(`MCP connection ${name} was closed`));
|
|
1646
|
+
}
|
|
1647
|
+
const pendingConnects = [...this.connectPromises.values(), ...this.reconnectPromises.values()];
|
|
1648
|
+
const currentNames = [...this.connections.keys()];
|
|
1649
|
+
const pendingResults = await Promise.allSettled(pendingConnects);
|
|
1650
|
+
const results = await Promise.allSettled(currentNames.map(name => this.close(name)));
|
|
1651
|
+
// A connect that resolved during the first close snapshot is still fenced;
|
|
1652
|
+
// close any handle that was already inserted before its attempt settled.
|
|
1653
|
+
const lateNames = [...this.connections.keys()];
|
|
1654
|
+
const lateResults = await Promise.allSettled(lateNames.map(name => this.close(name)));
|
|
1655
|
+
const failures = [...pendingResults, ...results, ...lateResults]
|
|
1656
|
+
.flatMap(result => result.status === "rejected" ? [result.reason] : [])
|
|
1657
|
+
.filter(error => this.containsCleanupFailure(error));
|
|
1658
|
+
this.uiStreamListeners.clear();
|
|
1659
|
+
this.resourceUpdatedListeners.clear();
|
|
1660
|
+
this.acceptedUrlElicitations.clear();
|
|
1661
|
+
this.pendingMetadataPublications.clear();
|
|
1662
|
+
this.samplingConfig = undefined;
|
|
1663
|
+
this.elicitationConfig = undefined;
|
|
1664
|
+
await this.traceWriter?.flush();
|
|
1665
|
+
if (failures.length > 0)
|
|
1666
|
+
throw new AggregateError(failures, "MCP manager cleanup failed");
|
|
1667
|
+
}
|
|
1668
|
+
containsCleanupFailure(error) {
|
|
1669
|
+
const pending = [error];
|
|
1670
|
+
const seen = new Set();
|
|
1671
|
+
while (pending.length > 0) {
|
|
1672
|
+
const current = pending.pop();
|
|
1673
|
+
if (!(current instanceof Error) || seen.has(current))
|
|
1674
|
+
continue;
|
|
1675
|
+
seen.add(current);
|
|
1676
|
+
if (current instanceof AggregateError) {
|
|
1677
|
+
if (/cleanup failed|setup failed/.test(current.message))
|
|
1678
|
+
return true;
|
|
1679
|
+
pending.push(...current.errors);
|
|
1680
|
+
}
|
|
1681
|
+
if (current.cause !== undefined)
|
|
1682
|
+
pending.push(current.cause);
|
|
1683
|
+
}
|
|
1684
|
+
return false;
|
|
1685
|
+
}
|
|
1686
|
+
isConnecting(name) {
|
|
1687
|
+
return this.connectPromises.has(name);
|
|
1688
|
+
}
|
|
1689
|
+
getConnection(name) {
|
|
1690
|
+
return this.connections.get(name);
|
|
1691
|
+
}
|
|
1692
|
+
getAllConnections() {
|
|
1693
|
+
return new Map(this.connections);
|
|
1694
|
+
}
|
|
1695
|
+
touch(name) {
|
|
1696
|
+
const connection = this.connections.get(name);
|
|
1697
|
+
if (connection) {
|
|
1698
|
+
connection.lastUsedAt = Date.now();
|
|
1699
|
+
}
|
|
1700
|
+
}
|
|
1701
|
+
incrementInFlight(name) {
|
|
1702
|
+
const connection = this.connections.get(name);
|
|
1703
|
+
if (connection) {
|
|
1704
|
+
connection.inFlight = (connection.inFlight ?? 0) + 1;
|
|
1705
|
+
}
|
|
1706
|
+
}
|
|
1707
|
+
decrementInFlight(name) {
|
|
1708
|
+
const connection = this.connections.get(name);
|
|
1709
|
+
if (connection && connection.inFlight) {
|
|
1710
|
+
connection.inFlight--;
|
|
1711
|
+
}
|
|
1712
|
+
}
|
|
1713
|
+
isIdle(name, timeoutMs) {
|
|
1714
|
+
const connection = this.connections.get(name);
|
|
1715
|
+
if (!connection || connection.status !== "connected")
|
|
1716
|
+
return false;
|
|
1717
|
+
if (connection.inFlight > 0)
|
|
1718
|
+
return false;
|
|
1719
|
+
return (Date.now() - connection.lastUsedAt) > timeoutMs;
|
|
1720
|
+
}
|
|
1721
|
+
}
|
|
1722
|
+
/**
|
|
1723
|
+
* Resolve environment variables with interpolation.
|
|
1724
|
+
*/
|
|
1725
|
+
function resolveEnv(env, serverName, literalEnv = false, inheritEnv = true) {
|
|
1726
|
+
const resolved = {};
|
|
1727
|
+
if (inheritEnv) {
|
|
1728
|
+
for (const [key, value] of Object.entries(process.env)) {
|
|
1729
|
+
if (value !== undefined)
|
|
1730
|
+
resolved[key] = value;
|
|
1731
|
+
}
|
|
1732
|
+
}
|
|
1733
|
+
if (literalEnv)
|
|
1734
|
+
return env ? { ...resolved, ...env } : resolved;
|
|
1735
|
+
const overrides = resolveCommandSecretsRecord(env, key => `MCP server "${serverName}" stdio env "${key}"`);
|
|
1736
|
+
return overrides ? { ...resolved, ...overrides } : resolved;
|
|
1737
|
+
}
|
|
1738
|
+
function normalizeRequestTimeoutMs(timeoutMs) {
|
|
1739
|
+
return typeof timeoutMs === "number" && Number.isFinite(timeoutMs) && timeoutMs > 0
|
|
1740
|
+
? timeoutMs
|
|
1741
|
+
: undefined;
|
|
1742
|
+
}
|
|
1743
|
+
//# sourceMappingURL=server-manager.js.map
|