@anvia/core 1.0.0-rc.9 → 1.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.
Files changed (50) hide show
  1. package/README.md +99 -77
  2. package/dist/agent/index.d.ts +11 -16
  3. package/dist/agent/index.js +8 -8
  4. package/dist/{agent-XPQBM4rX.d.ts → agent-qRKa3ibC.d.ts} +11 -7
  5. package/dist/{chunk-PISJAAMX.js → chunk-3ZLM6OAZ.js} +318 -114
  6. package/dist/chunk-3ZLM6OAZ.js.map +1 -0
  7. package/dist/{chunk-WZVHZZW6.js → chunk-6BBOCFHV.js} +2 -2
  8. package/dist/{chunk-WTRGYFCD.js → chunk-7PHMK7W4.js} +4 -4
  9. package/dist/{chunk-X4LK4ODN.js → chunk-AHLKV6KP.js} +1 -1
  10. package/dist/chunk-AHLKV6KP.js.map +1 -0
  11. package/dist/chunk-J6LVLV6P.js +13 -0
  12. package/dist/chunk-J6LVLV6P.js.map +1 -0
  13. package/dist/{chunk-KIXN5DGS.js → chunk-LTXABCOO.js} +2 -2
  14. package/dist/{chunk-QOUPWOGW.js → chunk-SPD4XVR7.js} +1 -1
  15. package/dist/{chunk-TC4FILD3.js → chunk-YA7BMX7D.js} +51 -4
  16. package/dist/chunk-YA7BMX7D.js.map +1 -0
  17. package/dist/completion/index.js +2 -2
  18. package/dist/documents/index.js +26 -1
  19. package/dist/documents/index.js.map +1 -1
  20. package/dist/evals/index.d.ts +5 -5
  21. package/dist/evals/index.js +6 -6
  22. package/dist/evals/index.js.map +1 -1
  23. package/dist/extractor/index.js +3 -3
  24. package/dist/index.d.ts +7 -12
  25. package/dist/index.js +22 -20
  26. package/dist/internal/agent.d.ts +4 -9
  27. package/dist/internal/agent.js +8 -8
  28. package/dist/mcp/index.d.ts +3 -17
  29. package/dist/mcp/index.js +1 -15
  30. package/dist/memory/index.d.ts +6 -3
  31. package/dist/memory/index.js +6 -4
  32. package/dist/observability/index.d.ts +2 -2
  33. package/dist/observability/index.js +3 -3
  34. package/dist/pipeline/index.d.ts +6 -11
  35. package/dist/pipeline/index.js +6 -6
  36. package/dist/pipeline/index.js.map +1 -1
  37. package/dist/{types-Sue2hb_L.d.ts → types-CLCLFpAL.d.ts} +23 -15
  38. package/dist/{types-DKOXVTcq.d.ts → types-CSYt7-It.d.ts} +18 -3
  39. package/dist/types-DjqRHeAi.d.ts +31 -0
  40. package/package.json +10 -4
  41. package/dist/chunk-76JLMBVT.js +0 -716
  42. package/dist/chunk-76JLMBVT.js.map +0 -1
  43. package/dist/chunk-PISJAAMX.js.map +0 -1
  44. package/dist/chunk-TC4FILD3.js.map +0 -1
  45. package/dist/chunk-X4LK4ODN.js.map +0 -1
  46. package/dist/client-DTPl0hZv.d.ts +0 -84
  47. /package/dist/{chunk-WZVHZZW6.js.map → chunk-6BBOCFHV.js.map} +0 -0
  48. /package/dist/{chunk-WTRGYFCD.js.map → chunk-7PHMK7W4.js.map} +0 -0
  49. /package/dist/{chunk-KIXN5DGS.js.map → chunk-LTXABCOO.js.map} +0 -0
  50. /package/dist/{chunk-QOUPWOGW.js.map → chunk-SPD4XVR7.js.map} +0 -0
