mcp-use 1.7.0-canary.1 → 1.7.0-canary.3

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 (52) hide show
  1. package/dist/.tsbuildinfo +1 -1
  2. package/dist/{chunk-PE7UMCVO.js → chunk-3R5PDYIN.js} +27 -1
  3. package/dist/{chunk-XN2PU4PS.js → chunk-BBEY6HHN.js} +59 -7
  4. package/dist/{chunk-YURRUCIM.js → chunk-CPG2WZUL.js} +9 -11
  5. package/dist/{chunk-R5DJJ4IV.js → chunk-F4UHAA5L.js} +3 -91
  6. package/dist/chunk-MTHLLDCX.js +97 -0
  7. package/dist/{chunk-QSLJXXMG.js → chunk-PSO6HYXH.js} +4 -4
  8. package/dist/{chunk-GVVPUU5K.js → chunk-S6K5QZBJ.js} +739 -29
  9. package/dist/{display-YIYC6WJE.js → display-A5IEINAP.js} +79 -17
  10. package/dist/index.cjs +952 -107
  11. package/dist/index.js +6 -5
  12. package/dist/{langfuse-C4HKZ3NL.js → langfuse-N5Y5BSXK.js} +1 -1
  13. package/dist/{oauth-CNGBFOZW.js → oauth-U4NNKN4B.js} +2 -1
  14. package/dist/src/agents/display.d.ts.map +1 -1
  15. package/dist/src/agents/index.cjs +854 -78
  16. package/dist/src/agents/index.js +3 -2
  17. package/dist/src/auth/index.cjs +30 -5
  18. package/dist/src/auth/index.js +1 -1
  19. package/dist/src/browser.cjs +888 -90
  20. package/dist/src/browser.js +5 -4
  21. package/dist/src/connectors/base.d.ts +53 -391
  22. package/dist/src/connectors/base.d.ts.map +1 -1
  23. package/dist/src/managers/server_manager.d.ts.map +1 -1
  24. package/dist/src/managers/tools/acquire_active_mcp_server.d.ts +2 -2
  25. package/dist/src/managers/tools/acquire_active_mcp_server.d.ts.map +1 -1
  26. package/dist/src/managers/tools/add_server_from_config.d.ts +1 -7
  27. package/dist/src/managers/tools/add_server_from_config.d.ts.map +1 -1
  28. package/dist/src/managers/tools/connect_mcp_server.d.ts +2 -10
  29. package/dist/src/managers/tools/connect_mcp_server.d.ts.map +1 -1
  30. package/dist/src/managers/tools/list_mcp_servers.d.ts +2 -2
  31. package/dist/src/managers/tools/list_mcp_servers.d.ts.map +1 -1
  32. package/dist/src/managers/tools/release_mcp_server_connection.d.ts +2 -2
  33. package/dist/src/managers/tools/release_mcp_server_connection.d.ts.map +1 -1
  34. package/dist/src/observability/langfuse.d.ts +4 -0
  35. package/dist/src/observability/langfuse.d.ts.map +1 -1
  36. package/dist/src/react/McpUseProvider.d.ts.map +1 -1
  37. package/dist/src/react/index.cjs +86 -12
  38. package/dist/src/react/index.js +4 -3
  39. package/dist/src/server/connect-adapter.d.ts.map +1 -1
  40. package/dist/src/server/index.cjs +28 -17
  41. package/dist/src/server/index.js +38 -25
  42. package/dist/src/server/mcp-server.d.ts.map +1 -1
  43. package/dist/src/utils/json-schema-to-zod/JSONSchemaToZod.d.ts +270 -0
  44. package/dist/src/utils/json-schema-to-zod/JSONSchemaToZod.d.ts.map +1 -0
  45. package/dist/src/utils/json-schema-to-zod/Type.d.ts +24 -0
  46. package/dist/src/utils/json-schema-to-zod/Type.d.ts.map +1 -0
  47. package/dist/src/utils/json-schema-to-zod/index.d.ts +3 -0
  48. package/dist/src/utils/json-schema-to-zod/index.d.ts.map +1 -0
  49. package/dist/src/utils/url-sanitize.d.ts +17 -0
  50. package/dist/src/utils/url-sanitize.d.ts.map +1 -0
  51. package/dist/tsup.config.d.ts.map +1 -1
  52. package/package.json +20 -37
