@nest-mcp/client 1.0.2 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +139 -0
- package/README.md +845 -69
- package/dist/ai-sdk/index.d.mts +14 -0
- package/dist/ai-sdk/index.d.mts.map +1 -0
- package/dist/ai-sdk/index.mjs +27 -0
- package/dist/ai-sdk/index.mjs.map +1 -0
- package/dist/bootstrap-BIAcDnHp.d.mts +394 -0
- package/dist/bootstrap-BIAcDnHp.d.mts.map +1 -0
- package/dist/index.d.mts +480 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +1960 -0
- package/dist/index.mjs.map +1 -0
- package/dist/oauth/dynamic-registration.d.mts +92 -0
- package/dist/oauth/dynamic-registration.d.mts.map +1 -0
- package/dist/oauth/dynamic-registration.mjs +392 -0
- package/dist/oauth/dynamic-registration.mjs.map +1 -0
- package/dist/oauth/index.d.mts +422 -0
- package/dist/oauth/index.d.mts.map +1 -0
- package/dist/oauth/index.mjs +3349 -0
- package/dist/oauth/index.mjs.map +1 -0
- package/dist/scope-CxGBCDdr.mjs +22 -0
- package/dist/scope-CxGBCDdr.mjs.map +1 -0
- package/package.json +76 -50
- package/scripts/external-smoke.mjs +693 -0
- package/dist/decorators/inject-mcp-client.decorator.d.ts +0 -3
- package/dist/decorators/inject-mcp-client.decorator.js +0 -12
- package/dist/decorators/on-notification.decorator.d.ts +0 -7
- package/dist/decorators/on-notification.decorator.js +0 -13
- package/dist/health/mcp-client.health.d.ts +0 -20
- package/dist/health/mcp-client.health.js +0 -42
- package/dist/index.d.ts +0 -21
- package/dist/index.js +0 -64
- package/dist/interfaces/client-options.interface.d.ts +0 -139
- package/dist/interfaces/client-options.interface.js +0 -3
- package/dist/mcp-client.module.d.ts +0 -20
- package/dist/mcp-client.module.js +0 -188
- package/dist/mcp-client.service.d.ts +0 -558
- package/dist/mcp-client.service.js +0 -532
- package/dist/mcp-clients.service.d.ts +0 -39
- package/dist/mcp-clients.service.js +0 -104
- package/dist/testing/mock-client.d.ts +0 -67
- package/dist/testing/mock-client.js +0 -154
- package/dist/transport/apply-auth-headers.d.ts +0 -3
- package/dist/transport/apply-auth-headers.js +0 -13
- package/dist/transport/client-transport.factory.d.ts +0 -4
- package/dist/transport/client-transport.factory.js +0 -21
- package/dist/transport/sse-client.transport.d.ts +0 -4
- package/dist/transport/sse-client.transport.js +0 -15
- package/dist/transport/stdio-client.transport.d.ts +0 -4
- package/dist/transport/stdio-client.transport.js +0 -14
- package/dist/transport/streamable-client.transport.d.ts +0 -4
- package/dist/transport/streamable-client.transport.js +0 -17
- package/dist/utils/format-error-message.d.ts +0 -2
- package/dist/utils/format-error-message.js +0 -7
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,1960 @@
|
|
|
1
|
+
import { AuthorizationServerMismatchError, Client, Client as Client$1, ClientCredentialsProvider, CrossAppAccessProvider, InsecureTokenEndpointError, InsufficientScopeError, IssuerMismatchError, METHOD_NOT_FOUND, OAuthClientFlowError, PrivateKeyJwtProvider, ProtocolError, RegistrationRejectedError, StaticPrivateKeyJwtProvider, StreamableHTTPClientTransport, StreamableHTTPClientTransport as StreamableHTTPClientTransport$1, UnauthorizedError, applyMiddlewares, applyMiddlewares as applyMiddlewares$1, auth, createMiddleware, createPrivateKeyJwtAuth, discoverOAuthMetadata, discoverOAuthProtectedResourceMetadata, discoverOAuthServerInfo, isInputRequiredResult, refreshAuthorization, specTypeSchemas, withInputRequired, withInputRequired as withInputRequired$1, withLogging, withOAuth } from "@modelcontextprotocol/client";
|
|
2
|
+
import { StdioClientTransport, StdioClientTransport as StdioClientTransport$1 } from "@modelcontextprotocol/client/stdio";
|
|
3
|
+
import { randomUUID } from "node:crypto";
|
|
4
|
+
import { composeMcpMiddleware, createMcpLifecycleMiddleware, createMcpOperation, createMcpOperationContext, createMcpPassthroughMiddleware, toMcpErrorDetails } from "@nest-mcp/core";
|
|
5
|
+
import { captureMcpConformanceValue, captureMcpToolArguments } from "@nest-mcp/conformance";
|
|
6
|
+
import { AjvJsonSchemaValidator } from "@modelcontextprotocol/client/validators/ajv";
|
|
7
|
+
import { z } from "zod/v4";
|
|
8
|
+
//#region src/errors.ts
|
|
9
|
+
const MCP_CLIENT_RUNTIME_CLOSED = "MCP_CLIENT_RUNTIME_CLOSED";
|
|
10
|
+
const MCP_CLIENT_SERVER_EXISTS = "MCP_CLIENT_SERVER_EXISTS";
|
|
11
|
+
const MCP_CLIENT_SERVER_NOT_FOUND = "MCP_CLIENT_SERVER_NOT_FOUND";
|
|
12
|
+
const MCP_CLIENT_NOT_CONNECTED = "MCP_CLIENT_NOT_CONNECTED";
|
|
13
|
+
const MCP_CLIENT_SHUTDOWN_TIMEOUT = "MCP_CLIENT_SHUTDOWN_TIMEOUT";
|
|
14
|
+
const MCP_CLIENT_LEASE_MANAGER_CLOSED = "MCP_CLIENT_LEASE_MANAGER_CLOSED";
|
|
15
|
+
const MCP_CLIENT_LEASE_CAPACITY_EXCEEDED = "MCP_CLIENT_LEASE_CAPACITY_EXCEEDED";
|
|
16
|
+
const MCP_CLIENT_LEASE_RELEASE_MODE_CONFLICT = "MCP_CLIENT_LEASE_RELEASE_MODE_CONFLICT";
|
|
17
|
+
const MCP_CLIENT_LEASE_INVALIDATED = "MCP_CLIENT_LEASE_INVALIDATED";
|
|
18
|
+
/** Base error for deterministic registry and lifecycle failures. */
|
|
19
|
+
var McpClientRuntimeError = class extends Error {
|
|
20
|
+
code;
|
|
21
|
+
serverName;
|
|
22
|
+
constructor(code, message, serverName) {
|
|
23
|
+
super(message);
|
|
24
|
+
this.name = "McpClientRuntimeError";
|
|
25
|
+
this.code = code;
|
|
26
|
+
if (serverName !== void 0) this.serverName = serverName;
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
/** Key-free error for deterministic lease-manager admission and lifecycle failures. */
|
|
30
|
+
var McpClientLeaseManagerError = class extends Error {
|
|
31
|
+
code;
|
|
32
|
+
constructor(code, message) {
|
|
33
|
+
super(message);
|
|
34
|
+
this.name = "McpClientLeaseManagerError";
|
|
35
|
+
this.code = code;
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
function runtimeClosedError() {
|
|
39
|
+
return new McpClientRuntimeError(MCP_CLIENT_RUNTIME_CLOSED, "The MCP client runtime is closed and cannot accept new work.");
|
|
40
|
+
}
|
|
41
|
+
function serverExistsError(serverName) {
|
|
42
|
+
return new McpClientRuntimeError(MCP_CLIENT_SERVER_EXISTS, `An MCP server named ${JSON.stringify(serverName)} is already registered.`, serverName);
|
|
43
|
+
}
|
|
44
|
+
function serverNotFoundError(serverName) {
|
|
45
|
+
return new McpClientRuntimeError(MCP_CLIENT_SERVER_NOT_FOUND, `No MCP server named ${JSON.stringify(serverName)} is registered.`, serverName);
|
|
46
|
+
}
|
|
47
|
+
function clientNotConnectedError(serverName) {
|
|
48
|
+
return new McpClientRuntimeError(MCP_CLIENT_NOT_CONNECTED, `The MCP server ${JSON.stringify(serverName)} is not connected.`, serverName);
|
|
49
|
+
}
|
|
50
|
+
function shutdownTimeoutError(serverName, timeoutMs) {
|
|
51
|
+
return new McpClientRuntimeError(MCP_CLIENT_SHUTDOWN_TIMEOUT, `The MCP server ${JSON.stringify(serverName)} connection did not stop within ${String(timeoutMs)}ms.`, serverName);
|
|
52
|
+
}
|
|
53
|
+
function leaseManagerClosedError() {
|
|
54
|
+
return new McpClientLeaseManagerError(MCP_CLIENT_LEASE_MANAGER_CLOSED, "The MCP client lease manager is closed and cannot accept new work.");
|
|
55
|
+
}
|
|
56
|
+
function leaseCapacityExceededError() {
|
|
57
|
+
return new McpClientLeaseManagerError(MCP_CLIENT_LEASE_CAPACITY_EXCEEDED, "The MCP client lease manager is at capacity.");
|
|
58
|
+
}
|
|
59
|
+
function leaseReleaseModeConflictError() {
|
|
60
|
+
return new McpClientLeaseManagerError(MCP_CLIENT_LEASE_RELEASE_MODE_CONFLICT, "The existing MCP client resource uses a different release mode.");
|
|
61
|
+
}
|
|
62
|
+
function leaseInvalidatedError() {
|
|
63
|
+
return new McpClientLeaseManagerError(MCP_CLIENT_LEASE_INVALIDATED, "The MCP client lease identity was invalidated before acquisition completed.");
|
|
64
|
+
}
|
|
65
|
+
//#endregion
|
|
66
|
+
//#region src/exact-result-profile.ts
|
|
67
|
+
/**
|
|
68
|
+
* Runtime-owned proof that an operation returns the ordinary official result.
|
|
69
|
+
* A method string alone is insufficient because custom-schema, manual-MRTR,
|
|
70
|
+
* and managed-subscription APIs deliberately use different result contracts.
|
|
71
|
+
*/
|
|
72
|
+
const exactResultMethods = /* @__PURE__ */ new WeakMap();
|
|
73
|
+
function markExactMcpClientResult(input, method) {
|
|
74
|
+
if (input.method !== method) throw new TypeError("The exact client result profile must match the operation method.");
|
|
75
|
+
exactResultMethods.set(input, method);
|
|
76
|
+
}
|
|
77
|
+
function hasExactMcpClientResult(input, method) {
|
|
78
|
+
return exactResultMethods.get(input) === method;
|
|
79
|
+
}
|
|
80
|
+
//#endregion
|
|
81
|
+
//#region src/middleware.ts
|
|
82
|
+
const exactClientTransforms = /* @__PURE__ */ new WeakSet();
|
|
83
|
+
/**
|
|
84
|
+
* Defines a transform for one ordinary official request/result pair.
|
|
85
|
+
*
|
|
86
|
+
* Runtime-owned custom-schema, manual-MRTR, input-required, and managed
|
|
87
|
+
* subscription operations are intentionally not dispatched to this helper,
|
|
88
|
+
* even when they share the same protocol method string.
|
|
89
|
+
*/
|
|
90
|
+
function defineMcpClientTransform(method, transform) {
|
|
91
|
+
assertRequestMethod(method);
|
|
92
|
+
if (typeof transform !== "function") throw new TypeError("client transform must be a function.");
|
|
93
|
+
const middleware = async (operation, next) => {
|
|
94
|
+
if (!isExactRequestOperation(operation, method)) return next();
|
|
95
|
+
operation.context.signal.throwIfAborted();
|
|
96
|
+
const result = await transform(operation, next);
|
|
97
|
+
operation.context.signal.throwIfAborted();
|
|
98
|
+
return result;
|
|
99
|
+
};
|
|
100
|
+
exactClientTransforms.add(middleware);
|
|
101
|
+
return middleware;
|
|
102
|
+
}
|
|
103
|
+
/** @internal Runtime partitioning keeps exact continuations downstream of broad middleware. */
|
|
104
|
+
function isExactMcpClientTransform(middleware) {
|
|
105
|
+
return exactClientTransforms.has(middleware);
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Binds provider-owned middleware without erasing exact-transform identity.
|
|
109
|
+
*
|
|
110
|
+
* Exact transforms carry runtime-only identity used to keep their typed
|
|
111
|
+
* continuation behind broad middleware. Since `Function.bind()` creates a new
|
|
112
|
+
* function, exact transforms must remain unchanged; their defining adapter
|
|
113
|
+
* already closes over the supplied transform callback.
|
|
114
|
+
*/
|
|
115
|
+
function bindMcpClientMiddleware(middleware, receiver) {
|
|
116
|
+
return isExactMcpClientTransform(middleware) ? middleware : middleware.bind(receiver);
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Creates client middleware that always returns the exact downstream result.
|
|
120
|
+
* The callback can run before and after `next()`, but cannot inspect, replace,
|
|
121
|
+
* or swallow a method-specific result.
|
|
122
|
+
*/
|
|
123
|
+
function createMcpClientPassthroughMiddleware(middleware) {
|
|
124
|
+
return createMcpPassthroughMiddleware(middleware);
|
|
125
|
+
}
|
|
126
|
+
function isExactRequestOperation(operation, method) {
|
|
127
|
+
return operation.input.method === method && operation.context.operation.kind === "request" && operation.context.operation.name === method && hasExactMcpClientResult(operation.input, method);
|
|
128
|
+
}
|
|
129
|
+
function assertRequestMethod(method) {
|
|
130
|
+
if (typeof method !== "string" || method.trim().length === 0) throw new TypeError("client transform method must be a non-empty string.");
|
|
131
|
+
}
|
|
132
|
+
//#endregion
|
|
133
|
+
//#region src/transport.ts
|
|
134
|
+
/** Applies the official SDK's fetch-middleware composition semantics. */
|
|
135
|
+
function composeMcpFetchMiddleware(middleware, baseFetch = defaultFetch) {
|
|
136
|
+
return applyMiddlewares$1(...middleware)(baseFetch);
|
|
137
|
+
}
|
|
138
|
+
/** Creates the official MCP v2 Streamable HTTP client transport. */
|
|
139
|
+
function createMcpHttpClientTransport(definition) {
|
|
140
|
+
const url = normalizeHttpUrl(definition.url);
|
|
141
|
+
const middleware = definition.middleware ?? [];
|
|
142
|
+
validateMiddleware(middleware);
|
|
143
|
+
const wrappedFetch = middleware.length === 0 ? definition.fetch : composeMcpFetchMiddleware(middleware, definition.fetch ?? defaultFetch);
|
|
144
|
+
const options = {
|
|
145
|
+
...definition.options,
|
|
146
|
+
...definition.authProvider === void 0 ? {} : { authProvider: definition.authProvider },
|
|
147
|
+
...wrappedFetch === void 0 ? {} : { fetch: wrappedFetch },
|
|
148
|
+
...definition.requestInit === void 0 ? {} : { requestInit: definition.requestInit }
|
|
149
|
+
};
|
|
150
|
+
return new StreamableHTTPClientTransport$1(url, options);
|
|
151
|
+
}
|
|
152
|
+
/** Creates the official Node.js stdio transport. */
|
|
153
|
+
function createMcpStdioClientTransport(definition) {
|
|
154
|
+
assertNonEmpty$1(definition.command, "stdio command");
|
|
155
|
+
const parameters = {
|
|
156
|
+
command: definition.command,
|
|
157
|
+
...definition.args === void 0 ? {} : { args: [...definition.args] },
|
|
158
|
+
...definition.env === void 0 ? {} : { env: { ...definition.env } },
|
|
159
|
+
...definition.stderr === void 0 ? {} : { stderr: definition.stderr },
|
|
160
|
+
...definition.cwd === void 0 ? {} : { cwd: definition.cwd },
|
|
161
|
+
...definition.maxBufferSize === void 0 ? {} : { maxBufferSize: definition.maxBufferSize }
|
|
162
|
+
};
|
|
163
|
+
return new StdioClientTransport$1(parameters);
|
|
164
|
+
}
|
|
165
|
+
/** Creates one of the official transports from a discriminated definition. */
|
|
166
|
+
function createMcpClientTransport(definition) {
|
|
167
|
+
switch (definition.kind) {
|
|
168
|
+
case "http": return createMcpHttpClientTransport(definition);
|
|
169
|
+
case "stdio": return createMcpStdioClientTransport(definition);
|
|
170
|
+
default: throw new TypeError("MCP client transport kind must be http or stdio.");
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
/** Stateless transport factory used by runtimes that do not inject a custom factory. */
|
|
174
|
+
const defaultMcpClientTransportFactory = Object.freeze({ createTransport(definition) {
|
|
175
|
+
return createMcpClientTransport(definition);
|
|
176
|
+
} });
|
|
177
|
+
const defaultFetch = (url, init) => globalThis.fetch(url, init);
|
|
178
|
+
function normalizeHttpUrl(value) {
|
|
179
|
+
const url = new URL(value);
|
|
180
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") throw new TypeError("MCP Streamable HTTP URLs must use http: or https:.");
|
|
181
|
+
return url;
|
|
182
|
+
}
|
|
183
|
+
function validateMiddleware(middleware) {
|
|
184
|
+
for (const [index, entry] of middleware.entries()) if (typeof entry !== "function") throw new TypeError(`HTTP middleware[${String(index)}] must be a function.`);
|
|
185
|
+
}
|
|
186
|
+
function assertNonEmpty$1(value, field) {
|
|
187
|
+
if (value.trim().length === 0) throw new TypeError(`${field} must be a non-empty string.`);
|
|
188
|
+
}
|
|
189
|
+
//#endregion
|
|
190
|
+
//#region src/runtime.ts
|
|
191
|
+
const DEFAULT_CLIENT_INFO = Object.freeze({
|
|
192
|
+
name: "@nest-mcp/client",
|
|
193
|
+
version: "2.0.0"
|
|
194
|
+
});
|
|
195
|
+
const DEFAULT_SHUTDOWN_TIMEOUT_MS = 3e4;
|
|
196
|
+
const MRTR_CAPABILITY = Object.freeze({
|
|
197
|
+
"prompts/get": "prompts",
|
|
198
|
+
"resources/read": "resources",
|
|
199
|
+
"tools/call": "tools"
|
|
200
|
+
});
|
|
201
|
+
const defaultSdkClientFactory = Object.freeze({ createClient(clientInfo, options) {
|
|
202
|
+
return new Client$1(clientInfo, options);
|
|
203
|
+
} });
|
|
204
|
+
/**
|
|
205
|
+
* Owns a registry of named MCP servers and their independent official Client
|
|
206
|
+
* instances. One runtime may safely connect, disconnect, and inspect many
|
|
207
|
+
* upstreams while applying a shared middleware and lifecycle policy.
|
|
208
|
+
*/
|
|
209
|
+
var McpClientRuntime = class {
|
|
210
|
+
#entries = /* @__PURE__ */ new Map();
|
|
211
|
+
#clientInfo;
|
|
212
|
+
#clientFactory;
|
|
213
|
+
#transportFactory;
|
|
214
|
+
#middleware;
|
|
215
|
+
#transforms;
|
|
216
|
+
#lifecycleMiddleware;
|
|
217
|
+
#principal;
|
|
218
|
+
#resolvePrincipal;
|
|
219
|
+
#attributes;
|
|
220
|
+
#resolveAttributes;
|
|
221
|
+
#operationIdFactory;
|
|
222
|
+
#shutdownTimeoutMs;
|
|
223
|
+
#now;
|
|
224
|
+
#closed = false;
|
|
225
|
+
#lifecycleEpoch = 0;
|
|
226
|
+
#closeTask;
|
|
227
|
+
constructor(options = {}) {
|
|
228
|
+
assertPositiveFinite(options.shutdownTimeoutMs ?? DEFAULT_SHUTDOWN_TIMEOUT_MS, "shutdownTimeoutMs");
|
|
229
|
+
this.#clientInfo = Object.freeze({ ...options.clientInfo ?? DEFAULT_CLIENT_INFO });
|
|
230
|
+
this.#clientFactory = options.clientFactory ?? defaultSdkClientFactory;
|
|
231
|
+
this.#transportFactory = options.transportFactory ?? defaultMcpClientTransportFactory;
|
|
232
|
+
this.#principal = options.principal;
|
|
233
|
+
this.#resolvePrincipal = options.resolvePrincipal;
|
|
234
|
+
this.#attributes = Object.freeze({ ...options.attributes });
|
|
235
|
+
this.#resolveAttributes = options.resolveAttributes;
|
|
236
|
+
this.#operationIdFactory = options.operationIdFactory ?? randomUUID;
|
|
237
|
+
this.#shutdownTimeoutMs = options.shutdownTimeoutMs ?? DEFAULT_SHUTDOWN_TIMEOUT_MS;
|
|
238
|
+
this.#now = options.now ?? Date.now;
|
|
239
|
+
const middleware = [...options.middleware ?? []];
|
|
240
|
+
this.#middleware = Object.freeze(middleware.filter((entry) => !isExactMcpClientTransform(entry)));
|
|
241
|
+
this.#transforms = Object.freeze(middleware.filter((entry) => isExactMcpClientTransform(entry)));
|
|
242
|
+
this.#lifecycleMiddleware = options.observer === void 0 ? void 0 : createMcpLifecycleMiddleware(options.observer, options.lifecycle);
|
|
243
|
+
for (const definition of options.servers ?? []) this.register(definition);
|
|
244
|
+
}
|
|
245
|
+
get closed() {
|
|
246
|
+
return this.#closed;
|
|
247
|
+
}
|
|
248
|
+
get size() {
|
|
249
|
+
return this.names().length;
|
|
250
|
+
}
|
|
251
|
+
register(definition) {
|
|
252
|
+
this.#assertOpen();
|
|
253
|
+
const normalized = normalizeServerDefinition(definition);
|
|
254
|
+
if (this.#entries.has(normalized.name)) throw serverExistsError(normalized.name);
|
|
255
|
+
this.#entries.set(normalized.name, createRegistryEntry(normalized));
|
|
256
|
+
return this;
|
|
257
|
+
}
|
|
258
|
+
async unregister(serverName) {
|
|
259
|
+
this.#assertOpen();
|
|
260
|
+
const entry = this.#entries.get(serverName);
|
|
261
|
+
if (entry === void 0 || entry.retired) return false;
|
|
262
|
+
entry.retired = true;
|
|
263
|
+
try {
|
|
264
|
+
const operation = this.#runOperation(entry, { method: "runtime/disconnect" }, () => this.#disconnectEntry(entry), true);
|
|
265
|
+
this.#abortConnectAttempt(entry, serverNotFoundError(serverName));
|
|
266
|
+
await operation;
|
|
267
|
+
} finally {
|
|
268
|
+
if (this.#entries.get(serverName) === entry) this.#entries.delete(serverName);
|
|
269
|
+
}
|
|
270
|
+
return true;
|
|
271
|
+
}
|
|
272
|
+
has(serverName) {
|
|
273
|
+
return this.#entries.get(serverName)?.retired === false;
|
|
274
|
+
}
|
|
275
|
+
names() {
|
|
276
|
+
return Object.freeze([...this.#entries].filter(([, entry]) => !entry.retired).map(([serverName]) => serverName));
|
|
277
|
+
}
|
|
278
|
+
getDefinition(serverName) {
|
|
279
|
+
return this.#entry(serverName).definition;
|
|
280
|
+
}
|
|
281
|
+
setPriorDiscovery(serverName, prior) {
|
|
282
|
+
this.#entry(serverName).prior = prior;
|
|
283
|
+
return this;
|
|
284
|
+
}
|
|
285
|
+
/** Returns a persistable current verdict without automatically reusing it. */
|
|
286
|
+
getPriorDiscovery(serverName) {
|
|
287
|
+
const entry = this.#entry(serverName);
|
|
288
|
+
this.#refreshMetadata(entry);
|
|
289
|
+
if (entry.metadata.discoverResult !== void 0) return Object.freeze({
|
|
290
|
+
kind: "modern",
|
|
291
|
+
discover: entry.metadata.discoverResult
|
|
292
|
+
});
|
|
293
|
+
if (entry.metadata.protocolEra === "legacy") return Object.freeze({ kind: "legacy" });
|
|
294
|
+
return entry.prior;
|
|
295
|
+
}
|
|
296
|
+
getClient(serverName) {
|
|
297
|
+
const entry = this.#entries.get(serverName);
|
|
298
|
+
return entry?.retired === false && entry.state === "connected" ? entry.client : void 0;
|
|
299
|
+
}
|
|
300
|
+
requireClient(serverName) {
|
|
301
|
+
const client = this.getClient(serverName);
|
|
302
|
+
if (client === void 0) throw clientNotConnectedError(serverName);
|
|
303
|
+
return client;
|
|
304
|
+
}
|
|
305
|
+
snapshot(serverName) {
|
|
306
|
+
if (serverName !== void 0) return this.#snapshotEntry(this.#entry(serverName));
|
|
307
|
+
return Object.freeze([...this.#entries.values()].filter((entry) => !entry.retired).map((entry) => this.#snapshotEntry(entry)));
|
|
308
|
+
}
|
|
309
|
+
async connect(serverName, options) {
|
|
310
|
+
return (await this.#connectAttempt(serverName, options)).client;
|
|
311
|
+
}
|
|
312
|
+
async connectAll(options = {}) {
|
|
313
|
+
this.#assertOpen();
|
|
314
|
+
const attempts = this.names().map((name) => {
|
|
315
|
+
return {
|
|
316
|
+
name,
|
|
317
|
+
entry: this.#entry(name),
|
|
318
|
+
promise: this.#connectAttempt(name, options[name])
|
|
319
|
+
};
|
|
320
|
+
});
|
|
321
|
+
const settled = await Promise.allSettled(attempts.map((attempt) => attempt.promise));
|
|
322
|
+
const connectFailures = settled.filter((result) => result.status === "rejected").map((result) => result.reason);
|
|
323
|
+
if (connectFailures.length > 0) {
|
|
324
|
+
const rollback = attempts.flatMap((attempt, index) => {
|
|
325
|
+
const result = settled[index];
|
|
326
|
+
if (result?.status !== "fulfilled" || result.value.ownedConnectionToken === void 0 || attempt.entry.state !== "connected" || attempt.entry.client !== result.value.client || attempt.entry.connectionGeneration !== result.value.generation || attempt.entry.connectionToken !== result.value.ownedConnectionToken) return [];
|
|
327
|
+
return [this.#runOperation(attempt.entry, { method: "runtime/disconnect" }, () => this.#disconnectEntry(attempt.entry), true)];
|
|
328
|
+
});
|
|
329
|
+
const rollbackFailures = (await Promise.allSettled(rollback)).filter((result) => result.status === "rejected").map((result) => result.reason);
|
|
330
|
+
throwFailures([...connectFailures, ...rollbackFailures], "One or more MCP clients failed to connect, and rollback may also have failed.");
|
|
331
|
+
}
|
|
332
|
+
const connected = /* @__PURE__ */ new Map();
|
|
333
|
+
for (const [index, attempt] of attempts.entries()) {
|
|
334
|
+
const result = settled[index];
|
|
335
|
+
if (result?.status === "fulfilled") connected.set(attempt.name, result.value.client);
|
|
336
|
+
}
|
|
337
|
+
return connected;
|
|
338
|
+
}
|
|
339
|
+
async disconnect(serverName) {
|
|
340
|
+
const entry = this.#entry(serverName, true);
|
|
341
|
+
const operation = this.#runOperation(entry, { method: "runtime/disconnect" }, () => this.#disconnectEntry(entry), true);
|
|
342
|
+
this.#abortConnectAttempt(entry, connectionAbortedError(serverName));
|
|
343
|
+
await operation;
|
|
344
|
+
}
|
|
345
|
+
async disconnectAll() {
|
|
346
|
+
throwSettledFailures(await Promise.allSettled([...this.#entries.keys()].map((name) => this.disconnect(name))), "One or more MCP clients failed to disconnect.");
|
|
347
|
+
}
|
|
348
|
+
close() {
|
|
349
|
+
if (this.#closeTask !== void 0) return this.#closeTask;
|
|
350
|
+
this.#closed = true;
|
|
351
|
+
this.#lifecycleEpoch += 1;
|
|
352
|
+
this.#closeTask = Promise.resolve().then(() => this.disconnectAll());
|
|
353
|
+
for (const entry of this.#entries.values()) this.#abortConnectAttempt(entry, runtimeClosedError());
|
|
354
|
+
return this.#closeTask;
|
|
355
|
+
}
|
|
356
|
+
async [Symbol.asyncDispose]() {
|
|
357
|
+
await this.close();
|
|
358
|
+
}
|
|
359
|
+
async discover(serverName, options) {
|
|
360
|
+
const stableOptions = snapshotRequestOptions(options);
|
|
361
|
+
const result = await this.#delegate(serverName, {
|
|
362
|
+
method: "server/discover",
|
|
363
|
+
exactResultMethod: "server/discover",
|
|
364
|
+
options: stableOptions,
|
|
365
|
+
signal: stableOptions?.signal
|
|
366
|
+
}, (client) => client.discover(stableOptions));
|
|
367
|
+
this.#refreshMetadata(this.#entry(serverName));
|
|
368
|
+
return result;
|
|
369
|
+
}
|
|
370
|
+
/** Checks that a connected server is responsive. */
|
|
371
|
+
ping(serverName, options) {
|
|
372
|
+
const stableOptions = snapshotRequestOptions(options);
|
|
373
|
+
return this.#delegate(serverName, {
|
|
374
|
+
method: "ping",
|
|
375
|
+
exactResultMethod: "ping",
|
|
376
|
+
options: stableOptions,
|
|
377
|
+
signal: stableOptions?.signal
|
|
378
|
+
}, (client) => client.ping(stableOptions));
|
|
379
|
+
}
|
|
380
|
+
request(serverName, request, options) {
|
|
381
|
+
const stableRequest = snapshotProtocolValue(request, "MCP client request");
|
|
382
|
+
const stableOptions = snapshotRequestOptions(options);
|
|
383
|
+
return this.#delegate(serverName, {
|
|
384
|
+
method: stableRequest.method,
|
|
385
|
+
exactResultMethod: stableRequest.method,
|
|
386
|
+
params: stableRequest.params,
|
|
387
|
+
options: stableOptions,
|
|
388
|
+
signal: stableOptions?.signal
|
|
389
|
+
}, (client) => client.request(toOfficialProtocolRequest(stableRequest), stableOptions));
|
|
390
|
+
}
|
|
391
|
+
/** Sends a custom extension request and validates its result with a Standard Schema. */
|
|
392
|
+
requestWithSchema(serverName, request, resultSchema, options) {
|
|
393
|
+
const stableRequest = snapshotProtocolValue(request, "MCP client extension request");
|
|
394
|
+
const stableOptions = snapshotRequestOptions(options);
|
|
395
|
+
return this.#delegate(serverName, {
|
|
396
|
+
method: stableRequest.method,
|
|
397
|
+
params: stableRequest.params,
|
|
398
|
+
options: stableOptions,
|
|
399
|
+
signal: stableOptions?.signal
|
|
400
|
+
}, (client) => client.request(stableRequest, resultSchema, stableOptions));
|
|
401
|
+
}
|
|
402
|
+
/**
|
|
403
|
+
* Sends a modern multi-round-trip request in manual mode.
|
|
404
|
+
*
|
|
405
|
+
* A complete response is validated by `resultSchema`; an `input_required`
|
|
406
|
+
* response is returned as the official typed continuation payload.
|
|
407
|
+
*/
|
|
408
|
+
requestWithInputRequired(serverName, request, resultSchema, options) {
|
|
409
|
+
return this.#requestWithInputRequired(serverName, request, resultSchema, options);
|
|
410
|
+
}
|
|
411
|
+
/**
|
|
412
|
+
* Resumes one manual modern multi-round-trip round through a fresh official
|
|
413
|
+
* request. The server-owned `requestState` is echoed without interpretation.
|
|
414
|
+
* Only this round's `inputResponses` are included.
|
|
415
|
+
*/
|
|
416
|
+
resumeInputRequired(serverName, originalRequest, inputRequired, inputResponses, resultSchema, options) {
|
|
417
|
+
const stableOriginalRequest = snapshotProtocolValue(originalRequest, "MCP input-required original request");
|
|
418
|
+
const stableInputResponses = snapshotProtocolValue(inputResponses, "MCP input-required responses");
|
|
419
|
+
const params = { ...stableOriginalRequest.params };
|
|
420
|
+
Reflect.deleteProperty(params, "inputResponses");
|
|
421
|
+
Reflect.deleteProperty(params, "requestState");
|
|
422
|
+
if (Object.keys(stableInputResponses).length > 0) params.inputResponses = stableInputResponses;
|
|
423
|
+
if (inputRequired.requestState !== void 0) params.requestState = inputRequired.requestState;
|
|
424
|
+
return this.#requestWithInputRequired(serverName, {
|
|
425
|
+
method: stableOriginalRequest.method,
|
|
426
|
+
params
|
|
427
|
+
}, resultSchema, options);
|
|
428
|
+
}
|
|
429
|
+
/** Sends an official notification through runtime policy and lifecycle hooks. */
|
|
430
|
+
notification(serverName, notification, options) {
|
|
431
|
+
const stableNotification = snapshotProtocolValue(notification, "MCP client notification");
|
|
432
|
+
const stableOptions = snapshotProtocolValue(options, "MCP notification options");
|
|
433
|
+
return this.#delegate(serverName, {
|
|
434
|
+
method: stableNotification.method,
|
|
435
|
+
kind: "notification",
|
|
436
|
+
params: stableNotification.params,
|
|
437
|
+
options: stableOptions
|
|
438
|
+
}, (client) => client.notification(stableNotification, stableOptions));
|
|
439
|
+
}
|
|
440
|
+
/** Requests argument suggestions for a prompt or resource template. */
|
|
441
|
+
complete(serverName, params, options) {
|
|
442
|
+
const stableParams = snapshotProtocolValue(params, "MCP completion parameters");
|
|
443
|
+
const stableOptions = snapshotRequestOptions(options);
|
|
444
|
+
return this.#delegate(serverName, {
|
|
445
|
+
method: "completion/complete",
|
|
446
|
+
exactResultMethod: "completion/complete",
|
|
447
|
+
capability: "completions",
|
|
448
|
+
params: stableParams,
|
|
449
|
+
options: stableOptions,
|
|
450
|
+
signal: stableOptions?.signal
|
|
451
|
+
}, (client) => client.complete(stableParams, stableOptions));
|
|
452
|
+
}
|
|
453
|
+
/**
|
|
454
|
+
* Sets the minimum server log level on protocol eras that support it.
|
|
455
|
+
*
|
|
456
|
+
* @deprecated Deprecated by MCP 2026-07-28. Prefer stderr or OpenTelemetry.
|
|
457
|
+
*/
|
|
458
|
+
setLoggingLevel(serverName, level, options) {
|
|
459
|
+
const stableParams = snapshotProtocolValue({ level }, "MCP logging/setLevel parameters");
|
|
460
|
+
const stableOptions = snapshotRequestOptions(options);
|
|
461
|
+
return this.#delegate(serverName, {
|
|
462
|
+
method: "logging/setLevel",
|
|
463
|
+
exactResultMethod: "logging/setLevel",
|
|
464
|
+
capability: "logging",
|
|
465
|
+
params: stableParams,
|
|
466
|
+
options: stableOptions,
|
|
467
|
+
signal: stableOptions?.signal
|
|
468
|
+
}, (client) => client.setLoggingLevel(stableParams.level, stableOptions));
|
|
469
|
+
}
|
|
470
|
+
listTools(serverName, params, options) {
|
|
471
|
+
const stableParams = snapshotProtocolValue(params, "MCP tools/list parameters");
|
|
472
|
+
const stableOptions = snapshotRequestOptions(options);
|
|
473
|
+
return this.#delegate(serverName, {
|
|
474
|
+
method: "tools/list",
|
|
475
|
+
exactResultMethod: "tools/list",
|
|
476
|
+
capability: "tools",
|
|
477
|
+
params: stableParams,
|
|
478
|
+
options: stableOptions,
|
|
479
|
+
signal: stableOptions?.signal
|
|
480
|
+
}, (client) => client.listTools(stableParams, stableOptions));
|
|
481
|
+
}
|
|
482
|
+
callTool(serverName, params, options) {
|
|
483
|
+
const stableParams = snapshotProtocolValue(params, "MCP tools/call parameters");
|
|
484
|
+
const stableOptions = snapshotRequestOptions(options);
|
|
485
|
+
return this.#delegate(serverName, {
|
|
486
|
+
method: "tools/call",
|
|
487
|
+
exactResultMethod: "tools/call",
|
|
488
|
+
capability: "tools",
|
|
489
|
+
params: stableParams,
|
|
490
|
+
options: stableOptions,
|
|
491
|
+
signal: stableOptions?.signal
|
|
492
|
+
}, (client) => client.callTool(stableParams, stableOptions));
|
|
493
|
+
}
|
|
494
|
+
listResources(serverName, params, options) {
|
|
495
|
+
const stableParams = snapshotProtocolValue(params, "MCP resources/list parameters");
|
|
496
|
+
const stableOptions = snapshotRequestOptions(options);
|
|
497
|
+
return this.#delegate(serverName, {
|
|
498
|
+
method: "resources/list",
|
|
499
|
+
exactResultMethod: "resources/list",
|
|
500
|
+
capability: "resources",
|
|
501
|
+
params: stableParams,
|
|
502
|
+
options: stableOptions,
|
|
503
|
+
signal: stableOptions?.signal
|
|
504
|
+
}, (client) => client.listResources(stableParams, stableOptions));
|
|
505
|
+
}
|
|
506
|
+
listResourceTemplates(serverName, params, options) {
|
|
507
|
+
const stableParams = snapshotProtocolValue(params, "MCP resources/templates/list parameters");
|
|
508
|
+
const stableOptions = snapshotRequestOptions(options);
|
|
509
|
+
return this.#delegate(serverName, {
|
|
510
|
+
method: "resources/templates/list",
|
|
511
|
+
exactResultMethod: "resources/templates/list",
|
|
512
|
+
capability: "resources",
|
|
513
|
+
params: stableParams,
|
|
514
|
+
options: stableOptions,
|
|
515
|
+
signal: stableOptions?.signal
|
|
516
|
+
}, (client) => client.listResourceTemplates(stableParams, stableOptions));
|
|
517
|
+
}
|
|
518
|
+
readResource(serverName, params, options) {
|
|
519
|
+
const stableParams = snapshotProtocolValue(params, "MCP resources/read parameters");
|
|
520
|
+
const stableOptions = snapshotRequestOptions(options);
|
|
521
|
+
return this.#delegate(serverName, {
|
|
522
|
+
method: "resources/read",
|
|
523
|
+
exactResultMethod: "resources/read",
|
|
524
|
+
capability: "resources",
|
|
525
|
+
params: stableParams,
|
|
526
|
+
options: stableOptions,
|
|
527
|
+
signal: stableOptions?.signal
|
|
528
|
+
}, (client) => client.readResource(stableParams, stableOptions));
|
|
529
|
+
}
|
|
530
|
+
/** Uses the legacy-era per-resource subscription request. */
|
|
531
|
+
subscribeResource(serverName, params, options) {
|
|
532
|
+
const stableParams = snapshotProtocolValue(params, "MCP resources/subscribe parameters");
|
|
533
|
+
const stableOptions = snapshotRequestOptions(options);
|
|
534
|
+
return this.#delegate(serverName, {
|
|
535
|
+
method: "resources/subscribe",
|
|
536
|
+
exactResultMethod: "resources/subscribe",
|
|
537
|
+
capability: "resources",
|
|
538
|
+
params: stableParams,
|
|
539
|
+
options: stableOptions,
|
|
540
|
+
signal: stableOptions?.signal
|
|
541
|
+
}, (client) => client.subscribeResource(stableParams, stableOptions));
|
|
542
|
+
}
|
|
543
|
+
/** Uses the legacy-era per-resource unsubscribe request. */
|
|
544
|
+
unsubscribeResource(serverName, params, options) {
|
|
545
|
+
const stableParams = snapshotProtocolValue(params, "MCP resources/unsubscribe parameters");
|
|
546
|
+
const stableOptions = snapshotRequestOptions(options);
|
|
547
|
+
return this.#delegate(serverName, {
|
|
548
|
+
method: "resources/unsubscribe",
|
|
549
|
+
exactResultMethod: "resources/unsubscribe",
|
|
550
|
+
capability: "resources",
|
|
551
|
+
params: stableParams,
|
|
552
|
+
options: stableOptions,
|
|
553
|
+
signal: stableOptions?.signal
|
|
554
|
+
}, (client) => client.unsubscribeResource(stableParams, stableOptions));
|
|
555
|
+
}
|
|
556
|
+
/**
|
|
557
|
+
* Opens a modern change-notification stream and binds it to this runtime's
|
|
558
|
+
* connection lifecycle. Register notification handlers in `configureClient`
|
|
559
|
+
* before connecting.
|
|
560
|
+
*/
|
|
561
|
+
async listen(serverName, filter, options) {
|
|
562
|
+
const stableFilter = snapshotProtocolValue(filter, "MCP subscription filter");
|
|
563
|
+
const stableOptions = snapshotRequestOptions(options);
|
|
564
|
+
const lifecycleEpoch = this.#lifecycleEpoch;
|
|
565
|
+
const entry = this.#entry(serverName);
|
|
566
|
+
return this.#delegate(serverName, {
|
|
567
|
+
method: "subscriptions/listen",
|
|
568
|
+
capability: "subscriptions",
|
|
569
|
+
params: stableFilter,
|
|
570
|
+
options: stableOptions,
|
|
571
|
+
signal: stableOptions?.signal
|
|
572
|
+
}, async (client) => {
|
|
573
|
+
const subscription = await client.listen(stableFilter, stableOptions);
|
|
574
|
+
try {
|
|
575
|
+
this.#assertOperationCurrent(entry, lifecycleEpoch);
|
|
576
|
+
} catch (entryError) {
|
|
577
|
+
return closeUnmanagedSubscription(subscription, entryError);
|
|
578
|
+
}
|
|
579
|
+
return this.#manageSubscription(entry, subscription);
|
|
580
|
+
});
|
|
581
|
+
}
|
|
582
|
+
/** Returns runtime-opened subscription streams for one logical server. */
|
|
583
|
+
activeSubscriptions(serverName) {
|
|
584
|
+
return Object.freeze([...this.#entry(serverName).subscriptions].map((subscription) => subscription.handle));
|
|
585
|
+
}
|
|
586
|
+
/** Returns the runtime-owned stream opened by `ClientOptions.listChanged`, when present. */
|
|
587
|
+
getAutoOpenedSubscription(serverName) {
|
|
588
|
+
return this.#entry(serverName).autoOpenedSubscription;
|
|
589
|
+
}
|
|
590
|
+
listPrompts(serverName, params, options) {
|
|
591
|
+
const stableParams = snapshotProtocolValue(params, "MCP prompts/list parameters");
|
|
592
|
+
const stableOptions = snapshotRequestOptions(options);
|
|
593
|
+
return this.#delegate(serverName, {
|
|
594
|
+
method: "prompts/list",
|
|
595
|
+
exactResultMethod: "prompts/list",
|
|
596
|
+
capability: "prompts",
|
|
597
|
+
params: stableParams,
|
|
598
|
+
options: stableOptions,
|
|
599
|
+
signal: stableOptions?.signal
|
|
600
|
+
}, (client) => client.listPrompts(stableParams, stableOptions));
|
|
601
|
+
}
|
|
602
|
+
getPrompt(serverName, params, options) {
|
|
603
|
+
const stableParams = snapshotProtocolValue(params, "MCP prompts/get parameters");
|
|
604
|
+
const stableOptions = snapshotRequestOptions(options);
|
|
605
|
+
return this.#delegate(serverName, {
|
|
606
|
+
method: "prompts/get",
|
|
607
|
+
exactResultMethod: "prompts/get",
|
|
608
|
+
capability: "prompts",
|
|
609
|
+
params: stableParams,
|
|
610
|
+
options: stableOptions,
|
|
611
|
+
signal: stableOptions?.signal
|
|
612
|
+
}, (client) => client.getPrompt(stableParams, stableOptions));
|
|
613
|
+
}
|
|
614
|
+
/**
|
|
615
|
+
* Notifies a legacy-era server that the client's roots changed.
|
|
616
|
+
*
|
|
617
|
+
* @deprecated Deprecated by MCP 2026-07-28. Pass paths through tool inputs,
|
|
618
|
+
* resource URIs, or configuration instead.
|
|
619
|
+
*/
|
|
620
|
+
sendRootsListChanged(serverName) {
|
|
621
|
+
return this.#delegate(serverName, {
|
|
622
|
+
method: "notifications/roots/list_changed",
|
|
623
|
+
kind: "notification",
|
|
624
|
+
capability: "roots"
|
|
625
|
+
}, (client) => client.sendRootsListChanged());
|
|
626
|
+
}
|
|
627
|
+
#manageSubscription(entry, sdkSubscription) {
|
|
628
|
+
let closeTask;
|
|
629
|
+
let settled = false;
|
|
630
|
+
let managed;
|
|
631
|
+
const handle = Object.freeze({
|
|
632
|
+
serverName: entry.definition.name,
|
|
633
|
+
honoredFilter: sdkSubscription.honoredFilter,
|
|
634
|
+
closed: sdkSubscription.closed,
|
|
635
|
+
close: () => {
|
|
636
|
+
if (settled) return Promise.resolve();
|
|
637
|
+
if (closeTask !== void 0) return closeTask;
|
|
638
|
+
const task = this.#runOperation(entry, {
|
|
639
|
+
method: "notifications/cancelled",
|
|
640
|
+
kind: "notification",
|
|
641
|
+
capability: "subscriptions"
|
|
642
|
+
}, () => sdkSubscription.close(), true);
|
|
643
|
+
closeTask = task;
|
|
644
|
+
task.catch(() => {
|
|
645
|
+
if (closeTask === task) closeTask = void 0;
|
|
646
|
+
});
|
|
647
|
+
return task;
|
|
648
|
+
}
|
|
649
|
+
});
|
|
650
|
+
managed = Object.freeze({
|
|
651
|
+
sdk: sdkSubscription,
|
|
652
|
+
handle
|
|
653
|
+
});
|
|
654
|
+
entry.subscriptions.add(managed);
|
|
655
|
+
sdkSubscription.closed.then(() => {
|
|
656
|
+
settled = true;
|
|
657
|
+
entry.subscriptions.delete(managed);
|
|
658
|
+
if (entry.autoOpenedSubscription === handle) entry.autoOpenedSubscription = void 0;
|
|
659
|
+
});
|
|
660
|
+
return handle;
|
|
661
|
+
}
|
|
662
|
+
#requestWithInputRequired(serverName, request, resultSchema, options) {
|
|
663
|
+
const stableRequest = snapshotProtocolValue(request, "MCP input-required request");
|
|
664
|
+
const requestOptions = snapshotRequestOptions({
|
|
665
|
+
...options,
|
|
666
|
+
allowInputRequired: true
|
|
667
|
+
});
|
|
668
|
+
return this.#delegate(serverName, {
|
|
669
|
+
method: stableRequest.method,
|
|
670
|
+
capability: MRTR_CAPABILITY[stableRequest.method],
|
|
671
|
+
params: stableRequest.params,
|
|
672
|
+
options: requestOptions,
|
|
673
|
+
signal: requestOptions.signal
|
|
674
|
+
}, (client) => client.request(stableRequest, withInputRequired$1(resultSchema), requestOptions));
|
|
675
|
+
}
|
|
676
|
+
#connectAttempt(serverName, options) {
|
|
677
|
+
this.#assertOpen();
|
|
678
|
+
const lifecycleEpoch = this.#lifecycleEpoch;
|
|
679
|
+
const entry = this.#entry(serverName);
|
|
680
|
+
this.#assertConnectAttemptCurrent(entry, lifecycleEpoch);
|
|
681
|
+
const connectOptions = mergeConnectOptions(entry, options);
|
|
682
|
+
return this.#runOperation(entry, {
|
|
683
|
+
method: "runtime/connect",
|
|
684
|
+
params: connectOptions.prior === void 0 ? void 0 : { prior: connectOptions.prior },
|
|
685
|
+
options: connectOptions,
|
|
686
|
+
signal: connectOptions.signal
|
|
687
|
+
}, () => {
|
|
688
|
+
this.#assertConnectAttemptCurrent(entry, lifecycleEpoch);
|
|
689
|
+
return this.#connectEntry(entry, connectOptions, lifecycleEpoch);
|
|
690
|
+
}).then((result) => {
|
|
691
|
+
this.#assertConnectAttemptCurrent(entry, lifecycleEpoch);
|
|
692
|
+
return result;
|
|
693
|
+
});
|
|
694
|
+
}
|
|
695
|
+
async #delegate(serverName, descriptor, terminal) {
|
|
696
|
+
this.#assertOpen();
|
|
697
|
+
const lifecycleEpoch = this.#lifecycleEpoch;
|
|
698
|
+
const entry = this.#entry(serverName);
|
|
699
|
+
this.#assertOperationCurrent(entry, lifecycleEpoch);
|
|
700
|
+
const result = await this.#runOperation(entry, descriptor, () => {
|
|
701
|
+
this.#assertOperationCurrent(entry, lifecycleEpoch);
|
|
702
|
+
const client = entry.state === "connected" && entry.client !== void 0 ? entry.client : void 0;
|
|
703
|
+
if (client === void 0) throw clientNotConnectedError(serverName);
|
|
704
|
+
return terminal(client);
|
|
705
|
+
});
|
|
706
|
+
this.#assertOperationCurrent(entry, lifecycleEpoch);
|
|
707
|
+
return result;
|
|
708
|
+
}
|
|
709
|
+
async #runOperation(entry, descriptor, terminal, requireTerminal = false) {
|
|
710
|
+
let terminalTask;
|
|
711
|
+
const invokeTerminal = () => {
|
|
712
|
+
terminalTask ??= Promise.resolve().then(terminal);
|
|
713
|
+
return terminalTask;
|
|
714
|
+
};
|
|
715
|
+
try {
|
|
716
|
+
const operationInput = freezeOperationInput(entry.definition.name, descriptor);
|
|
717
|
+
if (descriptor.exactResultMethod !== void 0 && !canReturnInputRequired(descriptor.exactResultMethod, descriptor.options)) markExactMcpClientResult(operationInput, descriptor.exactResultMethod);
|
|
718
|
+
const resolvedPrincipal = this.#resolvePrincipal === void 0 ? this.#principal : await this.#resolvePrincipal(operationInput);
|
|
719
|
+
const resolvedAttributes = this.#resolveAttributes === void 0 ? {} : await this.#resolveAttributes(operationInput);
|
|
720
|
+
const context = createMcpOperationContext({
|
|
721
|
+
operationId: this.#operationIdFactory(),
|
|
722
|
+
role: "client",
|
|
723
|
+
operation: {
|
|
724
|
+
name: descriptor.method,
|
|
725
|
+
kind: descriptor.kind ?? "request",
|
|
726
|
+
...descriptor.capability === void 0 ? {} : { capability: descriptor.capability },
|
|
727
|
+
target: entry.definition.name,
|
|
728
|
+
attributes: { transportKind: entry.definition.transport.kind }
|
|
729
|
+
},
|
|
730
|
+
...descriptor.signal === void 0 ? {} : { signal: descriptor.signal },
|
|
731
|
+
...entry.transport?.sessionId === void 0 ? {} : { sessionId: entry.transport.sessionId },
|
|
732
|
+
...resolvedPrincipal === void 0 ? {} : { principal: resolvedPrincipal },
|
|
733
|
+
attributes: {
|
|
734
|
+
...this.#attributes,
|
|
735
|
+
...entry.definition.attributes,
|
|
736
|
+
...resolvedAttributes
|
|
737
|
+
}
|
|
738
|
+
});
|
|
739
|
+
const operation = createMcpOperation(operationInput, context);
|
|
740
|
+
const middleware = this.#lifecycleMiddleware === void 0 ? [] : [this.#lifecycleMiddleware];
|
|
741
|
+
if (requireTerminal) middleware.push(async (_operation, next) => {
|
|
742
|
+
try {
|
|
743
|
+
await next();
|
|
744
|
+
} catch (middlewareError) {
|
|
745
|
+
return invokeRequiredTerminal(invokeTerminal, middlewareError);
|
|
746
|
+
}
|
|
747
|
+
return invokeTerminal();
|
|
748
|
+
});
|
|
749
|
+
middleware.push(...this.#middleware, ...this.#transforms);
|
|
750
|
+
return await composeMcpMiddleware(middleware, requireTerminal ? invokeTerminal : terminal)(operation);
|
|
751
|
+
} catch (operationError) {
|
|
752
|
+
if (!requireTerminal || terminalTask !== void 0) throw operationError;
|
|
753
|
+
return invokeRequiredTerminal(invokeTerminal, operationError);
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
async #connectEntry(entry, options, lifecycleEpoch) {
|
|
757
|
+
this.#assertConnectAttemptCurrent(entry, lifecycleEpoch);
|
|
758
|
+
options.signal?.throwIfAborted();
|
|
759
|
+
if (entry.state === "connected" && entry.client !== void 0) return {
|
|
760
|
+
client: entry.client,
|
|
761
|
+
generation: entry.connectionGeneration
|
|
762
|
+
};
|
|
763
|
+
if (entry.connectTask !== void 0) {
|
|
764
|
+
const { client, generation } = await observeConnectAttempt(entry.connectTask, entry.connectDetachment?.promise, options.signal);
|
|
765
|
+
return {
|
|
766
|
+
client,
|
|
767
|
+
generation
|
|
768
|
+
};
|
|
769
|
+
}
|
|
770
|
+
if (entry.disconnectTask !== void 0) {
|
|
771
|
+
await entry.disconnectTask;
|
|
772
|
+
this.#assertConnectAttemptCurrent(entry, lifecycleEpoch);
|
|
773
|
+
return this.#connectEntry(entry, options, lifecycleEpoch);
|
|
774
|
+
}
|
|
775
|
+
entry.state = "connecting";
|
|
776
|
+
entry.connectedAt = void 0;
|
|
777
|
+
entry.disconnectedAt = void 0;
|
|
778
|
+
entry.lastError = void 0;
|
|
779
|
+
const connectionToken = Symbol(entry.definition.name);
|
|
780
|
+
const connectAttemptToken = Symbol(`${entry.definition.name}:connect-attempt`);
|
|
781
|
+
const connectAbortController = new AbortController();
|
|
782
|
+
const connectDetachment = createConnectAttemptDetachment();
|
|
783
|
+
const unlinkCallerSignal = linkAbortSignal(options.signal, connectAbortController);
|
|
784
|
+
const connectOptions = {
|
|
785
|
+
...options,
|
|
786
|
+
signal: connectAbortController.signal
|
|
787
|
+
};
|
|
788
|
+
entry.connectAttemptToken = connectAttemptToken;
|
|
789
|
+
entry.connectAbortController = connectAbortController;
|
|
790
|
+
entry.connectDetachment = connectDetachment;
|
|
791
|
+
entry.connectUnlinkCallerSignal = unlinkCallerSignal;
|
|
792
|
+
const task = this.#establishConnection(entry, connectOptions, connectionToken, connectAttemptToken, lifecycleEpoch);
|
|
793
|
+
entry.connectTask = task;
|
|
794
|
+
task.then(() => {
|
|
795
|
+
this.#releaseConnectAttempt(entry, task, connectAttemptToken);
|
|
796
|
+
}, () => {
|
|
797
|
+
this.#releaseConnectAttempt(entry, task, connectAttemptToken);
|
|
798
|
+
});
|
|
799
|
+
const established = await observeConnectAttempt(task, connectDetachment.promise, options.signal);
|
|
800
|
+
return {
|
|
801
|
+
client: established.client,
|
|
802
|
+
generation: established.generation,
|
|
803
|
+
ownedConnectionToken: established.connectionToken
|
|
804
|
+
};
|
|
805
|
+
}
|
|
806
|
+
async #establishConnection(entry, options, connectionToken, connectAttemptToken, lifecycleEpoch) {
|
|
807
|
+
const definition = entry.definition;
|
|
808
|
+
const clientOptions = resolveClientOptions(definition.clientOptions);
|
|
809
|
+
const client = this.#clientFactory.createClient(definition.clientInfo ?? this.#clientInfo, clientOptions, {
|
|
810
|
+
serverName: definition.name,
|
|
811
|
+
definition
|
|
812
|
+
});
|
|
813
|
+
entry.client = client;
|
|
814
|
+
let unownedTransport;
|
|
815
|
+
try {
|
|
816
|
+
options.signal.throwIfAborted();
|
|
817
|
+
await definition.configureClient?.(client, {
|
|
818
|
+
serverName: definition.name,
|
|
819
|
+
definition
|
|
820
|
+
});
|
|
821
|
+
options.signal.throwIfAborted();
|
|
822
|
+
this.#assertConnectAttemptCurrent(entry, lifecycleEpoch, connectAttemptToken);
|
|
823
|
+
this.#attachClientLifecycle(entry, client);
|
|
824
|
+
unownedTransport = await (definition.transportFactory ?? this.#transportFactory).createTransport(definition.transport, {
|
|
825
|
+
serverName: definition.name,
|
|
826
|
+
signal: options.signal
|
|
827
|
+
});
|
|
828
|
+
options.signal.throwIfAborted();
|
|
829
|
+
this.#assertConnectAttemptCurrent(entry, lifecycleEpoch, connectAttemptToken);
|
|
830
|
+
const transport = unownedTransport;
|
|
831
|
+
entry.transport = transport;
|
|
832
|
+
unownedTransport = void 0;
|
|
833
|
+
await client.connect(transport, options);
|
|
834
|
+
options.signal.throwIfAborted();
|
|
835
|
+
this.#assertConnectAttemptCurrent(entry, lifecycleEpoch, connectAttemptToken);
|
|
836
|
+
if (client.autoOpenedSubscription !== void 0) entry.autoOpenedSubscription = this.#manageSubscription(entry, client.autoOpenedSubscription);
|
|
837
|
+
entry.connectionGeneration += 1;
|
|
838
|
+
entry.connectionToken = connectionToken;
|
|
839
|
+
entry.state = "connected";
|
|
840
|
+
entry.connectedAt = this.#timestamp();
|
|
841
|
+
entry.lastError = void 0;
|
|
842
|
+
this.#refreshMetadata(entry);
|
|
843
|
+
return {
|
|
844
|
+
client,
|
|
845
|
+
generation: entry.connectionGeneration,
|
|
846
|
+
connectionToken
|
|
847
|
+
};
|
|
848
|
+
} catch (error) {
|
|
849
|
+
const failure = await closeAfterFailedConnect(client, error, unownedTransport);
|
|
850
|
+
if (entry.connectAttemptToken === connectAttemptToken) {
|
|
851
|
+
entry.state = "failed";
|
|
852
|
+
entry.lastError = toMcpErrorDetails(failure);
|
|
853
|
+
if (entry.client === client) {
|
|
854
|
+
entry.client = void 0;
|
|
855
|
+
entry.transport = void 0;
|
|
856
|
+
entry.connectionToken = void 0;
|
|
857
|
+
entry.subscriptions.clear();
|
|
858
|
+
entry.autoOpenedSubscription = void 0;
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
throw failure;
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
#attachClientLifecycle(entry, client) {
|
|
865
|
+
const configuredOnClose = client.onclose;
|
|
866
|
+
client.onclose = () => {
|
|
867
|
+
if (entry.client === client && entry.state === "connected") {
|
|
868
|
+
this.#refreshMetadata(entry);
|
|
869
|
+
entry.state = "disconnected";
|
|
870
|
+
entry.disconnectedAt = this.#timestamp();
|
|
871
|
+
entry.client = void 0;
|
|
872
|
+
entry.transport = void 0;
|
|
873
|
+
entry.connectionToken = void 0;
|
|
874
|
+
entry.subscriptions.clear();
|
|
875
|
+
entry.autoOpenedSubscription = void 0;
|
|
876
|
+
}
|
|
877
|
+
configuredOnClose?.();
|
|
878
|
+
};
|
|
879
|
+
const configuredOnError = client.onerror;
|
|
880
|
+
client.onerror = (error) => {
|
|
881
|
+
entry.lastError = toMcpErrorDetails(error);
|
|
882
|
+
configuredOnError?.(error);
|
|
883
|
+
};
|
|
884
|
+
}
|
|
885
|
+
#disconnectEntry(entry) {
|
|
886
|
+
if (entry.disconnectTask !== void 0) return entry.disconnectTask;
|
|
887
|
+
const disconnectToken = Symbol(`${entry.definition.name}:disconnect`);
|
|
888
|
+
entry.disconnectToken = disconnectToken;
|
|
889
|
+
const task = this.#performDisconnect(entry, disconnectToken);
|
|
890
|
+
entry.disconnectTask = task;
|
|
891
|
+
task.then(() => {
|
|
892
|
+
this.#releaseDisconnect(entry, task, disconnectToken);
|
|
893
|
+
}, () => {
|
|
894
|
+
this.#releaseDisconnect(entry, task, disconnectToken);
|
|
895
|
+
});
|
|
896
|
+
return task;
|
|
897
|
+
}
|
|
898
|
+
async #performDisconnect(entry, disconnectToken) {
|
|
899
|
+
const failures = [];
|
|
900
|
+
const deadline = performance.now() + this.#shutdownTimeoutMs;
|
|
901
|
+
let timedOut = false;
|
|
902
|
+
const connectTask = entry.connectTask;
|
|
903
|
+
const connectAttemptToken = entry.connectAttemptToken;
|
|
904
|
+
if (connectTask !== void 0) {
|
|
905
|
+
if ((await settleTaskWithin(connectTask, remainingTime(deadline))).status === "timeout") {
|
|
906
|
+
timedOut = true;
|
|
907
|
+
const timeoutError = shutdownTimeoutError(entry.definition.name, this.#shutdownTimeoutMs);
|
|
908
|
+
failures.push(timeoutError);
|
|
909
|
+
entry.connectDetachment?.detach(timeoutError);
|
|
910
|
+
this.#releaseConnectAttempt(entry, connectTask, connectAttemptToken);
|
|
911
|
+
}
|
|
912
|
+
}
|
|
913
|
+
const client = entry.client;
|
|
914
|
+
if (client === void 0) {
|
|
915
|
+
entry.state = "disconnected";
|
|
916
|
+
entry.disconnectedAt = this.#timestamp();
|
|
917
|
+
entry.transport = void 0;
|
|
918
|
+
entry.connectionToken = void 0;
|
|
919
|
+
entry.subscriptions.clear();
|
|
920
|
+
entry.autoOpenedSubscription = void 0;
|
|
921
|
+
} else {
|
|
922
|
+
entry.state = "disconnecting";
|
|
923
|
+
this.#refreshMetadata(entry);
|
|
924
|
+
const cleanupFailures = [];
|
|
925
|
+
const cleanupTimedOut = await this.#closeConnection(entry, client, disconnectToken, cleanupFailures, deadline);
|
|
926
|
+
failures.push(...cleanupFailures);
|
|
927
|
+
if (cleanupTimedOut && !timedOut) {
|
|
928
|
+
timedOut = true;
|
|
929
|
+
failures.push(shutdownTimeoutError(entry.definition.name, this.#shutdownTimeoutMs));
|
|
930
|
+
}
|
|
931
|
+
}
|
|
932
|
+
if (failures.length === 0) return;
|
|
933
|
+
const failure = failures.length === 1 ? failures[0] : new AggregateError(failures, `The MCP server ${JSON.stringify(entry.definition.name)} did not shut down cleanly.`);
|
|
934
|
+
entry.state = "failed";
|
|
935
|
+
entry.lastError = toMcpErrorDetails(failure);
|
|
936
|
+
throw failure;
|
|
937
|
+
}
|
|
938
|
+
async #closeConnection(entry, client, disconnectToken, failures, deadline) {
|
|
939
|
+
let timedOut = false;
|
|
940
|
+
const subscriptionOutcome = await settleTaskWithin(Promise.all([...entry.subscriptions].map(async (subscription) => {
|
|
941
|
+
try {
|
|
942
|
+
await subscription.handle.close();
|
|
943
|
+
} catch (error) {
|
|
944
|
+
failures.push(error);
|
|
945
|
+
}
|
|
946
|
+
})), remainingTime(deadline));
|
|
947
|
+
switch (subscriptionOutcome.status) {
|
|
948
|
+
case "fulfilled": break;
|
|
949
|
+
case "rejected":
|
|
950
|
+
failures.push(subscriptionOutcome.reason);
|
|
951
|
+
break;
|
|
952
|
+
case "timeout": timedOut = true;
|
|
953
|
+
}
|
|
954
|
+
const clientCloseOutcome = await settleTaskWithin(Promise.resolve().then(() => client.close()), remainingTime(deadline));
|
|
955
|
+
switch (clientCloseOutcome.status) {
|
|
956
|
+
case "fulfilled": break;
|
|
957
|
+
case "rejected":
|
|
958
|
+
failures.push(clientCloseOutcome.reason);
|
|
959
|
+
break;
|
|
960
|
+
case "timeout": timedOut = true;
|
|
961
|
+
}
|
|
962
|
+
if (entry.disconnectToken === disconnectToken) this.#detachConnection(entry, client);
|
|
963
|
+
if (entry.disconnectToken !== disconnectToken) return timedOut;
|
|
964
|
+
entry.disconnectedAt = this.#timestamp();
|
|
965
|
+
if (failures.length === 0) entry.state = "disconnected";
|
|
966
|
+
return timedOut;
|
|
967
|
+
}
|
|
968
|
+
#detachConnection(entry, client) {
|
|
969
|
+
entry.subscriptions.clear();
|
|
970
|
+
entry.autoOpenedSubscription = void 0;
|
|
971
|
+
if (entry.client === client) {
|
|
972
|
+
entry.client = void 0;
|
|
973
|
+
entry.transport = void 0;
|
|
974
|
+
entry.connectionToken = void 0;
|
|
975
|
+
}
|
|
976
|
+
}
|
|
977
|
+
#releaseDisconnect(entry, task, disconnectToken) {
|
|
978
|
+
if (entry.disconnectTask === task) entry.disconnectTask = void 0;
|
|
979
|
+
if (entry.disconnectToken === disconnectToken) entry.disconnectToken = void 0;
|
|
980
|
+
}
|
|
981
|
+
#snapshotEntry(entry) {
|
|
982
|
+
this.#refreshMetadata(entry);
|
|
983
|
+
return Object.freeze({
|
|
984
|
+
name: entry.definition.name,
|
|
985
|
+
state: entry.state,
|
|
986
|
+
transportKind: entry.definition.transport.kind,
|
|
987
|
+
...entry.metadata.sessionId === void 0 ? {} : { sessionId: entry.metadata.sessionId },
|
|
988
|
+
...entry.connectedAt === void 0 ? {} : { connectedAt: entry.connectedAt },
|
|
989
|
+
...entry.disconnectedAt === void 0 ? {} : { disconnectedAt: entry.disconnectedAt },
|
|
990
|
+
...entry.metadata.negotiatedProtocolVersion === void 0 ? {} : { negotiatedProtocolVersion: entry.metadata.negotiatedProtocolVersion },
|
|
991
|
+
...entry.metadata.protocolEra === void 0 ? {} : { protocolEra: entry.metadata.protocolEra },
|
|
992
|
+
...entry.metadata.serverInfo === void 0 ? {} : { serverInfo: entry.metadata.serverInfo },
|
|
993
|
+
...entry.metadata.serverCapabilities === void 0 ? {} : { serverCapabilities: entry.metadata.serverCapabilities },
|
|
994
|
+
...entry.metadata.instructions === void 0 ? {} : { instructions: entry.metadata.instructions },
|
|
995
|
+
...entry.metadata.discoverResult === void 0 ? {} : { discoverResult: entry.metadata.discoverResult },
|
|
996
|
+
...entry.lastError === void 0 ? {} : { lastError: entry.lastError }
|
|
997
|
+
});
|
|
998
|
+
}
|
|
999
|
+
#refreshMetadata(entry) {
|
|
1000
|
+
const client = entry.client;
|
|
1001
|
+
if (client === void 0) return;
|
|
1002
|
+
entry.metadata.sessionId = entry.transport?.sessionId;
|
|
1003
|
+
entry.metadata.negotiatedProtocolVersion = client.getNegotiatedProtocolVersion();
|
|
1004
|
+
entry.metadata.protocolEra = client.getProtocolEra();
|
|
1005
|
+
entry.metadata.serverInfo = client.getServerVersion();
|
|
1006
|
+
entry.metadata.serverCapabilities = client.getServerCapabilities();
|
|
1007
|
+
entry.metadata.instructions = client.getInstructions();
|
|
1008
|
+
entry.metadata.discoverResult = client.getDiscoverResult();
|
|
1009
|
+
}
|
|
1010
|
+
#entry(serverName, allowRetired = false) {
|
|
1011
|
+
const entry = this.#entries.get(serverName);
|
|
1012
|
+
if (entry === void 0 || !allowRetired && entry.retired) throw serverNotFoundError(serverName);
|
|
1013
|
+
return entry;
|
|
1014
|
+
}
|
|
1015
|
+
#assertOpen() {
|
|
1016
|
+
if (this.#closed) throw runtimeClosedError();
|
|
1017
|
+
}
|
|
1018
|
+
#abortConnectAttempt(entry, reason) {
|
|
1019
|
+
entry.connectAbortController?.abort(reason);
|
|
1020
|
+
}
|
|
1021
|
+
#releaseConnectAttempt(entry, task, connectAttemptToken) {
|
|
1022
|
+
if (entry.connectTask === task) entry.connectTask = void 0;
|
|
1023
|
+
if (connectAttemptToken !== void 0 && entry.connectAttemptToken === connectAttemptToken) {
|
|
1024
|
+
entry.connectUnlinkCallerSignal?.();
|
|
1025
|
+
entry.connectAttemptToken = void 0;
|
|
1026
|
+
entry.connectAbortController = void 0;
|
|
1027
|
+
entry.connectDetachment = void 0;
|
|
1028
|
+
entry.connectUnlinkCallerSignal = void 0;
|
|
1029
|
+
}
|
|
1030
|
+
}
|
|
1031
|
+
#assertConnectAttemptCurrent(entry, lifecycleEpoch, connectAttemptToken) {
|
|
1032
|
+
if (connectAttemptToken !== void 0 && entry.connectAttemptToken !== connectAttemptToken) throw staleConnectAttemptError(entry, this.#closed);
|
|
1033
|
+
this.#assertOperationCurrent(entry, lifecycleEpoch);
|
|
1034
|
+
}
|
|
1035
|
+
#assertOperationCurrent(entry, lifecycleEpoch) {
|
|
1036
|
+
if (this.#closed || lifecycleEpoch !== this.#lifecycleEpoch) throw runtimeClosedError();
|
|
1037
|
+
this.#assertEntryActive(entry);
|
|
1038
|
+
}
|
|
1039
|
+
#assertEntryActive(entry) {
|
|
1040
|
+
if (entry.retired || this.#entries.get(entry.definition.name) !== entry) throw serverNotFoundError(entry.definition.name);
|
|
1041
|
+
}
|
|
1042
|
+
#timestamp() {
|
|
1043
|
+
const timestamp = this.#now();
|
|
1044
|
+
if (!Number.isFinite(timestamp)) throw new TypeError("Runtime clock must return a finite timestamp.");
|
|
1045
|
+
return timestamp;
|
|
1046
|
+
}
|
|
1047
|
+
};
|
|
1048
|
+
function createRegistryEntry(definition) {
|
|
1049
|
+
return {
|
|
1050
|
+
definition,
|
|
1051
|
+
state: "disconnected",
|
|
1052
|
+
prior: definition.prior ?? definition.connectOptions?.prior,
|
|
1053
|
+
client: void 0,
|
|
1054
|
+
transport: void 0,
|
|
1055
|
+
connectTask: void 0,
|
|
1056
|
+
connectAbortController: void 0,
|
|
1057
|
+
connectAttemptToken: void 0,
|
|
1058
|
+
connectDetachment: void 0,
|
|
1059
|
+
connectUnlinkCallerSignal: void 0,
|
|
1060
|
+
disconnectTask: void 0,
|
|
1061
|
+
disconnectToken: void 0,
|
|
1062
|
+
connectedAt: void 0,
|
|
1063
|
+
disconnectedAt: void 0,
|
|
1064
|
+
lastError: void 0,
|
|
1065
|
+
subscriptions: /* @__PURE__ */ new Set(),
|
|
1066
|
+
autoOpenedSubscription: void 0,
|
|
1067
|
+
connectionGeneration: 0,
|
|
1068
|
+
connectionToken: void 0,
|
|
1069
|
+
retired: false,
|
|
1070
|
+
metadata: {
|
|
1071
|
+
sessionId: void 0,
|
|
1072
|
+
negotiatedProtocolVersion: void 0,
|
|
1073
|
+
protocolEra: void 0,
|
|
1074
|
+
serverInfo: void 0,
|
|
1075
|
+
serverCapabilities: void 0,
|
|
1076
|
+
instructions: void 0,
|
|
1077
|
+
discoverResult: void 0
|
|
1078
|
+
}
|
|
1079
|
+
};
|
|
1080
|
+
}
|
|
1081
|
+
async function invokeRequiredTerminal(terminal, primaryError) {
|
|
1082
|
+
try {
|
|
1083
|
+
await terminal();
|
|
1084
|
+
} catch (cleanupError) {
|
|
1085
|
+
if (cleanupError !== primaryError) throw new AggregateError([primaryError, cleanupError], "MCP cleanup middleware and its required terminal both failed.", { cause: cleanupError });
|
|
1086
|
+
}
|
|
1087
|
+
throw primaryError;
|
|
1088
|
+
}
|
|
1089
|
+
async function closeUnmanagedSubscription(subscription, primaryError) {
|
|
1090
|
+
try {
|
|
1091
|
+
await subscription.close();
|
|
1092
|
+
} catch (cleanupError) {
|
|
1093
|
+
throw new AggregateError([primaryError, cleanupError], "The MCP subscription opened for a retired client failed to close.", { cause: cleanupError });
|
|
1094
|
+
}
|
|
1095
|
+
throw primaryError;
|
|
1096
|
+
}
|
|
1097
|
+
function toOfficialProtocolRequest(request) {
|
|
1098
|
+
return {
|
|
1099
|
+
method: request.method,
|
|
1100
|
+
...!("params" in request) || request.params === void 0 ? {} : { params: request.params }
|
|
1101
|
+
};
|
|
1102
|
+
}
|
|
1103
|
+
function normalizeServerDefinition(definition) {
|
|
1104
|
+
if (typeof definition !== "object" || definition === null) throw new TypeError("MCP server definition must be an object.");
|
|
1105
|
+
assertNonEmpty(definition.name, "server name");
|
|
1106
|
+
if (typeof definition.transport !== "object" || definition.transport === null) throw new TypeError("MCP server transport definition must be an object.");
|
|
1107
|
+
let transport;
|
|
1108
|
+
switch (definition.transport.kind) {
|
|
1109
|
+
case "http":
|
|
1110
|
+
transport = Object.freeze({
|
|
1111
|
+
...definition.transport,
|
|
1112
|
+
...definition.transport.middleware === void 0 ? {} : { middleware: Object.freeze([...definition.transport.middleware]) }
|
|
1113
|
+
});
|
|
1114
|
+
break;
|
|
1115
|
+
case "stdio":
|
|
1116
|
+
transport = Object.freeze({
|
|
1117
|
+
...definition.transport,
|
|
1118
|
+
...definition.transport.args === void 0 ? {} : { args: Object.freeze([...definition.transport.args]) },
|
|
1119
|
+
...definition.transport.env === void 0 ? {} : { env: Object.freeze({ ...definition.transport.env }) }
|
|
1120
|
+
});
|
|
1121
|
+
break;
|
|
1122
|
+
default: throw new TypeError("MCP server transport kind must be http or stdio.");
|
|
1123
|
+
}
|
|
1124
|
+
return Object.freeze({
|
|
1125
|
+
...definition,
|
|
1126
|
+
transport,
|
|
1127
|
+
...definition.clientInfo === void 0 ? {} : { clientInfo: Object.freeze({ ...definition.clientInfo }) },
|
|
1128
|
+
...definition.clientOptions === void 0 ? {} : { clientOptions: { ...definition.clientOptions } },
|
|
1129
|
+
...definition.connectOptions === void 0 ? {} : { connectOptions: { ...definition.connectOptions } },
|
|
1130
|
+
...definition.attributes === void 0 ? {} : { attributes: Object.freeze({ ...definition.attributes }) }
|
|
1131
|
+
});
|
|
1132
|
+
}
|
|
1133
|
+
function resolveClientOptions(options) {
|
|
1134
|
+
return {
|
|
1135
|
+
...options,
|
|
1136
|
+
versionNegotiation: {
|
|
1137
|
+
...options?.versionNegotiation,
|
|
1138
|
+
mode: options?.versionNegotiation?.mode ?? "auto"
|
|
1139
|
+
}
|
|
1140
|
+
};
|
|
1141
|
+
}
|
|
1142
|
+
function mergeConnectOptions(entry, override) {
|
|
1143
|
+
const configured = entry.definition.connectOptions;
|
|
1144
|
+
const prior = override?.prior ?? entry.prior ?? configured?.prior;
|
|
1145
|
+
return {
|
|
1146
|
+
...configured,
|
|
1147
|
+
...override,
|
|
1148
|
+
...prior === void 0 ? {} : { prior }
|
|
1149
|
+
};
|
|
1150
|
+
}
|
|
1151
|
+
function linkAbortSignal(source, target) {
|
|
1152
|
+
if (source === void 0) return () => void 0;
|
|
1153
|
+
const abort = () => target.abort(source.reason);
|
|
1154
|
+
if (source.aborted) {
|
|
1155
|
+
abort();
|
|
1156
|
+
return () => void 0;
|
|
1157
|
+
}
|
|
1158
|
+
source.addEventListener("abort", abort, { once: true });
|
|
1159
|
+
return () => source.removeEventListener("abort", abort);
|
|
1160
|
+
}
|
|
1161
|
+
function observeConnectAttempt(task, detachment, callerSignal) {
|
|
1162
|
+
const alternatives = [task];
|
|
1163
|
+
if (detachment !== void 0) alternatives.push(detachment);
|
|
1164
|
+
if (callerSignal === void 0) return alternatives.length === 1 ? task : Promise.race(alternatives);
|
|
1165
|
+
if (callerSignal.aborted) return Promise.reject(abortReason$1(callerSignal));
|
|
1166
|
+
return new Promise((resolve, reject) => {
|
|
1167
|
+
const aborted = () => reject(abortReason$1(callerSignal));
|
|
1168
|
+
callerSignal.addEventListener("abort", aborted, { once: true });
|
|
1169
|
+
Promise.race(alternatives).then((value) => {
|
|
1170
|
+
callerSignal.removeEventListener("abort", aborted);
|
|
1171
|
+
resolve(value);
|
|
1172
|
+
}, (error) => {
|
|
1173
|
+
callerSignal.removeEventListener("abort", aborted);
|
|
1174
|
+
reject(error);
|
|
1175
|
+
});
|
|
1176
|
+
});
|
|
1177
|
+
}
|
|
1178
|
+
function staleConnectAttemptError(entry, runtimeClosed) {
|
|
1179
|
+
if (runtimeClosed) return runtimeClosedError();
|
|
1180
|
+
return entry.retired ? serverNotFoundError(entry.definition.name) : connectionAbortedError(entry.definition.name);
|
|
1181
|
+
}
|
|
1182
|
+
function abortReason$1(signal) {
|
|
1183
|
+
return signal.reason ?? new DOMException("The MCP connection was aborted.", "AbortError");
|
|
1184
|
+
}
|
|
1185
|
+
function createConnectAttemptDetachment() {
|
|
1186
|
+
let detach;
|
|
1187
|
+
let detached = false;
|
|
1188
|
+
return {
|
|
1189
|
+
promise: new Promise((_resolve, reject) => {
|
|
1190
|
+
detach = reject;
|
|
1191
|
+
}),
|
|
1192
|
+
detach(error) {
|
|
1193
|
+
if (detached) return;
|
|
1194
|
+
detached = true;
|
|
1195
|
+
detach?.(error);
|
|
1196
|
+
}
|
|
1197
|
+
};
|
|
1198
|
+
}
|
|
1199
|
+
async function settleTaskWithin(task, timeoutMs) {
|
|
1200
|
+
let timeout;
|
|
1201
|
+
const expired = new Promise((resolve) => {
|
|
1202
|
+
timeout = setTimeout(resolve, timeoutMs, { status: "timeout" });
|
|
1203
|
+
});
|
|
1204
|
+
try {
|
|
1205
|
+
return await Promise.race([task.then((value) => ({
|
|
1206
|
+
status: "fulfilled",
|
|
1207
|
+
value
|
|
1208
|
+
}), (reason) => ({
|
|
1209
|
+
status: "rejected",
|
|
1210
|
+
reason
|
|
1211
|
+
})), expired]);
|
|
1212
|
+
} finally {
|
|
1213
|
+
if (timeout !== void 0) clearTimeout(timeout);
|
|
1214
|
+
}
|
|
1215
|
+
}
|
|
1216
|
+
function remainingTime(deadline) {
|
|
1217
|
+
return Math.max(0, deadline - performance.now());
|
|
1218
|
+
}
|
|
1219
|
+
function connectionAbortedError(serverName) {
|
|
1220
|
+
return new DOMException(`The MCP server ${JSON.stringify(serverName)} connection was disconnected.`, "AbortError");
|
|
1221
|
+
}
|
|
1222
|
+
function freezeOperationInput(serverName, descriptor) {
|
|
1223
|
+
return Object.freeze({
|
|
1224
|
+
serverName,
|
|
1225
|
+
method: descriptor.method,
|
|
1226
|
+
...descriptor.params === void 0 ? {} : { params: descriptor.params },
|
|
1227
|
+
...descriptor.options === void 0 ? {} : { options: descriptor.options }
|
|
1228
|
+
});
|
|
1229
|
+
}
|
|
1230
|
+
function snapshotRequestOptions(options) {
|
|
1231
|
+
if (options === void 0) return options;
|
|
1232
|
+
const toolDefinition = "toolDefinition" in options ? Reflect.get(options, "toolDefinition") : void 0;
|
|
1233
|
+
return Object.freeze({
|
|
1234
|
+
...options,
|
|
1235
|
+
...options.headers === void 0 ? {} : { headers: Object.freeze({ ...options.headers }) },
|
|
1236
|
+
...toolDefinition === void 0 ? {} : { toolDefinition: snapshotProtocolValue(toolDefinition, "MCP call tool definition") }
|
|
1237
|
+
});
|
|
1238
|
+
}
|
|
1239
|
+
function snapshotProtocolValue(value, label) {
|
|
1240
|
+
let snapshot;
|
|
1241
|
+
try {
|
|
1242
|
+
snapshot = structuredClone(value);
|
|
1243
|
+
} catch (cause) {
|
|
1244
|
+
throw new TypeError(`${label} must be structured-cloneable JSON.`, { cause });
|
|
1245
|
+
}
|
|
1246
|
+
freezeProtocolValue(snapshot, label, /* @__PURE__ */ new Set(), /* @__PURE__ */ new Set());
|
|
1247
|
+
return snapshot;
|
|
1248
|
+
}
|
|
1249
|
+
function freezeProtocolValue(value, label, ancestors, visited) {
|
|
1250
|
+
if (value === void 0 || value === null || typeof value === "string" || typeof value === "boolean") return;
|
|
1251
|
+
if (typeof value === "number") {
|
|
1252
|
+
if (Number.isFinite(value)) return;
|
|
1253
|
+
throw new TypeError(`${label} must not contain non-finite numbers.`);
|
|
1254
|
+
}
|
|
1255
|
+
if (typeof value !== "object") throw new TypeError(`${label} must contain only JSON-compatible values.`);
|
|
1256
|
+
if (visited.has(value)) return;
|
|
1257
|
+
if (ancestors.has(value)) throw new TypeError(`${label} must not contain cycles.`);
|
|
1258
|
+
if (!Array.isArray(value)) {
|
|
1259
|
+
const prototype = Object.getPrototypeOf(value);
|
|
1260
|
+
if (prototype !== Object.prototype && prototype !== null) throw new TypeError(`${label} must contain only JSON arrays and objects.`);
|
|
1261
|
+
}
|
|
1262
|
+
ancestors.add(value);
|
|
1263
|
+
for (const entry of Array.isArray(value) ? value : Object.values(value)) freezeProtocolValue(entry, label, ancestors, visited);
|
|
1264
|
+
ancestors.delete(value);
|
|
1265
|
+
visited.add(value);
|
|
1266
|
+
Object.freeze(value);
|
|
1267
|
+
}
|
|
1268
|
+
function canReturnInputRequired(method, options) {
|
|
1269
|
+
return (method === "tools/call" || method === "prompts/get" || method === "resources/read") && typeof options === "object" && options !== null && "allowInputRequired" in options && options.allowInputRequired === true;
|
|
1270
|
+
}
|
|
1271
|
+
async function closeAfterFailedConnect(client, primary, unownedTransport) {
|
|
1272
|
+
const failures = [primary];
|
|
1273
|
+
if (unownedTransport !== void 0) try {
|
|
1274
|
+
await unownedTransport.close();
|
|
1275
|
+
} catch (cleanupError) {
|
|
1276
|
+
failures.push(cleanupError);
|
|
1277
|
+
}
|
|
1278
|
+
try {
|
|
1279
|
+
await client.close();
|
|
1280
|
+
} catch (cleanupError) {
|
|
1281
|
+
failures.push(cleanupError);
|
|
1282
|
+
}
|
|
1283
|
+
return failures.length === 1 ? primary : new AggregateError(failures, "The MCP connection failed and one or more owned resources failed to close.");
|
|
1284
|
+
}
|
|
1285
|
+
function throwSettledFailures(settled, message) {
|
|
1286
|
+
throwFailures(settled.filter((result) => result.status === "rejected").map((result) => result.reason), message);
|
|
1287
|
+
}
|
|
1288
|
+
function throwFailures(failures, message) {
|
|
1289
|
+
if (failures.length === 1) throw failures[0];
|
|
1290
|
+
if (failures.length > 1) throw new AggregateError(failures, message);
|
|
1291
|
+
}
|
|
1292
|
+
function assertNonEmpty(value, field) {
|
|
1293
|
+
if (typeof value !== "string" || value.trim().length === 0) throw new TypeError(`${field} must be a non-empty string.`);
|
|
1294
|
+
}
|
|
1295
|
+
function assertPositiveFinite(value, field) {
|
|
1296
|
+
if (!Number.isFinite(value) || value <= 0) throw new TypeError(`MCP client ${field} must be a positive finite number.`);
|
|
1297
|
+
}
|
|
1298
|
+
//#endregion
|
|
1299
|
+
//#region src/tool-schema.ts
|
|
1300
|
+
const JSON_SCHEMA_2020_12 = "https://json-schema.org/draft/2020-12/schema";
|
|
1301
|
+
const JSON_SCHEMA_2020_12_URIS = /* @__PURE__ */ new Set([JSON_SCHEMA_2020_12, "http://json-schema.org/draft/2020-12/schema"]);
|
|
1302
|
+
/**
|
|
1303
|
+
* Converts a discovered MCP tool JSON Schema into a Zod v4 schema.
|
|
1304
|
+
*
|
|
1305
|
+
* Zod v4 schemas also implement Standard Schema and Standard JSON Schema, so
|
|
1306
|
+
* the returned schema can be passed directly to either kind of consumer. The
|
|
1307
|
+
* official MCP validator remains the exact predicate because a discovered
|
|
1308
|
+
* Draft 2020-12 schema can contain constraints that Zod cannot reconstruct.
|
|
1309
|
+
* Invalid or unsupported schemas fail synchronously during construction.
|
|
1310
|
+
*/
|
|
1311
|
+
function createMcpClientToolSchema(schema) {
|
|
1312
|
+
const jsonSchema = Object.fromEntries(Object.entries(structuredClone(schema)));
|
|
1313
|
+
assertDraft202012(jsonSchema);
|
|
1314
|
+
deepFreezeJson(jsonSchema);
|
|
1315
|
+
const validatorSchema = structuredClone(jsonSchema);
|
|
1316
|
+
const validate = new AjvJsonSchemaValidator().getValidator(validatorSchema);
|
|
1317
|
+
const zodMetadata = structuredClone(jsonSchema);
|
|
1318
|
+
zodMetadata.$schema = JSON_SCHEMA_2020_12;
|
|
1319
|
+
deepFreezeJson(zodMetadata);
|
|
1320
|
+
const zodSchema = z.unknown().superRefine((value, context) => {
|
|
1321
|
+
const result = validate(value);
|
|
1322
|
+
if (!result.valid) context.addIssue({
|
|
1323
|
+
code: "custom",
|
|
1324
|
+
message: result.errorMessage
|
|
1325
|
+
});
|
|
1326
|
+
}).meta(zodMetadata);
|
|
1327
|
+
const validateWithZod = zodSchema["~standard"].validate;
|
|
1328
|
+
const toJsonSchemaWithZod = zodSchema.toJSONSchema.bind(zodSchema);
|
|
1329
|
+
const projectJsonSchema = (options) => {
|
|
1330
|
+
assertDraft202012Target(readTarget(options));
|
|
1331
|
+
return structuredClone(jsonSchema);
|
|
1332
|
+
};
|
|
1333
|
+
Object.defineProperties(zodSchema["~standard"], {
|
|
1334
|
+
validate: {
|
|
1335
|
+
configurable: false,
|
|
1336
|
+
enumerable: true,
|
|
1337
|
+
writable: false,
|
|
1338
|
+
async value(value) {
|
|
1339
|
+
return await validateWithZod(value);
|
|
1340
|
+
}
|
|
1341
|
+
},
|
|
1342
|
+
jsonSchema: {
|
|
1343
|
+
configurable: false,
|
|
1344
|
+
enumerable: true,
|
|
1345
|
+
writable: false,
|
|
1346
|
+
value: Object.freeze({
|
|
1347
|
+
input: projectJsonSchema,
|
|
1348
|
+
output: projectJsonSchema
|
|
1349
|
+
})
|
|
1350
|
+
}
|
|
1351
|
+
});
|
|
1352
|
+
Object.defineProperty(zodSchema, "toJSONSchema", {
|
|
1353
|
+
configurable: false,
|
|
1354
|
+
enumerable: true,
|
|
1355
|
+
writable: false,
|
|
1356
|
+
value(parameters) {
|
|
1357
|
+
assertDraft202012Target(parameters?.target);
|
|
1358
|
+
return toJsonSchemaWithZod({
|
|
1359
|
+
...parameters,
|
|
1360
|
+
target: "draft-2020-12"
|
|
1361
|
+
});
|
|
1362
|
+
}
|
|
1363
|
+
});
|
|
1364
|
+
return zodSchema;
|
|
1365
|
+
}
|
|
1366
|
+
function assertDraft202012(schema) {
|
|
1367
|
+
if (!("$schema" in schema)) return;
|
|
1368
|
+
const dialect = schema.$schema;
|
|
1369
|
+
if (typeof dialect === "string" && JSON_SCHEMA_2020_12_URIS.has(dialect.replace(/#$/u, ""))) return;
|
|
1370
|
+
throw new TypeError("createMcpClientToolSchema supports JSON Schema Draft 2020-12 declarations only.");
|
|
1371
|
+
}
|
|
1372
|
+
function assertDraft202012Target(target) {
|
|
1373
|
+
if (target === void 0 || target === "draft-2020-12") return;
|
|
1374
|
+
throw new TypeError("MCP tool schemas use JSON Schema Draft 2020-12 and cannot be projected to another target.");
|
|
1375
|
+
}
|
|
1376
|
+
function readTarget(options) {
|
|
1377
|
+
return isJsonObject(options) ? options.target : void 0;
|
|
1378
|
+
}
|
|
1379
|
+
function deepFreezeJson(value, seen = /* @__PURE__ */ new WeakSet()) {
|
|
1380
|
+
if (Array.isArray(value)) {
|
|
1381
|
+
if (seen.has(value)) return;
|
|
1382
|
+
seen.add(value);
|
|
1383
|
+
const items = value;
|
|
1384
|
+
for (const item of items) deepFreezeJson(item, seen);
|
|
1385
|
+
Object.freeze(value);
|
|
1386
|
+
return;
|
|
1387
|
+
}
|
|
1388
|
+
if (!isJsonObject(value) || seen.has(value)) return;
|
|
1389
|
+
seen.add(value);
|
|
1390
|
+
for (const nested of Object.values(value)) deepFreezeJson(nested, seen);
|
|
1391
|
+
Object.freeze(value);
|
|
1392
|
+
}
|
|
1393
|
+
function isJsonObject(value) {
|
|
1394
|
+
return typeof value === "object" && value !== null;
|
|
1395
|
+
}
|
|
1396
|
+
//#endregion
|
|
1397
|
+
//#region src/catalog-inspection.ts
|
|
1398
|
+
var McpClientCatalogLimitError = class extends Error {
|
|
1399
|
+
code = "MCP_CLIENT_CATALOG_LIMIT_EXCEEDED";
|
|
1400
|
+
constructor() {
|
|
1401
|
+
super("The MCP catalog exceeds its configured page or item limit.");
|
|
1402
|
+
this.name = "McpClientCatalogLimitError";
|
|
1403
|
+
}
|
|
1404
|
+
};
|
|
1405
|
+
const ITEM_LIMITS = Object.freeze({
|
|
1406
|
+
maxBytes: 2097152,
|
|
1407
|
+
maxDepth: 64,
|
|
1408
|
+
maxItems: 8192,
|
|
1409
|
+
maxProperties: 2e4,
|
|
1410
|
+
maxStringBytes: 1048576
|
|
1411
|
+
});
|
|
1412
|
+
/** Fresh bounded protocol traversal on an already acquired runtime; owns no lease or cache. */
|
|
1413
|
+
async function discoverMcpClientCatalog(input) {
|
|
1414
|
+
if (![input.maxPages, input.maxItems].every((n) => Number.isSafeInteger(n) && n > 0) || input.mode !== void 0 && input.mode !== "sequential" && input.mode !== "parallel") throw new TypeError("MCP catalog inspection requires positive bounds and a supported mode.");
|
|
1415
|
+
const { runtime, serverName, signal } = input;
|
|
1416
|
+
signal.throwIfAborted();
|
|
1417
|
+
const capabilities = runtime.snapshot(serverName).serverCapabilities;
|
|
1418
|
+
let totalItems = 0;
|
|
1419
|
+
const account = (items) => {
|
|
1420
|
+
totalItems += items.length;
|
|
1421
|
+
if (totalItems > input.maxItems) throw new McpClientCatalogLimitError();
|
|
1422
|
+
return items.map((item) => captureMcpConformanceValue(item, ITEM_LIMITS));
|
|
1423
|
+
};
|
|
1424
|
+
const tools = () => capabilities?.tools === void 0 ? Promise.resolve([]) : aggregatePages(async (cursor) => {
|
|
1425
|
+
const page = await runtime.request(serverName, {
|
|
1426
|
+
method: "tools/list",
|
|
1427
|
+
params: cursor === void 0 ? {} : { cursor }
|
|
1428
|
+
}, { signal });
|
|
1429
|
+
return {
|
|
1430
|
+
items: account(page.tools),
|
|
1431
|
+
...page.nextCursor === void 0 ? {} : { nextCursor: page.nextCursor }
|
|
1432
|
+
};
|
|
1433
|
+
}, input.maxPages, signal);
|
|
1434
|
+
const resources = () => capabilities?.resources === void 0 ? Promise.resolve([]) : aggregatePages(async (cursor) => {
|
|
1435
|
+
const page = await runtime.request(serverName, {
|
|
1436
|
+
method: "resources/list",
|
|
1437
|
+
params: cursor === void 0 ? {} : { cursor }
|
|
1438
|
+
}, { signal });
|
|
1439
|
+
return {
|
|
1440
|
+
items: account(page.resources),
|
|
1441
|
+
...page.nextCursor === void 0 ? {} : { nextCursor: page.nextCursor }
|
|
1442
|
+
};
|
|
1443
|
+
}, input.maxPages, signal);
|
|
1444
|
+
const resourceTemplates = async () => {
|
|
1445
|
+
if (capabilities?.resources === void 0) return [];
|
|
1446
|
+
try {
|
|
1447
|
+
return await aggregatePages(async (cursor) => {
|
|
1448
|
+
const page = await runtime.request(serverName, {
|
|
1449
|
+
method: "resources/templates/list",
|
|
1450
|
+
params: cursor === void 0 ? {} : { cursor }
|
|
1451
|
+
}, { signal });
|
|
1452
|
+
return {
|
|
1453
|
+
items: account(page.resourceTemplates),
|
|
1454
|
+
...page.nextCursor === void 0 ? {} : { nextCursor: page.nextCursor }
|
|
1455
|
+
};
|
|
1456
|
+
}, input.maxPages, signal);
|
|
1457
|
+
} catch (error) {
|
|
1458
|
+
signal.throwIfAborted();
|
|
1459
|
+
if (ProtocolError.isInstance(error) && error.code === METHOD_NOT_FOUND) return [];
|
|
1460
|
+
throw error;
|
|
1461
|
+
}
|
|
1462
|
+
};
|
|
1463
|
+
const prompts = () => capabilities?.prompts === void 0 ? Promise.resolve([]) : aggregatePages(async (cursor) => {
|
|
1464
|
+
const page = await runtime.request(serverName, {
|
|
1465
|
+
method: "prompts/list",
|
|
1466
|
+
params: cursor === void 0 ? {} : { cursor }
|
|
1467
|
+
}, { signal });
|
|
1468
|
+
return {
|
|
1469
|
+
items: account(page.prompts),
|
|
1470
|
+
...page.nextCursor === void 0 ? {} : { nextCursor: page.nextCursor }
|
|
1471
|
+
};
|
|
1472
|
+
}, input.maxPages, signal);
|
|
1473
|
+
let catalog;
|
|
1474
|
+
if (input.mode === "parallel") {
|
|
1475
|
+
const [t, r, rt, p] = await Promise.allSettled([
|
|
1476
|
+
tools(),
|
|
1477
|
+
resources(),
|
|
1478
|
+
resourceTemplates(),
|
|
1479
|
+
prompts()
|
|
1480
|
+
]);
|
|
1481
|
+
catalog = {
|
|
1482
|
+
tools: settledValue(t),
|
|
1483
|
+
resources: settledValue(r),
|
|
1484
|
+
resourceTemplates: settledValue(rt),
|
|
1485
|
+
prompts: settledValue(p)
|
|
1486
|
+
};
|
|
1487
|
+
} else catalog = {
|
|
1488
|
+
tools: await tools(),
|
|
1489
|
+
resources: await resources(),
|
|
1490
|
+
resourceTemplates: await resourceTemplates(),
|
|
1491
|
+
prompts: await prompts()
|
|
1492
|
+
};
|
|
1493
|
+
signal.throwIfAborted();
|
|
1494
|
+
return Object.freeze({
|
|
1495
|
+
tools: Object.freeze(catalog.tools),
|
|
1496
|
+
resources: Object.freeze(catalog.resources),
|
|
1497
|
+
resourceTemplates: Object.freeze(catalog.resourceTemplates),
|
|
1498
|
+
prompts: Object.freeze(catalog.prompts)
|
|
1499
|
+
});
|
|
1500
|
+
}
|
|
1501
|
+
/** Per-run diagnostic target. It shares discovery across checks and never opens a nested lease. */
|
|
1502
|
+
function createMcpClientInspectionTarget(input) {
|
|
1503
|
+
let catalogTask;
|
|
1504
|
+
return Object.freeze({
|
|
1505
|
+
snapshot: () => input.runtime.snapshot(input.serverName),
|
|
1506
|
+
async ping(signal) {
|
|
1507
|
+
await input.runtime.request(input.serverName, { method: "ping" }, { signal: AbortSignal.any([input.leaseSignal, signal]) });
|
|
1508
|
+
},
|
|
1509
|
+
catalog(signal) {
|
|
1510
|
+
input.leaseSignal.throwIfAborted();
|
|
1511
|
+
signal.throwIfAborted();
|
|
1512
|
+
catalogTask ??= discoverMcpClientCatalog({
|
|
1513
|
+
...input,
|
|
1514
|
+
signal: AbortSignal.any([input.leaseSignal, signal]),
|
|
1515
|
+
mode: "sequential"
|
|
1516
|
+
});
|
|
1517
|
+
return catalogTask;
|
|
1518
|
+
},
|
|
1519
|
+
schemaCompiles(schema) {
|
|
1520
|
+
try {
|
|
1521
|
+
const captured = captureMcpToolArguments(schema, ITEM_LIMITS);
|
|
1522
|
+
if (captured.type !== "object") return false;
|
|
1523
|
+
createMcpClientToolSchema({
|
|
1524
|
+
...captured,
|
|
1525
|
+
type: "object"
|
|
1526
|
+
});
|
|
1527
|
+
return true;
|
|
1528
|
+
} catch {
|
|
1529
|
+
return false;
|
|
1530
|
+
}
|
|
1531
|
+
}
|
|
1532
|
+
});
|
|
1533
|
+
}
|
|
1534
|
+
async function aggregatePages(load, maxPages, signal) {
|
|
1535
|
+
const result = [];
|
|
1536
|
+
const cursors = /* @__PURE__ */ new Set();
|
|
1537
|
+
let cursor;
|
|
1538
|
+
for (let index = 0; index < maxPages; index += 1) {
|
|
1539
|
+
signal.throwIfAborted();
|
|
1540
|
+
const page = await load(cursor);
|
|
1541
|
+
signal.throwIfAborted();
|
|
1542
|
+
result.push(...page.items);
|
|
1543
|
+
if (page.nextCursor === void 0 || page.nextCursor.length === 0) return result;
|
|
1544
|
+
if (cursors.has(page.nextCursor)) throw new TypeError("The MCP catalog cursor repeated.");
|
|
1545
|
+
cursors.add(page.nextCursor);
|
|
1546
|
+
cursor = page.nextCursor;
|
|
1547
|
+
}
|
|
1548
|
+
throw new McpClientCatalogLimitError();
|
|
1549
|
+
}
|
|
1550
|
+
function settledValue(result) {
|
|
1551
|
+
if (result.status === "rejected") throw result.reason;
|
|
1552
|
+
return result.value;
|
|
1553
|
+
}
|
|
1554
|
+
//#endregion
|
|
1555
|
+
//#region src/lease-manager.ts
|
|
1556
|
+
const DEFAULT_MAX_RESOURCES = 100;
|
|
1557
|
+
const DEFAULT_IDLE_TTL_MS = 6e4;
|
|
1558
|
+
const MAX_TIMER_DELAY_MS = 2147483647;
|
|
1559
|
+
const CREATION_SETTLED = Symbol("creation-settled");
|
|
1560
|
+
const ENTRY_RETIRED = Symbol("entry-retired");
|
|
1561
|
+
const CALLER_ABORTED = Symbol("caller-aborted");
|
|
1562
|
+
/**
|
|
1563
|
+
* Bounded, framework-neutral ownership for identity-isolated MCP client resources.
|
|
1564
|
+
* Identity keys are compared opaquely with `Map` semantics and are never emitted.
|
|
1565
|
+
*/
|
|
1566
|
+
var McpClientLeaseManager = class {
|
|
1567
|
+
#entries = /* @__PURE__ */ new Map();
|
|
1568
|
+
#generations = /* @__PURE__ */ new Set();
|
|
1569
|
+
#create;
|
|
1570
|
+
#closeResource;
|
|
1571
|
+
#maxResources;
|
|
1572
|
+
#idleTtlMs;
|
|
1573
|
+
#now;
|
|
1574
|
+
#onCapacityAvailable;
|
|
1575
|
+
#closed = false;
|
|
1576
|
+
#closeTask;
|
|
1577
|
+
constructor(options) {
|
|
1578
|
+
const maxResources = options.maxResources ?? DEFAULT_MAX_RESOURCES;
|
|
1579
|
+
const idleTtlMs = options.idleTtlMs ?? DEFAULT_IDLE_TTL_MS;
|
|
1580
|
+
if (!Number.isInteger(maxResources) || maxResources <= 0) throw new RangeError("McpClientLeaseManager maxResources must be a positive integer.");
|
|
1581
|
+
if (!Number.isFinite(idleTtlMs) || idleTtlMs < 0) throw new RangeError("McpClientLeaseManager idleTtlMs must be a non-negative number.");
|
|
1582
|
+
this.#create = options.create;
|
|
1583
|
+
this.#closeResource = options.close;
|
|
1584
|
+
this.#maxResources = maxResources;
|
|
1585
|
+
this.#idleTtlMs = idleTtlMs;
|
|
1586
|
+
this.#now = options.now ?? Date.now;
|
|
1587
|
+
this.#onCapacityAvailable = options.onCapacityAvailable;
|
|
1588
|
+
}
|
|
1589
|
+
get closed() {
|
|
1590
|
+
return this.#closed;
|
|
1591
|
+
}
|
|
1592
|
+
get size() {
|
|
1593
|
+
return this.#generations.size;
|
|
1594
|
+
}
|
|
1595
|
+
snapshot() {
|
|
1596
|
+
let pendingResourceCount = 0;
|
|
1597
|
+
let activeResourceCount = 0;
|
|
1598
|
+
let idleResourceCount = 0;
|
|
1599
|
+
let closingResourceCount = 0;
|
|
1600
|
+
let failedResourceCount = 0;
|
|
1601
|
+
let referenceCount = 0;
|
|
1602
|
+
for (const entry of this.#generations) {
|
|
1603
|
+
referenceCount += entry.refCount;
|
|
1604
|
+
switch (entry.state) {
|
|
1605
|
+
case "pending":
|
|
1606
|
+
pendingResourceCount += 1;
|
|
1607
|
+
break;
|
|
1608
|
+
case "ready":
|
|
1609
|
+
if (entry.refCount === 0) idleResourceCount += 1;
|
|
1610
|
+
else activeResourceCount += 1;
|
|
1611
|
+
break;
|
|
1612
|
+
case "closing":
|
|
1613
|
+
closingResourceCount += 1;
|
|
1614
|
+
break;
|
|
1615
|
+
case "close-failed": failedResourceCount += 1;
|
|
1616
|
+
}
|
|
1617
|
+
}
|
|
1618
|
+
return Object.freeze({
|
|
1619
|
+
closed: this.#closed,
|
|
1620
|
+
maxResources: this.#maxResources,
|
|
1621
|
+
resourceCount: this.#generations.size,
|
|
1622
|
+
pendingResourceCount,
|
|
1623
|
+
activeResourceCount,
|
|
1624
|
+
idleResourceCount,
|
|
1625
|
+
closingResourceCount,
|
|
1626
|
+
failedResourceCount,
|
|
1627
|
+
referenceCount
|
|
1628
|
+
});
|
|
1629
|
+
}
|
|
1630
|
+
/** Read-only availability for a synchronous acquire reservation. Includes all cleanup. */
|
|
1631
|
+
canAcquire(identity) {
|
|
1632
|
+
if (this.#closed) return false;
|
|
1633
|
+
const entry = this.#entries.get(identity);
|
|
1634
|
+
return entry !== void 0 && !entry.retired || this.#generations.size < this.#maxResources;
|
|
1635
|
+
}
|
|
1636
|
+
async acquire(identity, options = {}) {
|
|
1637
|
+
const releaseMode = options.releaseMode ?? "close";
|
|
1638
|
+
assertReleaseMode(releaseMode);
|
|
1639
|
+
if (options.awaitCleanupOnCancel !== void 0 && typeof options.awaitCleanupOnCancel !== "boolean") throw new TypeError("McpClientLeaseManager awaitCleanupOnCancel must be a boolean.");
|
|
1640
|
+
throwIfAborted(options.signal);
|
|
1641
|
+
for (;;) {
|
|
1642
|
+
this.#assertOpen();
|
|
1643
|
+
throwIfAborted(options.signal);
|
|
1644
|
+
const existing = this.#entries.get(identity);
|
|
1645
|
+
if (existing !== void 0 && !existing.retired) {
|
|
1646
|
+
if (existing.releaseMode !== releaseMode) throw leaseReleaseModeConflictError();
|
|
1647
|
+
this.#reserve(existing);
|
|
1648
|
+
return this.#awaitLease(existing, options.signal, options.awaitCleanupOnCancel ?? false);
|
|
1649
|
+
}
|
|
1650
|
+
if (this.#generations.size < this.#maxResources) {
|
|
1651
|
+
const entry = this.#createEntry(identity, releaseMode);
|
|
1652
|
+
this.#reserve(entry);
|
|
1653
|
+
return this.#awaitLease(entry, options.signal, options.awaitCleanupOnCancel ?? false);
|
|
1654
|
+
}
|
|
1655
|
+
const idle = this.#oldestIdleEntry();
|
|
1656
|
+
if (idle === void 0) throw leaseCapacityExceededError();
|
|
1657
|
+
await waitForTask(this.#retireEntry(idle, resourceEvictedReason()), options.signal);
|
|
1658
|
+
}
|
|
1659
|
+
}
|
|
1660
|
+
/** Retires the current identity generation before waiting for its close. */
|
|
1661
|
+
async invalidate(identity) {
|
|
1662
|
+
this.#assertOpen();
|
|
1663
|
+
const entry = this.#entries.get(identity);
|
|
1664
|
+
if (entry === void 0 || entry.retired) return false;
|
|
1665
|
+
await this.#retireEntry(entry, leaseInvalidatedError());
|
|
1666
|
+
return true;
|
|
1667
|
+
}
|
|
1668
|
+
close() {
|
|
1669
|
+
if (this.#closeTask !== void 0) return this.#closeTask;
|
|
1670
|
+
this.#closed = true;
|
|
1671
|
+
let resolveClose;
|
|
1672
|
+
let rejectClose;
|
|
1673
|
+
this.#closeTask = new Promise((resolve, reject) => {
|
|
1674
|
+
resolveClose = resolve;
|
|
1675
|
+
rejectClose = reject;
|
|
1676
|
+
});
|
|
1677
|
+
const reason = leaseManagerClosedError();
|
|
1678
|
+
const closeTasks = [...this.#generations].map((entry) => this.#retireEntry(entry, reason));
|
|
1679
|
+
Promise.allSettled(closeTasks).then((settled) => {
|
|
1680
|
+
const failures = settled.flatMap((result) => result.status === "rejected" ? [result.reason] : []);
|
|
1681
|
+
if (failures.length === 0) resolveClose?.();
|
|
1682
|
+
else rejectClose?.(new AggregateError(failures, "One or more MCP client lease resources failed to close."));
|
|
1683
|
+
});
|
|
1684
|
+
return this.#closeTask;
|
|
1685
|
+
}
|
|
1686
|
+
async [Symbol.asyncDispose]() {
|
|
1687
|
+
await this.close();
|
|
1688
|
+
}
|
|
1689
|
+
#createEntry(identity, releaseMode) {
|
|
1690
|
+
const entry = {
|
|
1691
|
+
identity,
|
|
1692
|
+
token: Symbol("mcp-client-lease-generation"),
|
|
1693
|
+
releaseMode,
|
|
1694
|
+
controller: new AbortController(),
|
|
1695
|
+
state: "pending",
|
|
1696
|
+
refCount: 0,
|
|
1697
|
+
resource: void 0,
|
|
1698
|
+
creationFailed: false,
|
|
1699
|
+
creationFailure: void 0,
|
|
1700
|
+
createTask: void 0,
|
|
1701
|
+
retired: false,
|
|
1702
|
+
retirementReason: void 0,
|
|
1703
|
+
drainTask: void 0,
|
|
1704
|
+
resolveDrain: void 0,
|
|
1705
|
+
closeTask: void 0,
|
|
1706
|
+
idleSince: void 0,
|
|
1707
|
+
idleTimer: void 0
|
|
1708
|
+
};
|
|
1709
|
+
this.#entries.set(identity, entry);
|
|
1710
|
+
this.#generations.add(entry);
|
|
1711
|
+
const context = Object.freeze({ signal: entry.controller.signal });
|
|
1712
|
+
entry.createTask = Promise.resolve().then(async () => {
|
|
1713
|
+
try {
|
|
1714
|
+
const resource = await this.#create(identity, context);
|
|
1715
|
+
assertResource(resource);
|
|
1716
|
+
entry.resource = resource;
|
|
1717
|
+
if (!entry.retired) entry.state = "ready";
|
|
1718
|
+
} catch (error) {
|
|
1719
|
+
entry.creationFailed = true;
|
|
1720
|
+
entry.creationFailure = error;
|
|
1721
|
+
if (!entry.retired) this.#failCreation(entry, error);
|
|
1722
|
+
}
|
|
1723
|
+
});
|
|
1724
|
+
return entry;
|
|
1725
|
+
}
|
|
1726
|
+
#reserve(entry) {
|
|
1727
|
+
this.#clearIdle(entry);
|
|
1728
|
+
entry.refCount += 1;
|
|
1729
|
+
}
|
|
1730
|
+
async #awaitLease(entry, callerSignal, awaitCleanupOnCancel) {
|
|
1731
|
+
const createTask = requireCreateTask(entry);
|
|
1732
|
+
const retired = waitForAbort(entry.controller.signal, ENTRY_RETIRED);
|
|
1733
|
+
const caller = callerSignal === void 0 ? void 0 : waitForAbort(callerSignal, CALLER_ABORTED);
|
|
1734
|
+
try {
|
|
1735
|
+
const outcome = await Promise.race([
|
|
1736
|
+
createTask.then(() => CREATION_SETTLED),
|
|
1737
|
+
retired.promise,
|
|
1738
|
+
...caller === void 0 ? [] : [caller.promise]
|
|
1739
|
+
]);
|
|
1740
|
+
if (outcome === CALLER_ABORTED) {
|
|
1741
|
+
const cleanup = this.#cancelReservation(entry);
|
|
1742
|
+
if (awaitCleanupOnCancel) await cleanup;
|
|
1743
|
+
else this.#observeBackground(cleanup);
|
|
1744
|
+
throw abortReason(callerSignal);
|
|
1745
|
+
}
|
|
1746
|
+
if (entry.retired || outcome === ENTRY_RETIRED) {
|
|
1747
|
+
this.#dropReference(entry);
|
|
1748
|
+
if (awaitCleanupOnCancel) await entry.closeTask;
|
|
1749
|
+
throw entry.retirementReason;
|
|
1750
|
+
}
|
|
1751
|
+
if (entry.creationFailed) {
|
|
1752
|
+
this.#dropReference(entry);
|
|
1753
|
+
throw entry.creationFailure;
|
|
1754
|
+
}
|
|
1755
|
+
if (entry.state !== "ready" || entry.resource === void 0) {
|
|
1756
|
+
const cleanup = this.#cancelReservation(entry);
|
|
1757
|
+
if (awaitCleanupOnCancel) await cleanup;
|
|
1758
|
+
else this.#observeBackground(cleanup);
|
|
1759
|
+
throw new Error("The MCP client lease resource did not become ready.");
|
|
1760
|
+
}
|
|
1761
|
+
return new ManagedMcpClientLease(entry.resource, () => this.#releaseReference(entry));
|
|
1762
|
+
} finally {
|
|
1763
|
+
retired.detach();
|
|
1764
|
+
caller?.detach();
|
|
1765
|
+
}
|
|
1766
|
+
}
|
|
1767
|
+
#releaseReference(entry) {
|
|
1768
|
+
this.#dropReference(entry);
|
|
1769
|
+
if (entry.refCount !== 0) return Promise.resolve();
|
|
1770
|
+
if (entry.retired) return entry.closeTask ?? Promise.resolve();
|
|
1771
|
+
if (entry.state === "pending") return this.#retireEntry(entry, acquisitionAbandonedReason());
|
|
1772
|
+
if (entry.state !== "ready") return Promise.resolve();
|
|
1773
|
+
if (entry.releaseMode === "close") return this.#retireEntry(entry, finalReleaseReason());
|
|
1774
|
+
return this.#scheduleIdle(entry);
|
|
1775
|
+
}
|
|
1776
|
+
#cancelReservation(entry) {
|
|
1777
|
+
this.#dropReference(entry);
|
|
1778
|
+
if (entry.refCount !== 0) return Promise.resolve();
|
|
1779
|
+
if (entry.retired) return entry.closeTask ?? Promise.resolve();
|
|
1780
|
+
return this.#retireEntry(entry, acquisitionAbandonedReason());
|
|
1781
|
+
}
|
|
1782
|
+
#dropReference(entry) {
|
|
1783
|
+
if (entry.refCount === 0) return;
|
|
1784
|
+
entry.refCount -= 1;
|
|
1785
|
+
if (entry.refCount === 0) {
|
|
1786
|
+
entry.resolveDrain?.();
|
|
1787
|
+
entry.resolveDrain = void 0;
|
|
1788
|
+
}
|
|
1789
|
+
}
|
|
1790
|
+
#scheduleIdle(entry) {
|
|
1791
|
+
entry.idleSince = this.#now();
|
|
1792
|
+
if (this.#idleTtlMs === 0) return this.#retireEntry(entry, idleExpiredReason());
|
|
1793
|
+
this.#armIdleTimer(entry, entry.idleSince);
|
|
1794
|
+
return Promise.resolve();
|
|
1795
|
+
}
|
|
1796
|
+
#armIdleTimer(entry, idleSince) {
|
|
1797
|
+
const remaining = Math.max(0, idleSince + this.#idleTtlMs - this.#now());
|
|
1798
|
+
const timer = setTimeout(() => {
|
|
1799
|
+
if (entry.idleTimer !== timer) return;
|
|
1800
|
+
entry.idleTimer = void 0;
|
|
1801
|
+
if (entry.retired || entry.state !== "ready" || entry.refCount !== 0 || entry.idleSince !== idleSince) return;
|
|
1802
|
+
if (this.#now() < idleSince + this.#idleTtlMs) {
|
|
1803
|
+
this.#armIdleTimer(entry, idleSince);
|
|
1804
|
+
return;
|
|
1805
|
+
}
|
|
1806
|
+
this.#observeBackground(this.#retireEntry(entry, idleExpiredReason()));
|
|
1807
|
+
}, Math.min(remaining, MAX_TIMER_DELAY_MS));
|
|
1808
|
+
timer.unref?.();
|
|
1809
|
+
entry.idleTimer = timer;
|
|
1810
|
+
}
|
|
1811
|
+
#clearIdle(entry) {
|
|
1812
|
+
if (entry.idleTimer !== void 0) clearTimeout(entry.idleTimer);
|
|
1813
|
+
entry.idleTimer = void 0;
|
|
1814
|
+
entry.idleSince = void 0;
|
|
1815
|
+
}
|
|
1816
|
+
#oldestIdleEntry() {
|
|
1817
|
+
let oldest;
|
|
1818
|
+
for (const entry of this.#entries.values()) {
|
|
1819
|
+
if (entry.retired || entry.state !== "ready" || entry.refCount !== 0 || entry.releaseMode !== "idle" || entry.idleSince === void 0) continue;
|
|
1820
|
+
if (oldest === void 0 || entry.idleSince < (oldest.idleSince ?? Infinity)) oldest = entry;
|
|
1821
|
+
}
|
|
1822
|
+
return oldest;
|
|
1823
|
+
}
|
|
1824
|
+
#retireEntry(entry, reason) {
|
|
1825
|
+
if (entry.closeTask !== void 0) return entry.closeTask;
|
|
1826
|
+
entry.retired = true;
|
|
1827
|
+
entry.retirementReason = reason;
|
|
1828
|
+
entry.state = "closing";
|
|
1829
|
+
this.#clearIdle(entry);
|
|
1830
|
+
if (this.#entries.get(entry.identity)?.token === entry.token) this.#entries.delete(entry.identity);
|
|
1831
|
+
if (entry.refCount === 0) entry.drainTask = Promise.resolve();
|
|
1832
|
+
else entry.drainTask = new Promise((resolve) => {
|
|
1833
|
+
entry.resolveDrain = resolve;
|
|
1834
|
+
});
|
|
1835
|
+
entry.closeTask = Promise.resolve().then(async () => {
|
|
1836
|
+
await Promise.all([requireCreateTask(entry), requireDrainTask(entry)]);
|
|
1837
|
+
if (entry.resource !== void 0) {
|
|
1838
|
+
await this.#closeResource(entry.resource);
|
|
1839
|
+
entry.resource = void 0;
|
|
1840
|
+
}
|
|
1841
|
+
this.#generations.delete(entry);
|
|
1842
|
+
this.#notifyCapacity();
|
|
1843
|
+
}).catch((error) => {
|
|
1844
|
+
entry.state = "close-failed";
|
|
1845
|
+
throw error;
|
|
1846
|
+
});
|
|
1847
|
+
entry.controller.abort(reason);
|
|
1848
|
+
return entry.closeTask;
|
|
1849
|
+
}
|
|
1850
|
+
#failCreation(entry, error) {
|
|
1851
|
+
entry.retired = true;
|
|
1852
|
+
entry.retirementReason = error;
|
|
1853
|
+
if (this.#entries.get(entry.identity)?.token === entry.token) this.#entries.delete(entry.identity);
|
|
1854
|
+
this.#generations.delete(entry);
|
|
1855
|
+
entry.controller.abort(error);
|
|
1856
|
+
this.#notifyCapacity();
|
|
1857
|
+
}
|
|
1858
|
+
#notifyCapacity() {
|
|
1859
|
+
try {
|
|
1860
|
+
this.#onCapacityAvailable?.();
|
|
1861
|
+
} catch {}
|
|
1862
|
+
}
|
|
1863
|
+
#observeBackground(task) {
|
|
1864
|
+
task.catch(() => void 0);
|
|
1865
|
+
}
|
|
1866
|
+
#assertOpen() {
|
|
1867
|
+
if (this.#closed) throw leaseManagerClosedError();
|
|
1868
|
+
}
|
|
1869
|
+
};
|
|
1870
|
+
var ManagedMcpClientLease = class {
|
|
1871
|
+
resource;
|
|
1872
|
+
#releaseLease;
|
|
1873
|
+
#releaseTask;
|
|
1874
|
+
constructor(resource, releaseLease) {
|
|
1875
|
+
this.resource = resource;
|
|
1876
|
+
this.#releaseLease = releaseLease;
|
|
1877
|
+
}
|
|
1878
|
+
get released() {
|
|
1879
|
+
return this.#releaseTask !== void 0;
|
|
1880
|
+
}
|
|
1881
|
+
release() {
|
|
1882
|
+
if (this.#releaseTask === void 0) try {
|
|
1883
|
+
this.#releaseTask = this.#releaseLease();
|
|
1884
|
+
} catch (error) {
|
|
1885
|
+
this.#releaseTask = Promise.reject(error);
|
|
1886
|
+
}
|
|
1887
|
+
return this.#releaseTask;
|
|
1888
|
+
}
|
|
1889
|
+
async [Symbol.asyncDispose]() {
|
|
1890
|
+
await this.release();
|
|
1891
|
+
}
|
|
1892
|
+
};
|
|
1893
|
+
function requireCreateTask(entry) {
|
|
1894
|
+
if (entry.createTask === void 0) throw new Error("The MCP client lease resource factory did not start.");
|
|
1895
|
+
return entry.createTask;
|
|
1896
|
+
}
|
|
1897
|
+
function requireDrainTask(entry) {
|
|
1898
|
+
if (entry.drainTask === void 0) throw new Error("The MCP client lease resource retirement did not start.");
|
|
1899
|
+
return entry.drainTask;
|
|
1900
|
+
}
|
|
1901
|
+
function waitForAbort(signal, result) {
|
|
1902
|
+
if (signal.aborted) return {
|
|
1903
|
+
promise: Promise.resolve(result),
|
|
1904
|
+
detach: noop
|
|
1905
|
+
};
|
|
1906
|
+
let resolveAbort;
|
|
1907
|
+
const promise = new Promise((resolve) => {
|
|
1908
|
+
resolveAbort = resolve;
|
|
1909
|
+
});
|
|
1910
|
+
const onAbort = () => resolveAbort?.(result);
|
|
1911
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
1912
|
+
return {
|
|
1913
|
+
promise,
|
|
1914
|
+
detach() {
|
|
1915
|
+
signal.removeEventListener("abort", onAbort);
|
|
1916
|
+
}
|
|
1917
|
+
};
|
|
1918
|
+
}
|
|
1919
|
+
async function waitForTask(task, signal) {
|
|
1920
|
+
if (signal === void 0) {
|
|
1921
|
+
await task;
|
|
1922
|
+
return;
|
|
1923
|
+
}
|
|
1924
|
+
throwIfAborted(signal);
|
|
1925
|
+
const aborted = waitForAbort(signal, CALLER_ABORTED);
|
|
1926
|
+
try {
|
|
1927
|
+
if (await Promise.race([task.then(() => CREATION_SETTLED), aborted.promise]) === CALLER_ABORTED) throw abortReason(signal);
|
|
1928
|
+
} finally {
|
|
1929
|
+
aborted.detach();
|
|
1930
|
+
}
|
|
1931
|
+
}
|
|
1932
|
+
function throwIfAborted(signal) {
|
|
1933
|
+
if (signal?.aborted === true) throw abortReason(signal);
|
|
1934
|
+
}
|
|
1935
|
+
function abortReason(signal) {
|
|
1936
|
+
return signal?.reason ?? new DOMException("The operation was aborted.", "AbortError");
|
|
1937
|
+
}
|
|
1938
|
+
function assertReleaseMode(mode) {
|
|
1939
|
+
if (mode !== "close" && mode !== "idle") throw new TypeError("McpClientLeaseManager releaseMode must be \"close\" or \"idle\".");
|
|
1940
|
+
}
|
|
1941
|
+
function assertResource(resource) {
|
|
1942
|
+
if (resource === null || typeof resource !== "object" && typeof resource !== "function") throw new TypeError("McpClientLeaseManager create must resolve to a resource object.");
|
|
1943
|
+
}
|
|
1944
|
+
function acquisitionAbandonedReason() {
|
|
1945
|
+
return new DOMException("The MCP client resource creation was abandoned.", "AbortError");
|
|
1946
|
+
}
|
|
1947
|
+
function resourceEvictedReason() {
|
|
1948
|
+
return new DOMException("The idle MCP client resource was evicted.", "AbortError");
|
|
1949
|
+
}
|
|
1950
|
+
function idleExpiredReason() {
|
|
1951
|
+
return new DOMException("The idle MCP client resource expired.", "AbortError");
|
|
1952
|
+
}
|
|
1953
|
+
function finalReleaseReason() {
|
|
1954
|
+
return new DOMException("The MCP client resource's final lease was released.", "AbortError");
|
|
1955
|
+
}
|
|
1956
|
+
function noop() {}
|
|
1957
|
+
//#endregion
|
|
1958
|
+
export { AuthorizationServerMismatchError, Client, ClientCredentialsProvider, CrossAppAccessProvider, InsecureTokenEndpointError, InsufficientScopeError, IssuerMismatchError, MCP_CLIENT_LEASE_CAPACITY_EXCEEDED, MCP_CLIENT_LEASE_INVALIDATED, MCP_CLIENT_LEASE_MANAGER_CLOSED, MCP_CLIENT_LEASE_RELEASE_MODE_CONFLICT, MCP_CLIENT_NOT_CONNECTED, MCP_CLIENT_RUNTIME_CLOSED, MCP_CLIENT_SERVER_EXISTS, MCP_CLIENT_SERVER_NOT_FOUND, MCP_CLIENT_SHUTDOWN_TIMEOUT, McpClientCatalogLimitError, McpClientLeaseManager, McpClientLeaseManagerError, McpClientRuntime, McpClientRuntimeError, OAuthClientFlowError, PrivateKeyJwtProvider, RegistrationRejectedError, StaticPrivateKeyJwtProvider, StdioClientTransport, StreamableHTTPClientTransport, UnauthorizedError, applyMiddlewares, auth, bindMcpClientMiddleware, composeMcpFetchMiddleware, createMcpClientInspectionTarget, createMcpClientPassthroughMiddleware, createMcpClientToolSchema, createMcpClientTransport, createMcpHttpClientTransport, createMcpStdioClientTransport, createMiddleware, createPrivateKeyJwtAuth, defaultMcpClientTransportFactory, defineMcpClientTransform, discoverMcpClientCatalog, discoverOAuthMetadata, discoverOAuthProtectedResourceMetadata, discoverOAuthServerInfo, isInputRequiredResult, refreshAuthorization, specTypeSchemas, withInputRequired, withLogging, withOAuth };
|
|
1959
|
+
|
|
1960
|
+
//# sourceMappingURL=index.mjs.map
|