@@ -1,716 +0,0 @@
1
- import {
2
- ToolOutput
3
- } from "./chunk-EMZKPRE6.js";
4
- import {
5
- isJsonValue
6
- } from "./chunk-3XQGVDU5.js";
7
- import {
8
- abortError,
9
- throwIfAborted
10
- } from "./chunk-3RWESPUG.js";
11
-
12
- // src/mcp/client.ts
13
- import { readFileSync } from "fs";
14
- import { Client } from "@modelcontextprotocol/sdk/client/index.js";
15
- import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
16
- import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
17
-
18
- // src/mcp/abort.ts
19
- function linkAbortSignal(source, target) {
20
- if (source === void 0) {
21
- return () => void 0;
22
- }
23
- if (source.aborted) {
24
- target.abort(source.reason);
25
- return () => void 0;
26
- }
27
- const onAbort = () => target.abort(source.reason);
28
- source.addEventListener("abort", onAbort, { once: true });
29
- return () => source.removeEventListener("abort", onAbort);
30
- }
31
-
32
- // src/mcp/result.ts
33
- function createCallToolParams(name, args) {
34
- if (args === void 0) {
35
- return { name };
36
- }
37
- return { name, arguments: parseMcpToolArguments(args) };
38
- }
39
- function parseMcpToolArguments(args) {
40
- if (!isMcpJsonObject(args)) {
41
- throw new TypeError("MCP tool arguments must be a strict JSON object");
42
- }
43
- return args;
44
- }
45
- function isMcpJsonObject(value) {
46
- return typeof value === "object" && value !== null && !Array.isArray(value) && isJsonValue(value);
47
- }
48
- function mapMcpToolResult(result) {
49
- if ("toolResult" in result) {
50
- return [{ type: "text", text: serializeMcpValue(result.toolResult) }];
51
- }
52
- if (result.isError === true) {
53
- throw new Error(mcpErrorMessage(result.content));
54
- }
55
- const content = result.content.map(mapMcpContent);
56
- if (content.length === 0 && result.structuredContent !== void 0) {
57
- content.push({ type: "text", text: serializeMcpValue(result.structuredContent) });
58
- }
59
- return content;
60
- }
61
- function mcpErrorMessage(content) {
62
- const text = content.map((item) => item.type === "text" ? item.text : void 0).filter((item) => item !== void 0).join("\n");
63
- return text === "" ? "MCP tool returned an error" : text;
64
- }
65
- function mapMcpContent(content) {
66
- if (content.type === "text") {
67
- return { type: "text", text: content.text };
68
- }
69
- if (content.type === "image") {
70
- return {
71
- type: "file",
72
- data: { type: "data", data: content.data },
73
- mediaType: content.mimeType
74
- };
75
- }
76
- if (content.type === "resource") {
77
- return { type: "text", text: serializeResource(content.resource) };
78
- }
79
- if (content.type === "audio") {
80
- throw new Error(`Unsupported MCP tool result content type: audio (${content.mimeType})`);
81
- }
82
- throw new Error(`Unsupported MCP tool result content type: resource_link (${content.uri})`);
83
- }
84
- function serializeResource(resource) {
85
- const mediaType = resource.mimeType ?? ("text" in resource ? "text/plain" : "application/octet-stream");
86
- const encoding = "text" in resource ? "text" : "base64";
87
- const data = "text" in resource ? resource.text : resource.blob;
88
- return `MCP resource (${resource.uri}; ${mediaType}; ${encoding})
89
- ${data}`;
90
- }
91
- function serializeMcpValue(value) {
92
- if (typeof value === "string") {
93
- return value;
94
- }
95
- if (!isJsonValue(value)) {
96
- throw new TypeError("MCP tool results must be strict JSON values.");
97
- }
98
- let serialized;
99
- try {
100
- serialized = JSON.stringify(value);
101
- } catch (error) {
102
- throw new TypeError("MCP tool results must be strict JSON values.", { cause: error });
103
- }
104
- if (serialized === void 0) {
105
- throw new TypeError("MCP tool results must be strict JSON values.");
106
- }
107
- return serialized;
108
- }
109
-
110
- // src/mcp/tool.ts
111
- function createMcpTool(options) {
112
- const { definition, client, serverName, prefix = "" } = options;
113
- const exposedName = `${prefix}${definition.name}`;
114
- const provenance = Object.freeze({
115
- serverName,
116
- remoteName: definition.name
117
- });
118
- const toolDefinition = Object.freeze({
119
- name: exposedName,
120
- description: definition.description ?? "",
121
- parameters: deepFreeze(structuredClone(definition.inputSchema))
122
- });
123
- const tool = {
124
- name: exposedName,
125
- mcp: provenance,
126
- definition() {
127
- return toolDefinition;
128
- },
129
- parseInput(args) {
130
- return parseMcpToolArguments(args);
131
- },
132
- async call(args, context) {
133
- const result = await client.callTool(
134
- createCallToolParams(definition.name, args),
135
- void 0,
136
- context?.abortSignal === void 0 ? {} : { signal: context.abortSignal }
137
- );
138
- return ToolOutput.content(mapMcpToolResult(result));
139
- }
140
- };
141
- return Object.freeze(tool);
142
- }
143
- function isMcpTool(tool) {
144
- if (typeof tool !== "object" || tool === null || !("mcp" in tool)) {
145
- return false;
146
- }
147
- const mcp = tool.mcp;
148
- return typeof mcp === "object" && mcp !== null && "serverName" in mcp && typeof mcp.serverName === "string" && mcp.serverName.length > 0 && "remoteName" in mcp && typeof mcp.remoteName === "string" && mcp.remoteName.length > 0;
149
- }
150
- function deepFreeze(value) {
151
- if (typeof value !== "object" || value === null || Object.isFrozen(value)) {
152
- return value;
153
- }
154
- for (const child of Object.values(value)) {
155
- deepFreeze(child);
156
- }
157
- return Object.freeze(value);
158
- }
159
-
160
- // src/mcp/url-safety.ts
161
- import { lookup } from "dns/promises";
162
- import { BlockList, isIP } from "net";
163
- import { Agent, Pool, fetch as undiciFetch } from "undici";
164
- var blockedIpv4Addresses = new BlockList();
165
- var blockedIpv6Addresses = new BlockList();
166
- for (const [network, prefix] of [
167
- ["0.0.0.0", 8],
168
- ["10.0.0.0", 8],
169
- ["100.64.0.0", 10],
170
- ["127.0.0.0", 8],
171
- ["169.254.0.0", 16],
172
- ["172.16.0.0", 12],
173
- ["192.0.0.0", 24],
174
- ["192.0.2.0", 24],
175
- ["192.88.99.0", 24],
176
- ["192.168.0.0", 16],
177
- ["198.18.0.0", 15],
178
- ["198.51.100.0", 24],
179
- ["203.0.113.0", 24],
180
- ["224.0.0.0", 4],
181
- ["240.0.0.0", 4]
182
- ]) {
183
- blockedIpv4Addresses.addSubnet(network, prefix, "ipv4");
184
- }
185
- for (const [network, prefix] of [
186
- ["::", 96],
187
- ["::ffff:0:0", 96],
188
- ["64:ff9b::", 96],
189
- ["64:ff9b:1::", 48],
190
- ["100::", 64],
191
- ["2001::", 32],
192
- ["2001:2::", 48],
193
- ["2001:10::", 28],
194
- ["2001:20::", 28],
195
- ["2001:db8::", 32],
196
- ["2002::", 16],
197
- ["fc00::", 7],
198
- ["fe80::", 10],
199
- ["fec0::", 10],
200
- ["ff00::", 8]
201
- ]) {
202
- blockedIpv6Addresses.addSubnet(network, prefix, "ipv6");
203
- }
204
- var defaultAddressResolver = (hostname) => lookup(hostname, { all: true, verbatim: true });
205
- function parseAndValidateMcpUrl(url) {
206
- const parsed = parseMcpHttpUrl(url);
207
- validateMcpHostname(parsed.hostname);
208
- return parsed;
209
- }
210
- function parseMcpHttpUrl(url) {
211
- let parsed;
212
- try {
213
- parsed = new URL(url);
214
- } catch {
215
- throw new Error(`Invalid MCP URL: ${url}`);
216
- }
217
- if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
218
- throw new Error(`MCP URL blocked: only HTTP(S) URLs are allowed (${parsed.protocol})`);
219
- }
220
- return parsed;
221
- }
222
- async function resolveAndValidateMcpHostname(hostname, resolveAddresses = defaultAddressResolver) {
223
- const normalizedHostname = normalizeHostname(hostname);
224
- validateMcpHostname(normalizedHostname);
225
- const family = isIP(normalizedHostname);
226
- if (family !== 0) {
227
- return [{ address: normalizedHostname, family }];
228
- }
229
- let addresses;
230
- try {
231
- addresses = await resolveAddresses(normalizedHostname);
232
- } catch (cause) {
233
- throw new Error(`Unable to resolve MCP URL hostname (${normalizedHostname})`, { cause });
234
- }
235
- if (addresses.length === 0) {
236
- throw new Error(`Unable to resolve MCP URL hostname (${normalizedHostname})`);
237
- }
238
- for (const { address } of addresses) {
239
- validateMcpHostname(address);
240
- }
241
- return addresses;
242
- }
243
- function createSafeMcpLookup(resolveAddresses = defaultAddressResolver) {
244
- return (hostname, options, callback) => {
245
- void resolveAndValidateMcpHostname(hostname, resolveAddresses).then(
246
- (addresses) => {
247
- const requestedFamily = normalizeRequestedFamily(options.family);
248
- const matchingAddresses = requestedFamily === 0 ? addresses : addresses.filter(({ family }) => family === requestedFamily);
249
- if (matchingAddresses.length === 0) {
250
- const error = new Error(`No matching address family for MCP URL (${hostname})`);
251
- Object.assign(error, { code: "EAI_ADDRFAMILY" });
252
- callback(error, []);
253
- return;
254
- }
255
- if (options.all) {
256
- callback(null, matchingAddresses);
257
- return;
258
- }
259
- const address = matchingAddresses[0];
260
- if (!address) {
261
- callback(new Error(`Unable to resolve MCP URL hostname (${hostname})`), []);
262
- return;
263
- }
264
- callback(null, address.address, address.family);
265
- },
266
- (cause) => {
267
- callback(asError(cause), []);
268
- }
269
- );
270
- };
271
- }
272
- function createSafeMcpFetch() {
273
- return (url, init) => {
274
- parseAndValidateMcpUrl(url);
275
- return undiciFetch(url, {
276
- ...init,
277
- dispatcher: safeMcpDispatcher
278
- });
279
- };
280
- }
281
- function validateMcpHostname(hostname) {
282
- const normalizedHostname = normalizeHostname(hostname);
283
- if (normalizedHostname === "localhost" || normalizedHostname.endsWith(".localhost")) {
284
- throw new Error(`MCP URL blocked: localhost not allowed (${normalizedHostname})`);
285
- }
286
- const family = isIP(normalizedHostname);
287
- if (family === 0) {
288
- return;
289
- }
290
- if (family === 4 && normalizedHostname.startsWith("127.") || family === 6 && normalizedHostname === "::1") {
291
- throw new Error(`MCP URL blocked: localhost not allowed (${normalizedHostname})`);
292
- }
293
- if (normalizedHostname === "169.254.169.254" || normalizedHostname === "fd00:ec2::254") {
294
- throw new Error(`MCP URL blocked: cloud metadata endpoint not allowed (${normalizedHostname})`);
295
- }
296
- if (family === 4 && blockedIpv4Addresses.check(normalizedHostname, "ipv4") || family === 6 && blockedIpv6Addresses.check(normalizedHostname, "ipv6")) {
297
- const range = family === 4 ? "IP" : "IPv6";
298
- throw new Error(`MCP URL blocked: private ${range} range not allowed (${normalizedHostname})`);
299
- }
300
- }
301
- function normalizeHostname(hostname) {
302
- const withoutBrackets = hostname.startsWith("[") && hostname.endsWith("]") ? hostname.slice(1, -1) : hostname;
303
- return withoutBrackets.toLowerCase().replace(/\.+$/, "");
304
- }
305
- function normalizeRequestedFamily(family) {
306
- if (family === 4 || family === "IPv4") {
307
- return 4;
308
- }
309
- if (family === 6 || family === "IPv6") {
310
- return 6;
311
- }
312
- return 0;
313
- }
314
- function asError(cause) {
315
- return cause instanceof Error ? cause : new Error(String(cause));
316
- }
317
- var safeMcpDispatcher = new Agent({
318
- autoSelectFamily: true,
319
- connect: {
320
- lookup: createSafeMcpLookup()
321
- },
322
- factory(origin, options) {
323
- parseAndValidateMcpUrl(origin);
324
- return new Pool(origin, options);
325
- }
326
- });
327
-
328
- // src/mcp/client.ts
329
- var coreClientVersion;
330
- var transportOwnedHttpHeaders = /* @__PURE__ */ new Set([
331
- "accept",
332
- "content-type",
333
- "last-event-id",
334
- "mcp-protocol-version",
335
- "mcp-session-id"
336
- ]);
337
- var McpClient = class {
338
- name;
339
- #options;
340
- #closed = false;
341
- #connectAbortController;
342
- #connecting;
343
- #resource;
344
- #server;
345
- constructor(options) {
346
- if (options.name.trim() === "") {
347
- throw new TypeError("MCP client name must not be empty");
348
- }
349
- this.name = options.name;
350
- this.#options = options;
351
- }
352
- connect(options = {}) {
353
- if (this.#closed) {
354
- return Promise.reject(new Error(`MCP client "${this.name}" is closed`));
355
- }
356
- if (this.#server !== void 0) {
357
- return Promise.resolve(this.#server);
358
- }
359
- if (this.#connecting !== void 0) {
360
- return this.#connecting;
361
- }
362
- if (options.abortSignal?.aborted === true) {
363
- return Promise.reject(abortError(options.abortSignal.reason));
364
- }
365
- const abortController = new AbortController();
366
- const unlinkAbortSignal = linkAbortSignal(options.abortSignal, abortController);
367
- this.#connectAbortController = abortController;
368
- const connecting = this.#initialize(abortController.signal);
369
- this.#connecting = connecting;
370
- const clearConnecting = () => {
371
- unlinkAbortSignal();
372
- if (this.#connecting === connecting) {
373
- this.#connecting = void 0;
374
- }
375
- if (this.#connectAbortController === abortController) {
376
- this.#connectAbortController = void 0;
377
- }
378
- };
379
- void connecting.then(clearConnecting, clearConnecting);
380
- return connecting;
381
- }
382
- async close() {
383
- this.#closed = true;
384
- this.#connectAbortController?.abort(
385
- abortError(new Error(`MCP client "${this.name}" was closed during connection`))
386
- );
387
- const resource = this.#resource;
388
- if (resource !== void 0) {
389
- await closeResource(resource);
390
- }
391
- }
392
- async #initialize(abortSignal) {
393
- const client = createSdkClient();
394
- const resource = { client };
395
- this.#resource = resource;
396
- try {
397
- throwIfAborted(abortSignal);
398
- const transport = await createTransport(this.#options, { abortSignal });
399
- throwIfAborted(abortSignal);
400
- await client.connect(transport, requestOptions(abortSignal));
401
- throwIfAborted(abortSignal);
402
- const definitions = await listAllTools(client, abortSignal);
403
- throwIfAborted(abortSignal);
404
- const tools = definitions.map(
405
- (definition) => createMcpTool({
406
- definition,
407
- client,
408
- serverName: this.name,
409
- prefix: this.#options.tools?.prefix
410
- })
411
- );
412
- assertUniqueToolNames(tools, this.name);
413
- if (this.#closed) {
414
- throw new Error(`MCP client "${this.name}" was closed during connection`);
415
- }
416
- const serverInfo = copyServerInfo(client.getServerVersion());
417
- const capabilities = copyJsonObject(client.getServerCapabilities());
418
- const instructions = client.getInstructions();
419
- let registration = {
420
- name: this.name,
421
- tools
422
- };
423
- if (serverInfo !== void 0) registration = { ...registration, serverInfo };
424
- if (capabilities !== void 0) registration = { ...registration, capabilities };
425
- if (instructions !== void 0) registration = { ...registration, instructions };
426
- const server = freezeServer(registration);
427
- this.#server = server;
428
- return server;
429
- } catch (error) {
430
- try {
431
- await closeResource(resource);
432
- } catch {
433
- }
434
- if (this.#resource === resource) {
435
- this.#resource = void 0;
436
- }
437
- this.#server = void 0;
438
- throw error;
439
- }
440
- }
441
- };
442
- async function createTransport(options, connectOptions) {
443
- const transport = options.transport;
444
- if (transport.type === "custom") {
445
- return transport.create({ abortSignal: connectOptions.abortSignal });
446
- }
447
- if (transport.type === "stdio") {
448
- let parameters2 = {
449
- command: transport.command
450
- };
451
- if (transport.args !== void 0) parameters2 = { ...parameters2, args: transport.args };
452
- if (transport.env !== void 0) parameters2 = { ...parameters2, env: transport.env };
453
- if (transport.cwd !== void 0) parameters2 = { ...parameters2, cwd: transport.cwd };
454
- if (transport.stderr !== void 0) parameters2 = { ...parameters2, stderr: transport.stderr };
455
- if (transport.maxBufferSize !== void 0) {
456
- parameters2 = { ...parameters2, maxBufferSize: transport.maxBufferSize };
457
- }
458
- return new StdioClientTransport(parameters2);
459
- }
460
- const ssrfProtection = transport.ssrfProtection ?? "strict";
461
- if (ssrfProtection !== "strict" && ssrfProtection !== "disabled") {
462
- throw new TypeError("MCP Streamable HTTP ssrfProtection must be strict or disabled");
463
- }
464
- let parameters = {};
465
- let url;
466
- let transportFetch;
467
- if (ssrfProtection === "strict") {
468
- transportFetch = createSafeMcpFetch();
469
- url = parseAndValidateMcpUrl(transport.url);
470
- } else {
471
- url = parseMcpHttpUrl(transport.url);
472
- }
473
- if (transport.headers !== void 0) {
474
- const headers = copyMcpHeaders(transport.headers, transport.authProvider !== void 0);
475
- const fetchRequest = transportFetch ?? defaultMcpFetch;
476
- transportFetch = createMcpEndpointFetch(url, headers, fetchRequest);
477
- }
478
- if (transportFetch !== void 0) parameters = { ...parameters, fetch: transportFetch };
479
- if (transport.authProvider !== void 0) {
480
- parameters = { ...parameters, authProvider: transport.authProvider };
481
- }
482
- if (transport.reconnectionOptions !== void 0) {
483
- parameters = { ...parameters, reconnectionOptions: transport.reconnectionOptions };
484
- }
485
- if (transport.sessionId !== void 0) {
486
- parameters = { ...parameters, sessionId: transport.sessionId };
487
- }
488
- return asSdkTransport(new StreamableHTTPClientTransport(url, parameters));
489
- }
490
- function copyMcpHeaders(value, hasAuthProvider) {
491
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
492
- throw new TypeError("MCP Streamable HTTP headers must be a plain object");
493
- }
494
- const prototype = Object.getPrototypeOf(value);
495
- if (prototype !== Object.prototype && prototype !== null) {
496
- throw new TypeError("MCP Streamable HTTP headers must be a plain object");
497
- }
498
- const headers = new Headers();
499
- for (const [name, headerValue] of Object.entries(value)) {
500
- if (typeof headerValue !== "string") {
501
- throw new TypeError(`MCP Streamable HTTP header ${name} must be a string`);
502
- }
503
- const normalizedName = name.toLowerCase();
504
- if (transportOwnedHttpHeaders.has(normalizedName)) {
505
- throw new TypeError(`MCP Streamable HTTP header ${name} is owned by the transport`);
506
- }
507
- if (hasAuthProvider && normalizedName === "authorization") {
508
- throw new TypeError(
509
- "MCP Streamable HTTP authorization header cannot be combined with authProvider"
510
- );
511
- }
512
- headers.set(name, headerValue);
513
- }
514
- return headers;
515
- }
516
- function createMcpEndpointFetch(endpoint, configuredHeaders, fetchRequest) {
517
- return (input, init) => {
518
- const requestUrl = input instanceof Request ? new URL(input.url) : new URL(input);
519
- if (requestUrl.href !== endpoint.href) return fetchRequest(input, init);
520
- const requestHeaders = new Headers(
521
- init?.headers ?? (input instanceof Request ? input.headers : void 0)
522
- );
523
- configuredHeaders.forEach((value, name) => {
524
- requestHeaders.set(name, value);
525
- });
526
- return fetchRequest(input, { ...init, headers: requestHeaders, redirect: "error" });
527
- };
528
- }
529
- var defaultMcpFetch = (input, init) => globalThis.fetch(input, init);
530
- async function listAllTools(client, abortSignal) {
531
- const tools = [];
532
- const seenCursors = /* @__PURE__ */ new Set();
533
- let cursor;
534
- do {
535
- const page = await client.listTools(
536
- cursor === void 0 ? void 0 : { cursor },
537
- requestOptions(abortSignal)
538
- );
539
- tools.push(...page.tools);
540
- cursor = page.nextCursor;
541
- if (cursor !== void 0 && seenCursors.has(cursor)) {
542
- throw new Error(`MCP server returned a repeated tools cursor: ${cursor}`);
543
- }
544
- if (cursor !== void 0) {
545
- seenCursors.add(cursor);
546
- }
547
- } while (cursor !== void 0);
548
- return tools;
549
- }
550
- function assertUniqueToolNames(tools, serverName) {
551
- const names = /* @__PURE__ */ new Set();
552
- for (const tool of tools) {
553
- if (names.has(tool.name)) {
554
- throw new Error(`Duplicate MCP tool name "${tool.name}" from server "${serverName}"`);
555
- }
556
- names.add(tool.name);
557
- }
558
- }
559
- function createSdkClient() {
560
- return new Client({
561
- name: "@anvia/core",
562
- version: getCoreClientVersion()
563
- });
564
- }
565
- function getCoreClientVersion() {
566
- if (coreClientVersion === void 0) {
567
- coreClientVersion = readCorePackageVersion();
568
- }
569
- return coreClientVersion;
570
- }
571
- function requestOptions(signal) {
572
- return signal === void 0 ? {} : { signal };
573
- }
574
- function asSdkTransport(transport) {
575
- return transport;
576
- }
577
- function closeResource(resource) {
578
- resource.closePromise ??= resource.client.close();
579
- return resource.closePromise;
580
- }
581
- function readCorePackageVersion() {
582
- try {
583
- const packageJson = JSON.parse(
584
- readFileSync(new URL("../../package.json", import.meta.url), "utf8")
585
- );
586
- return typeof packageJson.version === "string" ? packageJson.version : "0.0.0";
587
- } catch {
588
- return "0.0.0";
589
- }
590
- }
591
- function copyServerInfo(value) {
592
- if (value === void 0) {
593
- return void 0;
594
- }
595
- return deepFreeze2(structuredClone(value));
596
- }
597
- function copyJsonObject(value) {
598
- if (value === void 0) {
599
- return void 0;
600
- }
601
- return deepFreeze2(structuredClone(value));
602
- }
603
- function freezeServer(server) {
604
- Object.freeze(server.tools);
605
- return Object.freeze(server);
606
- }
607
- function deepFreeze2(value) {
608
- if (typeof value !== "object" || value === null || Object.isFrozen(value)) {
609
- return value;
610
- }
611
- for (const child of Object.values(value)) {
612
- deepFreeze2(child);
613
- }
614
- return Object.freeze(value);
615
- }
616
-
617
- // src/mcp/client-group.ts
618
- var McpClientGroup = class _McpClientGroup {
619
- clients;
620
- servers;
621
- #closePromise;
622
- constructor(clients, servers) {
623
- this.clients = Object.freeze([...clients]);
624
- this.servers = Object.freeze([...servers]);
625
- }
626
- static async connect(options) {
627
- const clients = [...options.clients];
628
- assertUniqueClientNames(clients);
629
- const abortController = new AbortController();
630
- const unlinkAbortSignal = linkAbortSignal(options.abortSignal, abortController);
631
- let firstConnectionFailure;
632
- let connectionFailed = false;
633
- const connections = clients.map(
634
- (client) => client.connect({ abortSignal: abortController.signal }).catch((error) => {
635
- if (!connectionFailed) {
636
- connectionFailed = true;
637
- firstConnectionFailure = error;
638
- abortController.abort(error);
639
- }
640
- throw error;
641
- })
642
- );
643
- const settled = await Promise.allSettled(connections).finally(unlinkAbortSignal);
644
- const firstFailure = settled.find(
645
- (result) => result.status === "rejected"
646
- );
647
- if (firstFailure !== void 0) {
648
- await rollbackSuccessfulClients(clients, settled);
649
- throw connectionFailed ? firstConnectionFailure : firstFailure.reason;
650
- }
651
- const servers = settled.map((result) => result.value);
652
- try {
653
- assertUniqueServerAndToolNames(servers);
654
- } catch (error) {
655
- try {
656
- await closeAll(clients);
657
- } catch {
658
- }
659
- throw error;
660
- }
661
- return new _McpClientGroup(clients, servers);
662
- }
663
- close() {
664
- this.#closePromise ??= closeAll(this.clients);
665
- return this.#closePromise;
666
- }
667
- };
668
- function assertUniqueClientNames(clients) {
669
- const names = /* @__PURE__ */ new Set();
670
- for (const client of clients) {
671
- if (names.has(client.name)) {
672
- throw new Error(`Duplicate MCP client name "${client.name}"`);
673
- }
674
- names.add(client.name);
675
- }
676
- }
677
- function assertUniqueServerAndToolNames(servers) {
678
- const serverNames = /* @__PURE__ */ new Set();
679
- const toolNames = /* @__PURE__ */ new Map();
680
- for (const server of servers) {
681
- if (serverNames.has(server.name)) {
682
- throw new Error(`Duplicate MCP server name "${server.name}"`);
683
- }
684
- serverNames.add(server.name);
685
- for (const tool of server.tools) {
686
- const existing = toolNames.get(tool.name);
687
- if (existing !== void 0) {
688
- throw new Error(
689
- `Duplicate MCP tool name "${tool.name}" from servers "${existing}" and "${server.name}"`
690
- );
691
- }
692
- toolNames.set(tool.name, server.name);
693
- }
694
- }
695
- }
696
- async function rollbackSuccessfulClients(clients, settled) {
697
- const successful = clients.filter((_, index) => settled[index]?.status === "fulfilled");
698
- try {
699
- await closeAll(successful);
700
- } catch {
701
- }
702
- }
703
- async function closeAll(clients) {
704
- const settled = await Promise.allSettled(clients.map((client) => client.close()));
705
- const errors = settled.flatMap((result) => result.status === "rejected" ? [result.reason] : []);
706
- if (errors.length > 0) {
707
- throw new AggregateError(errors, "Failed to close one or more MCP clients");
708
- }
709
- }
710
-
711
- export {
712
- isMcpTool,
713
- McpClient,
714
- McpClientGroup
715
- };
716
- //# sourceMappingURL=chunk-76JLMBVT.js.map