@@ -335,13 +335,13 @@ async function initializeLangfuse(agentId, metadata, metadataProvider, tagsProvi
335
335
  metadataProvider;
336
336
  tagsProvider;
337
337
  verbose;
338
- constructor(config3, agentId2, metadata2, metadataProvider2, tagsProvider2) {
339
- super(config3);
338
+ constructor(config2, agentId2, metadata2, metadataProvider2, tagsProvider2) {
339
+ super(config2);
340
340
  this.agentId = agentId2;
341
341
  this.metadata = metadata2;
342
342
  this.metadataProvider = metadataProvider2;
343
343
  this.tagsProvider = tagsProvider2;
344
- this.verbose = config3?.verbose ?? false;
344
+ this.verbose = config2?.verbose ?? false;
345
345
  }
346
346
  // Override to add custom metadata to traces
347
347
  async handleChainStart(chain, inputs, runId, parentRunId, tags, metadata2, name, kwargs) {
@@ -466,7 +466,7 @@ async function initializeLangfuse(agentId, metadata, metadataProvider, tagsProvi
466
466
  }
467
467
  const initialMetadata = metadata || (metadataProvider ? metadataProvider() : {});
468
468
  const initialTags = tagsProvider ? tagsProvider() : [];
469
- const config2 = {
469
+ const config = {
470
470
  publicKey: process.env.LANGFUSE_PUBLIC_KEY,
471
471
  secretKey: process.env.LANGFUSE_SECRET_KEY,
472
472
  baseUrl: process.env.LANGFUSE_HOST || process.env.LANGFUSE_BASEURL || "https://cloud.langfuse.com",
@@ -491,17 +491,17 @@ async function initializeLangfuse(agentId, metadata, metadataProvider, tagsProvi
491
491
  "Langfuse handler config:",
492
492
  JSON.stringify(
493
493
  {
494
- traceName: config2.traceName,
495
- sessionId: config2.sessionId,
496
- userId: config2.userId,
497
- tags: config2.tags
494
+ traceName: config.traceName,
495
+ sessionId: config.sessionId,
496
+ userId: config.userId,
497
+ tags: config.tags
498
498
  },
499
499
  null,
500
500
  2
501
501
  )
502
502
  );
503
503
  langfuseState.handler = new LoggingCallbackHandler(
504
- config2,
504
+ config,
505
505
  agentId,
506
506
  metadata,
507
507
  metadataProvider,
@@ -528,13 +528,11 @@ async function initializeLangfuse(agentId, metadata, metadataProvider, tagsProvi
528
528
  logger.debug(`Langfuse initialization error: ${error}`);
529
529
  }
530
530
  }
531
- var import_dotenv, langfuseDisabled, langfuseState, langfuseHandler, langfuseClient, langfuseInitPromise;
531
+ var langfuseDisabled, langfuseState, langfuseHandler, langfuseClient, langfuseInitPromise;
532
532
  var init_langfuse = __esm({
533
533
  "src/observability/langfuse.ts"() {
534
534
  "use strict";
535
- import_dotenv = require("dotenv");
536
535
  init_logging();
537
- (0, import_dotenv.config)();
538
536
  langfuseDisabled = process.env.MCP_USE_LANGFUSE?.toLowerCase() === "false";
539
537
  langfuseState = {
540
538
  handler: null,
@@ -573,8 +571,24 @@ __export(display_exports, {
573
571
  renderContent: () => renderContent,
574
572
  unwrapToolInput: () => unwrapToolInput
575
573
  });
574
+ function highlightCode(content, language) {
575
+ if (!highlight) {
576
+ return content;
577
+ }
578
+ try {
579
+ return highlight(content, {
580
+ language: language ?? "javascript",
581
+ ignoreIllegals: true
582
+ });
583
+ } catch {
584
+ return content;
585
+ }
586
+ }
576
587
  function stripAnsi(str) {
577
- return (0, import_strip_ansi.default)(str);
588
+ if (stripVTControlCharacters) {
589
+ return stripVTControlCharacters(str);
590
+ }
591
+ return str.replace(/\x1b\[[0-9;]*m/g, "");
578
592
  }
579
593
  function wrapAnsiLine(line, maxWidth) {
580
594
  const stripped = stripAnsi(line);
@@ -614,28 +628,28 @@ function printBox(content, title, language, bgColor = false) {
614
628
  let displayContent = content;
615
629
  if (language) {
616
630
  try {
617
- displayContent = (0, import_cli_highlight.highlight)(content, { language, ignoreIllegals: true });
631
+ displayContent = highlightCode(content, language);
618
632
  } catch {
619
633
  }
620
634
  }
621
635
  const lines = displayContent.split("\n").flatMap((line) => wrapAnsiLine(line, width - 4));
622
- console.log(import_chalk.default.gray("\u250C" + "\u2500".repeat(width - 2) + "\u2510"));
636
+ console.log(chalkHelper.gray("\u250C" + "\u2500".repeat(width - 2) + "\u2510"));
623
637
  if (title) {
624
638
  const stripped = stripAnsi(title);
625
639
  const lineText = `${title} `;
626
640
  const padding = Math.max(0, width - 4 - stripped.length - 2);
627
641
  console.log(
628
- import_chalk.default.gray("\u2502 ") + import_chalk.default.bold.white(lineText) + " ".repeat(padding) + import_chalk.default.gray(" \u2502")
642
+ chalkHelper.gray("\u2502 ") + chalkHelper.bold.white(lineText) + " ".repeat(padding) + chalkHelper.gray(" \u2502")
629
643
  );
630
- console.log(import_chalk.default.gray("\u251C" + "\u2500".repeat(width - 2) + "\u2524"));
644
+ console.log(chalkHelper.gray("\u251C" + "\u2500".repeat(width - 2) + "\u2524"));
631
645
  }
632
646
  lines.forEach((line) => {
633
647
  const stripped = stripAnsi(line);
634
648
  const padding = Math.max(0, width - 4 - stripped.length);
635
- const finalLine = bgColor ? import_chalk.default.bgGray(line + " ".repeat(padding)) : line + " ".repeat(padding);
636
- console.log(import_chalk.default.gray("\u2502 ") + finalLine + import_chalk.default.gray(" \u2502"));
649
+ const finalLine = bgColor ? chalkHelper.bgGray(line + " ".repeat(padding)) : line + " ".repeat(padding);
650
+ console.log(chalkHelper.gray("\u2502 ") + finalLine + chalkHelper.gray(" \u2502"));
637
651
  });
638
- console.log(import_chalk.default.gray("\u2514" + "\u2500".repeat(width - 2) + "\u2518"));
652
+ console.log(chalkHelper.gray("\u2514" + "\u2500".repeat(width - 2) + "\u2518"));
639
653
  }
640
654
  function extractCodeFromToolInput(input) {
641
655
  if (typeof input === "object" && input !== null && "code" in input) {
@@ -774,7 +788,7 @@ ${noResultsMsg}`;
774
788
  const isLastServer = i === servers.length - 1;
775
789
  const serverPrefix = isLastServer ? "\u2514\u2500" : "\u251C\u2500";
776
790
  lines.push(
777
- `${serverPrefix} ${import_chalk.default.cyan(server)} (${serverTools.length} tools)`
791
+ `${serverPrefix} ${chalkHelper.cyan(server)} (${serverTools.length} tools)`
778
792
  );
779
793
  for (let j = 0; j < serverTools.length; j++) {
780
794
  const tool = serverTools[j];
@@ -806,7 +820,7 @@ ${noResultsMsg}`;
806
820
  wrappedLines.push(currentLine.trimEnd());
807
821
  }
808
822
  for (const descLine of wrappedLines) {
809
- lines.push(`${descriptionIndent}${import_chalk.default.dim(descLine)}`);
823
+ lines.push(`${descriptionIndent}${chalkHelper.dim(descLine)}`);
810
824
  }
811
825
  }
812
826
  }
@@ -833,7 +847,7 @@ function handleToolEnd(event) {
833
847
  const timeMs = execResult2.execution_time ? Math.round(execResult2.execution_time * 1e3) : 0;
834
848
  const timeStr = `${timeMs}ms`;
835
849
  const isError2 = execResult2.error !== null && execResult2.error !== void 0 && execResult2.error !== "";
836
- const statusText = isError2 ? import_chalk.default.red("error") : import_chalk.default.green("success");
850
+ const statusText = isError2 ? chalkHelper.red("error") : chalkHelper.green("success");
837
851
  const title2 = `${toolName} - ${statusText} - ${timeStr}`;
838
852
  if (execResult2.result !== null && execResult2.result !== void 0) {
839
853
  const resultStr = renderContent(execResult2.result);
@@ -846,7 +860,12 @@ function handleToolEnd(event) {
846
860
  printBox(execResult2.logs.join("\n"), `Logs`, void 0, false);
847
861
  }
848
862
  if (execResult2.error) {
849
- printBox(execResult2.error, import_chalk.default.red("Error"), void 0, false);
863
+ printBox(
864
+ execResult2.error,
865
+ chalkHelper.red("Error"),
866
+ void 0,
867
+ false
868
+ );
850
869
  }
851
870
  return;
852
871
  }
@@ -872,7 +891,7 @@ function handleToolEnd(event) {
872
891
  const contentWithMeta = actualContent;
873
892
  const meta = contentWithMeta.meta;
874
893
  const treeStr = formatSearchToolsAsTree(results, meta, query);
875
- const statusText = status === "success" ? import_chalk.default.green("Success") : import_chalk.default.red("Error");
894
+ const statusText = status === "success" ? chalk.green("Success") : chalk.red("Error");
876
895
  const title2 = `${statusText}: ${toolName} - Result`;
877
896
  printBox(treeStr, title2, void 0, false);
878
897
  return;
@@ -883,7 +902,7 @@ function handleToolEnd(event) {
883
902
  void 0,
884
903
  query
885
904
  );
886
- const statusText = status === "success" ? import_chalk.default.green("Success") : import_chalk.default.red("Error");
905
+ const statusText = status === "success" ? chalk.green("Success") : chalk.red("Error");
887
906
  const title2 = `${statusText}: ${toolName} - Result`;
888
907
  printBox(treeStr, title2, void 0, false);
889
908
  return;
@@ -902,7 +921,7 @@ function handleToolEnd(event) {
902
921
  }
903
922
  const contentStr = renderContent(displayContent);
904
923
  const language2 = typeof displayContent === "object" ? "json" : void 0;
905
- const statusLabel = status === "success" ? import_chalk.default.green("Success") : isError ? import_chalk.default.red("Error") : "Result";
924
+ const statusLabel = status === "success" ? chalkHelper.green("Success") : isError ? chalkHelper.red("Error") : "Result";
906
925
  const title = `${statusLabel}: ${toolName} - Result`;
907
926
  printBox(contentStr, title, language2, false);
908
927
  return;
@@ -920,7 +939,7 @@ function handleToolEnd(event) {
920
939
  printBox(execResult.logs.join("\n"), `Logs`, void 0, false);
921
940
  }
922
941
  if (execResult.error) {
923
- printBox(execResult.error, import_chalk.default.red("Error"), void 0, false);
942
+ printBox(execResult.error, chalkHelper.red("Error"), void 0, false);
924
943
  }
925
944
  return;
926
945
  }
@@ -960,14 +979,55 @@ async function* prettyStreamEvents(streamEventsGenerator) {
960
979
  }
961
980
  return finalResponse;
962
981
  }
963
- var import_chalk, import_cli_highlight, import_strip_ansi, TERMINAL_WIDTH;
982
+ var chalk, highlight, stripVTControlCharacters, displayPackagesWarned, isNode, TERMINAL_WIDTH, chalkHelper;
964
983
  var init_display = __esm({
965
984
  "src/agents/display.ts"() {
966
985
  "use strict";
967
- import_chalk = __toESM(require("chalk"), 1);
968
- import_cli_highlight = require("cli-highlight");
969
- import_strip_ansi = __toESM(require("strip-ansi"), 1);
986
+ chalk = null;
987
+ highlight = null;
988
+ stripVTControlCharacters = null;
989
+ displayPackagesWarned = false;
990
+ isNode = typeof process !== "undefined" && process.versions?.node;
991
+ (async () => {
992
+ if (isNode) {
993
+ try {
994
+ const utilModule = await import("util");
995
+ stripVTControlCharacters = utilModule.stripVTControlCharacters;
996
+ } catch {
997
+ }
998
+ }
999
+ try {
1000
+ const chalkModule = await import("chalk");
1001
+ chalk = chalkModule.default;
1002
+ } catch {
1003
+ }
1004
+ try {
1005
+ const cliHighlightModule = await import("cli-highlight");
1006
+ highlight = cliHighlightModule.highlight;
1007
+ } catch {
1008
+ }
1009
+ if (isNode && (!chalk || !highlight)) {
1010
+ if (!displayPackagesWarned) {
1011
+ displayPackagesWarned = true;
1012
+ console.warn(
1013
+ "\n\u2728 For enhanced console output with colors and syntax highlighting, install:\n\n npm install chalk cli-highlight\n # or\n pnpm add chalk cli-highlight\n"
1014
+ );
1015
+ }
1016
+ }
1017
+ })();
970
1018
  TERMINAL_WIDTH = process.stdout.columns || 120;
1019
+ chalkHelper = {
1020
+ gray: /* @__PURE__ */ __name((str) => chalk?.gray(str) ?? str, "gray"),
1021
+ bold: {
1022
+ white: /* @__PURE__ */ __name((str) => chalk?.bold?.white(str) ?? str, "white")
1023
+ },
1024
+ bgGray: /* @__PURE__ */ __name((str) => chalk?.bgGray(str) ?? str, "bgGray"),
1025
+ cyan: /* @__PURE__ */ __name((str) => chalk?.cyan(str) ?? str, "cyan"),
1026
+ dim: /* @__PURE__ */ __name((str) => chalk?.dim(str) ?? str, "dim"),
1027
+ red: /* @__PURE__ */ __name((str) => chalk?.red(str) ?? str, "red"),
1028
+ green: /* @__PURE__ */ __name((str) => chalk?.green(str) ?? str, "green")
1029
+ };
1030
+ __name(highlightCode, "highlightCode");
971
1031
  __name(stripAnsi, "stripAnsi");
972
1032
  __name(wrapAnsiLine, "wrapAnsiLine");
973
1033
  __name(printBox, "printBox");
@@ -1838,8 +1898,14 @@ var HttpConnector = class extends BaseConnector {
1838
1898
  }
1839
1899
  };
1840
1900
 
1901
+ // src/server/utils/runtime.ts
1902
+ var isDeno = typeof globalThis.Deno !== "undefined";
1903
+ function generateUUID() {
1904
+ return globalThis.crypto.randomUUID();
1905
+ }
1906
+ __name(generateUUID, "generateUUID");
1907
+
1841
1908
  // src/connectors/websocket.ts
1842
- var import_uuid = require("uuid");
1843
1909
  init_logging();
1844
1910
 
1845
1911
  // src/task_managers/websocket.ts
@@ -1961,7 +2027,7 @@ var WebSocketConnector = class extends BaseConnector {
1961
2027
  }
1962
2028
  sendRequest(method, params = null) {
1963
2029
  if (!this.ws) throw new Error("WebSocket is not connected");
1964
- const id = (0, import_uuid.v4)();
2030
+ const id = generateUUID();
1965
2031
  const payload = JSON.stringify({ id, method, params: params ?? {} });
1966
2032
  return new Promise((resolve, reject) => {
1967
2033
  this.pending.set(id, { resolve, reject });
@@ -2200,9 +2266,9 @@ var BaseMCPClient = class {
2200
2266
  config = {};
2201
2267
  sessions = {};
2202
2268
  activeSessions = [];
2203
- constructor(config2) {
2204
- if (config2) {
2205
- this.config = config2;
2269
+ constructor(config) {
2270
+ if (config) {
2271
+ this.config = config;
2206
2272
  }
2207
2273
  }
2208
2274
  static fromDict(_cfg) {
@@ -2314,8 +2380,8 @@ var BrowserMCPClient = class _BrowserMCPClient extends BaseMCPClient {
2314
2380
  static {
2315
2381
  __name(this, "BrowserMCPClient");
2316
2382
  }
2317
- constructor(config2) {
2318
- super(config2);
2383
+ constructor(config) {
2384
+ super(config);
2319
2385
  }
2320
2386
  static fromDict(cfg) {
2321
2387
  return new _BrowserMCPClient(cfg);
@@ -2372,12 +2438,699 @@ var BrowserMCPClient = class _BrowserMCPClient extends BaseMCPClient {
2372
2438
 
2373
2439
  // src/agents/mcp_agent.ts
2374
2440
  var import_langchain2 = require("langchain");
2375
- var import_zod_to_json_schema2 = require("zod-to-json-schema");
2441
+ var import_zod9 = require("zod");
2442
+
2443
+ // src/utils/json-schema-to-zod/JSONSchemaToZod.ts
2444
+ var import_zod = require("zod");
2445
+ var JSONSchemaToZod = class {
2446
+ static {
2447
+ __name(this, "JSONSchemaToZod");
2448
+ }
2449
+ /**
2450
+ * Converts a JSON schema to a Zod schema.
2451
+ *
2452
+ * @param {JSONSchema} schema - The JSON schema.
2453
+ * @returns {ZodSchema} - The Zod schema.
2454
+ */
2455
+ static convert(schema) {
2456
+ return this.parseSchema(schema);
2457
+ }
2458
+ /**
2459
+ * Checks if data matches a condition schema.
2460
+ *
2461
+ * @param {JSONValue} data - The data to check.
2462
+ * @param {JSONSchema} condition - The condition schema.
2463
+ * @returns {boolean} - Whether the data matches the condition.
2464
+ */
2465
+ static matchesCondition(data, condition) {
2466
+ if (!condition.properties) {
2467
+ return true;
2468
+ }
2469
+ if (typeof data !== "object" || data === null || Array.isArray(data)) {
2470
+ return false;
2471
+ }
2472
+ const objectData = data;
2473
+ for (const [key, propCondition] of Object.entries(condition.properties)) {
2474
+ if (!(key in objectData)) {
2475
+ if ("const" in propCondition) {
2476
+ return false;
2477
+ }
2478
+ continue;
2479
+ }
2480
+ const value = objectData[key];
2481
+ if ("const" in propCondition && value !== propCondition["const"]) {
2482
+ return false;
2483
+ }
2484
+ if ("minimum" in propCondition && typeof value === "number" && value < propCondition["minimum"]) {
2485
+ return false;
2486
+ }
2487
+ if ("maximum" in propCondition && typeof value === "number" && value > propCondition["maximum"]) {
2488
+ return false;
2489
+ }
2490
+ }
2491
+ return true;
2492
+ }
2493
+ /**
2494
+ * Validates data against a conditional schema and adds issues to context if validation fails.
2495
+ *
2496
+ * @param {JSONValue} data - The data to validate.
2497
+ * @param {JSONSchema} schema - The conditional schema.
2498
+ * @param {z.RefinementCtx} ctx - The Zod refinement context.
2499
+ */
2500
+ static validateConditionalSchema(data, schema, ctx) {
2501
+ this.validateRequiredProperties(data, schema, ctx);
2502
+ this.validatePropertyPatterns(data, schema, ctx);
2503
+ this.validateNestedConditions(data, schema, ctx);
2504
+ }
2505
+ /**
2506
+ * Validates that all required properties are present in the data.
2507
+ *
2508
+ * @param {JSONValue} data - The data to validate.
2509
+ * @param {JSONSchema} schema - The schema containing required properties.
2510
+ * @param {z.RefinementCtx} ctx - The Zod refinement context.
2511
+ */
2512
+ static validateRequiredProperties(data, schema, ctx) {
2513
+ if (!schema.required) {
2514
+ return;
2515
+ }
2516
+ if (typeof data !== "object" || data === null) {
2517
+ for (const requiredProp of schema.required) {
2518
+ ctx.addIssue({
2519
+ code: import_zod.z.ZodIssueCode.custom,
2520
+ message: `Required property '${requiredProp}' is missing`,
2521
+ path: [requiredProp]
2522
+ });
2523
+ }
2524
+ return;
2525
+ }
2526
+ for (const requiredProp of schema.required) {
2527
+ if (!(requiredProp in data)) {
2528
+ ctx.addIssue({
2529
+ code: import_zod.z.ZodIssueCode.custom,
2530
+ message: `Required property '${requiredProp}' is missing`,
2531
+ path: [requiredProp]
2532
+ });
2533
+ }
2534
+ }
2535
+ }
2536
+ /**
2537
+ * Validates property patterns for string properties.
2538
+ *
2539
+ * @param {JSONValue} data - The data to validate.
2540
+ * @param {JSONSchema} schema - The schema containing property patterns.
2541
+ * @param {z.RefinementCtx} ctx - The Zod refinement context.
2542
+ */
2543
+ static validatePropertyPatterns(data, schema, ctx) {
2544
+ if (!schema.properties) {
2545
+ return;
2546
+ }
2547
+ if (typeof data !== "object" || data === null) {
2548
+ return;
2549
+ }
2550
+ if (Array.isArray(data)) {
2551
+ return;
2552
+ }
2553
+ const objectData = data;
2554
+ for (const [key, propSchema] of Object.entries(schema.properties)) {
2555
+ if (!(key in objectData)) {
2556
+ continue;
2557
+ }
2558
+ const value = objectData[key];
2559
+ if (propSchema["pattern"] && typeof value === "string") {
2560
+ const regex = new RegExp(propSchema["pattern"]);
2561
+ if (!regex.test(value)) {
2562
+ ctx.addIssue({
2563
+ code: import_zod.z.ZodIssueCode.custom,
2564
+ message: `String '${value}' does not match pattern '${propSchema["pattern"]}'`,
2565
+ path: [key]
2566
+ });
2567
+ }
2568
+ }
2569
+ }
2570
+ }
2571
+ /**
2572
+ * Validates nested if-then-else conditions.
2573
+ *
2574
+ * @param {JSONValue} data - The data to validate.
2575
+ * @param {JSONSchema} schema - The schema containing if-then-else conditions.
2576
+ * @param {z.RefinementCtx} ctx - The Zod refinement context.
2577
+ */
2578
+ static validateNestedConditions(data, schema, ctx) {
2579
+ if (!schema["if"] || !schema["then"]) {
2580
+ return;
2581
+ }
2582
+ const matchesIf = this.matchesCondition(data, schema["if"]);
2583
+ if (matchesIf) {
2584
+ this.validateConditionalSchema(data, schema["then"], ctx);
2585
+ } else if (schema["else"]) {
2586
+ this.validateConditionalSchema(data, schema["else"], ctx);
2587
+ }
2588
+ }
2589
+ /**
2590
+ * Parses a JSON schema and returns the corresponding Zod schema.
2591
+ * This is the main entry point for schema conversion.
2592
+ *
2593
+ * @param {JSONSchema} schema - The JSON schema.
2594
+ * @returns {ZodTypeAny} - The ZodTypeAny schema.
2595
+ */
2596
+ static parseSchema(schema) {
2597
+ if (Array.isArray(schema.type)) {
2598
+ return this.handleTypeArray(schema);
2599
+ }
2600
+ if (schema.oneOf || schema.anyOf || schema.allOf) {
2601
+ return this.parseCombinator(schema);
2602
+ }
2603
+ if (schema["if"] && schema["then"]) {
2604
+ return this.parseObject(schema);
2605
+ }
2606
+ if (schema.properties && (!schema.type || schema.type === "object")) {
2607
+ return this.parseObject(schema);
2608
+ }
2609
+ return this.handleSingleType(schema);
2610
+ }
2611
+ /**
2612
+ * Handles schemas with an array of types.
2613
+ *
2614
+ * @param {JSONSchema} schema - The JSON schema with type array.
2615
+ * @returns {ZodTypeAny} - The ZodTypeAny schema.
2616
+ */
2617
+ static handleTypeArray(schema) {
2618
+ if (!Array.isArray(schema.type)) {
2619
+ throw new Error("Expected schema.type to be an array");
2620
+ }
2621
+ if (schema.type.includes("null")) {
2622
+ return this.handleNullableType(schema);
2623
+ }
2624
+ return this.createUnionFromTypes(schema.type, schema);
2625
+ }
2626
+ /**
2627
+ * Handles nullable types by creating a nullable schema.
2628
+ *
2629
+ * @param {JSONSchema} schema - The JSON schema with nullable type.
2630
+ * @returns {ZodTypeAny} - The nullable Zod schema.
2631
+ */
2632
+ static handleNullableType(schema) {
2633
+ if (!Array.isArray(schema.type)) {
2634
+ throw new Error("Expected schema.type to be an array");
2635
+ }
2636
+ const nonNullSchema = { ...schema };
2637
+ nonNullSchema.type = schema.type.filter((t) => t !== "null");
2638
+ if (nonNullSchema.type.length === 1) {
2639
+ const singleTypeSchema = this.handleSingleType({
2640
+ ...schema,
2641
+ type: nonNullSchema.type[0]
2642
+ });
2643
+ return singleTypeSchema.nullable();
2644
+ }
2645
+ const unionSchema = this.parseSchema(nonNullSchema);
2646
+ return unionSchema.nullable();
2647
+ }
2648
+ /**
2649
+ * Creates a union type from an array of types.
2650
+ *
2651
+ * @param {string[]} types - Array of type strings.
2652
+ * @param {JSONSchema} baseSchema - The base schema to apply to each type.
2653
+ * @returns {ZodTypeAny} - The union Zod schema.
2654
+ */
2655
+ static createUnionFromTypes(types, baseSchema) {
2656
+ const schemas = types.map((type) => {
2657
+ const singleTypeSchema = { ...baseSchema, type };
2658
+ return this.parseSchema(singleTypeSchema);
2659
+ });
2660
+ return import_zod.z.union(schemas);
2661
+ }
2662
+ /**
2663
+ * Handles schemas with a single type.
2664
+ *
2665
+ * @param {JSONSchema} schema - The JSON schema with single type.
2666
+ * @returns {ZodTypeAny} - The ZodTypeAny schema.
2667
+ */
2668
+ static handleSingleType(schema) {
2669
+ if (schema.type === void 0) {
2670
+ if (schema.oneOf || schema.anyOf || schema.allOf) {
2671
+ return this.parseCombinator(schema);
2672
+ }
2673
+ if (schema.properties) {
2674
+ return this.parseObject(schema);
2675
+ }
2676
+ return import_zod.z.any();
2677
+ }
2678
+ switch (schema.type) {
2679
+ case "string":
2680
+ return this.parseString(schema);
2681
+ case "number":
2682
+ case "integer":
2683
+ return this.parseNumberSchema(schema);
2684
+ case "boolean":
2685
+ return import_zod.z.boolean();
2686
+ case "array":
2687
+ return this.parseArray(schema);
2688
+ case "object":
2689
+ return this.parseObject(schema);
2690
+ default:
2691
+ throw new Error("Unsupported schema type");
2692
+ }
2693
+ }
2694
+ /**
2695
+ * Parses a number schema.
2696
+ *
2697
+ * @param {JSONSchema} schema - The JSON schema for a number.
2698
+ * @returns {ZodTypeAny} - The ZodTypeAny schema.
2699
+ */
2700
+ static parseNumberSchema(schema) {
2701
+ const numberSchema = import_zod.z.number();
2702
+ let result = numberSchema;
2703
+ result = this.applyNumberBounds(numberSchema, schema);
2704
+ result = this.applyNumberMultipleOf(numberSchema, schema);
2705
+ result = this.applyNumberEnum(numberSchema, schema);
2706
+ result = this.applyIntegerConstraint(numberSchema, schema);
2707
+ return result;
2708
+ }
2709
+ /**
2710
+ * Applies bounds validation to a number schema.
2711
+ *
2712
+ * @param {z.ZodNumber} numberSchema - The base number schema.
2713
+ * @param {JSONSchema} schema - The JSON schema with bounds.
2714
+ * @returns {z.ZodNumber} - The updated schema with bounds validation.
2715
+ */
2716
+ static applyNumberBounds(numberSchema, schema) {
2717
+ let result = numberSchema;
2718
+ if (schema["minimum"] !== void 0) {
2719
+ result = schema["exclusiveMinimum"] ? result.gt(schema["minimum"]) : result.gte(schema["minimum"]);
2720
+ }
2721
+ if (schema["maximum"] !== void 0) {
2722
+ result = schema["exclusiveMaximum"] ? result.lt(schema["maximum"]) : result.lte(schema["maximum"]);
2723
+ }
2724
+ return result;
2725
+ }
2726
+ /**
2727
+ * Applies multipleOf validation to a number schema.
2728
+ *
2729
+ * @param {z.ZodNumber} numberSchema - The base number schema.
2730
+ * @param {JSONSchema} schema - The JSON schema with multipleOf.
2731
+ * @returns {z.ZodNumber} - The updated schema with multipleOf validation.
2732
+ */
2733
+ static applyNumberMultipleOf(numberSchema, schema) {
2734
+ if (schema["multipleOf"] === void 0) {
2735
+ return numberSchema;
2736
+ }
2737
+ return numberSchema.refine((val) => val % schema["multipleOf"] === 0, {
2738
+ message: `Number must be a multiple of ${schema["multipleOf"]}`
2739
+ });
2740
+ }
2741
+ /**
2742
+ * Applies enum validation to a number schema.
2743
+ *
2744
+ * @param {z.ZodNumber} numberSchema - The base number schema.
2745
+ * @param {JSONSchema} schema - The JSON schema with enum.
2746
+ * @returns {z.ZodNumber} - The updated schema with enum validation.
2747
+ */
2748
+ static applyNumberEnum(numberSchema, schema) {
2749
+ if (!schema.enum) {
2750
+ return numberSchema;
2751
+ }
2752
+ const numberEnums = schema.enum.filter(
2753
+ (val) => typeof val === "number"
2754
+ );
2755
+ if (numberEnums.length === 0) {
2756
+ return numberSchema;
2757
+ }
2758
+ return numberSchema.refine((val) => numberEnums.includes(val), {
2759
+ message: `Number must be one of: ${numberEnums.join(", ")}`
2760
+ });
2761
+ }
2762
+ /**
2763
+ * Applies integer constraint to a number schema if needed.
2764
+ *
2765
+ * @param {z.ZodNumber} numberSchema - The base number schema.
2766
+ * @param {JSONSchema} schema - The JSON schema.
2767
+ * @returns {z.ZodNumber} - The updated schema with integer validation if needed.
2768
+ */
2769
+ static applyIntegerConstraint(numberSchema, schema) {
2770
+ if (schema.type !== "integer") {
2771
+ return numberSchema;
2772
+ }
2773
+ return numberSchema.refine((val) => Number.isInteger(val), {
2774
+ message: "Number must be an integer"
2775
+ });
2776
+ }
2777
+ /**
2778
+ * Parses a string schema.
2779
+ *
2780
+ * @param {JSONSchema} schema - The JSON schema for a string.
2781
+ * @returns {ZodTypeAny} - The ZodTypeAny schema.
2782
+ */
2783
+ static parseString(schema) {
2784
+ const stringSchema = import_zod.z.string();
2785
+ let result = stringSchema;
2786
+ if (schema.format) {
2787
+ return this.applyStringFormat(stringSchema, schema);
2788
+ } else {
2789
+ result = this.applyStringPattern(stringSchema, schema);
2790
+ result = this.applyStringLength(stringSchema, schema);
2791
+ result = this.applyStringEnum(stringSchema, schema);
2792
+ }
2793
+ return result;
2794
+ }
2795
+ /**
2796
+ * Applies format validation to a string schema.
2797
+ *
2798
+ * @param {z.ZodString} stringSchema - The base string schema.
2799
+ * @param {JSONSchema} schema - The JSON schema with format.
2800
+ * @returns {ZodTypeAny} - The updated schema with format validation.
2801
+ */
2802
+ static applyStringFormat(stringSchema, schema) {
2803
+ if (!schema.format) {
2804
+ return stringSchema;
2805
+ }
2806
+ switch (schema.format) {
2807
+ case "email":
2808
+ return stringSchema.email();
2809
+ case "date-time":
2810
+ return stringSchema.datetime();
2811
+ case "uri":
2812
+ return stringSchema.url();
2813
+ case "uuid":
2814
+ return stringSchema.uuid();
2815
+ case "date":
2816
+ return stringSchema.date();
2817
+ default:
2818
+ return stringSchema;
2819
+ }
2820
+ }
2821
+ /**
2822
+ * Applies pattern validation to a string schema.
2823
+ *
2824
+ * @param {z.ZodString} stringSchema - The base string schema.
2825
+ * @param {JSONSchema} schema - The JSON schema with pattern.
2826
+ * @returns {z.ZodString} - The updated schema with pattern validation.
2827
+ */
2828
+ static applyStringPattern(stringSchema, schema) {
2829
+ if (!schema["pattern"]) {
2830
+ return stringSchema;
2831
+ }
2832
+ const regex = new RegExp(schema["pattern"]);
2833
+ return stringSchema.regex(regex, {
2834
+ message: `String must match pattern: ${schema["pattern"]}`
2835
+ });
2836
+ }
2837
+ /**
2838
+ * Applies length constraints to a string schema.
2839
+ *
2840
+ * @param {z.ZodString} stringSchema - The base string schema.
2841
+ * @param {JSONSchema} schema - The JSON schema with length constraints.
2842
+ * @returns {z.ZodString} - The updated schema with length validation.
2843
+ */
2844
+ static applyStringLength(stringSchema, schema) {
2845
+ const result = stringSchema;
2846
+ if (schema["minLength"] !== void 0) {
2847
+ stringSchema = stringSchema.min(schema["minLength"]);
2848
+ }
2849
+ if (schema["maxLength"] !== void 0) {
2850
+ stringSchema = stringSchema.max(schema["maxLength"]);
2851
+ }
2852
+ return result;
2853
+ }
2854
+ /**
2855
+ * Applies enum validation to a string schema.
2856
+ *
2857
+ * @param {z.ZodString} stringSchema - The base string schema.
2858
+ * @param {JSONSchema} schema - The JSON schema with enum.
2859
+ * @returns {ZodTypeAny} - The updated schema with enum validation.
2860
+ */
2861
+ static applyStringEnum(stringSchema, schema) {
2862
+ if (!schema.enum) {
2863
+ return stringSchema;
2864
+ }
2865
+ return stringSchema.refine((val) => schema.enum?.includes(val), {
2866
+ message: `Value must be one of: ${schema.enum?.join(", ")}`
2867
+ });
2868
+ }
2869
+ /**
2870
+ * Parses a JSON schema of type array and returns the corresponding Zod schema.
2871
+ *
2872
+ * @param {JSONSchema} schema - The JSON schema.
2873
+ * @returns {ZodTypeAny} - The ZodTypeAny schema.
2874
+ */
2875
+ static parseArray(schema) {
2876
+ if (Array.isArray(schema.items)) {
2877
+ const tupleSchemas = schema.items.map((item) => this.parseSchema(item));
2878
+ return import_zod.z.union(tupleSchemas);
2879
+ }
2880
+ const itemSchema = schema.items ? this.parseSchema(schema.items) : import_zod.z.any();
2881
+ const arraySchema = import_zod.z.array(itemSchema);
2882
+ let result = arraySchema;
2883
+ result = this.applyArrayConstraints(arraySchema, schema);
2884
+ return result;
2885
+ }
2886
+ /**
2887
+ * Applies constraints to an array schema.
2888
+ *
2889
+ * @param {z.ZodArray<any>} arraySchema - The base array schema.
2890
+ * @param {JSONSchema} schema - The JSON schema with array constraints.
2891
+ * @returns {z.ZodTypeAny} - The updated array schema with constraints.
2892
+ */
2893
+ static applyArrayConstraints(arraySchema, schema) {
2894
+ if (schema["minItems"] !== void 0) {
2895
+ arraySchema = arraySchema.min(schema["minItems"]);
2896
+ }
2897
+ if (schema["maxItems"] !== void 0) {
2898
+ arraySchema = arraySchema.max(schema["maxItems"]);
2899
+ }
2900
+ if (schema["uniqueItems"]) {
2901
+ return arraySchema.refine(
2902
+ (items) => new Set(items).size === items.length,
2903
+ { message: "Array items must be unique" }
2904
+ );
2905
+ }
2906
+ return arraySchema;
2907
+ }
2908
+ /**
2909
+ * Parses an object schema.
2910
+ *
2911
+ * @param {JSONSchema} schema - The JSON schema for an object.
2912
+ * @returns {ZodTypeAny} - The ZodTypeAny schema.
2913
+ */
2914
+ static parseObject(schema) {
2915
+ if (schema["if"] && schema["then"]) {
2916
+ return this.parseConditional(schema);
2917
+ }
2918
+ const shape = {};
2919
+ this.processObjectProperties(schema, shape);
2920
+ return this.processAdditionalProperties(schema, import_zod.z.object(shape));
2921
+ }
2922
+ /**
2923
+ * Processes object properties and builds the shape object.
2924
+ *
2925
+ * @param {JSONSchema} schema - The JSON schema for an object.
2926
+ * @param {Record<string, ZodTypeAny>} shape - The shape object to populate.
2927
+ */
2928
+ static processObjectProperties(schema, shape) {
2929
+ const required = new Set(schema.required || []);
2930
+ if (!schema.properties) {
2931
+ return;
2932
+ }
2933
+ for (const [key, propSchema] of Object.entries(schema.properties)) {
2934
+ const zodSchema = this.parseSchema(propSchema);
2935
+ shape[key] = required.has(key) ? zodSchema : zodSchema.optional();
2936
+ }
2937
+ }
2938
+ /**
2939
+ * Processes additionalProperties configuration.
2940
+ *
2941
+ * @param {JSONSchema} schema - The JSON schema for an object.
2942
+ * @param {z.ZodObject<any, any>} objectSchema - The Zod object schema.
2943
+ * @returns {z.ZodObject<any, any>} - The updated Zod object schema.
2944
+ */
2945
+ static processAdditionalProperties(schema, objectSchema) {
2946
+ if (schema.additionalProperties === true) {
2947
+ return objectSchema.passthrough();
2948
+ } else if (schema.additionalProperties && typeof schema.additionalProperties === "object") {
2949
+ const additionalPropSchema = this.parseSchema(
2950
+ schema.additionalProperties
2951
+ );
2952
+ return objectSchema.catchall(additionalPropSchema);
2953
+ } else {
2954
+ return objectSchema.strict();
2955
+ }
2956
+ }
2957
+ /**
2958
+ * Parses a conditional schema with if-then-else.
2959
+ *
2960
+ * @param {JSONSchema} schema - The JSON schema with conditional validation.
2961
+ * @returns {ZodTypeAny} - The conditional Zod schema.
2962
+ */
2963
+ static parseConditional(schema) {
2964
+ const zodObject = this.createBaseObjectSchema(schema);
2965
+ const ifCondition = schema["if"];
2966
+ const thenSchema = schema["then"];
2967
+ const elseSchema = schema["else"];
2968
+ return zodObject.superRefine((data, ctx) => {
2969
+ const dataWithDefaults = this.applyDefaultValues(
2970
+ data,
2971
+ schema
2972
+ );
2973
+ if (this.matchesCondition(dataWithDefaults, ifCondition)) {
2974
+ this.validateConditionalSchema(dataWithDefaults, thenSchema, ctx);
2975
+ } else if (elseSchema) {
2976
+ this.validateConditionalSchema(dataWithDefaults, elseSchema, ctx);
2977
+ }
2978
+ });
2979
+ }
2980
+ /**
2981
+ * Creates a base object schema from the given JSON schema.
2982
+ *
2983
+ * @param {JSONSchema} schema - The JSON schema.
2984
+ * @returns {z.ZodObject<any, any>} - The base Zod object schema.
2985
+ */
2986
+ static createBaseObjectSchema(schema) {
2987
+ const shape = {};
2988
+ const required = new Set(schema.required || []);
2989
+ for (const [key, value] of Object.entries(schema.properties || {})) {
2990
+ const zodSchema = this.parseSchema(value);
2991
+ shape[key] = required.has(key) ? zodSchema : zodSchema.optional();
2992
+ }
2993
+ const zodObject = import_zod.z.object(shape);
2994
+ return this.processAdditionalProperties(schema, zodObject);
2995
+ }
2996
+ /**
2997
+ * Applies default values from schema properties to data object.
2998
+ *
2999
+ * @param {JSONValue} data - The original data object.
3000
+ * @param {JSONSchema} schema - The schema with default values.
3001
+ * @returns {JSONValue} - The data object with defaults applied.
3002
+ */
3003
+ static applyDefaultValues(data, schema) {
3004
+ if (typeof data !== "object" || data === null) {
3005
+ return data;
3006
+ }
3007
+ if (Array.isArray(data)) {
3008
+ return data;
3009
+ }
3010
+ const objectData = data;
3011
+ const dataWithDefaults = { ...objectData };
3012
+ if (!schema.properties) {
3013
+ return dataWithDefaults;
3014
+ }
3015
+ for (const [key, propSchema] of Object.entries(schema.properties)) {
3016
+ if (!(key in dataWithDefaults) && "default" in propSchema) {
3017
+ dataWithDefaults[key] = propSchema["default"];
3018
+ }
3019
+ }
3020
+ return dataWithDefaults;
3021
+ }
3022
+ /**
3023
+ * Parses a schema with combinators (oneOf, anyOf, allOf).
3024
+ * Delegates to the appropriate combinator parser based on which combinator is present.
3025
+ *
3026
+ * @param {JSONSchema} schema - The JSON schema with combinators.
3027
+ * @returns {ZodTypeAny} - The ZodTypeAny schema.
3028
+ */
3029
+ static parseCombinator(schema) {
3030
+ if (schema.oneOf) {
3031
+ return this.parseOneOf(schema.oneOf);
3032
+ }
3033
+ if (schema.anyOf) {
3034
+ return this.parseAnyOf(schema.anyOf);
3035
+ }
3036
+ if (schema.allOf) {
3037
+ return this.parseAllOf(schema.allOf);
3038
+ }
3039
+ throw new Error("Unsupported schema type");
3040
+ }
3041
+ /**
3042
+ * Parses a oneOf combinator schema.
3043
+ *
3044
+ * @param {JSONSchema[]} schemas - Array of JSON schemas in the oneOf.
3045
+ * @returns {ZodTypeAny} - The ZodTypeAny schema.
3046
+ */
3047
+ static parseOneOf(schemas) {
3048
+ return this.createUnionFromSchemas(schemas);
3049
+ }
3050
+ /**
3051
+ * Parses an anyOf combinator schema.
3052
+ *
3053
+ * @param {JSONSchema[]} schemas - Array of JSON schemas in the anyOf.
3054
+ * @returns {ZodTypeAny} - The ZodTypeAny schema.
3055
+ */
3056
+ static parseAnyOf(schemas) {
3057
+ return this.createUnionFromSchemas(schemas);
3058
+ }
3059
+ /**
3060
+ * Creates a union from an array of schemas, handling special cases.
3061
+ *
3062
+ * @param {JSONSchema[]} schemas - Array of JSON schemas to create a union from.
3063
+ * @returns {ZodTypeAny} - The union Zod schema.
3064
+ */
3065
+ static createUnionFromSchemas(schemas) {
3066
+ if (schemas.length === 0) {
3067
+ return import_zod.z.any();
3068
+ }
3069
+ if (schemas.length === 1) {
3070
+ return this.parseSchema(schemas[0]);
3071
+ }
3072
+ const zodSchemas = [];
3073
+ for (const subSchema of schemas) {
3074
+ if (subSchema.type === "null") {
3075
+ zodSchemas.push(import_zod.z.null());
3076
+ } else {
3077
+ zodSchemas.push(this.parseSchema(subSchema));
3078
+ }
3079
+ }
3080
+ if (zodSchemas.length >= 2) {
3081
+ return import_zod.z.union(zodSchemas);
3082
+ } else if (zodSchemas.length === 1) {
3083
+ return zodSchemas[0];
3084
+ }
3085
+ return import_zod.z.any();
3086
+ }
3087
+ /**
3088
+ * Parses an allOf combinator schema by merging all schemas.
3089
+ *
3090
+ * @param {JSONSchema[]} schemas - Array of JSON schemas in the allOf.
3091
+ * @returns {ZodTypeAny} - The ZodTypeAny schema.
3092
+ */
3093
+ static parseAllOf(schemas) {
3094
+ if (schemas.length === 0) {
3095
+ return import_zod.z.any();
3096
+ }
3097
+ if (schemas.length === 1) {
3098
+ return this.parseSchema(schemas[0]);
3099
+ }
3100
+ const mergedSchema = schemas.reduce(
3101
+ (acc, currentSchema) => this.mergeSchemas(acc, currentSchema)
3102
+ );
3103
+ return this.parseSchema(mergedSchema);
3104
+ }
3105
+ /**
3106
+ * Merges two JSON schemas together.
3107
+ *
3108
+ * @param {JSONSchema} baseSchema - The base JSON schema.
3109
+ * @param {JSONSchema} addSchema - The JSON schema to add.
3110
+ * @returns {JSONSchema} - The merged JSON schema
3111
+ */
3112
+ static mergeSchemas(baseSchema, addSchema) {
3113
+ const merged = { ...baseSchema, ...addSchema };
3114
+ if (baseSchema.properties && addSchema.properties) {
3115
+ const mergedProperties = {
3116
+ ...baseSchema.properties,
3117
+ ...addSchema.properties
3118
+ };
3119
+ merged.properties = mergedProperties;
3120
+ }
3121
+ if (baseSchema.required && addSchema.required) {
3122
+ const mergedRequired = [
3123
+ .../* @__PURE__ */ new Set([...baseSchema.required, ...addSchema.required])
3124
+ ];
3125
+ merged.required = mergedRequired;
3126
+ }
3127
+ return merged;
3128
+ }
3129
+ };
2376
3130
 
2377
3131
  // src/adapters/langchain_adapter.ts
2378
- var import_json_schema_to_zod = require("@dmitryrechkin/json-schema-to-zod");
2379
3132
  var import_tools = require("@langchain/core/tools");
2380
- var import_zod = require("zod");
3133
+ var import_zod2 = require("zod");
2381
3134
  init_logging();
2382
3135
 
2383
3136
  // src/adapters/base.ts
@@ -2497,10 +3250,10 @@ var BaseAdapter = class {
2497
3250
  // src/adapters/langchain_adapter.ts
2498
3251
  function schemaToZod(schema) {
2499
3252
  try {
2500
- return import_json_schema_to_zod.JSONSchemaToZod.convert(schema);
3253
+ return JSONSchemaToZod.convert(schema);
2501
3254
  } catch (err) {
2502
3255
  logger.warn(`Failed to convert JSON schema to Zod: ${err}`);
2503
- return import_zod.z.any();
3256
+ return import_zod2.z.any();
2504
3257
  }
2505
3258
  }
2506
3259
  __name(schemaToZod, "schemaToZod");
@@ -2518,7 +3271,7 @@ var LangChainAdapter = class extends BaseAdapter {
2518
3271
  if (this.disallowedTools.includes(mcpTool.name)) {
2519
3272
  return null;
2520
3273
  }
2521
- const argsSchema = mcpTool.inputSchema ? schemaToZod(mcpTool.inputSchema) : import_zod.z.object({}).optional();
3274
+ const argsSchema = mcpTool.inputSchema ? schemaToZod(mcpTool.inputSchema) : import_zod2.z.object({}).optional();
2522
3275
  const tool = new import_tools.DynamicStructuredTool({
2523
3276
  name: mcpTool.name ?? "NO NAME",
2524
3277
  description: mcpTool.description ?? "",
@@ -2548,11 +3301,10 @@ var LangChainAdapter = class extends BaseAdapter {
2548
3301
  init_logging();
2549
3302
 
2550
3303
  // src/managers/server_manager.ts
2551
- var import_lodash_es = require("lodash-es");
2552
3304
  init_logging();
2553
3305
 
2554
3306
  // src/managers/tools/acquire_active_mcp_server.ts
2555
- var import_zod2 = require("zod");
3307
+ var import_zod3 = require("zod");
2556
3308
 
2557
3309
  // src/managers/tools/base.ts
2558
3310
  var import_tools2 = require("@langchain/core/tools");
@@ -2577,7 +3329,7 @@ var MCPServerTool = class extends import_tools2.StructuredTool {
2577
3329
  };
2578
3330
 
2579
3331
  // src/managers/tools/acquire_active_mcp_server.ts
2580
- var PresentActiveServerSchema = import_zod2.z.object({});
3332
+ var PresentActiveServerSchema = import_zod3.z.object({});
2581
3333
  var AcquireActiveMCPServerTool = class extends MCPServerTool {
2582
3334
  static {
2583
3335
  __name(this, "AcquireActiveMCPServerTool");
@@ -2598,7 +3350,7 @@ var AcquireActiveMCPServerTool = class extends MCPServerTool {
2598
3350
 
2599
3351
  // src/managers/tools/add_server_from_config.ts
2600
3352
  var import_tools3 = require("@langchain/core/tools");
2601
- var import_zod3 = require("zod");
3353
+ var import_zod4 = require("zod");
2602
3354
  init_logging();
2603
3355
  var AddMCPServerFromConfigTool = class extends import_tools3.StructuredTool {
2604
3356
  static {
@@ -2606,9 +3358,9 @@ var AddMCPServerFromConfigTool = class extends import_tools3.StructuredTool {
2606
3358
  }
2607
3359
  name = "add_mcp_server_from_config";
2608
3360
  description = "Adds a new MCP server to the client from a configuration object and connects to it, making its tools available.";
2609
- schema = import_zod3.z.object({
2610
- serverName: import_zod3.z.string().describe("The name for the new MCP server."),
2611
- serverConfig: import_zod3.z.any().describe(
3361
+ schema = import_zod4.z.object({
3362
+ serverName: import_zod4.z.string().describe("The name for the new MCP server."),
3363
+ serverConfig: import_zod4.z.any().describe(
2612
3364
  'The configuration object for the server. This should not include the top-level "mcpServers" key.'
2613
3365
  )
2614
3366
  });
@@ -2650,10 +3402,10 @@ ${tools.map((t) => t.name).join("\n")}`;
2650
3402
  };
2651
3403
 
2652
3404
  // src/managers/tools/connect_mcp_server.ts
2653
- var import_zod4 = require("zod");
3405
+ var import_zod5 = require("zod");
2654
3406
  init_logging();
2655
- var ConnectMCPServerSchema = import_zod4.z.object({
2656
- serverName: import_zod4.z.string().describe("The name of the MCP server.")
3407
+ var ConnectMCPServerSchema = import_zod5.z.object({
3408
+ serverName: import_zod5.z.string().describe("The name of the MCP server.")
2657
3409
  });
2658
3410
  var ConnectMCPServerTool = class extends MCPServerTool {
2659
3411
  static {
@@ -2701,9 +3453,9 @@ var ConnectMCPServerTool = class extends MCPServerTool {
2701
3453
  };
2702
3454
 
2703
3455
  // src/managers/tools/list_mcp_servers.ts
2704
- var import_zod5 = require("zod");
3456
+ var import_zod6 = require("zod");
2705
3457
  init_logging();
2706
- var EnumerateServersSchema = import_zod5.z.object({});
3458
+ var EnumerateServersSchema = import_zod6.z.object({});
2707
3459
  var ListMCPServersTool = class extends MCPServerTool {
2708
3460
  static {
2709
3461
  __name(this, "ListMCPServersTool");
@@ -2740,8 +3492,8 @@ var ListMCPServersTool = class extends MCPServerTool {
2740
3492
  };
2741
3493
 
2742
3494
  // src/managers/tools/release_mcp_server_connection.ts
2743
- var import_zod6 = require("zod");
2744
- var ReleaseConnectionSchema = import_zod6.z.object({});
3495
+ var import_zod7 = require("zod");
3496
+ var ReleaseConnectionSchema = import_zod7.z.object({});
2745
3497
  var ReleaseMCPServerConnectionTool = class extends MCPServerTool {
2746
3498
  static {
2747
3499
  __name(this, "ReleaseMCPServerConnectionTool");
@@ -2763,6 +3515,28 @@ var ReleaseMCPServerConnectionTool = class extends MCPServerTool {
2763
3515
  };
2764
3516
 
2765
3517
  // src/managers/server_manager.ts
3518
+ function isEqual(a, b) {
3519
+ if (a === b) return true;
3520
+ if (a == null || b == null) return false;
3521
+ if (typeof a !== typeof b) return false;
3522
+ if (a instanceof Date && b instanceof Date) {
3523
+ return a.getTime() === b.getTime();
3524
+ }
3525
+ if (Array.isArray(a) && Array.isArray(b)) {
3526
+ if (a.length !== b.length) return false;
3527
+ return a.every((item, index) => isEqual(item, b[index]));
3528
+ }
3529
+ if (typeof a === "object" && typeof b === "object") {
3530
+ const keysA = Object.keys(a);
3531
+ const keysB = Object.keys(b);
3532
+ if (keysA.length !== keysB.length) return false;
3533
+ return keysA.every((key) => {
3534
+ return Object.prototype.hasOwnProperty.call(b, key) && isEqual(a[key], b[key]);
3535
+ });
3536
+ }
3537
+ return false;
3538
+ }
3539
+ __name(isEqual, "isEqual");
2766
3540
  var ServerManager = class {
2767
3541
  static {
2768
3542
  __name(this, "ServerManager");
@@ -2839,7 +3613,7 @@ var ServerManager = class {
2839
3613
  continue;
2840
3614
  }
2841
3615
  const cachedTools = this.serverTools[serverName];
2842
- const toolsChanged = !cachedTools || !(0, import_lodash_es.isEqual)(cachedTools, tools);
3616
+ const toolsChanged = !cachedTools || !isEqual(cachedTools, tools);
2843
3617
  if (toolsChanged) {
2844
3618
  this.serverTools[serverName] = tools;
2845
3619
  this.initializedServers[serverName] = true;
@@ -2901,14 +3675,14 @@ var ObservabilityManager = class {
2901
3675
  metadata;
2902
3676
  metadataProvider;
2903
3677
  tagsProvider;
2904
- constructor(config2 = {}) {
2905
- this.customCallbacks = config2.customCallbacks;
2906
- this.verbose = config2.verbose ?? false;
2907
- this.observe = config2.observe ?? true;
2908
- this.agentId = config2.agentId;
2909
- this.metadata = config2.metadata;
2910
- this.metadataProvider = config2.metadataProvider;
2911
- this.tagsProvider = config2.tagsProvider;
3678
+ constructor(config = {}) {
3679
+ this.customCallbacks = config.customCallbacks;
3680
+ this.verbose = config.verbose ?? false;
3681
+ this.observe = config.observe ?? true;
3682
+ this.agentId = config.agentId;
3683
+ this.metadata = config.metadata;
3684
+ this.metadataProvider = config.metadataProvider;
3685
+ this.tagsProvider = config.tagsProvider;
2912
3686
  }
2913
3687
  /**
2914
3688
  * Collect all available observability handlers from configured platforms.
@@ -3081,7 +3855,6 @@ var fs2 = __toESM(require("fs"), 1);
3081
3855
  var os = __toESM(require("os"), 1);
3082
3856
  var path2 = __toESM(require("path"), 1);
3083
3857
  var import_posthog_node = require("posthog-node");
3084
- var import_uuid2 = require("uuid");
3085
3858
  init_logging();
3086
3859
 
3087
3860
  // src/telemetry/events.ts
@@ -3345,7 +4118,7 @@ var Telemetry = class _Telemetry {
3345
4118
  if (isFirstTime) {
3346
4119
  logger.debug(`Creating user ID path: ${this.USER_ID_PATH}`);
3347
4120
  fs2.mkdirSync(path2.dirname(this.USER_ID_PATH), { recursive: true });
3348
- const newUserId = (0, import_uuid2.v4)();
4121
+ const newUserId = generateUUID();
3349
4122
  fs2.writeFileSync(this.USER_ID_PATH, newUserId);
3350
4123
  this._currUserId = newUserId;
3351
4124
  logger.debug(`User ID path created: ${this.USER_ID_PATH}`);
@@ -3561,7 +4334,7 @@ Here are the tools *currently* available to you (this list includes server manag
3561
4334
  `;
3562
4335
 
3563
4336
  // src/agents/remote.ts
3564
- var import_zod_to_json_schema = require("zod-to-json-schema");
4337
+ var import_zod8 = require("zod");
3565
4338
  init_logging();
3566
4339
  var API_CHATS_ENDPOINT = "/api/v1/chats";
3567
4340
  var API_CHAT_EXECUTE_ENDPOINT = "/api/v1/chats/{chat_id}/execute";
@@ -3585,7 +4358,7 @@ var RemoteAgent = class {
3585
4358
  this.apiKey = apiKey;
3586
4359
  }
3587
4360
  pydanticToJsonSchema(schema) {
3588
- return (0, import_zod_to_json_schema.zodToJsonSchema)(schema);
4361
+ return (0, import_zod8.toJSONSchema)(schema);
3589
4362
  }
3590
4363
  parseStructuredResponse(responseData, outputSchema) {
3591
4364
  let resultData;
@@ -4187,24 +4960,24 @@ var MCPAgent = class {
4187
4960
  const serverConfigs = {};
4188
4961
  for (const serverName of serverNames) {
4189
4962
  try {
4190
- const config2 = this.client.getServerConfig(serverName);
4191
- if (config2) {
4963
+ const config = this.client.getServerConfig(serverName);
4964
+ if (config) {
4192
4965
  let serverType = "unknown";
4193
- if (config2.command) {
4966
+ if (config.command) {
4194
4967
  serverType = "command";
4195
- } else if (config2.url) {
4968
+ } else if (config.url) {
4196
4969
  serverType = "http";
4197
- } else if (config2.ws_url) {
4970
+ } else if (config.ws_url) {
4198
4971
  serverType = "websocket";
4199
4972
  }
4200
4973
  serverConfigs[serverName] = {
4201
4974
  type: serverType,
4202
4975
  // Include safe configuration details (avoid sensitive data)
4203
- has_args: !!config2.args,
4204
- has_env: !!config2.env,
4205
- has_headers: !!config2.headers,
4206
- url: config2.url || null,
4207
- command: config2.command || null
4976
+ has_args: !!config.args,
4977
+ has_env: !!config.env,
4978
+ has_headers: !!config.headers,
4979
+ url: config.url || null,
4980
+ command: config.command || null
4208
4981
  };
4209
4982
  }
4210
4983
  } catch (error) {
@@ -5020,7 +5793,7 @@ var MCPAgent = class {
5020
5793
  let structuredLlm = null;
5021
5794
  let schemaDescription = "";
5022
5795
  logger.debug(
5023
- `\u{1F504} Structured output requested, schema: ${JSON.stringify((0, import_zod_to_json_schema2.zodToJsonSchema)(outputSchema), null, 2)}`
5796
+ `\u{1F504} Structured output requested, schema: ${JSON.stringify((0, import_zod9.toJSONSchema)(outputSchema), null, 2)}`
5024
5797
  );
5025
5798
  if (llm && "withStructuredOutput" in llm && typeof llm.withStructuredOutput === "function") {
5026
5799
  structuredLlm = llm.withStructuredOutput(outputSchema);
@@ -5029,7 +5802,7 @@ var MCPAgent = class {
5029
5802
  } else {
5030
5803
  throw new Error("LLM is required for structured output");
5031
5804
  }
5032
- const jsonSchema = (0, import_zod_to_json_schema2.zodToJsonSchema)(outputSchema);
5805
+ const jsonSchema = (0, import_zod9.toJSONSchema)(outputSchema);
5033
5806
  const { $schema, additionalProperties, ...cleanSchema } = jsonSchema;
5034
5807
  schemaDescription = JSON.stringify(cleanSchema, null, 2);
5035
5808
  logger.info(`\u{1F504} Schema description: ${schemaDescription}`);
@@ -5174,7 +5947,7 @@ ${formatPrompt}`
5174
5947
  */
5175
5948
  _enhanceQueryWithSchema(query, outputSchema) {
5176
5949
  try {
5177
- const jsonSchema = (0, import_zod_to_json_schema2.zodToJsonSchema)(outputSchema);
5950
+ const jsonSchema = (0, import_zod9.toJSONSchema)(outputSchema);
5178
5951
  const { $schema, additionalProperties, ...cleanSchema } = jsonSchema;
5179
5952
  const schemaDescription = JSON.stringify(cleanSchema, null, 2);
5180
5953
  const enhancedQuery = `
@@ -5195,8 +5968,33 @@ ${formatPrompt}`
5195
5968
  }
5196
5969
  };
5197
5970
 
5971
+ // src/utils/url-sanitize.ts
5972
+ function sanitizeUrl(raw) {
5973
+ const abort = /* @__PURE__ */ __name(() => {
5974
+ throw new Error(`Invalid url to pass to open(): ${raw}`);
5975
+ }, "abort");
5976
+ let url;
5977
+ try {
5978
+ url = new URL(raw);
5979
+ } catch (_) {
5980
+ abort();
5981
+ }
5982
+ if (url.protocol !== "https:" && url.protocol !== "http:") abort();
5983
+ if (url.hostname !== encodeURIComponent(url.hostname)) abort();
5984
+ if (url.username) url.username = encodeURIComponent(url.username);
5985
+ if (url.password) url.password = encodeURIComponent(url.password);
5986
+ url.pathname = url.pathname.slice(0, 1) + encodeURIComponent(url.pathname.slice(1)).replace(/%2f/gi, "/");
5987
+ url.search = url.search.slice(0, 1) + Array.from(url.searchParams.entries()).map(sanitizeParam).join("&");
5988
+ url.hash = url.hash.slice(0, 1) + encodeURIComponent(url.hash.slice(1));
5989
+ return url.href;
5990
+ }
5991
+ __name(sanitizeUrl, "sanitizeUrl");
5992
+ function sanitizeParam([k, v]) {
5993
+ return `${encodeURIComponent(k)}${v.length > 0 ? `=${encodeURIComponent(v)}` : ""}`;
5994
+ }
5995
+ __name(sanitizeParam, "sanitizeParam");
5996
+
5198
5997
  // src/auth/browser-provider.ts
5199
- var import_strict_url_sanitise = require("strict-url-sanitise");
5200
5998
  var BrowserOAuthClientProvider = class {
5201
5999
  static {
5202
6000
  __name(this, "BrowserOAuthClientProvider");
@@ -5216,7 +6014,7 @@ var BrowserOAuthClientProvider = class {
5216
6014
  this.serverUrlHash = this.hashString(serverUrl);
5217
6015
  this.clientName = options.clientName || "mcp-use";
5218
6016
  this.clientUri = options.clientUri || (typeof window !== "undefined" ? window.location.origin : "");
5219
- this.callbackUrl = (0, import_strict_url_sanitise.sanitizeUrl)(
6017
+ this.callbackUrl = sanitizeUrl(
5220
6018
  options.callbackUrl || (typeof window !== "undefined" ? new URL("/oauth/callback", window.location.origin).toString() : "/oauth/callback")
5221
6019
  );
5222
6020
  this.preventAutoAuth = options.preventAutoAuth;
@@ -5225,7 +6023,7 @@ var BrowserOAuthClientProvider = class {
5225
6023
  }
5226
6024
  // --- SDK Interface Methods ---
5227
6025
  get redirectUrl() {
5228
- return (0, import_strict_url_sanitise.sanitizeUrl)(this.callbackUrl);
6026
+ return sanitizeUrl(this.callbackUrl);
5229
6027
  }
5230
6028
  get clientMetadata() {
5231
6029
  return {
@@ -5321,7 +6119,7 @@ var BrowserOAuthClientProvider = class {
5321
6119
  localStorage.setItem(stateKey, JSON.stringify(stateData));
5322
6120
  authorizationUrl.searchParams.set("state", state);
5323
6121
  const authUrlString = authorizationUrl.toString();
5324
- const sanitizedAuthUrl = (0, import_strict_url_sanitise.sanitizeUrl)(authUrlString);
6122
+ const sanitizedAuthUrl = sanitizeUrl(authUrlString);
5325
6123
  localStorage.setItem(this.getKey("last_auth_url"), sanitizedAuthUrl);
5326
6124
  return sanitizedAuthUrl;
5327
6125
  }
@@ -5378,7 +6176,7 @@ var BrowserOAuthClientProvider = class {
5378
6176
  */
5379
6177
  getLastAttemptedAuthUrl() {
5380
6178
  const storedUrl = localStorage.getItem(this.getKey("last_auth_url"));
5381
- return storedUrl ? (0, import_strict_url_sanitise.sanitizeUrl)(storedUrl) : null;
6179
+ return storedUrl ? sanitizeUrl(storedUrl) : null;
5382
6180
  }
5383
6181
  clearStorage() {
5384
6182
  const prefixPattern = `${this.storageKeyPrefix}_${this.serverUrlHash}_`;