@alcyone-labs/arg-parser 2.3.0 → 2.4.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/dist/index.mjs CHANGED
@@ -9,16 +9,17 @@ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read fr
9
9
  var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
10
10
  var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
11
11
  var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
12
- var __flags, _throwForDuplicateFlags, _appName, _appCommandName, _subCommandName, _parameters, _handler, _throwForDuplicateFlags2, _description, _handleErrors, _autoExit, _parentParser, _lastParseResult, _inheritParentFlags, _subCommands, _flagManager, _dxtGenerator, _configurationManager, _fuzzyMode, _mcpResourcesManager, _mcpPromptsManager, _mcpNotificationsManager, _ArgParserBase_instances, _identifyCommandChainAndParsers_fn, _handleGlobalChecks_fn, _validateMandatoryFlags_fn, _applyDefaultValues_fn, _prepareAndExecuteHandler_fn, parseFlags_fn, _enableFuzzyMode_fn, displayErrorAndExit_fn, _printRecursiveToConsole_fn, _buildRecursiveString_fn, _buildRecursiveJson_fn, _handleSaveToEnvFlag_fn, _handleBuildDxtFlag_fn, _handleMcpServeFlag_fn, _getMcpServerConfiguration_fn, _startUnifiedMcpServer_fn, _findAllMcpSubCommands_fn, _parseMcpTransportOptions_fn, _ArgParser_instances, registerToolAsSubCommand_fn, _startSingleTransport_fn, processAsyncHandlerPromise_fn, _hasDate, _hasTime, _offset;
12
+ var __flags, _throwForDuplicateFlags, _appName, _appCommandName, _subCommandName, _parameters, _handler, _throwForDuplicateFlags2, _description, _handleErrors, _autoExit, _parentParser, _lastParseResult, _inheritParentFlags, _subCommands, _flagManager, _dxtGenerator, _configurationManager, _fuzzyMode, _mcpResourcesManager, _mcpPromptsManager, _mcpNotificationsManager, _ArgParserBase_instances, _identifyCommandChainAndParsers_fn, _handleGlobalChecks_fn, _validateMandatoryFlags_fn, _applyDefaultValues_fn, _prepareAndExecuteHandler_fn, parseFlags_fn, _enableFuzzyMode_fn, displayErrorAndExit_fn, _printRecursiveToConsole_fn, _buildRecursiveString_fn, _buildRecursiveJson_fn, _handleSaveToEnvFlag_fn, _handleBuildDxtFlag_fn, _handleMcpServeFlag_fn, _resolveLoggerConfigForServe_fn, _getMcpServerConfiguration_fn, _startUnifiedMcpServer_fn, _findAllMcpSubCommands_fn, _parseMcpTransportOptions_fn, _ArgParser_instances, _resolveLoggerConfig_fn, registerToolAsSubCommand_fn, _startSingleTransport_fn, processAsyncHandlerPromise_fn, _hasDate, _hasTime, _offset;
13
13
  import * as fs from "node:fs";
14
14
  import * as path from "node:path";
15
15
  import { createRegExp, anyOf as anyOf$1, oneOrMore, char } from "magic-regexp";
16
- import { z, ZodFirstPartyTypeKind, ZodType } from "zod";
16
+ import { getTsconfig, createPathsMatcher } from "get-tsconfig";
17
+ import { z } from "zod";
17
18
  import { createMcpLogger } from "@alcyone-labs/simple-mcp-logger";
18
19
  import { Logger, createCliLogger, createMcpLogger as createMcpLogger2, logger } from "@alcyone-labs/simple-mcp-logger";
19
20
  import process$1 from "node:process";
20
21
  import { randomUUID } from "node:crypto";
21
- import { URL as URL$1 } from "url";
22
+ import { URL as URL$1 } from "node:url";
22
23
  const RESET$1 = "\x1B[0m";
23
24
  const BOLD$1 = "\x1B[1m";
24
25
  const DIM$1 = "\x1B[2m";
@@ -1043,7 +1044,7 @@ const zodFlagSchema = z.object({
1043
1044
  allowMultiple: z.boolean().default(false).describe(
1044
1045
  "Allow passing the same flag multiple times, e.g., `-f val1 -f val2` results in an array."
1045
1046
  ),
1046
- description: z.union([z.string(), z.array(z.string())]).describe("Textual description for help messages."),
1047
+ description: z.union([z.string(), z.array(z.string())]).optional().describe("Textual description for help messages."),
1047
1048
  options: z.array(z.string().min(1)).min(1, "Flag must have at least one option (e.g., ['-f', '--flag'])").describe("Array of option strings, e.g., ['-f', '--flag']."),
1048
1049
  defaultValue: z.any().optional().describe("Default value if the flag is not provided."),
1049
1050
  type: z.union([
@@ -1064,7 +1065,10 @@ const zodFlagSchema = z.object({
1064
1065
  // Native Object constructor
1065
1066
  message: "Must be Object constructor"
1066
1067
  }),
1067
- z.function().args(z.string()).returns(z.union([z.any(), z.promise(z.any())])),
1068
+ z.custom(
1069
+ (val) => typeof val === "function",
1070
+ "Must be a custom parser function"
1071
+ ),
1068
1072
  // Custom parser function (value: string) => any | Promise<any>
1069
1073
  z.string().refine(
1070
1074
  // String literal types
@@ -1078,24 +1082,26 @@ const zodFlagSchema = z.object({
1078
1082
  ]).default("string").describe(
1079
1083
  "Expected data type (constructor or string literal) or a custom parser function. Defaults to 'string'."
1080
1084
  ),
1081
- mandatory: z.union([z.boolean(), z.function().args(z.any()).returns(z.boolean())]).optional().describe(
1085
+ mandatory: z.union([
1086
+ z.boolean(),
1087
+ z.custom(
1088
+ (val) => typeof val === "function",
1089
+ "Must be a boolean or function"
1090
+ )
1091
+ ]).optional().describe(
1082
1092
  "Makes the flag mandatory, can be a boolean or a function conditional on other args."
1083
1093
  ),
1084
1094
  flagOnly: z.boolean().default(false).describe(
1085
1095
  "If true, the flag's presence is noted (true/false), and any subsequent value is not consumed by this flag."
1086
1096
  ),
1087
- validate: z.function().args(z.any().optional(), z.any().optional()).returns(
1088
- z.union([
1089
- z.boolean(),
1090
- z.string(),
1091
- z.void(),
1092
- z.promise(z.union([z.boolean(), z.string(), z.void()]))
1093
- ])
1094
- ).optional().describe(
1097
+ validate: z.custom((val) => typeof val === "function", "Must be a validation function").optional().describe(
1095
1098
  "Custom validation function for the flag's value (receives value, parsedArgs)."
1096
1099
  ),
1097
- enum: z.array(z.any()).optional().describe("Array of allowed values for the flag.")
1098
- }).passthrough().transform((obj) => {
1100
+ enum: z.array(z.any()).optional().describe("Array of allowed values for the flag."),
1101
+ env: z.union([z.string(), z.array(z.string())]).optional().describe(
1102
+ "Environment variables that should be set from this flag's value in DXT packages."
1103
+ )
1104
+ }).transform((obj) => {
1099
1105
  const newObj = { ...obj };
1100
1106
  if ("default" in newObj && newObj["default"] !== void 0 && !("defaultValue" in newObj)) {
1101
1107
  newObj["defaultValue"] = newObj["default"];
@@ -1588,8 +1594,9 @@ class DxtGenerator {
1588
1594
  );
1589
1595
  }
1590
1596
  if (!fs.existsSync(logoPath)) {
1597
+ const currentDir2 = typeof process !== "undefined" ? process.cwd() : "/test";
1591
1598
  logoPath = path.join(
1592
- process.cwd(),
1599
+ currentDir2,
1593
1600
  "docs",
1594
1601
  "MCP",
1595
1602
  "icons",
@@ -1597,8 +1604,9 @@ class DxtGenerator {
1597
1604
  );
1598
1605
  }
1599
1606
  if (!fs.existsSync(logoPath)) {
1607
+ const currentDir2 = typeof process !== "undefined" ? process.cwd() : "/test";
1600
1608
  logoPath = path.join(
1601
- process.cwd(),
1609
+ currentDir2,
1602
1610
  "node_modules",
1603
1611
  "@alcyone-labs",
1604
1612
  "arg-parser",
@@ -1608,8 +1616,9 @@ class DxtGenerator {
1608
1616
  );
1609
1617
  }
1610
1618
  if (!fs.existsSync(logoPath)) {
1619
+ const currentDir2 = typeof process !== "undefined" ? process.cwd() : "/test";
1611
1620
  logoPath = path.join(
1612
- process.cwd(),
1621
+ currentDir2,
1613
1622
  "dist",
1614
1623
  "assets",
1615
1624
  "logo_1_small.jpg"
@@ -1644,12 +1653,12 @@ class DxtGenerator {
1644
1653
  * Builds a complete DXT package using TSDown CLI for autonomous execution
1645
1654
  */
1646
1655
  async buildDxtWithTsdown(entryPointFile, outputDir = "./dxt", withNodeModules = false) {
1656
+ var _a, _b;
1647
1657
  try {
1648
1658
  console.log(simpleChalk.cyan("🔧 Building DXT package with TSDown..."));
1649
1659
  const projectRoot = this.findProjectRoot(entryPointFile);
1650
1660
  const absoluteEntryPath = path.resolve(entryPointFile);
1651
1661
  const relativeEntryPath = path.relative(projectRoot, absoluteEntryPath);
1652
- const entryFileName = path.basename(entryPointFile);
1653
1662
  console.log(simpleChalk.gray(`Entry point: ${entryPointFile}`));
1654
1663
  console.log(simpleChalk.gray(`Project root: ${projectRoot}`));
1655
1664
  console.log(simpleChalk.gray(`Relative entry path: ${relativeEntryPath}`));
@@ -1666,9 +1675,8 @@ class DxtGenerator {
1666
1675
  console.log(
1667
1676
  logoFilename ? simpleChalk.gray(`✓ Logo prepared: ${logoFilename}`) : simpleChalk.gray("⚠ No logo available")
1668
1677
  );
1669
- const originalCwd = process.cwd();
1678
+ const originalCwd = typeof process !== "undefined" ? process.cwd() : "/test";
1670
1679
  try {
1671
- process.chdir(projectRoot);
1672
1680
  const { build } = await import("tsdown");
1673
1681
  console.log(simpleChalk.gray(`Building with TSDown: ${relativeEntryPath}`));
1674
1682
  console.log(
@@ -1676,23 +1684,51 @@ class DxtGenerator {
1676
1684
  `${withNodeModules ? "with node_modules" : "without node_modules"}`
1677
1685
  )
1678
1686
  );
1687
+ const mcpConfig = (_b = (_a = this.argParserInstance).getMcpServerConfig) == null ? void 0 : _b.call(_a);
1688
+ const entryDir = path.dirname(relativeEntryPath);
1689
+ const preservedOutDir = entryDir !== "." && entryDir !== "" ? path.resolve(originalCwd, outputDir, entryDir) : path.resolve(originalCwd, outputDir);
1679
1690
  const buildConfig = {
1680
1691
  entry: [relativeEntryPath],
1681
- outDir: path.resolve(originalCwd, outputDir),
1692
+ outDir: preservedOutDir,
1682
1693
  format: ["es"],
1683
1694
  target: "node22",
1684
1695
  define: {
1685
1696
  // Define any compile-time constants
1686
- NODE_ENV: '"production"'
1697
+ NODE_ENV: "production"
1687
1698
  },
1699
+ dts: true,
1688
1700
  minify: false,
1689
1701
  sourcemap: false,
1690
1702
  // Remove all output folders and artefacts
1691
1703
  clean: [outputDir, "./.dxtignore", `${outputDir}.dxt`],
1692
1704
  silent: process.env["NO_SILENCE"] !== "1",
1693
- external: (_, importer) => withNodeModules ? importer == null ? void 0 : importer.includes("node_modules") : false,
1694
- noExternal: (_, importer) => withNodeModules ? (importer == null ? void 0 : importer.includes("node_modules")) === false : true,
1705
+ unbundle: true,
1706
+ external: (id, importer) => {
1707
+ const external = this.shouldModuleBeExternal(
1708
+ id,
1709
+ importer,
1710
+ withNodeModules
1711
+ );
1712
+ if (Boolean(process.env["DEBUG"]))
1713
+ console.log(
1714
+ `[${simpleChalk.blue("External")}] ${simpleChalk.yellow(external ? "true" : "false")} for module: (${simpleChalk.green(id)}), path: '${simpleChalk.grey(importer ?? "")}'`
1715
+ );
1716
+ return external;
1717
+ },
1718
+ noExternal: (id, importer) => {
1719
+ const external = this.shouldModuleBeExternal(
1720
+ id,
1721
+ importer,
1722
+ withNodeModules
1723
+ );
1724
+ if (Boolean(process.env["DEBUG"]))
1725
+ console.log(
1726
+ `[${simpleChalk.yellow("noExternal")}] ${simpleChalk.yellow(external === false ? "true" : "false")} for module: (${simpleChalk.green(id)}), path: '${simpleChalk.grey(importer ?? "")}'`
1727
+ );
1728
+ return external === false;
1729
+ },
1695
1730
  copy: async (options) => {
1731
+ var _a2;
1696
1732
  const outputPaths = [
1697
1733
  "package.json"
1698
1734
  ];
@@ -1704,16 +1740,63 @@ class DxtGenerator {
1704
1740
  );
1705
1741
  outputPaths.push("node_modules");
1706
1742
  }
1743
+ const dxtPackageRoot = entryDir !== "." && entryDir !== "" ? path.dirname(options.outDir) : options.outDir;
1707
1744
  if (logoFilename) {
1708
- const logoPath = path.join(process.cwd(), logoFilename);
1745
+ const currentDir = typeof process !== "undefined" ? process.cwd() : "/test";
1746
+ const logoPath = path.join(currentDir, logoFilename);
1709
1747
  if (fs.existsSync(logoPath)) {
1710
1748
  console.log(simpleChalk.gray(`Adding logo from: ${logoPath}`));
1711
1749
  outputPaths.push({
1712
1750
  from: logoPath,
1713
- to: path.join(options.outDir, logoFilename)
1751
+ to: path.join(dxtPackageRoot, logoFilename)
1714
1752
  });
1715
1753
  }
1716
1754
  }
1755
+ if ((_a2 = mcpConfig == null ? void 0 : mcpConfig.dxt) == null ? void 0 : _a2.include) {
1756
+ console.log(
1757
+ simpleChalk.gray(
1758
+ "📁 Including additional files from DXT configuration..."
1759
+ )
1760
+ );
1761
+ for (const includeItem of mcpConfig.dxt.include) {
1762
+ if (typeof includeItem === "string") {
1763
+ const sourcePath = path.resolve(projectRoot, includeItem);
1764
+ if (fs.existsSync(sourcePath)) {
1765
+ console.log(simpleChalk.gray(` • ${includeItem}`));
1766
+ outputPaths.push({
1767
+ from: sourcePath,
1768
+ to: path.join(dxtPackageRoot, includeItem)
1769
+ });
1770
+ } else {
1771
+ console.warn(
1772
+ simpleChalk.yellow(
1773
+ ` ⚠ File not found: ${includeItem} (resolved to ${sourcePath})`
1774
+ )
1775
+ );
1776
+ }
1777
+ } else {
1778
+ const sourcePath = path.resolve(
1779
+ projectRoot,
1780
+ includeItem.from
1781
+ );
1782
+ if (fs.existsSync(sourcePath)) {
1783
+ console.log(
1784
+ simpleChalk.gray(` • ${includeItem.from} → ${includeItem.to}`)
1785
+ );
1786
+ outputPaths.push({
1787
+ from: sourcePath,
1788
+ to: path.join(dxtPackageRoot, includeItem.to)
1789
+ });
1790
+ } else {
1791
+ console.warn(
1792
+ simpleChalk.yellow(
1793
+ ` ⚠ File not found: ${includeItem.from} (resolved to ${sourcePath})`
1794
+ )
1795
+ );
1796
+ }
1797
+ }
1798
+ }
1799
+ }
1717
1800
  return outputPaths;
1718
1801
  },
1719
1802
  platform: "node",
@@ -1746,7 +1829,7 @@ export default ${JSON.stringify(buildConfig, null, 2)};
1746
1829
  console.log(simpleChalk.green("✅ TSDown bundling completed"));
1747
1830
  const detectedOutputFile = this.detectTsdownOutputFile(
1748
1831
  outputDir,
1749
- entryFileName
1832
+ relativeEntryPath.replace(/\.ts$/, ".js")
1750
1833
  );
1751
1834
  await this.setupDxtPackageFiles(
1752
1835
  entryPointFile,
@@ -1770,7 +1853,160 @@ export default ${JSON.stringify(buildConfig, null, 2)};
1770
1853
  }
1771
1854
  }
1772
1855
  /**
1773
- * Gets the path to the .dxtignore template file in assets
1856
+ * Checks if a module ID is a Node.js built-in
1857
+ */
1858
+ isNodeBuiltin(id) {
1859
+ const nodeBuiltins = [
1860
+ "stream",
1861
+ "fs",
1862
+ "path",
1863
+ "url",
1864
+ "util",
1865
+ "events",
1866
+ "child_process",
1867
+ "os",
1868
+ "tty",
1869
+ "process",
1870
+ "crypto",
1871
+ "http",
1872
+ "https",
1873
+ "net",
1874
+ "zlib",
1875
+ "fs/promises",
1876
+ "timers",
1877
+ "timers/promises",
1878
+ "perf_hooks",
1879
+ "async_hooks",
1880
+ "inspector",
1881
+ "v8",
1882
+ "vm",
1883
+ "assert",
1884
+ "constants",
1885
+ "module",
1886
+ "repl",
1887
+ "string_decoder",
1888
+ "punycode",
1889
+ "domain",
1890
+ "querystring",
1891
+ "readline",
1892
+ "worker_threads",
1893
+ "cluster",
1894
+ "dgram",
1895
+ "dns",
1896
+ "buffer"
1897
+ ];
1898
+ return nodeBuiltins.includes(id) || id.startsWith("node:");
1899
+ }
1900
+ /**
1901
+ * Determines if a module should be treated as external based on bundling configuration.
1902
+ * This logic is shared between external and noExternal configurations.
1903
+ *
1904
+ * @param id - The module identifier (e.g., 'lodash', '@types/node', './utils')
1905
+ * @param importer - The file path that is importing this module (undefined for entry points)
1906
+ * @param withNodeModules - Whether to include node_modules in the bundle
1907
+ * @returns true if the module should be external (not bundled), false if it should be bundled
1908
+ *
1909
+ * Logic flow:
1910
+ * 1. Node built-ins (fs, path, etc.) are always external
1911
+ * 2. If no importer (entry point), always bundle
1912
+ * 3. If withNodeModules is false, bundle everything except Node built-ins
1913
+ * 4. If withNodeModules is true:
1914
+ * - If importer is from node_modules, make external
1915
+ * - If module resolves to a project file (via TS paths or regular paths), bundle it
1916
+ * - Otherwise, make external (likely npm package)
1917
+ *
1918
+ * @example
1919
+ * // Node built-in - always external
1920
+ * shouldModuleBeExternal('fs', './src/main.ts', true) // returns true
1921
+ *
1922
+ * // Project file via TS paths or regular paths - bundle it
1923
+ * shouldModuleBeExternal('@/utils', './src/main.ts', true) // returns false
1924
+ *
1925
+ * // NPM package - external when withNodeModules=true
1926
+ * shouldModuleBeExternal('lodash', './src/main.ts', true) // returns true
1927
+ */
1928
+ shouldModuleBeExternal(id, importer, withNodeModules) {
1929
+ if (this.isNodeBuiltin(id)) {
1930
+ return true;
1931
+ }
1932
+ if (importer) {
1933
+ if (withNodeModules) {
1934
+ if (importer.includes("node_modules")) {
1935
+ return true;
1936
+ } else {
1937
+ const resolvedPath = this.resolveModulePath(id, importer);
1938
+ if (resolvedPath) {
1939
+ return false;
1940
+ } else {
1941
+ return true;
1942
+ }
1943
+ }
1944
+ } else {
1945
+ return false;
1946
+ }
1947
+ } else {
1948
+ return false;
1949
+ }
1950
+ }
1951
+ /**
1952
+ * Checks if a package ID exists in the local node_modules folder.
1953
+ * Only checks the folder or parent folder that contains the nearest package.json file.
1954
+ * Returns false if no package.json file is found after 3 parent directory traversals.
1955
+ *
1956
+ * Alternative approach using require.resolve():
1957
+ * ```ts
1958
+ * public isNodeModulesPackageWithResolve(packageId: string): boolean {
1959
+ * try {
1960
+ * require.resolve(packageId);
1961
+ * return true;
1962
+ * } catch {
1963
+ * return false;
1964
+ * }
1965
+ * }
1966
+ * ```
1967
+ *
1968
+ * Filesystem approach is preferred for bundler context because:
1969
+ * - Faster (no module resolution overhead)
1970
+ * - No side effects during build
1971
+ * - Predictable behavior in build vs runtime contexts
1972
+ */
1973
+ isNodeModulesPackage(packageId) {
1974
+ try {
1975
+ const currentDir = typeof process !== "undefined" ? process.cwd() : "/test";
1976
+ let searchDir = currentDir;
1977
+ let attempts = 0;
1978
+ const maxAttempts = 3;
1979
+ while (attempts < maxAttempts) {
1980
+ const packageJsonPath = path.join(searchDir, "package.json");
1981
+ if (fs.existsSync(packageJsonPath)) {
1982
+ const nodeModulesPath = path.join(searchDir, "node_modules");
1983
+ if (!fs.existsSync(nodeModulesPath)) {
1984
+ return false;
1985
+ }
1986
+ const packagePath = path.join(nodeModulesPath, packageId);
1987
+ if (fs.existsSync(packagePath)) {
1988
+ const packagePackageJsonPath = path.join(
1989
+ packagePath,
1990
+ "package.json"
1991
+ );
1992
+ return fs.existsSync(packagePackageJsonPath);
1993
+ }
1994
+ return false;
1995
+ }
1996
+ const parentDir = path.dirname(searchDir);
1997
+ if (parentDir === searchDir) {
1998
+ break;
1999
+ }
2000
+ searchDir = parentDir;
2001
+ attempts++;
2002
+ }
2003
+ return false;
2004
+ } catch (error) {
2005
+ return false;
2006
+ }
2007
+ }
2008
+ /**
2009
+ * Get the path to the .dxtignore template file
1774
2010
  */
1775
2011
  getDxtIgnoreTemplatePath() {
1776
2012
  const possiblePaths = [
@@ -1783,7 +2019,7 @@ export default ${JSON.stringify(buildConfig, null, 2)};
1783
2019
  ),
1784
2020
  // 2. From node_modules/@alcyone-labs/arg-parser/dist/assets (when installed via npm)
1785
2021
  path.join(
1786
- process.cwd(),
2022
+ typeof process !== "undefined" ? process.cwd() : "/test",
1787
2023
  "node_modules",
1788
2024
  "@alcyone-labs",
1789
2025
  "arg-parser",
@@ -1792,9 +2028,9 @@ export default ${JSON.stringify(buildConfig, null, 2)};
1792
2028
  ".dxtignore.template"
1793
2029
  ),
1794
2030
  // 3. From the root directory (development/local build)
1795
- path.join(process.cwd(), ".dxtignore.template"),
2031
+ path.join(typeof process !== "undefined" ? process.cwd() : "/test", ".dxtignore.template"),
1796
2032
  // 4. From the library root (when using local file dependency)
1797
- path.join(process.cwd(), "..", "..", "..", ".dxtignore.template")
2033
+ path.join(typeof process !== "undefined" ? process.cwd() : "/test", "..", "..", "..", ".dxtignore.template")
1798
2034
  ];
1799
2035
  for (const ignorePath of possiblePaths) {
1800
2036
  if (fs.existsSync(ignorePath)) {
@@ -1810,11 +2046,12 @@ export default ${JSON.stringify(buildConfig, null, 2)};
1810
2046
  */
1811
2047
  async setupDxtPackageFiles(entryPointFile, outputDir = "./dxt", actualOutputFilename, logoFilename = "logo.jpg") {
1812
2048
  var _a, _b, _c, _d, _e, _f;
1813
- const dxtDir = path.resolve(process.cwd(), outputDir);
2049
+ const currentDir = typeof process !== "undefined" ? process.cwd() : "/test";
2050
+ const dxtDir = path.resolve(currentDir, outputDir);
1814
2051
  if (!fs.existsSync(dxtDir)) {
1815
2052
  throw new Error(`TSDown output directory (${outputDir}) not found`);
1816
2053
  }
1817
- const packageJsonPath = path.join(process.cwd(), "package.json");
2054
+ const packageJsonPath = path.join(currentDir, "package.json");
1818
2055
  let packageInfo = {};
1819
2056
  if (fs.existsSync(packageJsonPath)) {
1820
2057
  try {
@@ -1919,16 +2156,41 @@ export default ${JSON.stringify(buildConfig, null, 2)};
1919
2156
  */
1920
2157
  detectTsdownOutputFile(outputDir, expectedBaseName) {
1921
2158
  try {
1922
- const dxtDir = path.resolve(process.cwd(), outputDir);
2159
+ let findJsFiles = function(dir, relativePath = "") {
2160
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
2161
+ for (const entry of entries) {
2162
+ const fullPath = path.join(dir, entry.name);
2163
+ const relativeFilePath = path.join(relativePath, entry.name);
2164
+ if (entry.isDirectory()) {
2165
+ if (entry.name === "node_modules" || entry.name.startsWith(".")) {
2166
+ continue;
2167
+ }
2168
+ findJsFiles(fullPath, relativeFilePath);
2169
+ } else if ((entry.name.endsWith(".js") || entry.name.endsWith(".mjs")) && !entry.name.includes("chunk-") && !entry.name.includes("dist-") && !entry.name.startsWith(".")) {
2170
+ files.push(relativeFilePath);
2171
+ }
2172
+ }
2173
+ };
2174
+ const currentDir = typeof process !== "undefined" ? process.cwd() : "/test";
2175
+ const dxtDir = path.resolve(currentDir, outputDir);
1923
2176
  if (!fs.existsSync(dxtDir)) {
1924
2177
  console.warn(
1925
2178
  simpleChalk.yellow(`⚠ Output directory (${outputDir}) not found`)
1926
2179
  );
1927
2180
  return null;
1928
2181
  }
1929
- const files = fs.readdirSync(dxtDir).filter(
1930
- (file) => (file.endsWith(".js") || file.endsWith(".mjs")) && !file.includes("chunk-") && !file.includes("dist-") && !file.startsWith(".")
1931
- );
2182
+ const files = [];
2183
+ findJsFiles(dxtDir);
2184
+ const expectedJsFile = expectedBaseName.endsWith(".js") ? expectedBaseName : expectedBaseName.replace(/\.ts$/, ".js");
2185
+ const expectedMjsFile = expectedBaseName.endsWith(".mjs") ? expectedBaseName : expectedBaseName.replace(/\.ts$/, ".mjs");
2186
+ if (files.includes(expectedJsFile)) {
2187
+ console.log(simpleChalk.gray(`✓ Detected TSDown output: ${expectedJsFile}`));
2188
+ return expectedJsFile;
2189
+ }
2190
+ if (files.includes(expectedMjsFile)) {
2191
+ console.log(simpleChalk.gray(`✓ Detected TSDown output: ${expectedMjsFile}`));
2192
+ return expectedMjsFile;
2193
+ }
1932
2194
  const baseNameWithoutExt = path.parse(expectedBaseName).name;
1933
2195
  for (const ext of [".js", ".mjs"]) {
1934
2196
  const exactMatch = `${baseNameWithoutExt}${ext}`;
@@ -2005,6 +2267,19 @@ export default ${JSON.stringify(buildConfig, null, 2)};
2005
2267
  generateEnvAndUserConfig() {
2006
2268
  const envVars = {};
2007
2269
  const userConfig = {};
2270
+ const shouldBeRequired = (flag) => {
2271
+ if (typeof flag.mandatory === "boolean") {
2272
+ return flag.mandatory;
2273
+ }
2274
+ if (typeof flag.mandatory === "function") {
2275
+ return false;
2276
+ }
2277
+ return false;
2278
+ };
2279
+ const shouldBeSensitive = (flag) => {
2280
+ const envVar = flag.env || flag.envVar;
2281
+ return !!envVar;
2282
+ };
2008
2283
  const mainFlags = this.argParserInstance.flags;
2009
2284
  for (const flag of mainFlags) {
2010
2285
  const envVar = flag.env || flag.envVar;
@@ -2014,10 +2289,10 @@ export default ${JSON.stringify(buildConfig, null, 2)};
2014
2289
  type: "string",
2015
2290
  title: envVar.replace(/_/g, " ").replace(/\b\w/g, (l) => l.toUpperCase()),
2016
2291
  description: flag.description || `${envVar} environment variable`,
2017
- required: true,
2018
- // Always require env vars in user_config for better UX
2019
- sensitive: true
2020
- // Assume env vars are sensitive
2292
+ required: shouldBeRequired(flag),
2293
+ // Respect the flag's mandatory setting
2294
+ sensitive: shouldBeSensitive(flag)
2295
+ // Set to sensitive if tied to ENV
2021
2296
  };
2022
2297
  }
2023
2298
  }
@@ -2033,10 +2308,10 @@ export default ${JSON.stringify(buildConfig, null, 2)};
2033
2308
  type: "string",
2034
2309
  title: envVar.replace(/_/g, " ").replace(/\b\w/g, (l) => l.toUpperCase()),
2035
2310
  description: flag.description || `${envVar} environment variable`,
2036
- required: true,
2037
- // Always require env vars in user_config for better UX
2038
- sensitive: true
2039
- // Assume env vars are sensitive
2311
+ required: shouldBeRequired(flag),
2312
+ // Respect the flag's mandatory setting
2313
+ sensitive: shouldBeSensitive(flag)
2314
+ // Set to sensitive if tied to ENV
2040
2315
  };
2041
2316
  }
2042
2317
  }
@@ -2044,6 +2319,176 @@ export default ${JSON.stringify(buildConfig, null, 2)};
2044
2319
  }
2045
2320
  return { envVars, userConfig };
2046
2321
  }
2322
+ resolveModulePath(id, importer) {
2323
+ var _a;
2324
+ try {
2325
+ if (Boolean(process.env["DEBUG"])) {
2326
+ console.log(
2327
+ ` <${simpleChalk.gray("module-resolve")}> Resolving '${simpleChalk.green(id)}' from '${simpleChalk.gray(importer)}'`
2328
+ );
2329
+ }
2330
+ const tsconfig = getTsconfig(importer);
2331
+ if (!((_a = tsconfig == null ? void 0 : tsconfig.config.compilerOptions) == null ? void 0 : _a.paths)) {
2332
+ if (Boolean(process.env["DEBUG"])) {
2333
+ console.log(
2334
+ ` <${simpleChalk.gray("ts-paths")}> No tsconfig or paths found for '${importer}'`
2335
+ );
2336
+ }
2337
+ } else {
2338
+ if (Boolean(process.env["DEBUG"])) {
2339
+ const currentDir = typeof process !== "undefined" ? process.cwd() : "/test";
2340
+ console.log(
2341
+ ` <${simpleChalk.gray("ts-paths")}> Found tsconfig at '${path.relative(currentDir, tsconfig.path)}' with paths:`,
2342
+ Object.keys(tsconfig.config.compilerOptions.paths)
2343
+ );
2344
+ }
2345
+ const pathsMatcher = createPathsMatcher(tsconfig);
2346
+ if (!pathsMatcher) {
2347
+ if (Boolean(process.env["DEBUG"])) {
2348
+ console.log(
2349
+ ` <${simpleChalk.gray("ts-paths")}> Failed to create paths matcher`
2350
+ );
2351
+ }
2352
+ } else {
2353
+ const possiblePaths = pathsMatcher(id);
2354
+ if (Boolean(process.env["DEBUG"])) {
2355
+ console.log(
2356
+ ` <${simpleChalk.grey("ts-paths")}> Possible paths for '${id}':`,
2357
+ possiblePaths
2358
+ );
2359
+ }
2360
+ for (const possiblePath of possiblePaths) {
2361
+ const resolvedPath = path.resolve(
2362
+ path.dirname(tsconfig.path),
2363
+ possiblePath
2364
+ );
2365
+ if (Boolean(process.env["DEBUG"])) {
2366
+ console.log(
2367
+ ` <${simpleChalk.grey("ts-paths")}> Trying resolved path: '${resolvedPath}'`
2368
+ );
2369
+ }
2370
+ const extensions2 = [".ts", ".js", ".tsx", ".jsx", ".mjs", ".cjs"];
2371
+ if (fs.existsSync(resolvedPath) && fs.statSync(resolvedPath).isFile()) {
2372
+ if (Boolean(process.env["DEBUG"])) {
2373
+ console.log(
2374
+ ` <${simpleChalk.grey("ts-paths")}> ✓ Resolved '${id}' to '${resolvedPath}'`
2375
+ );
2376
+ }
2377
+ return resolvedPath;
2378
+ }
2379
+ if (resolvedPath.endsWith(".js")) {
2380
+ const basePath = resolvedPath.slice(0, -3);
2381
+ for (const ext of [".ts", ".tsx"]) {
2382
+ const testPath2 = basePath + ext;
2383
+ if (fs.existsSync(testPath2) && fs.statSync(testPath2).isFile()) {
2384
+ if (Boolean(process.env["DEBUG"])) {
2385
+ console.log(
2386
+ ` <${simpleChalk.grey("ts-paths")}> ✓ Resolved '${id}' to '${testPath2}' (replaced .js)`
2387
+ );
2388
+ }
2389
+ return testPath2;
2390
+ }
2391
+ }
2392
+ }
2393
+ for (const ext of extensions2) {
2394
+ const testPath2 = resolvedPath + ext;
2395
+ if (fs.existsSync(testPath2) && fs.statSync(testPath2).isFile()) {
2396
+ if (Boolean(process.env["DEBUG"])) {
2397
+ console.log(
2398
+ ` <${simpleChalk.grey("ts-paths")}> ✓ Resolved '${id}' to '${testPath2}' (added extension)`
2399
+ );
2400
+ }
2401
+ return testPath2;
2402
+ }
2403
+ }
2404
+ if (fs.existsSync(resolvedPath) && fs.statSync(resolvedPath).isDirectory()) {
2405
+ for (const ext of extensions2) {
2406
+ const indexPath = path.join(resolvedPath, `index${ext}`);
2407
+ if (fs.existsSync(indexPath)) {
2408
+ if (Boolean(process.env["DEBUG"])) {
2409
+ console.log(
2410
+ ` <${simpleChalk.grey("ts-paths")}> ✓ Resolved '${id}' to '${indexPath}' (index)`
2411
+ );
2412
+ }
2413
+ return indexPath;
2414
+ }
2415
+ }
2416
+ }
2417
+ }
2418
+ }
2419
+ }
2420
+ if (Boolean(process.env["DEBUG"])) {
2421
+ console.log(
2422
+ ` <${simpleChalk.gray("file-resolve")}> Trying regular file resolution for '${id}'`
2423
+ );
2424
+ }
2425
+ let testPath;
2426
+ if (path.isAbsolute(id)) {
2427
+ testPath = id;
2428
+ } else {
2429
+ testPath = path.resolve(path.dirname(importer), id);
2430
+ }
2431
+ const extensions = [".ts", ".js", ".tsx", ".jsx", ".mjs", ".cjs"];
2432
+ if (fs.existsSync(testPath) && fs.statSync(testPath).isFile()) {
2433
+ if (Boolean(process.env["DEBUG"])) {
2434
+ console.log(
2435
+ ` <${simpleChalk.gray("file-resolve")}> ✓ Resolved '${id}' to '${testPath}'`
2436
+ );
2437
+ }
2438
+ return testPath;
2439
+ }
2440
+ if (testPath.endsWith(".js")) {
2441
+ const basePath = testPath.slice(0, -3);
2442
+ for (const ext of [".ts", ".tsx"]) {
2443
+ const tsPath = basePath + ext;
2444
+ if (fs.existsSync(tsPath) && fs.statSync(tsPath).isFile()) {
2445
+ if (Boolean(process.env["DEBUG"])) {
2446
+ console.log(
2447
+ ` <${simpleChalk.gray("file-resolve")}> ✓ Resolved '${id}' to '${tsPath}' (replaced .js)`
2448
+ );
2449
+ }
2450
+ return tsPath;
2451
+ }
2452
+ }
2453
+ }
2454
+ for (const ext of extensions) {
2455
+ const extPath = testPath + ext;
2456
+ if (fs.existsSync(extPath) && fs.statSync(extPath).isFile()) {
2457
+ if (Boolean(process.env["DEBUG"])) {
2458
+ console.log(
2459
+ ` <${simpleChalk.gray("file-resolve")}> ✓ Resolved '${id}' to '${extPath}' (added extension)`
2460
+ );
2461
+ }
2462
+ return extPath;
2463
+ }
2464
+ }
2465
+ if (fs.existsSync(testPath) && fs.statSync(testPath).isDirectory()) {
2466
+ for (const ext of extensions) {
2467
+ const indexPath = path.join(testPath, `index${ext}`);
2468
+ if (fs.existsSync(indexPath)) {
2469
+ if (Boolean(process.env["DEBUG"])) {
2470
+ console.log(
2471
+ ` <${simpleChalk.gray("file-resolve")}> ✓ Resolved '${id}' to '${indexPath}' (index)`
2472
+ );
2473
+ }
2474
+ return indexPath;
2475
+ }
2476
+ }
2477
+ }
2478
+ if (Boolean(process.env["DEBUG"])) {
2479
+ console.log(
2480
+ ` <${simpleChalk.gray("module-resolve")}> ✗ Could not resolve '${id}'`
2481
+ );
2482
+ }
2483
+ } catch (error) {
2484
+ console.warn(
2485
+ simpleChalk.yellow(
2486
+ `Warning: Failed to resolve module path '${id}': ${error}`
2487
+ )
2488
+ );
2489
+ }
2490
+ return null;
2491
+ }
2047
2492
  }
2048
2493
  class McpNotificationsManager {
2049
2494
  constructor() {
@@ -2515,6 +2960,61 @@ class McpResourcesManager {
2515
2960
  }
2516
2961
  }
2517
2962
  }
2963
+ const isDebugEnabled = () => {
2964
+ try {
2965
+ return Boolean(typeof process !== "undefined" && process.env && process.env["DEBUG"]);
2966
+ } catch {
2967
+ return false;
2968
+ }
2969
+ };
2970
+ const debug = {
2971
+ /**
2972
+ * Log a debug message to stderr (only when DEBUG=true)
2973
+ */
2974
+ log: (...args) => {
2975
+ if (isDebugEnabled()) {
2976
+ console.error("[DEBUG]", ...args);
2977
+ }
2978
+ },
2979
+ /**
2980
+ * Log an error debug message to stderr (only when DEBUG=true)
2981
+ */
2982
+ error: (...args) => {
2983
+ if (isDebugEnabled()) {
2984
+ console.error("[DEBUG ERROR]", ...args);
2985
+ }
2986
+ },
2987
+ /**
2988
+ * Log a warning debug message to stderr (only when DEBUG=true)
2989
+ */
2990
+ warn: (...args) => {
2991
+ if (isDebugEnabled()) {
2992
+ console.error("[DEBUG WARN]", ...args);
2993
+ }
2994
+ },
2995
+ /**
2996
+ * Log an info debug message to stderr (only when DEBUG=true)
2997
+ */
2998
+ info: (...args) => {
2999
+ if (isDebugEnabled()) {
3000
+ console.error("[DEBUG INFO]", ...args);
3001
+ }
3002
+ },
3003
+ /**
3004
+ * Log a debug message with a custom prefix (only when DEBUG=true)
3005
+ */
3006
+ prefixed: (prefix, ...args) => {
3007
+ if (isDebugEnabled()) {
3008
+ console.error(`[DEBUG ${prefix}]`, ...args);
3009
+ }
3010
+ },
3011
+ /**
3012
+ * Check if debug mode is currently enabled
3013
+ */
3014
+ get enabled() {
3015
+ return isDebugEnabled();
3016
+ }
3017
+ };
2518
3018
  const _FlagManager = class _FlagManager {
2519
3019
  constructor(options = {}, initialFlags = []) {
2520
3020
  __privateAdd(this, __flags, /* @__PURE__ */ new Map());
@@ -2555,7 +3055,8 @@ const _FlagManager = class _FlagManager {
2555
3055
  type: resolvedType,
2556
3056
  validate: parsedFromZod["validate"],
2557
3057
  enum: parsedFromZod["enum"],
2558
- mandatory: parsedFromZod["mandatory"]
3058
+ mandatory: parsedFromZod["mandatory"],
3059
+ env: parsedFromZod["env"]
2559
3060
  };
2560
3061
  }
2561
3062
  addFlag(flag) {
@@ -2949,6 +3450,7 @@ const _ArgParserBase = class _ArgParserBase {
2949
3450
  }
2950
3451
  async parse(processArgs, options) {
2951
3452
  var _a, _b;
3453
+ debug.log("ArgParserBase.parse() called with args:", processArgs);
2952
3454
  if (processArgs === void 0) {
2953
3455
  if (typeof process !== "undefined" && process.argv && Array.isArray(process.argv)) {
2954
3456
  processArgs = process.argv.slice(2);
@@ -3256,6 +3758,14 @@ ${indent(2)}${white(line)}`).join("")}
3256
3758
  hasFlag(name) {
3257
3759
  return __privateGet(this, _flagManager).hasFlag(name);
3258
3760
  }
3761
+ /**
3762
+ * Get flag definition by name
3763
+ * @param name Flag name
3764
+ * @returns Flag definition or undefined if not found
3765
+ */
3766
+ getFlagDefinition(name) {
3767
+ return __privateGet(this, _flagManager).getFlag(name);
3768
+ }
3259
3769
  getCommandChain() {
3260
3770
  const chain = [];
3261
3771
  let currentParser = this;
@@ -3491,11 +4001,15 @@ _handleGlobalChecks_fn = async function(processArgs, options) {
3491
4001
  return dxtResult === true ? true : dxtResult;
3492
4002
  }
3493
4003
  }
4004
+ debug.log("Checking for --s-mcp-serve flag in args:", processArgs);
3494
4005
  const mcpServeIndex = processArgs.findIndex(
3495
4006
  (arg) => arg === "--s-mcp-serve"
3496
4007
  );
4008
+ debug.log("mcpServeIndex:", mcpServeIndex);
3497
4009
  if (mcpServeIndex !== -1) {
4010
+ debug.log("Found --s-mcp-serve flag, calling handler");
3498
4011
  const mcpServeResult = await __privateMethod(this, _ArgParserBase_instances, _handleMcpServeFlag_fn).call(this, processArgs, mcpServeIndex);
4012
+ debug.log("MCP serve handler returned:", typeof mcpServeResult);
3499
4013
  if (mcpServeResult !== false) {
3500
4014
  return mcpServeResult === true ? true : mcpServeResult;
3501
4015
  }
@@ -4092,20 +4606,39 @@ _handleBuildDxtFlag_fn = async function(processArgs, buildDxtIndex) {
4092
4606
  };
4093
4607
  _handleMcpServeFlag_fn = async function(processArgs, _mcpServeIndex) {
4094
4608
  var _a;
4609
+ debug.log("#_handleMcpServeFlag started");
4095
4610
  const transportOptions = __privateMethod(this, _ArgParserBase_instances, _parseMcpTransportOptions_fn).call(this, processArgs);
4611
+ debug.log("Transport options parsed:", JSON.stringify(transportOptions));
4096
4612
  const mcpServerConfig = __privateMethod(this, _ArgParserBase_instances, _getMcpServerConfiguration_fn).call(this);
4613
+ debug.log("Got MCP server config:", JSON.stringify(mcpServerConfig));
4097
4614
  const effectiveLogPath = transportOptions.logPath || (mcpServerConfig == null ? void 0 : mcpServerConfig.logPath) || "./logs/mcp.log";
4615
+ debug.log("Effective log path:", effectiveLogPath);
4098
4616
  const resolvedLogPath = resolveLogPath(effectiveLogPath);
4617
+ debug.log("Resolved log path:", resolvedLogPath);
4099
4618
  let mcpLogger;
4619
+ debug.log("About to import simple-mcp-logger");
4100
4620
  try {
4101
4621
  const mcpLoggerModule = await import("@alcyone-labs/simple-mcp-logger");
4102
- mcpLogger = mcpLoggerModule.createMcpLogger("MCP Serve", resolvedLogPath);
4622
+ debug.log("Successfully imported simple-mcp-logger");
4623
+ const loggerConfig = __privateMethod(this, _ArgParserBase_instances, _resolveLoggerConfigForServe_fn).call(this, mcpServerConfig, resolvedLogPath);
4624
+ if (typeof loggerConfig === "string") {
4625
+ mcpLogger = mcpLoggerModule.createMcpLogger("MCP Serve", loggerConfig);
4626
+ } else {
4627
+ mcpLogger = mcpLoggerModule.createMcpLogger(
4628
+ loggerConfig.prefix || "MCP Serve",
4629
+ loggerConfig.logToFile
4630
+ );
4631
+ }
4632
+ debug.log("Created MCP logger, about to hijack console");
4103
4633
  globalThis.console = mcpLogger;
4634
+ debug.log("Console hijacked successfully");
4104
4635
  } catch {
4636
+ debug.log("Failed to import simple-mcp-logger, using fallback");
4105
4637
  mcpLogger = {
4106
4638
  mcpError: (message) => console.error(`[MCP Serve] ${message}`)
4107
4639
  };
4108
4640
  }
4641
+ debug.log("MCP logger setup complete, starting MCP serve handler");
4109
4642
  try {
4110
4643
  mcpLogger.mcpError(
4111
4644
  "Starting --s-mcp-serve system flag handler - console hijacked for MCP safety"
@@ -4128,11 +4661,13 @@ _handleMcpServeFlag_fn = async function(processArgs, _mcpServeIndex) {
4128
4661
  `Transport options: ${JSON.stringify(transportOptions)}`
4129
4662
  );
4130
4663
  try {
4664
+ debug.log("About to call #_startUnifiedMcpServer");
4131
4665
  mcpLogger.mcpError("Starting unified MCP server with all tools");
4132
4666
  await __privateMethod(this, _ArgParserBase_instances, _startUnifiedMcpServer_fn).call(this, mcpServerConfig, {
4133
4667
  ...transportOptions,
4134
4668
  logPath: resolvedLogPath
4135
4669
  });
4670
+ debug.log("#_startUnifiedMcpServer completed");
4136
4671
  mcpLogger.mcpError("Successfully started unified MCP server");
4137
4672
  } catch (error) {
4138
4673
  mcpLogger.mcpError(
@@ -4163,6 +4698,36 @@ _handleMcpServeFlag_fn = async function(processArgs, _mcpServeIndex) {
4163
4698
  );
4164
4699
  }
4165
4700
  };
4701
+ /**
4702
+ * Resolve logger configuration for MCP serve with proper priority
4703
+ * @param mcpServerConfig MCP server configuration
4704
+ * @param resolvedLogPath Resolved log path from CLI flags
4705
+ * @returns Logger configuration object or string path
4706
+ */
4707
+ _resolveLoggerConfigForServe_fn = function(mcpServerConfig, resolvedLogPath) {
4708
+ if (mcpServerConfig == null ? void 0 : mcpServerConfig.log) {
4709
+ if (typeof mcpServerConfig.log === "string") {
4710
+ return {
4711
+ prefix: "MCP Serve",
4712
+ logToFile: resolvedLogPath,
4713
+ level: "error",
4714
+ // Default level for backward compatibility
4715
+ mcpMode: true
4716
+ };
4717
+ } else {
4718
+ return {
4719
+ prefix: "MCP Serve",
4720
+ level: "error",
4721
+ // Default level for backward compatibility
4722
+ mcpMode: true,
4723
+ ...mcpServerConfig.log,
4724
+ // Use CLI-resolved path if available, otherwise use config path
4725
+ logToFile: resolvedLogPath
4726
+ };
4727
+ }
4728
+ }
4729
+ return resolvedLogPath;
4730
+ };
4166
4731
  /**
4167
4732
  * Get MCP server configuration from withMcp() or fallback to addMcpSubCommand()
4168
4733
  */
@@ -4353,6 +4918,26 @@ _parseMcpTransportOptions_fn = function(processArgs) {
4353
4918
  return options;
4354
4919
  };
4355
4920
  let ArgParserBase = _ArgParserBase;
4921
+ function sanitizeMcpToolName(name) {
4922
+ if (!name || typeof name !== "string") {
4923
+ throw new Error("Tool name must be a non-empty string");
4924
+ }
4925
+ let sanitized = name.replace(/[^a-zA-Z0-9_-]/g, "_");
4926
+ if (!sanitized || /^_+$/.test(sanitized)) {
4927
+ sanitized = "tool";
4928
+ }
4929
+ if (sanitized.length > 64) {
4930
+ sanitized = sanitized.substring(0, 64);
4931
+ }
4932
+ return sanitized;
4933
+ }
4934
+ function isValidMcpToolName(name) {
4935
+ if (!name || typeof name !== "string") {
4936
+ return false;
4937
+ }
4938
+ const mcpNamePattern = /^[a-zA-Z0-9_-]{1,64}$/;
4939
+ return mcpNamePattern.test(name);
4940
+ }
4356
4941
  function createMcpSuccessResponse(data2) {
4357
4942
  return {
4358
4943
  content: [
@@ -4611,7 +5196,7 @@ function generateMcpToolsFromArgParser(rootParser, options) {
4611
5196
  } else {
4612
5197
  toolName = effectiveCommandName || "cmd";
4613
5198
  }
4614
- toolName = toolName.replace(/[^a-zA-Z0-9_-]/g, "_");
5199
+ toolName = sanitizeMcpToolName(toolName);
4615
5200
  }
4616
5201
  if (!toolName)
4617
5202
  toolName = currentParser === rootParser && appName ? appName : "cmd";
@@ -4653,7 +5238,7 @@ function generateMcpToolsFromArgParser(rootParser, options) {
4653
5238
  inputSchema,
4654
5239
  outputSchema,
4655
5240
  async execute(mcpInputArgs) {
4656
- var _a;
5241
+ var _a, _b, _c, _d, _e, _f;
4657
5242
  if (process.env["MCP_DEBUG"]) {
4658
5243
  console.error(
4659
5244
  `[MCP Execute] Starting execution for tool '${toolName}'`
@@ -4775,12 +5360,32 @@ function generateMcpToolsFromArgParser(rootParser, options) {
4775
5360
  JSON.stringify(mcpInputArgs, null, 2)
4776
5361
  );
4777
5362
  }
5363
+ const getFlag = (name) => {
5364
+ if (mcpInputArgs && mcpInputArgs[name] !== void 0) {
5365
+ return mcpInputArgs[name];
5366
+ }
5367
+ if (rootParser) {
5368
+ const flagDef = rootParser.getFlagDefinition(name);
5369
+ if (flagDef) {
5370
+ const envVar = flagDef["env"];
5371
+ if (envVar) {
5372
+ const envKey = Array.isArray(envVar) ? envVar[0] : envVar;
5373
+ if (envKey && process.env[envKey]) {
5374
+ return process.env[envKey];
5375
+ }
5376
+ }
5377
+ return flagDef["defaultValue"];
5378
+ }
5379
+ }
5380
+ return void 0;
5381
+ };
4778
5382
  const handlerContext = {
4779
5383
  args: mcpInputArgs,
4780
5384
  commandChain: [toolName],
4781
5385
  parser: rootParser,
4782
5386
  parentArgs: void 0,
4783
- isMcp: true
5387
+ isMcp: true,
5388
+ getFlag
4784
5389
  };
4785
5390
  const handlerResult = await toolConfig.handler(handlerContext);
4786
5391
  if (process.env["MCP_DEBUG"]) {
@@ -4846,49 +5451,67 @@ function generateMcpToolsFromArgParser(rootParser, options) {
4846
5451
  error: errPayload.message,
4847
5452
  message: errPayload.message
4848
5453
  };
4849
- if (outputSchema && typeof outputSchema === "object" && outputSchema !== null && outputSchema._def) {
4850
- const zodSchema = outputSchema;
4851
- if (process.env["MCP_DEBUG"]) {
4852
- console.error(
4853
- `[MCP Debug] Output schema type:`,
4854
- zodSchema._def.typeName
4855
- );
4856
- }
4857
- if (zodSchema._def.typeName === "ZodObject") {
4858
- const shapeGetter = zodSchema._def.shape;
4859
- const shape = typeof shapeGetter === "function" ? shapeGetter() : shapeGetter;
5454
+ try {
5455
+ if (outputSchema && typeof outputSchema === "object" && outputSchema !== null && outputSchema._def) {
5456
+ const zodSchema = outputSchema;
4860
5457
  if (process.env["MCP_DEBUG"]) {
4861
5458
  console.error(
4862
- `[MCP Debug] Schema shape keys:`,
4863
- Object.keys(shape)
5459
+ `[MCP Debug] Output schema type:`,
5460
+ ((_b = zodSchema._def) == null ? void 0 : _b.typeName) || ((_c = zodSchema._def) == null ? void 0 : _c.type)
4864
5461
  );
4865
5462
  }
4866
- Object.keys(shape).forEach((key) => {
4867
- if (!(key in structuredError)) {
4868
- const fieldSchema = shape[key];
4869
- if (fieldSchema && fieldSchema._def) {
4870
- switch (fieldSchema._def.typeName) {
4871
- case "ZodString":
4872
- structuredError[key] = "";
4873
- break;
4874
- case "ZodNumber":
4875
- structuredError[key] = 0;
4876
- break;
4877
- case "ZodBoolean":
4878
- structuredError[key] = false;
4879
- break;
4880
- case "ZodArray":
4881
- structuredError[key] = [];
4882
- break;
4883
- case "ZodObject":
4884
- structuredError[key] = {};
4885
- break;
4886
- default:
4887
- structuredError[key] = null;
5463
+ if (((_d = zodSchema._def) == null ? void 0 : _d.typeName) === "ZodObject" || ((_e = zodSchema._def) == null ? void 0 : _e.type) === "object") {
5464
+ const shapeGetter = (_f = zodSchema._def) == null ? void 0 : _f.shape;
5465
+ if (shapeGetter) {
5466
+ const shape = typeof shapeGetter === "function" ? shapeGetter() : shapeGetter;
5467
+ if (shape && typeof shape === "object") {
5468
+ if (process.env["MCP_DEBUG"]) {
5469
+ console.error(
5470
+ `[MCP Debug] Schema shape keys:`,
5471
+ Object.keys(shape)
5472
+ );
4888
5473
  }
5474
+ Object.keys(shape).forEach((key) => {
5475
+ if (!(key in structuredError)) {
5476
+ const fieldSchema = shape[key];
5477
+ if (fieldSchema && fieldSchema._def) {
5478
+ switch (fieldSchema._def.typeName || fieldSchema._def.type) {
5479
+ case "ZodString":
5480
+ case "string":
5481
+ structuredError[key] = "";
5482
+ break;
5483
+ case "ZodNumber":
5484
+ case "number":
5485
+ structuredError[key] = 0;
5486
+ break;
5487
+ case "ZodBoolean":
5488
+ case "boolean":
5489
+ structuredError[key] = false;
5490
+ break;
5491
+ case "ZodArray":
5492
+ case "array":
5493
+ structuredError[key] = [];
5494
+ break;
5495
+ case "ZodObject":
5496
+ case "object":
5497
+ structuredError[key] = {};
5498
+ break;
5499
+ default:
5500
+ structuredError[key] = null;
5501
+ }
5502
+ }
5503
+ }
5504
+ });
4889
5505
  }
4890
5506
  }
4891
- });
5507
+ }
5508
+ }
5509
+ } catch (schemaError) {
5510
+ if (process.env["MCP_DEBUG"]) {
5511
+ console.error(
5512
+ `[MCP Debug] Error processing output schema for structured error:`,
5513
+ schemaError
5514
+ );
4892
5515
  }
4893
5516
  }
4894
5517
  if (process.env["MCP_DEBUG"]) {
@@ -4978,12 +5601,32 @@ function generateMcpToolsFromArgParser(rootParser, options) {
4978
5601
  const handlerToCall = finalHandler;
4979
5602
  const cleanArgs = { ...mcpInputArgs };
4980
5603
  delete cleanArgs["help"];
5604
+ const getFlag = (name) => {
5605
+ if (cleanArgs && cleanArgs[name] !== void 0) {
5606
+ return cleanArgs[name];
5607
+ }
5608
+ if (finalParser) {
5609
+ const flagDef = finalParser.getFlagDefinition(name);
5610
+ if (flagDef) {
5611
+ const envVar = flagDef["env"];
5612
+ if (envVar) {
5613
+ const envKey = Array.isArray(envVar) ? envVar[0] : envVar;
5614
+ if (envKey && process.env[envKey]) {
5615
+ return process.env[envKey];
5616
+ }
5617
+ }
5618
+ return flagDef["defaultValue"];
5619
+ }
5620
+ }
5621
+ return void 0;
5622
+ };
4981
5623
  const handlerContext = {
4982
5624
  args: cleanArgs,
4983
5625
  commandChain: chain,
4984
5626
  parser: finalParser,
4985
5627
  parentArgs: resolvedParentArgs,
4986
- isMcp: true
5628
+ isMcp: true,
5629
+ getFlag
4987
5630
  };
4988
5631
  try {
4989
5632
  handlerResponse = await handlerToCall(handlerContext);
@@ -5092,27 +5735,27 @@ function generateMcpToolsFromArgParser(rootParser, options) {
5092
5735
  };
5093
5736
  if (outputSchema && typeof outputSchema === "object" && outputSchema !== null && outputSchema._def) {
5094
5737
  const zodSchema = outputSchema;
5095
- if (zodSchema._def.typeName === "ZodObject") {
5738
+ if (zodSchema._def.type === "object") {
5096
5739
  const shapeGetter = zodSchema._def.shape;
5097
5740
  const shape = typeof shapeGetter === "function" ? shapeGetter() : shapeGetter;
5098
5741
  Object.keys(shape).forEach((key) => {
5099
5742
  if (!(key in structuredError)) {
5100
5743
  const fieldSchema = shape[key];
5101
5744
  if (fieldSchema && fieldSchema._def) {
5102
- switch (fieldSchema._def.typeName) {
5103
- case "ZodString":
5745
+ switch (fieldSchema._def.type) {
5746
+ case "string":
5104
5747
  structuredError[key] = "";
5105
5748
  break;
5106
- case "ZodNumber":
5749
+ case "number":
5107
5750
  structuredError[key] = 0;
5108
5751
  break;
5109
- case "ZodBoolean":
5752
+ case "boolean":
5110
5753
  structuredError[key] = false;
5111
5754
  break;
5112
- case "ZodArray":
5755
+ case "array":
5113
5756
  structuredError[key] = [];
5114
5757
  break;
5115
- case "ZodObject":
5758
+ case "object":
5116
5759
  structuredError[key] = {};
5117
5760
  break;
5118
5761
  default:
@@ -5174,18 +5817,61 @@ function compareVersions(v1, v2) {
5174
5817
  if (v1 === v2) return 0;
5175
5818
  return v1 < v2 ? -1 : 1;
5176
5819
  }
5177
- const _ArgParser = class _ArgParser extends ArgParserBase {
5178
- constructor() {
5179
- super(...arguments);
5180
- __privateAdd(this, _ArgParser_instances);
5181
- this._mcpTools = /* @__PURE__ */ new Map();
5182
- this._tools = /* @__PURE__ */ new Map();
5183
- this._outputSchemaMap = /* @__PURE__ */ new Map();
5184
- this._mcpProtocolVersion = CURRENT_MCP_PROTOCOL_VERSION;
5820
+ function debugSchemaStructure(schema, label = "Schema") {
5821
+ var _a, _b, _c;
5822
+ if (process.env["MCP_DEBUG"]) {
5823
+ console.error(`[Zod Compatibility Debug] ${label} structure:`);
5824
+ console.error(` - Type: ${typeof schema}`);
5825
+ console.error(` - Constructor: ${(_a = schema == null ? void 0 : schema.constructor) == null ? void 0 : _a.name}`);
5826
+ console.error(` - Has shape: ${!!(schema == null ? void 0 : schema.shape)}`);
5827
+ console.error(` - Has _def: ${!!(schema == null ? void 0 : schema._def)}`);
5828
+ console.error(` - _def.typeName: ${(_b = schema == null ? void 0 : schema._def) == null ? void 0 : _b.typeName}`);
5829
+ console.error(` - _def.type: ${(_c = schema == null ? void 0 : schema._def) == null ? void 0 : _c.type}`);
5830
+ console.error(` - Has parse: ${typeof (schema == null ? void 0 : schema.parse)}`);
5831
+ console.error(` - Has safeParse: ${typeof (schema == null ? void 0 : schema.safeParse)}`);
5832
+ if (schema == null ? void 0 : schema.shape) {
5833
+ console.error(` - Shape keys: ${Object.keys(schema.shape)}`);
5834
+ }
5185
5835
  }
5186
- /**
5187
- * Get the stored MCP server configuration
5188
- * @returns MCP server configuration if set via withMcp(), undefined otherwise
5836
+ }
5837
+ function validateMcpSchemaCompatibility(schema) {
5838
+ var _a, _b;
5839
+ try {
5840
+ if (typeof (schema == null ? void 0 : schema.parse) !== "function") {
5841
+ console.warn("[Zod Compatibility] Schema missing parse method");
5842
+ return false;
5843
+ }
5844
+ if (typeof (schema == null ? void 0 : schema.safeParse) !== "function") {
5845
+ console.warn("[Zod Compatibility] Schema missing safeParse method");
5846
+ return false;
5847
+ }
5848
+ if ((((_a = schema == null ? void 0 : schema._def) == null ? void 0 : _a.typeName) === "ZodObject" || ((_b = schema == null ? void 0 : schema._def) == null ? void 0 : _b.type) === "object") && !(schema == null ? void 0 : schema.shape)) {
5849
+ console.warn(
5850
+ "[Zod Compatibility] ZodObject schema missing shape property"
5851
+ );
5852
+ return false;
5853
+ }
5854
+ return true;
5855
+ } catch (error) {
5856
+ console.error(
5857
+ "[Zod Compatibility] Error validating schema compatibility:",
5858
+ error
5859
+ );
5860
+ return false;
5861
+ }
5862
+ }
5863
+ const _ArgParser = class _ArgParser extends ArgParserBase {
5864
+ constructor() {
5865
+ super(...arguments);
5866
+ __privateAdd(this, _ArgParser_instances);
5867
+ this._mcpTools = /* @__PURE__ */ new Map();
5868
+ this._tools = /* @__PURE__ */ new Map();
5869
+ this._outputSchemaMap = /* @__PURE__ */ new Map();
5870
+ this._mcpProtocolVersion = CURRENT_MCP_PROTOCOL_VERSION;
5871
+ }
5872
+ /**
5873
+ * Get the stored MCP server configuration
5874
+ * @returns MCP server configuration if set via withMcp(), undefined otherwise
5189
5875
  */
5190
5876
  getMcpServerConfig() {
5191
5877
  return this._mcpServerConfig;
@@ -5244,19 +5930,33 @@ const _ArgParser = class _ArgParser extends ArgParserBase {
5244
5930
  * @returns This ArgParser instance for chaining
5245
5931
  */
5246
5932
  addTool(toolConfig) {
5247
- if (this._tools.has(toolConfig.name)) {
5248
- throw new Error(`Tool with name '${toolConfig.name}' already exists`);
5249
- }
5933
+ var _a;
5250
5934
  if (!toolConfig.name || typeof toolConfig.name !== "string") {
5251
5935
  throw new Error("Tool name is required and must be a string");
5252
5936
  }
5253
5937
  if (!toolConfig.handler || typeof toolConfig.handler !== "function") {
5254
5938
  throw new Error("Tool handler is required and must be a function");
5255
5939
  }
5940
+ const sanitizedName = sanitizeMcpToolName(toolConfig.name);
5941
+ if (sanitizedName !== toolConfig.name) {
5942
+ const isMcpMode = (_a = globalThis.console) == null ? void 0 : _a.mcpError;
5943
+ if (!isMcpMode) {
5944
+ console.warn(
5945
+ `[ArgParser] Tool name '${toolConfig.name}' was sanitized to '${sanitizedName}' for MCP compatibility`
5946
+ );
5947
+ }
5948
+ }
5949
+ if (this._tools.has(sanitizedName)) {
5950
+ throw new Error(`Tool with name '${sanitizedName}' already exists`);
5951
+ }
5256
5952
  if (!Array.isArray(toolConfig.flags)) {
5257
5953
  throw new Error("Tool flags must be an array");
5258
5954
  }
5259
- this._tools.set(toolConfig.name, toolConfig);
5955
+ const sanitizedToolConfig = {
5956
+ ...toolConfig,
5957
+ name: sanitizedName
5958
+ };
5959
+ this._tools.set(sanitizedName, sanitizedToolConfig);
5260
5960
  __privateMethod(this, _ArgParser_instances, registerToolAsSubCommand_fn).call(this, toolConfig);
5261
5961
  return this;
5262
5962
  }
@@ -5267,13 +5967,40 @@ const _ArgParser = class _ArgParser extends ArgParserBase {
5267
5967
  * @returns This ArgParser instance for chaining
5268
5968
  */
5269
5969
  addMcpTool(toolConfig) {
5270
- console.warn(`[DEPRECATED] addMcpTool() is deprecated and will be removed in v2.0.
5970
+ var _a;
5971
+ try {
5972
+ if (typeof process !== "undefined" && process.stderr) {
5973
+ process.stderr.write(`[DEPRECATED] addMcpTool() is deprecated and will be removed in v2.0.
5974
+ Please use addTool() instead for a unified CLI/MCP experience.
5975
+ Migration guide: https://github.com/alcyone-labs/arg-parser/blob/main/docs/MCP-MIGRATION.md
5976
+ `);
5977
+ } else {
5978
+ console.warn(`[DEPRECATED] addMcpTool() is deprecated and will be removed in v2.0.
5979
+ Please use addTool() instead for a unified CLI/MCP experience.
5980
+ Migration guide: https://github.com/alcyone-labs/arg-parser/blob/main/docs/MCP-MIGRATION.md`);
5981
+ }
5982
+ } catch {
5983
+ console.warn(`[DEPRECATED] addMcpTool() is deprecated and will be removed in v2.0.
5271
5984
  Please use addTool() instead for a unified CLI/MCP experience.
5272
5985
  Migration guide: https://github.com/alcyone-labs/arg-parser/blob/main/docs/MCP-MIGRATION.md`);
5273
- if (this._mcpTools.has(toolConfig.name)) {
5274
- throw new Error(`MCP tool with name '${toolConfig.name}' already exists`);
5275
5986
  }
5276
- this._mcpTools.set(toolConfig.name, toolConfig);
5987
+ const sanitizedName = sanitizeMcpToolName(toolConfig.name);
5988
+ if (sanitizedName !== toolConfig.name) {
5989
+ const isMcpMode = (_a = globalThis.console) == null ? void 0 : _a.mcpError;
5990
+ if (!isMcpMode) {
5991
+ console.warn(
5992
+ `[ArgParser] Tool name '${toolConfig.name}' was sanitized to '${sanitizedName}' for MCP compatibility`
5993
+ );
5994
+ }
5995
+ }
5996
+ if (this._mcpTools.has(sanitizedName)) {
5997
+ throw new Error(`MCP tool with name '${sanitizedName}' already exists`);
5998
+ }
5999
+ const sanitizedToolConfig = {
6000
+ ...toolConfig,
6001
+ name: sanitizedName
6002
+ };
6003
+ this._mcpTools.set(sanitizedName, sanitizedToolConfig);
5277
6004
  return this;
5278
6005
  }
5279
6006
  /**
@@ -5545,7 +6272,7 @@ Migration guide: https://github.com/alcyone-labs/arg-parser/blob/main/docs/MCP-M
5545
6272
  ).map((toolConfig) => ({
5546
6273
  name: toolConfig.name,
5547
6274
  description: toolConfig.description || `Executes the ${toolConfig.name} tool.`,
5548
- inputSchema: toolConfig.inputSchema || { type: "object", properties: {} },
6275
+ inputSchema: toolConfig.inputSchema || z.object({}),
5549
6276
  outputSchema: toolConfig.outputSchema,
5550
6277
  execute: async (args) => {
5551
6278
  try {
@@ -5605,16 +6332,18 @@ Migration guide: https://github.com/alcyone-labs/arg-parser/blob/main/docs/MCP-M
5605
6332
  * Create an MCP server with tools generated from this ArgParser
5606
6333
  * @param serverInfo Server configuration
5607
6334
  * @param toolOptions Optional MCP tool generation options
6335
+ * @param logPath Optional log path (deprecated, use log config in withMcp instead)
5608
6336
  * @returns Configured MCP server instance
5609
6337
  */
5610
6338
  async createMcpServer(serverInfo, toolOptions, logPath) {
5611
- var _a, _b;
5612
- const resolvedLogPath = resolveLogPath(
5613
- logPath || ((_a = this._mcpServerConfig) == null ? void 0 : _a.logPath) || "./logs/mcp.log"
6339
+ var _a, _b, _c;
6340
+ const loggerConfig = __privateMethod(this, _ArgParser_instances, _resolveLoggerConfig_fn).call(this, logPath);
6341
+ const logger2 = typeof loggerConfig === "string" ? createMcpLogger("MCP Server Creation", loggerConfig) : createMcpLogger(
6342
+ loggerConfig.prefix || "MCP Server Creation",
6343
+ loggerConfig.logToFile
5614
6344
  );
5615
- const logger2 = createMcpLogger("MCP Server Creation", resolvedLogPath);
5616
6345
  try {
5617
- const effectiveServerInfo = serverInfo || ((_b = this._mcpServerConfig) == null ? void 0 : _b.serverInfo);
6346
+ const effectiveServerInfo = serverInfo || ((_a = this._mcpServerConfig) == null ? void 0 : _a.serverInfo);
5618
6347
  if (!effectiveServerInfo) {
5619
6348
  throw new Error(
5620
6349
  "No MCP server configuration found. Use withMcp() to configure server info or provide serverInfo parameter."
@@ -5623,8 +6352,10 @@ Migration guide: https://github.com/alcyone-labs/arg-parser/blob/main/docs/MCP-M
5623
6352
  logger2.mcpError(
5624
6353
  `Creating MCP server: ${effectiveServerInfo.name} v${effectiveServerInfo.version}`
5625
6354
  );
5626
- const { McpServer: McpServer2 } = await Promise.resolve().then(() => mcp);
5627
- logger2.mcpError("Successfully imported McpServer from SDK");
6355
+ const { McpServer: McpServer2, ResourceTemplate: ResourceTemplate2 } = await Promise.resolve().then(() => mcp);
6356
+ logger2.mcpError(
6357
+ "Successfully imported McpServer and ResourceTemplate from SDK"
6358
+ );
5628
6359
  const server = new McpServer2({
5629
6360
  id: effectiveServerInfo.name,
5630
6361
  version: effectiveServerInfo.version,
@@ -5632,6 +6363,61 @@ Migration guide: https://github.com/alcyone-labs/arg-parser/blob/main/docs/MCP-M
5632
6363
  description: effectiveServerInfo.description
5633
6364
  });
5634
6365
  logger2.mcpError("Successfully created McpServer instance");
6366
+ const isInMcpServeMode = process.argv.includes("--s-mcp-serve");
6367
+ if (((_b = this._mcpServerConfig) == null ? void 0 : _b.lifecycle) && !isInMcpServeMode) {
6368
+ const { McpLifecycleManager: McpLifecycleManager2 } = await Promise.resolve().then(() => mcpLifecycle);
6369
+ const lifecycleManager = new McpLifecycleManager2(
6370
+ this._mcpServerConfig.lifecycle,
6371
+ logger2,
6372
+ effectiveServerInfo,
6373
+ this
6374
+ );
6375
+ try {
6376
+ const filteredArgs = process.argv.slice(2).filter(
6377
+ (arg) => !arg.startsWith("--s-mcp-") && arg !== "--s-mcp-serve"
6378
+ );
6379
+ const parsedResult = await this.parse(filteredArgs, {
6380
+ skipHandlerExecution: true,
6381
+ isMcp: true
6382
+ });
6383
+ const parsedArgs = (parsedResult == null ? void 0 : parsedResult.args) || parsedResult || {};
6384
+ lifecycleManager.setParsedArgs(parsedArgs);
6385
+ logger2.mcpError(`Lifecycle manager initialized with parsed args: ${Object.keys(parsedArgs).join(", ")}`);
6386
+ } catch (parseError) {
6387
+ logger2.mcpError(`Warning: Could not parse arguments for lifecycle manager: ${parseError instanceof Error ? parseError.message : String(parseError)}`);
6388
+ }
6389
+ const originalConnect = server.connect.bind(server);
6390
+ server.connect = async (transport) => {
6391
+ logger2.mcpError("MCP server connecting with lifecycle events...");
6392
+ const result = await originalConnect(transport);
6393
+ try {
6394
+ await lifecycleManager.handleInitialize(
6395
+ { name: "mcp-client", version: "1.0.0" },
6396
+ // Default client info
6397
+ "2024-11-05",
6398
+ // Default protocol version
6399
+ {}
6400
+ // Default capabilities
6401
+ );
6402
+ setTimeout(async () => {
6403
+ try {
6404
+ await lifecycleManager.handleInitialized();
6405
+ } catch (error) {
6406
+ logger2.mcpError(
6407
+ `Lifecycle onInitialized error: ${error instanceof Error ? error.message : String(error)}`
6408
+ );
6409
+ }
6410
+ }, 100);
6411
+ } catch (error) {
6412
+ logger2.mcpError(
6413
+ `Lifecycle onInitialize error: ${error instanceof Error ? error.message : String(error)}`
6414
+ );
6415
+ }
6416
+ return result;
6417
+ };
6418
+ server._lifecycleManager = lifecycleManager;
6419
+ logger2.mcpError("Successfully set up MCP lifecycle manager");
6420
+ }
5635
6421
  logger2.mcpError(
5636
6422
  "MCP server will register actual resources and prompts for full capability support"
5637
6423
  );
@@ -5648,29 +6434,122 @@ Migration guide: https://github.com/alcyone-labs/arg-parser/blob/main/docs/MCP-M
5648
6434
  `After deduplication: ${uniqueTools.length} unique tools`
5649
6435
  );
5650
6436
  uniqueTools.forEach((tool) => {
6437
+ var _a2, _b2, _c2, _d, _e, _f;
5651
6438
  logger2.mcpError(`Registering tool: ${tool.name}`);
5652
- let inputSchema;
5653
- if (tool.inputSchema === null || tool.inputSchema === void 0) {
5654
- inputSchema = {};
5655
- } else if (tool.inputSchema && typeof tool.inputSchema === "object" && tool.inputSchema !== null && tool.inputSchema._def) {
5656
- const zodObjectSchema = tool.inputSchema;
5657
- if (zodObjectSchema._def.typeName === "ZodObject") {
5658
- const shapeGetter = zodObjectSchema._def.shape;
5659
- const shape = typeof shapeGetter === "function" ? shapeGetter() : shapeGetter;
5660
- inputSchema = shape;
5661
- } else {
5662
- inputSchema = tool.inputSchema;
5663
- }
6439
+ let zodSchema;
6440
+ const toolFromUnified = Array.from(this._tools.values()).find(
6441
+ (t) => t.name === tool.name
6442
+ );
6443
+ const toolFromLegacy = Array.from(this._mcpTools.values()).find(
6444
+ (t) => t.name === tool.name
6445
+ );
6446
+ if (toolFromUnified && toolFromUnified.flags) {
6447
+ zodSchema = convertFlagsToZodSchema(toolFromUnified.flags);
6448
+ } else if (toolFromLegacy && toolFromLegacy.inputSchema) {
6449
+ zodSchema = toolFromLegacy.inputSchema;
5664
6450
  } else {
5665
- inputSchema = tool.inputSchema || {};
6451
+ zodSchema = z.object({});
6452
+ }
6453
+ let mcpCompatibleSchema;
6454
+ try {
6455
+ if (process.env["MCP_DEBUG"]) {
6456
+ console.error(`[MCP Debug] Preparing schema for tool ${tool.name}`);
6457
+ console.error(`[MCP Debug] Input zodSchema:`, zodSchema);
6458
+ }
6459
+ mcpCompatibleSchema = zodSchema;
6460
+ if (process.env["MCP_DEBUG"]) {
6461
+ console.error(
6462
+ `[MCP Debug] Successfully prepared schema for tool ${tool.name}`
6463
+ );
6464
+ }
6465
+ } catch (schemaError) {
6466
+ console.error(
6467
+ `[MCP Debug] Error preparing schema for tool ${tool.name}:`,
6468
+ schemaError
6469
+ );
6470
+ throw schemaError;
6471
+ }
6472
+ if (process.env["MCP_DEBUG"]) {
6473
+ console.error(
6474
+ `[MCP Debug] Prepared mcpCompatibleSchema for tool ${tool.name}:`,
6475
+ JSON.stringify(mcpCompatibleSchema, null, 2)
6476
+ );
6477
+ console.error(
6478
+ `[MCP Debug] Schema properties:`,
6479
+ Object.keys(mcpCompatibleSchema || {})
6480
+ );
6481
+ console.error(
6482
+ `[MCP Debug] Schema def:`,
6483
+ mcpCompatibleSchema == null ? void 0 : mcpCompatibleSchema.def
6484
+ );
6485
+ console.error(
6486
+ `[MCP Debug] Schema shape:`,
6487
+ mcpCompatibleSchema == null ? void 0 : mcpCompatibleSchema.shape
6488
+ );
6489
+ console.error(
6490
+ `[MCP Debug] Schema parse function:`,
6491
+ typeof (mcpCompatibleSchema == null ? void 0 : mcpCompatibleSchema.parse)
6492
+ );
6493
+ }
6494
+ if (process.env["MCP_DEBUG"]) {
6495
+ console.error(
6496
+ `[MCP Debug] About to prepare schema for tool ${tool.name}`
6497
+ );
6498
+ console.error(`[MCP Debug] zodSchema type:`, typeof zodSchema);
6499
+ console.error(`[MCP Debug] zodSchema:`, zodSchema);
6500
+ console.error(
6501
+ `[MCP Debug] zodSchema constructor:`,
6502
+ (_a2 = zodSchema == null ? void 0 : zodSchema.constructor) == null ? void 0 : _a2.name
6503
+ );
6504
+ }
6505
+ debugSchemaStructure(mcpCompatibleSchema, `Tool ${tool.name} schema`);
6506
+ if (!validateMcpSchemaCompatibility(mcpCompatibleSchema)) {
6507
+ logger2.mcpError(
6508
+ `Warning: Schema for tool ${tool.name} may not be fully compatible with MCP SDK`
6509
+ );
5666
6510
  }
5667
6511
  const toolConfig = {
5668
6512
  title: tool.name,
5669
6513
  // MCP SDK requires title field
5670
6514
  description: tool.description || "No description provided.",
5671
- inputSchema
5672
- // Use Zod shape directly for MCP SDK compatibility
6515
+ inputSchema: mcpCompatibleSchema
6516
+ // Use Zod v3 compatible schema for MCP SDK
5673
6517
  };
6518
+ if (process.env["MCP_DEBUG"]) {
6519
+ console.error(
6520
+ `[MCP Debug] Final toolConfig for ${tool.name}:`,
6521
+ JSON.stringify(toolConfig, null, 2)
6522
+ );
6523
+ console.error(
6524
+ `[MCP Debug] toolConfig.inputSchema type:`,
6525
+ typeof toolConfig.inputSchema
6526
+ );
6527
+ console.error(
6528
+ `[MCP Debug] toolConfig.inputSchema constructor:`,
6529
+ (_c2 = (_b2 = toolConfig.inputSchema) == null ? void 0 : _b2.constructor) == null ? void 0 : _c2.name
6530
+ );
6531
+ console.error(
6532
+ `[MCP Debug] toolConfig.inputSchema._def:`,
6533
+ (_d = toolConfig.inputSchema) == null ? void 0 : _d._def
6534
+ );
6535
+ console.error(
6536
+ `[MCP Debug] toolConfig.inputSchema.shape:`,
6537
+ (_e = toolConfig.inputSchema) == null ? void 0 : _e.shape
6538
+ );
6539
+ console.error(
6540
+ `[MCP Debug] toolConfig.inputSchema._zod:`,
6541
+ (_f = toolConfig.inputSchema) == null ? void 0 : _f._zod
6542
+ );
6543
+ console.error(
6544
+ `[MCP Debug] Schema keys:`,
6545
+ Object.keys(mcpCompatibleSchema || {})
6546
+ );
6547
+ console.error(`[MCP Debug] About to call server.registerTool with:`, {
6548
+ name: tool.name,
6549
+ description: tool.description,
6550
+ inputSchema: mcpCompatibleSchema
6551
+ });
6552
+ }
5674
6553
  const simpleExecute = async (args) => {
5675
6554
  if (process.env["MCP_DEBUG"]) {
5676
6555
  console.error(
@@ -5720,37 +6599,194 @@ Migration guide: https://github.com/alcyone-labs/arg-parser/blob/main/docs/MCP-M
5720
6599
  });
5721
6600
  logger2.mcpError("Successfully registered all tools with MCP server");
5722
6601
  const resources = this.getMcpResources();
5723
- logger2.mcpError(
5724
- `Found ${resources.length} MCP resources (registration temporarily disabled)`
5725
- );
5726
- if (resources.length > 0) {
5727
- logger2.mcpError(
5728
- "Resource registration is temporarily disabled due to MCP SDK type compatibility"
5729
- );
5730
- logger2.mcpError(
5731
- "Resources are stored and will be available once SDK integration is completed"
5732
- );
5733
- }
5734
- logger2.mcpError(
5735
- "Resource registration step completed (temporarily disabled)"
5736
- );
6602
+ logger2.mcpError(`Registering ${resources.length} MCP resources`);
6603
+ resources.forEach((resource) => {
6604
+ try {
6605
+ const resourceConfig = {
6606
+ title: resource.title || resource.name,
6607
+ description: resource.description || `Resource: ${resource.name}`,
6608
+ mimeType: resource.mimeType || "application/json"
6609
+ };
6610
+ if (resource.uriTemplate.includes("{")) {
6611
+ const resourceTemplate = new ResourceTemplate2(
6612
+ resource.uriTemplate,
6613
+ { list: void 0 }
6614
+ );
6615
+ const templateHandler = async (uri, params = {}) => {
6616
+ try {
6617
+ const result = await resource.handler(
6618
+ new URL(uri.href || uri),
6619
+ params
6620
+ );
6621
+ return {
6622
+ contents: result.contents.map((content) => {
6623
+ const mcpContent = {
6624
+ uri: content.uri
6625
+ };
6626
+ if (content.text !== void 0) {
6627
+ mcpContent.text = content.text;
6628
+ }
6629
+ if (content.blob !== void 0) {
6630
+ mcpContent.blob = content.blob;
6631
+ }
6632
+ if (content.mimeType !== void 0) {
6633
+ mcpContent.mimeType = content.mimeType;
6634
+ }
6635
+ return mcpContent;
6636
+ })
6637
+ };
6638
+ } catch (error) {
6639
+ logger2.mcpError(
6640
+ `Resource template handler error for ${resource.name}: ${error instanceof Error ? error.message : String(error)}`
6641
+ );
6642
+ throw error;
6643
+ }
6644
+ };
6645
+ server.registerResource(
6646
+ resource.name,
6647
+ resourceTemplate,
6648
+ resourceConfig,
6649
+ templateHandler
6650
+ );
6651
+ } else {
6652
+ const resourceHandler = async (uri) => {
6653
+ try {
6654
+ const result = await resource.handler(
6655
+ new URL(uri.href || uri),
6656
+ {}
6657
+ );
6658
+ return {
6659
+ contents: result.contents.map((content) => {
6660
+ const mcpContent = {
6661
+ uri: content.uri
6662
+ };
6663
+ if (content.text !== void 0) {
6664
+ mcpContent.text = content.text;
6665
+ }
6666
+ if (content.blob !== void 0) {
6667
+ mcpContent.blob = content.blob;
6668
+ }
6669
+ if (content.mimeType !== void 0) {
6670
+ mcpContent.mimeType = content.mimeType;
6671
+ }
6672
+ return mcpContent;
6673
+ })
6674
+ };
6675
+ } catch (error) {
6676
+ logger2.mcpError(
6677
+ `Resource handler error for ${resource.name}: ${error instanceof Error ? error.message : String(error)}`
6678
+ );
6679
+ throw error;
6680
+ }
6681
+ };
6682
+ server.registerResource(
6683
+ resource.name,
6684
+ resource.uriTemplate,
6685
+ resourceConfig,
6686
+ resourceHandler
6687
+ );
6688
+ }
6689
+ logger2.mcpError(`Successfully registered resource: ${resource.name}`);
6690
+ } catch (error) {
6691
+ logger2.mcpError(
6692
+ `Failed to register resource ${resource.name}: ${error instanceof Error ? error.message : String(error)}`
6693
+ );
6694
+ }
6695
+ });
6696
+ logger2.mcpError("Successfully registered all resources with MCP server");
5737
6697
  const prompts = this.getMcpPrompts();
5738
- logger2.mcpError(
5739
- `Found ${prompts.length} MCP prompts (registration temporarily disabled)`
5740
- );
5741
- if (prompts.length > 0) {
5742
- logger2.mcpError(
5743
- "Prompt registration is temporarily disabled due to MCP SDK type compatibility"
5744
- );
5745
- logger2.mcpError(
5746
- "Prompts are stored and will be available once SDK integration is completed"
5747
- );
5748
- }
5749
- logger2.mcpError(
5750
- "Prompt registration step completed (temporarily disabled)"
5751
- );
6698
+ logger2.mcpError(`Registering ${prompts.length} MCP prompts`);
6699
+ prompts.forEach((prompt) => {
6700
+ try {
6701
+ let mcpCompatibleSchema;
6702
+ try {
6703
+ if (process.env["MCP_DEBUG"]) {
6704
+ console.error(
6705
+ `[MCP Debug] Preparing schema for prompt ${prompt.name}`
6706
+ );
6707
+ console.error(`[MCP Debug] Input argsSchema:`, prompt.argsSchema);
6708
+ }
6709
+ mcpCompatibleSchema = prompt.argsSchema;
6710
+ if (process.env["MCP_DEBUG"]) {
6711
+ console.error(
6712
+ `[MCP Debug] Successfully prepared schema for prompt ${prompt.name}`
6713
+ );
6714
+ }
6715
+ } catch (schemaError) {
6716
+ console.error(
6717
+ `[MCP Debug] Error preparing schema for prompt ${prompt.name}:`,
6718
+ schemaError
6719
+ );
6720
+ throw schemaError;
6721
+ }
6722
+ if (!validateMcpSchemaCompatibility(mcpCompatibleSchema)) {
6723
+ throw new Error(
6724
+ `Schema validation failed for prompt ${prompt.name}`
6725
+ );
6726
+ }
6727
+ if (process.env["MCP_DEBUG"]) {
6728
+ debugSchemaStructure(mcpCompatibleSchema, `prompt ${prompt.name}`);
6729
+ }
6730
+ const promptConfig = {
6731
+ title: prompt.title || prompt.name,
6732
+ // MCP SDK requires title field
6733
+ description: prompt.description || "No description provided.",
6734
+ argsSchema: mcpCompatibleSchema
6735
+ // Use Zod v3 compatible schema for MCP SDK
6736
+ };
6737
+ const promptHandler = async (args) => {
6738
+ try {
6739
+ const validatedArgs = prompt.argsSchema.parse(args);
6740
+ const result = await prompt.handler(validatedArgs);
6741
+ if (process.env["MCP_DEBUG"]) {
6742
+ console.error(
6743
+ `[MCP Debug] Prompt '${prompt.name}' executed successfully`
6744
+ );
6745
+ }
6746
+ return result;
6747
+ } catch (error) {
6748
+ if (process.env["MCP_DEBUG"]) {
6749
+ console.error(
6750
+ `[MCP Debug] Prompt '${prompt.name}' execution error:`,
6751
+ error
6752
+ );
6753
+ }
6754
+ throw error;
6755
+ }
6756
+ };
6757
+ server.registerPrompt(
6758
+ prompt.name,
6759
+ promptConfig,
6760
+ promptHandler
6761
+ );
6762
+ logger2.mcpError(`Successfully registered prompt: ${prompt.name}`);
6763
+ } catch (error) {
6764
+ logger2.mcpError(
6765
+ `Failed to register prompt ${prompt.name}: ${error instanceof Error ? error.message : String(error)}`
6766
+ );
6767
+ }
6768
+ });
6769
+ logger2.mcpError("Successfully registered all prompts with MCP server");
5752
6770
  this.setupMcpChangeNotifications(server);
5753
6771
  logger2.mcpError("Successfully set up MCP change notifications");
6772
+ if (server._lifecycleManager) {
6773
+ const originalClose = (_c = server.close) == null ? void 0 : _c.bind(server);
6774
+ server.close = async () => {
6775
+ logger2.mcpError("MCP server shutdown initiated");
6776
+ try {
6777
+ await server._lifecycleManager.handleShutdown(
6778
+ "server_shutdown"
6779
+ );
6780
+ } catch (error) {
6781
+ logger2.mcpError(
6782
+ `Error during lifecycle shutdown: ${error instanceof Error ? error.message : String(error)}`
6783
+ );
6784
+ }
6785
+ if (originalClose) {
6786
+ await originalClose();
6787
+ }
6788
+ };
6789
+ }
5754
6790
  return server;
5755
6791
  } catch (error) {
5756
6792
  logger2.mcpError(
@@ -5820,11 +6856,14 @@ Migration guide: https://github.com/alcyone-labs/arg-parser/blob/main/docs/MCP-M
5820
6856
  }, logPath);
5821
6857
  }
5822
6858
  async parse(processArgs, options) {
6859
+ debug.log("ArgParser.parse() called with args:", processArgs);
6860
+ debug.log("About to call ArgParserBase.prototype.parse.call()");
5823
6861
  let result = await ArgParserBase.prototype.parse.call(
5824
6862
  this,
5825
6863
  processArgs,
5826
6864
  options
5827
6865
  );
6866
+ debug.log("ArgParserBase.prototype.parse.call() returned:", typeof result);
5828
6867
  const anyResult = result;
5829
6868
  if (anyResult._fuzzyModePreventedExecution) {
5830
6869
  return result;
@@ -6059,6 +7098,63 @@ Migration guide: https://github.com/alcyone-labs/arg-parser/blob/main/docs/MCP-M
6059
7098
  }
6060
7099
  };
6061
7100
  _ArgParser_instances = new WeakSet();
7101
+ /**
7102
+ * Resolve logger configuration from various sources with proper priority
7103
+ * @param logPathOverride Optional log path override parameter
7104
+ * @returns Logger configuration object for createMcpLogger
7105
+ */
7106
+ _resolveLoggerConfig_fn = function(logPathOverride) {
7107
+ const mcpConfig = this._mcpServerConfig;
7108
+ if (logPathOverride) {
7109
+ const resolvedPath = resolveLogPath(logPathOverride);
7110
+ return {
7111
+ prefix: "MCP Server Creation",
7112
+ logToFile: resolvedPath,
7113
+ level: "error",
7114
+ // Default level for backward compatibility
7115
+ mcpMode: true
7116
+ };
7117
+ }
7118
+ const hasLogConfig = mcpConfig == null ? void 0 : mcpConfig.log;
7119
+ const hasLogPath = mcpConfig == null ? void 0 : mcpConfig.logPath;
7120
+ if (hasLogConfig || hasLogPath) {
7121
+ let config = {
7122
+ prefix: "MCP Server Creation",
7123
+ level: "error",
7124
+ // Default level for backward compatibility
7125
+ mcpMode: true
7126
+ };
7127
+ if (hasLogConfig && mcpConfig.log) {
7128
+ if (typeof mcpConfig.log === "string") {
7129
+ config.logToFile = resolveLogPath(mcpConfig.log);
7130
+ } else {
7131
+ config = {
7132
+ ...config,
7133
+ ...mcpConfig.log,
7134
+ // Resolve logToFile path if provided in log config
7135
+ ...mcpConfig.log.logToFile && {
7136
+ logToFile: resolveLogPath(mcpConfig.log.logToFile)
7137
+ }
7138
+ };
7139
+ }
7140
+ }
7141
+ if (hasLogPath && mcpConfig.logPath && !config.logToFile) {
7142
+ config.logToFile = resolveLogPath(mcpConfig.logPath);
7143
+ }
7144
+ if (hasLogPath && mcpConfig.logPath && hasLogConfig && mcpConfig.log && typeof mcpConfig.log === "object" && mcpConfig.log.logToFile) {
7145
+ config.logToFile = resolveLogPath(mcpConfig.logPath);
7146
+ }
7147
+ return config;
7148
+ }
7149
+ const defaultPath = resolveLogPath("./logs/mcp.log");
7150
+ return {
7151
+ prefix: "MCP Server Creation",
7152
+ logToFile: defaultPath,
7153
+ level: "error",
7154
+ // Default level for backward compatibility
7155
+ mcpMode: true
7156
+ };
7157
+ };
6062
7158
  /**
6063
7159
  * Register a tool as a CLI subcommand
6064
7160
  * @private
@@ -6832,53 +7928,62 @@ const SUPPORTED_PROTOCOL_VERSIONS = [
6832
7928
  const JSONRPC_VERSION = "2.0";
6833
7929
  const ProgressTokenSchema = z.union([z.string(), z.number().int()]);
6834
7930
  const CursorSchema = z.string();
6835
- const RequestMetaSchema = z.object({
7931
+ const RequestMetaSchema = z.looseObject({
6836
7932
  /**
6837
7933
  * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications.
6838
7934
  */
6839
7935
  progressToken: z.optional(ProgressTokenSchema)
6840
- }).passthrough();
6841
- const BaseRequestParamsSchema = z.object({
7936
+ });
7937
+ const BaseRequestParamsSchema = z.looseObject({
6842
7938
  _meta: z.optional(RequestMetaSchema)
6843
- }).passthrough();
7939
+ });
6844
7940
  const RequestSchema = z.object({
6845
7941
  method: z.string(),
6846
7942
  params: z.optional(BaseRequestParamsSchema)
6847
7943
  });
6848
- const BaseNotificationParamsSchema = z.object({
7944
+ const BaseNotificationParamsSchema = z.looseObject({
6849
7945
  /**
6850
7946
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
6851
7947
  * for notes on _meta usage.
6852
7948
  */
6853
- _meta: z.optional(z.object({}).passthrough())
6854
- }).passthrough();
7949
+ _meta: z.optional(z.looseObject({}))
7950
+ });
6855
7951
  const NotificationSchema = z.object({
6856
7952
  method: z.string(),
6857
7953
  params: z.optional(BaseNotificationParamsSchema)
6858
7954
  });
6859
- const ResultSchema = z.object({
7955
+ const ResultSchema = z.looseObject({
6860
7956
  /**
6861
7957
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
6862
7958
  * for notes on _meta usage.
6863
7959
  */
6864
- _meta: z.optional(z.object({}).passthrough())
6865
- }).passthrough();
7960
+ _meta: z.optional(z.looseObject({}))
7961
+ });
6866
7962
  const RequestIdSchema = z.union([z.string(), z.number().int()]);
6867
- const JSONRPCRequestSchema = z.object({
7963
+ const JSONRPCRequestSchema = z.strictObject({
6868
7964
  jsonrpc: z.literal(JSONRPC_VERSION),
6869
7965
  id: RequestIdSchema
6870
- }).merge(RequestSchema).strict();
6871
- const isJSONRPCRequest = (value) => JSONRPCRequestSchema.safeParse(value).success;
6872
- const JSONRPCNotificationSchema = z.object({
7966
+ }).extend(RequestSchema.shape);
7967
+ const isJSONRPCRequest = (value) => {
7968
+ const result = JSONRPCRequestSchema.safeParse(value);
7969
+ return result.success;
7970
+ };
7971
+ const JSONRPCNotificationSchema = z.strictObject({
6873
7972
  jsonrpc: z.literal(JSONRPC_VERSION)
6874
- }).merge(NotificationSchema).strict();
6875
- const isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value).success;
6876
- const JSONRPCResponseSchema = z.object({
7973
+ }).extend(NotificationSchema.shape);
7974
+ const isJSONRPCNotification = (value) => {
7975
+ const result = JSONRPCNotificationSchema.safeParse(value);
7976
+ return result.success;
7977
+ };
7978
+ const JSONRPCResponseSchema = z.strictObject({
6877
7979
  jsonrpc: z.literal(JSONRPC_VERSION),
6878
7980
  id: RequestIdSchema,
6879
7981
  result: ResultSchema
6880
- }).strict();
6881
- const isJSONRPCResponse = (value) => JSONRPCResponseSchema.safeParse(value).success;
7982
+ });
7983
+ const isJSONRPCResponse = (value) => {
7984
+ const result = JSONRPCResponseSchema.safeParse(value);
7985
+ return result.success;
7986
+ };
6882
7987
  var ErrorCode;
6883
7988
  (function(ErrorCode2) {
6884
7989
  ErrorCode2[ErrorCode2["ConnectionClosed"] = -32e3] = "ConnectionClosed";
@@ -6889,7 +7994,7 @@ var ErrorCode;
6889
7994
  ErrorCode2[ErrorCode2["InvalidParams"] = -32602] = "InvalidParams";
6890
7995
  ErrorCode2[ErrorCode2["InternalError"] = -32603] = "InternalError";
6891
7996
  })(ErrorCode || (ErrorCode = {}));
6892
- const JSONRPCErrorSchema = z.object({
7997
+ const JSONRPCErrorSchema = z.strictObject({
6893
7998
  jsonrpc: z.literal(JSONRPC_VERSION),
6894
7999
  id: RequestIdSchema,
6895
8000
  error: z.object({
@@ -6906,15 +8011,18 @@ const JSONRPCErrorSchema = z.object({
6906
8011
  */
6907
8012
  data: z.optional(z.unknown())
6908
8013
  })
6909
- }).strict();
6910
- const isJSONRPCError = (value) => JSONRPCErrorSchema.safeParse(value).success;
8014
+ });
8015
+ const isJSONRPCError = (value) => {
8016
+ const result = JSONRPCErrorSchema.safeParse(value);
8017
+ return result.success;
8018
+ };
6911
8019
  const JSONRPCMessageSchema = z.union([
6912
8020
  JSONRPCRequestSchema,
6913
8021
  JSONRPCNotificationSchema,
6914
8022
  JSONRPCResponseSchema,
6915
8023
  JSONRPCErrorSchema
6916
8024
  ]);
6917
- const EmptyResultSchema = ResultSchema.strict();
8025
+ const EmptyResultSchema = z.strictObject({}).extend(ResultSchema.shape);
6918
8026
  const CancelledNotificationSchema = NotificationSchema.extend({
6919
8027
  method: z.literal("notifications/cancelled"),
6920
8028
  params: BaseNotificationParamsSchema.extend({
@@ -6930,19 +8038,19 @@ const CancelledNotificationSchema = NotificationSchema.extend({
6930
8038
  reason: z.string().optional()
6931
8039
  })
6932
8040
  });
6933
- const BaseMetadataSchema = z.object({
8041
+ const BaseMetadataSchema = z.looseObject({
6934
8042
  /** Intended for programmatic or logical use, but used as a display name in past specs or fallback */
6935
8043
  name: z.string(),
6936
8044
  /**
6937
- * Intended for UI and end-user contexts — optimized to be human-readable and easily understood,
6938
- * even by those unfamiliar with domain-specific terminology.
6939
- *
6940
- * If not provided, the name should be used for display (except for Tool,
6941
- * where `annotations.title` should be given precedence over using `name`,
6942
- * if present).
6943
- */
8045
+ * Intended for UI and end-user contexts — optimized to be human-readable and easily understood,
8046
+ * even by those unfamiliar with domain-specific terminology.
8047
+ *
8048
+ * If not provided, the name should be used for display (except for Tool,
8049
+ * where `annotations.title` should be given precedence over using `name`,
8050
+ * if present).
8051
+ */
6944
8052
  title: z.optional(z.string())
6945
- }).passthrough();
8053
+ });
6946
8054
  const ImplementationSchema = BaseMetadataSchema.extend({
6947
8055
  version: z.string()
6948
8056
  });
@@ -6980,7 +8088,10 @@ const InitializeRequestSchema = RequestSchema.extend({
6980
8088
  clientInfo: ImplementationSchema
6981
8089
  })
6982
8090
  });
6983
- const isInitializeRequest = (value) => InitializeRequestSchema.safeParse(value).success;
8091
+ const isInitializeRequest = (value) => {
8092
+ const result = InitializeRequestSchema.safeParse(value);
8093
+ return result.success;
8094
+ };
6984
8095
  const ServerCapabilitiesSchema = z.object({
6985
8096
  /**
6986
8097
  * Experimental, non-standard capabilities that the server supports.
@@ -7062,7 +8173,8 @@ const ProgressSchema = z.object({
7062
8173
  }).passthrough();
7063
8174
  const ProgressNotificationSchema = NotificationSchema.extend({
7064
8175
  method: z.literal("notifications/progress"),
7065
- params: BaseNotificationParamsSchema.merge(ProgressSchema).extend({
8176
+ params: BaseNotificationParamsSchema.extend({
8177
+ ...ProgressSchema.shape,
7066
8178
  /**
7067
8179
  * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding.
7068
8180
  */
@@ -7085,7 +8197,7 @@ const PaginatedResultSchema = ResultSchema.extend({
7085
8197
  */
7086
8198
  nextCursor: z.optional(CursorSchema)
7087
8199
  });
7088
- const ResourceContentsSchema = z.object({
8200
+ const ResourceContentsSchema = z.looseObject({
7089
8201
  /**
7090
8202
  * The URI of this resource.
7091
8203
  */
@@ -7098,19 +8210,27 @@ const ResourceContentsSchema = z.object({
7098
8210
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
7099
8211
  * for notes on _meta usage.
7100
8212
  */
7101
- _meta: z.optional(z.object({}).passthrough())
7102
- }).passthrough();
8213
+ _meta: z.optional(z.looseObject({}))
8214
+ });
7103
8215
  const TextResourceContentsSchema = ResourceContentsSchema.extend({
7104
8216
  /**
7105
8217
  * The text of the item. This must only be set if the item can actually be represented as text (not binary data).
7106
8218
  */
7107
8219
  text: z.string()
7108
8220
  });
8221
+ const Base64Schema = z.string().refine((val) => {
8222
+ try {
8223
+ atob(val);
8224
+ return true;
8225
+ } catch (_a) {
8226
+ return false;
8227
+ }
8228
+ }, { message: "Invalid Base64 string" });
7109
8229
  const BlobResourceContentsSchema = ResourceContentsSchema.extend({
7110
8230
  /**
7111
8231
  * A base64-encoded string representing the binary data of the item.
7112
8232
  */
7113
- blob: z.string().base64()
8233
+ blob: Base64Schema
7114
8234
  });
7115
8235
  const ResourceSchema = BaseMetadataSchema.extend({
7116
8236
  /**
@@ -7208,7 +8328,7 @@ const ResourceUpdatedNotificationSchema = NotificationSchema.extend({
7208
8328
  uri: z.string()
7209
8329
  })
7210
8330
  });
7211
- const PromptArgumentSchema = z.object({
8331
+ const PromptArgumentSchema = z.looseObject({
7212
8332
  /**
7213
8333
  * The name of the argument.
7214
8334
  */
@@ -7218,10 +8338,10 @@ const PromptArgumentSchema = z.object({
7218
8338
  */
7219
8339
  description: z.optional(z.string()),
7220
8340
  /**
7221
- * Whether this argument must be provided.
8341
+ * Whether this argument is required.
7222
8342
  */
7223
8343
  required: z.optional(z.boolean())
7224
- }).passthrough();
8344
+ });
7225
8345
  const PromptSchema = BaseMetadataSchema.extend({
7226
8346
  /**
7227
8347
  * An optional description of what this prompt provides
@@ -7253,10 +8373,10 @@ const GetPromptRequestSchema = RequestSchema.extend({
7253
8373
  /**
7254
8374
  * Arguments to use for templating the prompt.
7255
8375
  */
7256
- arguments: z.optional(z.record(z.string()))
8376
+ arguments: z.optional(z.record(z.string(), z.string()))
7257
8377
  })
7258
8378
  });
7259
- const TextContentSchema = z.object({
8379
+ const TextContentSchema = z.looseObject({
7260
8380
  type: z.literal("text"),
7261
8381
  /**
7262
8382
  * The text content of the message.
@@ -7266,14 +8386,14 @@ const TextContentSchema = z.object({
7266
8386
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
7267
8387
  * for notes on _meta usage.
7268
8388
  */
7269
- _meta: z.optional(z.object({}).passthrough())
7270
- }).passthrough();
7271
- const ImageContentSchema = z.object({
8389
+ _meta: z.optional(z.looseObject({}))
8390
+ });
8391
+ const ImageContentSchema = z.looseObject({
7272
8392
  type: z.literal("image"),
7273
8393
  /**
7274
8394
  * The base64-encoded image data.
7275
8395
  */
7276
- data: z.string().base64(),
8396
+ data: Base64Schema,
7277
8397
  /**
7278
8398
  * The MIME type of the image. Different providers may support different image types.
7279
8399
  */
@@ -7282,14 +8402,14 @@ const ImageContentSchema = z.object({
7282
8402
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
7283
8403
  * for notes on _meta usage.
7284
8404
  */
7285
- _meta: z.optional(z.object({}).passthrough())
7286
- }).passthrough();
7287
- const AudioContentSchema = z.object({
8405
+ _meta: z.optional(z.looseObject({}))
8406
+ });
8407
+ const AudioContentSchema = z.looseObject({
7288
8408
  type: z.literal("audio"),
7289
8409
  /**
7290
8410
  * The base64-encoded audio data.
7291
8411
  */
7292
- data: z.string().base64(),
8412
+ data: Base64Schema,
7293
8413
  /**
7294
8414
  * The MIME type of the audio. Different providers may support different audio types.
7295
8415
  */
@@ -7298,17 +8418,17 @@ const AudioContentSchema = z.object({
7298
8418
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
7299
8419
  * for notes on _meta usage.
7300
8420
  */
7301
- _meta: z.optional(z.object({}).passthrough())
7302
- }).passthrough();
7303
- const EmbeddedResourceSchema = z.object({
8421
+ _meta: z.optional(z.looseObject({}))
8422
+ });
8423
+ const EmbeddedResourceSchema = z.looseObject({
7304
8424
  type: z.literal("resource"),
7305
8425
  resource: z.union([TextResourceContentsSchema, BlobResourceContentsSchema]),
7306
8426
  /**
7307
8427
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
7308
8428
  * for notes on _meta usage.
7309
8429
  */
7310
- _meta: z.optional(z.object({}).passthrough())
7311
- }).passthrough();
8430
+ _meta: z.optional(z.looseObject({}))
8431
+ });
7312
8432
  const ResourceLinkSchema = ResourceSchema.extend({
7313
8433
  type: z.literal("resource_link")
7314
8434
  });
@@ -7319,10 +8439,10 @@ const ContentBlockSchema = z.union([
7319
8439
  ResourceLinkSchema,
7320
8440
  EmbeddedResourceSchema
7321
8441
  ]);
7322
- const PromptMessageSchema = z.object({
8442
+ const PromptMessageSchema = z.looseObject({
7323
8443
  role: z.enum(["user", "assistant"]),
7324
8444
  content: ContentBlockSchema
7325
- }).passthrough();
8445
+ });
7326
8446
  const GetPromptResultSchema = ResultSchema.extend({
7327
8447
  /**
7328
8448
  * An optional description for the prompt.
@@ -7382,18 +8502,18 @@ const ToolSchema = BaseMetadataSchema.extend({
7382
8502
  */
7383
8503
  inputSchema: z.object({
7384
8504
  type: z.literal("object"),
7385
- properties: z.optional(z.object({}).passthrough()),
8505
+ properties: z.optional(z.looseObject({})),
7386
8506
  required: z.optional(z.array(z.string()))
7387
- }).passthrough(),
8507
+ }),
7388
8508
  /**
7389
8509
  * An optional JSON Schema object defining the structure of the tool's output returned in
7390
8510
  * the structuredContent field of a CallToolResult.
7391
8511
  */
7392
- outputSchema: z.optional(z.object({
8512
+ outputSchema: z.optional(z.looseObject({
7393
8513
  type: z.literal("object"),
7394
- properties: z.optional(z.object({}).passthrough()),
8514
+ properties: z.optional(z.looseObject({})),
7395
8515
  required: z.optional(z.array(z.string()))
7396
- }).passthrough()),
8516
+ })),
7397
8517
  /**
7398
8518
  * Optional additional tool information.
7399
8519
  */
@@ -7423,7 +8543,7 @@ const CallToolResultSchema = ResultSchema.extend({
7423
8543
  *
7424
8544
  * If the Tool defines an outputSchema, this field MUST be present in the result, and contain a JSON object that matches the schema.
7425
8545
  */
7426
- structuredContent: z.object({}).passthrough().optional(),
8546
+ structuredContent: z.looseObject({}).optional(),
7427
8547
  /**
7428
8548
  * Whether the tool call ended in an error.
7429
8549
  *
@@ -7447,7 +8567,7 @@ const CallToolRequestSchema = RequestSchema.extend({
7447
8567
  method: z.literal("tools/call"),
7448
8568
  params: BaseRequestParamsSchema.extend({
7449
8569
  name: z.string(),
7450
- arguments: z.optional(z.record(z.unknown()))
8570
+ arguments: z.optional(z.record(z.string(), z.unknown()))
7451
8571
  })
7452
8572
  });
7453
8573
  const ToolListChangedNotificationSchema = NotificationSchema.extend({
@@ -7489,34 +8609,34 @@ const LoggingMessageNotificationSchema = NotificationSchema.extend({
7489
8609
  data: z.unknown()
7490
8610
  })
7491
8611
  });
7492
- const ModelHintSchema = z.object({
8612
+ const ModelHintSchema = z.looseObject({
7493
8613
  /**
7494
8614
  * A hint for a model name.
7495
8615
  */
7496
8616
  name: z.string().optional()
7497
- }).passthrough();
7498
- const ModelPreferencesSchema = z.object({
8617
+ });
8618
+ const ModelPreferencesSchema = z.looseObject({
7499
8619
  /**
7500
- * Optional hints to use for model selection.
8620
+ * Optional hints to use for model selection. If multiple models are supported, the client MAY choose how to prioritize these hints to pick a model.
7501
8621
  */
7502
8622
  hints: z.optional(z.array(ModelHintSchema)),
7503
8623
  /**
7504
- * How much to prioritize cost when selecting a model.
8624
+ * A hint for the model's cost priority. 0 = highest cost, 1 = lowest cost. The client MAY use this to decide which model to use.
7505
8625
  */
7506
8626
  costPriority: z.optional(z.number().min(0).max(1)),
7507
8627
  /**
7508
- * How much to prioritize sampling speed (latency) when selecting a model.
8628
+ * A hint for the model's speed priority. 0 = slowest, 1 = fastest. The client MAY use this to decide which model to use.
7509
8629
  */
7510
8630
  speedPriority: z.optional(z.number().min(0).max(1)),
7511
8631
  /**
7512
- * How much to prioritize intelligence and capabilities when selecting a model.
8632
+ * A hint for the model's intelligence priority. 0 = least intelligent, 1 = most intelligent. The client MAY use this to decide which model to use.
7513
8633
  */
7514
8634
  intelligencePriority: z.optional(z.number().min(0).max(1))
7515
- }).passthrough();
7516
- const SamplingMessageSchema = z.object({
8635
+ });
8636
+ const SamplingMessageSchema = z.looseObject({
7517
8637
  role: z.enum(["user", "assistant"]),
7518
8638
  content: z.union([TextContentSchema, ImageContentSchema, AudioContentSchema])
7519
- }).passthrough();
8639
+ });
7520
8640
  const CreateMessageRequestSchema = RequestSchema.extend({
7521
8641
  method: z.literal("sampling/createMessage"),
7522
8642
  params: BaseRequestParamsSchema.extend({
@@ -7538,7 +8658,7 @@ const CreateMessageRequestSchema = RequestSchema.extend({
7538
8658
  /**
7539
8659
  * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific.
7540
8660
  */
7541
- metadata: z.optional(z.object({}).passthrough()),
8661
+ metadata: z.optional(z.looseObject({})),
7542
8662
  /**
7543
8663
  * The server's preferences for which model to select.
7544
8664
  */
@@ -7561,12 +8681,12 @@ const CreateMessageResultSchema = ResultSchema.extend({
7561
8681
  AudioContentSchema
7562
8682
  ])
7563
8683
  });
7564
- const BooleanSchemaSchema = z.object({
8684
+ const BooleanSchemaSchema = z.looseObject({
7565
8685
  type: z.literal("boolean"),
7566
8686
  title: z.optional(z.string()),
7567
8687
  description: z.optional(z.string()),
7568
8688
  default: z.optional(z.boolean())
7569
- }).passthrough();
8689
+ });
7570
8690
  const StringSchemaSchema = z.object({
7571
8691
  type: z.literal("string"),
7572
8692
  title: z.optional(z.string()),
@@ -7605,11 +8725,11 @@ const ElicitRequestSchema = RequestSchema.extend({
7605
8725
  /**
7606
8726
  * The schema for the requested user input.
7607
8727
  */
7608
- requestedSchema: z.object({
8728
+ requestedSchema: z.looseObject({
7609
8729
  type: z.literal("object"),
7610
8730
  properties: z.record(z.string(), PrimitiveSchemaDefinitionSchema),
7611
8731
  required: z.optional(z.array(z.string()))
7612
- }).passthrough()
8732
+ })
7613
8733
  })
7614
8734
  });
7615
8735
  const ElicitResultSchema = ResultSchema.extend({
@@ -7692,7 +8812,7 @@ const RootSchema = z.object({
7692
8812
  */
7693
8813
  _meta: z.optional(z.object({}).passthrough())
7694
8814
  }).passthrough();
7695
- const ListRootsRequestSchema = RequestSchema.extend({
8815
+ const ListRootsRequestSchema = PaginatedRequestSchema.extend({
7696
8816
  method: z.literal("roots/list")
7697
8817
  });
7698
8818
  const ListRootsResultSchema = ResultSchema.extend({
@@ -7857,6 +8977,10 @@ class Protocol {
7857
8977
  this._responseHandlers = /* @__PURE__ */ new Map();
7858
8978
  this._progressHandlers.clear();
7859
8979
  this._pendingDebouncedNotifications.clear();
8980
+ for (const info of this._timeoutInfo.values()) {
8981
+ clearTimeout(info.timeoutId);
8982
+ }
8983
+ this._timeoutInfo.clear();
7860
8984
  this._transport = void 0;
7861
8985
  (_a = this.onclose) === null || _a === void 0 ? void 0 : _a.call(this);
7862
8986
  const error = new McpError(ErrorCode.ConnectionClosed, "Connection closed");
@@ -7897,7 +9021,10 @@ class Protocol {
7897
9021
  sessionId: (_c = this._transport) === null || _c === void 0 ? void 0 : _c.sessionId,
7898
9022
  _meta: (_d = request.params) === null || _d === void 0 ? void 0 : _d._meta,
7899
9023
  sendNotification: (notification) => this.notification(notification, { relatedRequestId: request.id }),
7900
- sendRequest: (r, resultSchema, options) => this.request(r, resultSchema, { ...options, relatedRequestId: request.id }),
9024
+ sendRequest: (r, resultSchema, options) => this.request(r, resultSchema, {
9025
+ ...options,
9026
+ relatedRequestId: request.id
9027
+ }),
7901
9028
  authInfo: extra === null || extra === void 0 ? void 0 : extra.authInfo,
7902
9029
  requestId: request.id,
7903
9030
  requestInfo: extra === null || extra === void 0 ? void 0 : extra.requestInfo
@@ -7973,8 +9100,13 @@ class Protocol {
7973
9100
  * Closes the connection.
7974
9101
  */
7975
9102
  async close() {
7976
- var _a;
7977
- await ((_a = this._transport) === null || _a === void 0 ? void 0 : _a.close());
9103
+ const transport = this._transport;
9104
+ if (transport) {
9105
+ await transport.close();
9106
+ if (this._transport === transport) {
9107
+ this._onclose();
9108
+ }
9109
+ }
7978
9110
  }
7979
9111
  /**
7980
9112
  * Sends a request and wait for a response.
@@ -8044,9 +9176,15 @@ class Protocol {
8044
9176
  cancel((_a2 = options === null || options === void 0 ? void 0 : options.signal) === null || _a2 === void 0 ? void 0 : _a2.reason);
8045
9177
  });
8046
9178
  const timeout = (_e = options === null || options === void 0 ? void 0 : options.timeout) !== null && _e !== void 0 ? _e : DEFAULT_REQUEST_TIMEOUT_MSEC;
8047
- const timeoutHandler = () => cancel(new McpError(ErrorCode.RequestTimeout, "Request timed out", { timeout }));
9179
+ const timeoutHandler = () => cancel(new McpError(ErrorCode.RequestTimeout, "Request timed out", {
9180
+ timeout
9181
+ }));
8048
9182
  this._setupTimeout(messageId, timeout, options === null || options === void 0 ? void 0 : options.maxTotalTimeout, timeoutHandler, (_f = options === null || options === void 0 ? void 0 : options.resetTimeoutOnProgress) !== null && _f !== void 0 ? _f : false);
8049
- this._transport.send(jsonrpcRequest, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error) => {
9183
+ this._transport.send(jsonrpcRequest, {
9184
+ relatedRequestId,
9185
+ resumptionToken,
9186
+ onresumptiontoken
9187
+ }).catch((error) => {
8050
9188
  this._cleanupTimeout(messageId);
8051
9189
  reject(error);
8052
9190
  });
@@ -13849,7 +14987,7 @@ function requireAjv() {
13849
14987
  Ajv2.prototype.validateSchema = validateSchema;
13850
14988
  Ajv2.prototype.getSchema = getSchema;
13851
14989
  Ajv2.prototype.removeSchema = removeSchema;
13852
- Ajv2.prototype.addFormat = addFormat2;
14990
+ Ajv2.prototype.addFormat = addFormat;
13853
14991
  Ajv2.prototype.errorsText = errorsText;
13854
14992
  Ajv2.prototype._addSchema = _addSchema;
13855
14993
  Ajv2.prototype._compile = _compile;
@@ -14119,7 +15257,7 @@ function requireAjv() {
14119
15257
  }
14120
15258
  return text.slice(0, -separator.length);
14121
15259
  }
14122
- function addFormat2(name, format2) {
15260
+ function addFormat(name, format2) {
14123
15261
  if (typeof format2 == "string") format2 = new RegExp(format2);
14124
15262
  this._formats[name] = format2;
14125
15263
  return this;
@@ -14362,1288 +15500,390 @@ class Server extends Protocol {
14362
15500
  return this.notification({ method: "notifications/prompts/list_changed" });
14363
15501
  }
14364
15502
  }
14365
- const ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use");
14366
- const defaultOptions = {
14367
- name: void 0,
14368
- $refStrategy: "root",
14369
- basePath: ["#"],
14370
- effectStrategy: "input",
14371
- pipeStrategy: "all",
14372
- dateStrategy: "format:date-time",
14373
- mapStrategy: "entries",
14374
- removeAdditionalStrategy: "passthrough",
14375
- allowedAdditionalProperties: true,
14376
- rejectedAdditionalProperties: false,
14377
- definitionPath: "definitions",
14378
- target: "jsonSchema7",
14379
- strictUnions: false,
14380
- definitions: {},
14381
- errorMessages: false,
14382
- markdownDescription: false,
14383
- patternStrategy: "escape",
14384
- applyRegexFlags: false,
14385
- emailStrategy: "format:email",
14386
- base64Strategy: "contentEncoding:base64",
14387
- nameStrategy: "ref",
14388
- openAiAnyTypeName: "OpenAiAnyType"
14389
- };
14390
- const getDefaultOptions = (options) => typeof options === "string" ? {
14391
- ...defaultOptions,
14392
- name: options
14393
- } : {
14394
- ...defaultOptions,
14395
- ...options
14396
- };
14397
- const getRefs = (options) => {
14398
- const _options = getDefaultOptions(options);
14399
- const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath;
14400
- return {
14401
- ..._options,
14402
- flags: { hasReferencedOpenAiAnyType: false },
14403
- currentPath,
14404
- propertyPath: void 0,
14405
- seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [
14406
- def._def,
14407
- {
14408
- def: def._def,
14409
- path: [..._options.basePath, _options.definitionPath, name],
14410
- // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.
14411
- jsonSchema: void 0
14412
- }
14413
- ]))
14414
- };
14415
- };
14416
- function addErrorMessage(res, key, errorMessage, refs) {
14417
- if (!(refs == null ? void 0 : refs.errorMessages))
14418
- return;
14419
- if (errorMessage) {
14420
- res.errorMessage = {
14421
- ...res.errorMessage,
14422
- [key]: errorMessage
15503
+ var McpZodTypeKind;
15504
+ (function(McpZodTypeKind2) {
15505
+ McpZodTypeKind2["Completable"] = "McpCompletable";
15506
+ })(McpZodTypeKind || (McpZodTypeKind = {}));
15507
+ class Completable {
15508
+ // ZodType compatibility properties
15509
+ get _output() {
15510
+ return this._wrappedType._output;
15511
+ }
15512
+ get _input() {
15513
+ return this._wrappedType._input;
15514
+ }
15515
+ get def() {
15516
+ return this._wrappedType.def;
15517
+ }
15518
+ get type() {
15519
+ return this._wrappedType.type;
15520
+ }
15521
+ get _zod() {
15522
+ return this._wrappedType._zod;
15523
+ }
15524
+ get "~standard"() {
15525
+ return this._wrappedType["~standard"];
15526
+ }
15527
+ constructor(type2, complete) {
15528
+ this._wrappedType = type2;
15529
+ this._def = {
15530
+ type: type2._def.type,
15531
+ complete,
15532
+ typeName: McpZodTypeKind.Completable,
15533
+ wrappedType: type2
14423
15534
  };
14424
15535
  }
14425
- }
14426
- function setResponseValueAndErrors(res, key, value, errorMessage, refs) {
14427
- res[key] = value;
14428
- addErrorMessage(res, key, errorMessage, refs);
14429
- }
14430
- const getRelativePath = (pathA, pathB) => {
14431
- let i = 0;
14432
- for (; i < pathA.length && i < pathB.length; i++) {
14433
- if (pathA[i] !== pathB[i])
14434
- break;
15536
+ // Core parsing methods
15537
+ parse(input) {
15538
+ return this._wrappedType.parse(input);
14435
15539
  }
14436
- return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/");
14437
- };
14438
- function parseAnyDef(refs) {
14439
- if (refs.target !== "openAi") {
14440
- return {};
14441
- }
14442
- const anyDefinitionPath = [
14443
- ...refs.basePath,
14444
- refs.definitionPath,
14445
- refs.openAiAnyTypeName
14446
- ];
14447
- refs.flags.hasReferencedOpenAiAnyType = true;
14448
- return {
14449
- $ref: refs.$refStrategy === "relative" ? getRelativePath(anyDefinitionPath, refs.currentPath) : anyDefinitionPath.join("/")
14450
- };
14451
- }
14452
- function parseArrayDef(def, refs) {
14453
- var _a, _b, _c;
14454
- const res = {
14455
- type: "array"
14456
- };
14457
- if (((_a = def.type) == null ? void 0 : _a._def) && ((_c = (_b = def.type) == null ? void 0 : _b._def) == null ? void 0 : _c.typeName) !== ZodFirstPartyTypeKind.ZodAny) {
14458
- res.items = parseDef(def.type._def, {
14459
- ...refs,
14460
- currentPath: [...refs.currentPath, "items"]
14461
- });
15540
+ safeParse(input) {
15541
+ return this._wrappedType.safeParse(input);
14462
15542
  }
14463
- if (def.minLength) {
14464
- setResponseValueAndErrors(res, "minItems", def.minLength.value, def.minLength.message, refs);
15543
+ parseAsync(input) {
15544
+ return this._wrappedType.parseAsync(input);
14465
15545
  }
14466
- if (def.maxLength) {
14467
- setResponseValueAndErrors(res, "maxItems", def.maxLength.value, def.maxLength.message, refs);
15546
+ safeParseAsync(input) {
15547
+ return this._wrappedType.safeParseAsync(input);
14468
15548
  }
14469
- if (def.exactLength) {
14470
- setResponseValueAndErrors(res, "minItems", def.exactLength.value, def.exactLength.message, refs);
14471
- setResponseValueAndErrors(res, "maxItems", def.exactLength.value, def.exactLength.message, refs);
15549
+ // Schema manipulation methods
15550
+ optional() {
15551
+ return new Completable(this._wrappedType.optional(), this._def.complete);
14472
15552
  }
14473
- return res;
14474
- }
14475
- function parseBigintDef(def, refs) {
14476
- const res = {
14477
- type: "integer",
14478
- format: "int64"
14479
- };
14480
- if (!def.checks)
14481
- return res;
14482
- for (const check of def.checks) {
14483
- switch (check.kind) {
14484
- case "min":
14485
- if (refs.target === "jsonSchema7") {
14486
- if (check.inclusive) {
14487
- setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
14488
- } else {
14489
- setResponseValueAndErrors(res, "exclusiveMinimum", check.value, check.message, refs);
14490
- }
14491
- } else {
14492
- if (!check.inclusive) {
14493
- res.exclusiveMinimum = true;
14494
- }
14495
- setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
14496
- }
14497
- break;
14498
- case "max":
14499
- if (refs.target === "jsonSchema7") {
14500
- if (check.inclusive) {
14501
- setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
14502
- } else {
14503
- setResponseValueAndErrors(res, "exclusiveMaximum", check.value, check.message, refs);
14504
- }
14505
- } else {
14506
- if (!check.inclusive) {
14507
- res.exclusiveMaximum = true;
14508
- }
14509
- setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
14510
- }
14511
- break;
14512
- case "multipleOf":
14513
- setResponseValueAndErrors(res, "multipleOf", check.value, check.message, refs);
14514
- break;
14515
- }
15553
+ nullable() {
15554
+ return new Completable(this._wrappedType.nullable(), this._def.complete);
15555
+ }
15556
+ nullish() {
15557
+ return new Completable(this._wrappedType.nullish(), this._def.complete);
15558
+ }
15559
+ nonoptional() {
15560
+ return new Completable(this._wrappedType.nonoptional(), this._def.complete);
15561
+ }
15562
+ array() {
15563
+ return this._wrappedType.array();
15564
+ }
15565
+ or(schema) {
15566
+ return this._wrappedType.or(schema);
15567
+ }
15568
+ and(schema) {
15569
+ return this._wrappedType.and(schema);
15570
+ }
15571
+ // Transformation methods
15572
+ transform(transformer) {
15573
+ return this._wrappedType.transform(transformer);
15574
+ }
15575
+ default(defaultValue) {
15576
+ return new Completable(this._wrappedType.default(defaultValue), this._def.complete);
15577
+ }
15578
+ catch(catchValue) {
15579
+ return new Completable(this._wrappedType.catch(catchValue), this._def.complete);
15580
+ }
15581
+ pipe(schema) {
15582
+ return this._wrappedType.pipe(schema);
15583
+ }
15584
+ // Additional ZodType v4 methods
15585
+ register(registry, ...meta) {
15586
+ return this._wrappedType.register(registry, ...meta);
15587
+ }
15588
+ spa(input) {
15589
+ return this._wrappedType.spa(input);
15590
+ }
15591
+ overwrite(overrides) {
15592
+ return new Completable(this._wrappedType.overwrite(overrides), this._def.complete);
15593
+ }
15594
+ prefault(prefaultValue) {
15595
+ return new Completable(this._wrappedType.prefault(prefaultValue), this._def.complete);
15596
+ }
15597
+ // Refinement methods
15598
+ refine(refinement, message) {
15599
+ return this._wrappedType.refine(refinement, message);
15600
+ }
15601
+ superRefine(refinement) {
15602
+ return this._wrappedType.superRefine(refinement);
15603
+ }
15604
+ // Utility methods
15605
+ readonly() {
15606
+ return this._wrappedType.readonly();
15607
+ }
15608
+ describe(description2) {
15609
+ return new Completable(this._wrappedType.describe(description2), this._def.complete);
15610
+ }
15611
+ meta(meta) {
15612
+ return this._wrappedType.meta(meta);
15613
+ }
15614
+ brand() {
15615
+ return this._wrappedType.brand();
15616
+ }
15617
+ check(check) {
15618
+ return this._wrappedType.check(check);
15619
+ }
15620
+ clone() {
15621
+ return new Completable(this._wrappedType.clone(), this._def.complete);
15622
+ }
15623
+ // Status check methods
15624
+ isOptional() {
15625
+ return this._wrappedType.isOptional();
15626
+ }
15627
+ isNullable() {
15628
+ return this._wrappedType.isNullable();
15629
+ }
15630
+ // Utility getters
15631
+ get description() {
15632
+ return this._wrappedType.description;
15633
+ }
15634
+ // Completable-specific methods
15635
+ unwrap() {
15636
+ return this._def.wrappedType;
15637
+ }
15638
+ async complete(value, context) {
15639
+ return this._def.complete(value, context);
14516
15640
  }
14517
- return res;
14518
- }
14519
- function parseBooleanDef() {
14520
- return {
14521
- type: "boolean"
14522
- };
14523
- }
14524
- function parseBrandedDef(_def, refs) {
14525
- return parseDef(_def.type._def, refs);
14526
15641
  }
14527
- const parseCatchDef = (def, refs) => {
14528
- return parseDef(def.innerType._def, refs);
15642
+ Completable.create = (type2, complete) => {
15643
+ return new Completable(type2, complete);
14529
15644
  };
14530
- function parseDateDef(def, refs, overrideDateStrategy) {
14531
- const strategy = overrideDateStrategy ?? refs.dateStrategy;
14532
- if (Array.isArray(strategy)) {
14533
- return {
14534
- anyOf: strategy.map((item, i) => parseDateDef(def, refs, item))
14535
- };
15645
+ const MAX_TEMPLATE_LENGTH = 1e6;
15646
+ const MAX_VARIABLE_LENGTH = 1e6;
15647
+ const MAX_TEMPLATE_EXPRESSIONS = 1e4;
15648
+ const MAX_REGEX_LENGTH = 1e6;
15649
+ class UriTemplate {
15650
+ /**
15651
+ * Returns true if the given string contains any URI template expressions.
15652
+ * A template expression is a sequence of characters enclosed in curly braces,
15653
+ * like {foo} or {?bar}.
15654
+ */
15655
+ static isTemplate(str) {
15656
+ return /\{[^}\s]+\}/.test(str);
14536
15657
  }
14537
- switch (strategy) {
14538
- case "string":
14539
- case "format:date-time":
14540
- return {
14541
- type: "string",
14542
- format: "date-time"
14543
- };
14544
- case "format:date":
14545
- return {
14546
- type: "string",
14547
- format: "date"
14548
- };
14549
- case "integer":
14550
- return integerDateParser(def, refs);
15658
+ static validateLength(str, max, context) {
15659
+ if (str.length > max) {
15660
+ throw new Error(`${context} exceeds maximum length of ${max} characters (got ${str.length})`);
15661
+ }
14551
15662
  }
14552
- }
14553
- const integerDateParser = (def, refs) => {
14554
- const res = {
14555
- type: "integer",
14556
- format: "unix-time"
14557
- };
14558
- if (refs.target === "openApi3") {
14559
- return res;
15663
+ get variableNames() {
15664
+ return this.parts.flatMap((part) => typeof part === "string" ? [] : part.names);
14560
15665
  }
14561
- for (const check of def.checks) {
14562
- switch (check.kind) {
14563
- case "min":
14564
- setResponseValueAndErrors(
14565
- res,
14566
- "minimum",
14567
- check.value,
14568
- // This is in milliseconds
14569
- check.message,
14570
- refs
14571
- );
15666
+ constructor(template) {
15667
+ UriTemplate.validateLength(template, MAX_TEMPLATE_LENGTH, "Template");
15668
+ this.template = template;
15669
+ this.parts = this.parse(template);
15670
+ }
15671
+ toString() {
15672
+ return this.template;
15673
+ }
15674
+ parse(template) {
15675
+ const parts = [];
15676
+ let currentText = "";
15677
+ let i = 0;
15678
+ let expressionCount = 0;
15679
+ while (i < template.length) {
15680
+ if (template[i] === "{") {
15681
+ if (currentText) {
15682
+ parts.push(currentText);
15683
+ currentText = "";
15684
+ }
15685
+ const end = template.indexOf("}", i);
15686
+ if (end === -1)
15687
+ throw new Error("Unclosed template expression");
15688
+ expressionCount++;
15689
+ if (expressionCount > MAX_TEMPLATE_EXPRESSIONS) {
15690
+ throw new Error(`Template contains too many expressions (max ${MAX_TEMPLATE_EXPRESSIONS})`);
15691
+ }
15692
+ const expr = template.slice(i + 1, end);
15693
+ const operator = this.getOperator(expr);
15694
+ const exploded = expr.includes("*");
15695
+ const names = this.getNames(expr);
15696
+ const name = names[0];
15697
+ for (const name2 of names) {
15698
+ UriTemplate.validateLength(name2, MAX_VARIABLE_LENGTH, "Variable name");
15699
+ }
15700
+ parts.push({ name, operator, names, exploded });
15701
+ i = end + 1;
15702
+ } else {
15703
+ currentText += template[i];
15704
+ i++;
15705
+ }
15706
+ }
15707
+ if (currentText) {
15708
+ parts.push(currentText);
15709
+ }
15710
+ return parts;
15711
+ }
15712
+ getOperator(expr) {
15713
+ const operators = ["+", "#", ".", "/", "?", "&"];
15714
+ return operators.find((op) => expr.startsWith(op)) || "";
15715
+ }
15716
+ getNames(expr) {
15717
+ const operator = this.getOperator(expr);
15718
+ return expr.slice(operator.length).split(",").map((name) => name.replace("*", "").trim()).filter((name) => name.length > 0);
15719
+ }
15720
+ encodeValue(value, operator) {
15721
+ UriTemplate.validateLength(value, MAX_VARIABLE_LENGTH, "Variable value");
15722
+ if (operator === "+" || operator === "#") {
15723
+ return encodeURI(value);
15724
+ }
15725
+ return encodeURIComponent(value);
15726
+ }
15727
+ expandPart(part, variables) {
15728
+ if (part.operator === "?" || part.operator === "&") {
15729
+ const pairs = part.names.map((name) => {
15730
+ const value2 = variables[name];
15731
+ if (value2 === void 0)
15732
+ return "";
15733
+ const encoded2 = Array.isArray(value2) ? value2.map((v) => this.encodeValue(v, part.operator)).join(",") : this.encodeValue(value2.toString(), part.operator);
15734
+ return `${name}=${encoded2}`;
15735
+ }).filter((pair) => pair.length > 0);
15736
+ if (pairs.length === 0)
15737
+ return "";
15738
+ const separator = part.operator === "?" ? "?" : "&";
15739
+ return separator + pairs.join("&");
15740
+ }
15741
+ if (part.names.length > 1) {
15742
+ const values2 = part.names.map((name) => variables[name]).filter((v) => v !== void 0);
15743
+ if (values2.length === 0)
15744
+ return "";
15745
+ return values2.map((v) => Array.isArray(v) ? v[0] : v).join(",");
15746
+ }
15747
+ const value = variables[part.name];
15748
+ if (value === void 0)
15749
+ return "";
15750
+ const values = Array.isArray(value) ? value : [value];
15751
+ const encoded = values.map((v) => this.encodeValue(v, part.operator));
15752
+ switch (part.operator) {
15753
+ case "":
15754
+ return encoded.join(",");
15755
+ case "+":
15756
+ return encoded.join(",");
15757
+ case "#":
15758
+ return "#" + encoded.join(",");
15759
+ case ".":
15760
+ return "." + encoded.join(".");
15761
+ case "/":
15762
+ return "/" + encoded.join("/");
15763
+ default:
15764
+ return encoded.join(",");
15765
+ }
15766
+ }
15767
+ expand(variables) {
15768
+ let result = "";
15769
+ let hasQueryParam = false;
15770
+ for (const part of this.parts) {
15771
+ if (typeof part === "string") {
15772
+ result += part;
15773
+ continue;
15774
+ }
15775
+ const expanded = this.expandPart(part, variables);
15776
+ if (!expanded)
15777
+ continue;
15778
+ if ((part.operator === "?" || part.operator === "&") && hasQueryParam) {
15779
+ result += expanded.replace("?", "&");
15780
+ } else {
15781
+ result += expanded;
15782
+ }
15783
+ if (part.operator === "?" || part.operator === "&") {
15784
+ hasQueryParam = true;
15785
+ }
15786
+ }
15787
+ return result;
15788
+ }
15789
+ escapeRegExp(str) {
15790
+ return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
15791
+ }
15792
+ partToRegExp(part) {
15793
+ const patterns = [];
15794
+ for (const name2 of part.names) {
15795
+ UriTemplate.validateLength(name2, MAX_VARIABLE_LENGTH, "Variable name");
15796
+ }
15797
+ if (part.operator === "?" || part.operator === "&") {
15798
+ for (let i = 0; i < part.names.length; i++) {
15799
+ const name2 = part.names[i];
15800
+ const prefix = i === 0 ? "\\" + part.operator : "&";
15801
+ patterns.push({
15802
+ pattern: prefix + this.escapeRegExp(name2) + "=([^&]+)",
15803
+ name: name2
15804
+ });
15805
+ }
15806
+ return patterns;
15807
+ }
15808
+ let pattern2;
15809
+ const name = part.name;
15810
+ switch (part.operator) {
15811
+ case "":
15812
+ pattern2 = part.exploded ? "([^/]+(?:,[^/]+)*)" : "([^/,]+)";
14572
15813
  break;
14573
- case "max":
14574
- setResponseValueAndErrors(
14575
- res,
14576
- "maximum",
14577
- check.value,
14578
- // This is in milliseconds
14579
- check.message,
14580
- refs
14581
- );
15814
+ case "+":
15815
+ case "#":
15816
+ pattern2 = "(.+)";
14582
15817
  break;
15818
+ case ".":
15819
+ pattern2 = "\\.([^/,]+)";
15820
+ break;
15821
+ case "/":
15822
+ pattern2 = "/" + (part.exploded ? "([^/]+(?:,[^/]+)*)" : "([^/,]+)");
15823
+ break;
15824
+ default:
15825
+ pattern2 = "([^/]+)";
14583
15826
  }
15827
+ patterns.push({ pattern: pattern2, name });
15828
+ return patterns;
14584
15829
  }
14585
- return res;
14586
- };
14587
- function parseDefaultDef(_def, refs) {
14588
- return {
14589
- ...parseDef(_def.innerType._def, refs),
14590
- default: _def.defaultValue()
14591
- };
14592
- }
14593
- function parseEffectsDef(_def, refs) {
14594
- return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : parseAnyDef(refs);
14595
- }
14596
- function parseEnumDef(def) {
14597
- return {
14598
- type: "string",
14599
- enum: Array.from(def.values)
14600
- };
14601
- }
14602
- const isJsonSchema7AllOfType = (type2) => {
14603
- if ("type" in type2 && type2.type === "string")
14604
- return false;
14605
- return "allOf" in type2;
14606
- };
14607
- function parseIntersectionDef(def, refs) {
14608
- const allOf2 = [
14609
- parseDef(def.left._def, {
14610
- ...refs,
14611
- currentPath: [...refs.currentPath, "allOf", "0"]
14612
- }),
14613
- parseDef(def.right._def, {
14614
- ...refs,
14615
- currentPath: [...refs.currentPath, "allOf", "1"]
14616
- })
14617
- ].filter((x) => !!x);
14618
- let unevaluatedProperties = refs.target === "jsonSchema2019-09" ? { unevaluatedProperties: false } : void 0;
14619
- const mergedAllOf = [];
14620
- allOf2.forEach((schema) => {
14621
- if (isJsonSchema7AllOfType(schema)) {
14622
- mergedAllOf.push(...schema.allOf);
14623
- if (schema.unevaluatedProperties === void 0) {
14624
- unevaluatedProperties = void 0;
15830
+ match(uri) {
15831
+ UriTemplate.validateLength(uri, MAX_TEMPLATE_LENGTH, "URI");
15832
+ let pattern2 = "^";
15833
+ const names = [];
15834
+ for (const part of this.parts) {
15835
+ if (typeof part === "string") {
15836
+ pattern2 += this.escapeRegExp(part);
15837
+ } else {
15838
+ const patterns = this.partToRegExp(part);
15839
+ for (const { pattern: partPattern, name } of patterns) {
15840
+ pattern2 += partPattern;
15841
+ names.push({ name, exploded: part.exploded });
15842
+ }
14625
15843
  }
14626
- } else {
14627
- let nestedSchema = schema;
14628
- if ("additionalProperties" in schema && schema.additionalProperties === false) {
14629
- const { additionalProperties: additionalProperties2, ...rest } = schema;
14630
- nestedSchema = rest;
15844
+ }
15845
+ pattern2 += "$";
15846
+ UriTemplate.validateLength(pattern2, MAX_REGEX_LENGTH, "Generated regex pattern");
15847
+ const regex = new RegExp(pattern2);
15848
+ const match = uri.match(regex);
15849
+ if (!match)
15850
+ return null;
15851
+ const result = {};
15852
+ for (let i = 0; i < names.length; i++) {
15853
+ const { name, exploded } = names[i];
15854
+ const value = match[i + 1];
15855
+ const cleanName = name.replace("*", "");
15856
+ if (exploded && value.includes(",")) {
15857
+ result[cleanName] = value.split(",");
14631
15858
  } else {
14632
- unevaluatedProperties = void 0;
15859
+ result[cleanName] = value;
14633
15860
  }
14634
- mergedAllOf.push(nestedSchema);
14635
15861
  }
14636
- });
14637
- return mergedAllOf.length ? {
14638
- allOf: mergedAllOf,
14639
- ...unevaluatedProperties
14640
- } : void 0;
14641
- }
14642
- function parseLiteralDef(def, refs) {
14643
- const parsedType = typeof def.value;
14644
- if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") {
14645
- return {
14646
- type: Array.isArray(def.value) ? "array" : "object"
14647
- };
14648
- }
14649
- if (refs.target === "openApi3") {
14650
- return {
14651
- type: parsedType === "bigint" ? "integer" : parsedType,
14652
- enum: [def.value]
14653
- };
15862
+ return result;
14654
15863
  }
14655
- return {
14656
- type: parsedType === "bigint" ? "integer" : parsedType,
14657
- const: def.value
14658
- };
14659
15864
  }
14660
- let emojiRegex = void 0;
14661
- const zodPatterns = {
14662
- /**
14663
- * `c` was changed to `[cC]` to replicate /i flag
14664
- */
14665
- cuid: /^[cC][^\s-]{8,}$/,
14666
- cuid2: /^[0-9a-z]+$/,
14667
- ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
14668
- /**
14669
- * `a-z` was added to replicate /i flag
14670
- */
14671
- email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
15865
+ class McpServer {
15866
+ constructor(serverInfo, options) {
15867
+ this._registeredResources = {};
15868
+ this._registeredResourceTemplates = {};
15869
+ this._registeredTools = {};
15870
+ this._registeredPrompts = {};
15871
+ this._toolHandlersInitialized = false;
15872
+ this._completionHandlerInitialized = false;
15873
+ this._resourceHandlersInitialized = false;
15874
+ this._promptHandlersInitialized = false;
15875
+ this.server = new Server(serverInfo, options);
15876
+ }
14672
15877
  /**
14673
- * Constructed a valid Unicode RegExp
14674
- *
14675
- * Lazily instantiate since this type of regex isn't supported
14676
- * in all envs (e.g. React Native).
15878
+ * Attaches to the given transport, starts it, and starts listening for messages.
14677
15879
  *
14678
- * See:
14679
- * https://github.com/colinhacks/zod/issues/2433
14680
- * Fix in Zod:
14681
- * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b
14682
- */
14683
- emoji: () => {
14684
- if (emojiRegex === void 0) {
14685
- emojiRegex = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u");
14686
- }
14687
- return emojiRegex;
14688
- },
14689
- /**
14690
- * Unused
14691
- */
14692
- uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,
14693
- /**
14694
- * Unused
15880
+ * The `server` object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward.
14695
15881
  */
14696
- ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,
14697
- ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,
15882
+ async connect(transport) {
15883
+ return await this.server.connect(transport);
15884
+ }
14698
15885
  /**
14699
- * Unused
14700
- */
14701
- ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,
14702
- ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,
14703
- base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
14704
- base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,
14705
- nanoid: /^[a-zA-Z0-9_-]{21}$/,
14706
- jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/
14707
- };
14708
- function parseStringDef(def, refs) {
14709
- const res = {
14710
- type: "string"
14711
- };
14712
- if (def.checks) {
14713
- for (const check of def.checks) {
14714
- switch (check.kind) {
14715
- case "min":
14716
- setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs);
14717
- break;
14718
- case "max":
14719
- setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs);
14720
- break;
14721
- case "email":
14722
- switch (refs.emailStrategy) {
14723
- case "format:email":
14724
- addFormat(res, "email", check.message, refs);
14725
- break;
14726
- case "format:idn-email":
14727
- addFormat(res, "idn-email", check.message, refs);
14728
- break;
14729
- case "pattern:zod":
14730
- addPattern(res, zodPatterns.email, check.message, refs);
14731
- break;
14732
- }
14733
- break;
14734
- case "url":
14735
- addFormat(res, "uri", check.message, refs);
14736
- break;
14737
- case "uuid":
14738
- addFormat(res, "uuid", check.message, refs);
14739
- break;
14740
- case "regex":
14741
- addPattern(res, check.regex, check.message, refs);
14742
- break;
14743
- case "cuid":
14744
- addPattern(res, zodPatterns.cuid, check.message, refs);
14745
- break;
14746
- case "cuid2":
14747
- addPattern(res, zodPatterns.cuid2, check.message, refs);
14748
- break;
14749
- case "startsWith":
14750
- addPattern(res, RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`), check.message, refs);
14751
- break;
14752
- case "endsWith":
14753
- addPattern(res, RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`), check.message, refs);
14754
- break;
14755
- case "datetime":
14756
- addFormat(res, "date-time", check.message, refs);
14757
- break;
14758
- case "date":
14759
- addFormat(res, "date", check.message, refs);
14760
- break;
14761
- case "time":
14762
- addFormat(res, "time", check.message, refs);
14763
- break;
14764
- case "duration":
14765
- addFormat(res, "duration", check.message, refs);
14766
- break;
14767
- case "length":
14768
- setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs);
14769
- setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs);
14770
- break;
14771
- case "includes": {
14772
- addPattern(res, RegExp(escapeLiteralCheckValue(check.value, refs)), check.message, refs);
14773
- break;
14774
- }
14775
- case "ip": {
14776
- if (check.version !== "v6") {
14777
- addFormat(res, "ipv4", check.message, refs);
14778
- }
14779
- if (check.version !== "v4") {
14780
- addFormat(res, "ipv6", check.message, refs);
14781
- }
14782
- break;
14783
- }
14784
- case "base64url":
14785
- addPattern(res, zodPatterns.base64url, check.message, refs);
14786
- break;
14787
- case "jwt":
14788
- addPattern(res, zodPatterns.jwt, check.message, refs);
14789
- break;
14790
- case "cidr": {
14791
- if (check.version !== "v6") {
14792
- addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);
14793
- }
14794
- if (check.version !== "v4") {
14795
- addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);
14796
- }
14797
- break;
14798
- }
14799
- case "emoji":
14800
- addPattern(res, zodPatterns.emoji(), check.message, refs);
14801
- break;
14802
- case "ulid": {
14803
- addPattern(res, zodPatterns.ulid, check.message, refs);
14804
- break;
14805
- }
14806
- case "base64": {
14807
- switch (refs.base64Strategy) {
14808
- case "format:binary": {
14809
- addFormat(res, "binary", check.message, refs);
14810
- break;
14811
- }
14812
- case "contentEncoding:base64": {
14813
- setResponseValueAndErrors(res, "contentEncoding", "base64", check.message, refs);
14814
- break;
14815
- }
14816
- case "pattern:zod": {
14817
- addPattern(res, zodPatterns.base64, check.message, refs);
14818
- break;
14819
- }
14820
- }
14821
- break;
14822
- }
14823
- case "nanoid": {
14824
- addPattern(res, zodPatterns.nanoid, check.message, refs);
14825
- }
14826
- }
14827
- }
14828
- }
14829
- return res;
14830
- }
14831
- function escapeLiteralCheckValue(literal, refs) {
14832
- return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal) : literal;
14833
- }
14834
- const ALPHA_NUMERIC = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");
14835
- function escapeNonAlphaNumeric(source) {
14836
- let result = "";
14837
- for (let i = 0; i < source.length; i++) {
14838
- if (!ALPHA_NUMERIC.has(source[i])) {
14839
- result += "\\";
14840
- }
14841
- result += source[i];
14842
- }
14843
- return result;
14844
- }
14845
- function addFormat(schema, value, message, refs) {
14846
- var _a;
14847
- if (schema.format || ((_a = schema.anyOf) == null ? void 0 : _a.some((x) => x.format))) {
14848
- if (!schema.anyOf) {
14849
- schema.anyOf = [];
14850
- }
14851
- if (schema.format) {
14852
- schema.anyOf.push({
14853
- format: schema.format,
14854
- ...schema.errorMessage && refs.errorMessages && {
14855
- errorMessage: { format: schema.errorMessage.format }
14856
- }
14857
- });
14858
- delete schema.format;
14859
- if (schema.errorMessage) {
14860
- delete schema.errorMessage.format;
14861
- if (Object.keys(schema.errorMessage).length === 0) {
14862
- delete schema.errorMessage;
14863
- }
14864
- }
14865
- }
14866
- schema.anyOf.push({
14867
- format: value,
14868
- ...message && refs.errorMessages && { errorMessage: { format: message } }
14869
- });
14870
- } else {
14871
- setResponseValueAndErrors(schema, "format", value, message, refs);
14872
- }
14873
- }
14874
- function addPattern(schema, regex, message, refs) {
14875
- var _a;
14876
- if (schema.pattern || ((_a = schema.allOf) == null ? void 0 : _a.some((x) => x.pattern))) {
14877
- if (!schema.allOf) {
14878
- schema.allOf = [];
14879
- }
14880
- if (schema.pattern) {
14881
- schema.allOf.push({
14882
- pattern: schema.pattern,
14883
- ...schema.errorMessage && refs.errorMessages && {
14884
- errorMessage: { pattern: schema.errorMessage.pattern }
14885
- }
14886
- });
14887
- delete schema.pattern;
14888
- if (schema.errorMessage) {
14889
- delete schema.errorMessage.pattern;
14890
- if (Object.keys(schema.errorMessage).length === 0) {
14891
- delete schema.errorMessage;
14892
- }
14893
- }
14894
- }
14895
- schema.allOf.push({
14896
- pattern: stringifyRegExpWithFlags(regex, refs),
14897
- ...message && refs.errorMessages && { errorMessage: { pattern: message } }
14898
- });
14899
- } else {
14900
- setResponseValueAndErrors(schema, "pattern", stringifyRegExpWithFlags(regex, refs), message, refs);
14901
- }
14902
- }
14903
- function stringifyRegExpWithFlags(regex, refs) {
14904
- var _a;
14905
- if (!refs.applyRegexFlags || !regex.flags) {
14906
- return regex.source;
14907
- }
14908
- const flags = {
14909
- i: regex.flags.includes("i"),
14910
- m: regex.flags.includes("m"),
14911
- s: regex.flags.includes("s")
14912
- // `.` matches newlines
14913
- };
14914
- const source = flags.i ? regex.source.toLowerCase() : regex.source;
14915
- let pattern2 = "";
14916
- let isEscaped = false;
14917
- let inCharGroup = false;
14918
- let inCharRange = false;
14919
- for (let i = 0; i < source.length; i++) {
14920
- if (isEscaped) {
14921
- pattern2 += source[i];
14922
- isEscaped = false;
14923
- continue;
14924
- }
14925
- if (flags.i) {
14926
- if (inCharGroup) {
14927
- if (source[i].match(/[a-z]/)) {
14928
- if (inCharRange) {
14929
- pattern2 += source[i];
14930
- pattern2 += `${source[i - 2]}-${source[i]}`.toUpperCase();
14931
- inCharRange = false;
14932
- } else if (source[i + 1] === "-" && ((_a = source[i + 2]) == null ? void 0 : _a.match(/[a-z]/))) {
14933
- pattern2 += source[i];
14934
- inCharRange = true;
14935
- } else {
14936
- pattern2 += `${source[i]}${source[i].toUpperCase()}`;
14937
- }
14938
- continue;
14939
- }
14940
- } else if (source[i].match(/[a-z]/)) {
14941
- pattern2 += `[${source[i]}${source[i].toUpperCase()}]`;
14942
- continue;
14943
- }
14944
- }
14945
- if (flags.m) {
14946
- if (source[i] === "^") {
14947
- pattern2 += `(^|(?<=[\r
14948
- ]))`;
14949
- continue;
14950
- } else if (source[i] === "$") {
14951
- pattern2 += `($|(?=[\r
14952
- ]))`;
14953
- continue;
14954
- }
14955
- }
14956
- if (flags.s && source[i] === ".") {
14957
- pattern2 += inCharGroup ? `${source[i]}\r
14958
- ` : `[${source[i]}\r
14959
- ]`;
14960
- continue;
14961
- }
14962
- pattern2 += source[i];
14963
- if (source[i] === "\\") {
14964
- isEscaped = true;
14965
- } else if (inCharGroup && source[i] === "]") {
14966
- inCharGroup = false;
14967
- } else if (!inCharGroup && source[i] === "[") {
14968
- inCharGroup = true;
14969
- }
14970
- }
14971
- try {
14972
- new RegExp(pattern2);
14973
- } catch {
14974
- console.warn(`Could not convert regex pattern at ${refs.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`);
14975
- return regex.source;
14976
- }
14977
- return pattern2;
14978
- }
14979
- function parseRecordDef(def, refs) {
14980
- var _a, _b, _c, _d, _e, _f;
14981
- if (refs.target === "openAi") {
14982
- console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");
14983
- }
14984
- if (refs.target === "openApi3" && ((_a = def.keyType) == null ? void 0 : _a._def.typeName) === ZodFirstPartyTypeKind.ZodEnum) {
14985
- return {
14986
- type: "object",
14987
- required: def.keyType._def.values,
14988
- properties: def.keyType._def.values.reduce((acc, key) => ({
14989
- ...acc,
14990
- [key]: parseDef(def.valueType._def, {
14991
- ...refs,
14992
- currentPath: [...refs.currentPath, "properties", key]
14993
- }) ?? parseAnyDef(refs)
14994
- }), {}),
14995
- additionalProperties: refs.rejectedAdditionalProperties
14996
- };
14997
- }
14998
- const schema = {
14999
- type: "object",
15000
- additionalProperties: parseDef(def.valueType._def, {
15001
- ...refs,
15002
- currentPath: [...refs.currentPath, "additionalProperties"]
15003
- }) ?? refs.allowedAdditionalProperties
15004
- };
15005
- if (refs.target === "openApi3") {
15006
- return schema;
15007
- }
15008
- if (((_b = def.keyType) == null ? void 0 : _b._def.typeName) === ZodFirstPartyTypeKind.ZodString && ((_c = def.keyType._def.checks) == null ? void 0 : _c.length)) {
15009
- const { type: type2, ...keyType } = parseStringDef(def.keyType._def, refs);
15010
- return {
15011
- ...schema,
15012
- propertyNames: keyType
15013
- };
15014
- } else if (((_d = def.keyType) == null ? void 0 : _d._def.typeName) === ZodFirstPartyTypeKind.ZodEnum) {
15015
- return {
15016
- ...schema,
15017
- propertyNames: {
15018
- enum: def.keyType._def.values
15019
- }
15020
- };
15021
- } else if (((_e = def.keyType) == null ? void 0 : _e._def.typeName) === ZodFirstPartyTypeKind.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind.ZodString && ((_f = def.keyType._def.type._def.checks) == null ? void 0 : _f.length)) {
15022
- const { type: type2, ...keyType } = parseBrandedDef(def.keyType._def, refs);
15023
- return {
15024
- ...schema,
15025
- propertyNames: keyType
15026
- };
15027
- }
15028
- return schema;
15029
- }
15030
- function parseMapDef(def, refs) {
15031
- if (refs.mapStrategy === "record") {
15032
- return parseRecordDef(def, refs);
15033
- }
15034
- const keys = parseDef(def.keyType._def, {
15035
- ...refs,
15036
- currentPath: [...refs.currentPath, "items", "items", "0"]
15037
- }) || parseAnyDef(refs);
15038
- const values = parseDef(def.valueType._def, {
15039
- ...refs,
15040
- currentPath: [...refs.currentPath, "items", "items", "1"]
15041
- }) || parseAnyDef(refs);
15042
- return {
15043
- type: "array",
15044
- maxItems: 125,
15045
- items: {
15046
- type: "array",
15047
- items: [keys, values],
15048
- minItems: 2,
15049
- maxItems: 2
15050
- }
15051
- };
15052
- }
15053
- function parseNativeEnumDef(def) {
15054
- const object = def.values;
15055
- const actualKeys = Object.keys(def.values).filter((key) => {
15056
- return typeof object[object[key]] !== "number";
15057
- });
15058
- const actualValues = actualKeys.map((key) => object[key]);
15059
- const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values)));
15060
- return {
15061
- type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"],
15062
- enum: actualValues
15063
- };
15064
- }
15065
- function parseNeverDef(refs) {
15066
- return refs.target === "openAi" ? void 0 : {
15067
- not: parseAnyDef({
15068
- ...refs,
15069
- currentPath: [...refs.currentPath, "not"]
15070
- })
15071
- };
15072
- }
15073
- function parseNullDef(refs) {
15074
- return refs.target === "openApi3" ? {
15075
- enum: ["null"],
15076
- nullable: true
15077
- } : {
15078
- type: "null"
15079
- };
15080
- }
15081
- const primitiveMappings = {
15082
- ZodString: "string",
15083
- ZodNumber: "number",
15084
- ZodBigInt: "integer",
15085
- ZodBoolean: "boolean",
15086
- ZodNull: "null"
15087
- };
15088
- function parseUnionDef(def, refs) {
15089
- if (refs.target === "openApi3")
15090
- return asAnyOf(def, refs);
15091
- const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;
15092
- if (options.every((x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length))) {
15093
- const types = options.reduce((types2, x) => {
15094
- const type2 = primitiveMappings[x._def.typeName];
15095
- return type2 && !types2.includes(type2) ? [...types2, type2] : types2;
15096
- }, []);
15097
- return {
15098
- type: types.length > 1 ? types : types[0]
15099
- };
15100
- } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) {
15101
- const types = options.reduce((acc, x) => {
15102
- const type2 = typeof x._def.value;
15103
- switch (type2) {
15104
- case "string":
15105
- case "number":
15106
- case "boolean":
15107
- return [...acc, type2];
15108
- case "bigint":
15109
- return [...acc, "integer"];
15110
- case "object":
15111
- if (x._def.value === null)
15112
- return [...acc, "null"];
15113
- case "symbol":
15114
- case "undefined":
15115
- case "function":
15116
- default:
15117
- return acc;
15118
- }
15119
- }, []);
15120
- if (types.length === options.length) {
15121
- const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);
15122
- return {
15123
- type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
15124
- enum: options.reduce((acc, x) => {
15125
- return acc.includes(x._def.value) ? acc : [...acc, x._def.value];
15126
- }, [])
15127
- };
15128
- }
15129
- } else if (options.every((x) => x._def.typeName === "ZodEnum")) {
15130
- return {
15131
- type: "string",
15132
- enum: options.reduce((acc, x) => [
15133
- ...acc,
15134
- ...x._def.values.filter((x2) => !acc.includes(x2))
15135
- ], [])
15136
- };
15137
- }
15138
- return asAnyOf(def, refs);
15139
- }
15140
- const asAnyOf = (def, refs) => {
15141
- const anyOf2 = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map((x, i) => parseDef(x._def, {
15142
- ...refs,
15143
- currentPath: [...refs.currentPath, "anyOf", `${i}`]
15144
- })).filter((x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0));
15145
- return anyOf2.length ? { anyOf: anyOf2 } : void 0;
15146
- };
15147
- function parseNullableDef(def, refs) {
15148
- if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(def.innerType._def.typeName) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) {
15149
- if (refs.target === "openApi3") {
15150
- return {
15151
- type: primitiveMappings[def.innerType._def.typeName],
15152
- nullable: true
15153
- };
15154
- }
15155
- return {
15156
- type: [
15157
- primitiveMappings[def.innerType._def.typeName],
15158
- "null"
15159
- ]
15160
- };
15161
- }
15162
- if (refs.target === "openApi3") {
15163
- const base2 = parseDef(def.innerType._def, {
15164
- ...refs,
15165
- currentPath: [...refs.currentPath]
15166
- });
15167
- if (base2 && "$ref" in base2)
15168
- return { allOf: [base2], nullable: true };
15169
- return base2 && { ...base2, nullable: true };
15170
- }
15171
- const base = parseDef(def.innerType._def, {
15172
- ...refs,
15173
- currentPath: [...refs.currentPath, "anyOf", "0"]
15174
- });
15175
- return base && { anyOf: [base, { type: "null" }] };
15176
- }
15177
- function parseNumberDef(def, refs) {
15178
- const res = {
15179
- type: "number"
15180
- };
15181
- if (!def.checks)
15182
- return res;
15183
- for (const check of def.checks) {
15184
- switch (check.kind) {
15185
- case "int":
15186
- res.type = "integer";
15187
- addErrorMessage(res, "type", check.message, refs);
15188
- break;
15189
- case "min":
15190
- if (refs.target === "jsonSchema7") {
15191
- if (check.inclusive) {
15192
- setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
15193
- } else {
15194
- setResponseValueAndErrors(res, "exclusiveMinimum", check.value, check.message, refs);
15195
- }
15196
- } else {
15197
- if (!check.inclusive) {
15198
- res.exclusiveMinimum = true;
15199
- }
15200
- setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
15201
- }
15202
- break;
15203
- case "max":
15204
- if (refs.target === "jsonSchema7") {
15205
- if (check.inclusive) {
15206
- setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
15207
- } else {
15208
- setResponseValueAndErrors(res, "exclusiveMaximum", check.value, check.message, refs);
15209
- }
15210
- } else {
15211
- if (!check.inclusive) {
15212
- res.exclusiveMaximum = true;
15213
- }
15214
- setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
15215
- }
15216
- break;
15217
- case "multipleOf":
15218
- setResponseValueAndErrors(res, "multipleOf", check.value, check.message, refs);
15219
- break;
15220
- }
15221
- }
15222
- return res;
15223
- }
15224
- function parseObjectDef(def, refs) {
15225
- const forceOptionalIntoNullable = refs.target === "openAi";
15226
- const result = {
15227
- type: "object",
15228
- properties: {}
15229
- };
15230
- const required2 = [];
15231
- const shape = def.shape();
15232
- for (const propName in shape) {
15233
- let propDef = shape[propName];
15234
- if (propDef === void 0 || propDef._def === void 0) {
15235
- continue;
15236
- }
15237
- let propOptional = safeIsOptional(propDef);
15238
- if (propOptional && forceOptionalIntoNullable) {
15239
- if (propDef._def.typeName === "ZodOptional") {
15240
- propDef = propDef._def.innerType;
15241
- }
15242
- if (!propDef.isNullable()) {
15243
- propDef = propDef.nullable();
15244
- }
15245
- propOptional = false;
15246
- }
15247
- const parsedDef = parseDef(propDef._def, {
15248
- ...refs,
15249
- currentPath: [...refs.currentPath, "properties", propName],
15250
- propertyPath: [...refs.currentPath, "properties", propName]
15251
- });
15252
- if (parsedDef === void 0) {
15253
- continue;
15254
- }
15255
- result.properties[propName] = parsedDef;
15256
- if (!propOptional) {
15257
- required2.push(propName);
15258
- }
15259
- }
15260
- if (required2.length) {
15261
- result.required = required2;
15262
- }
15263
- const additionalProperties2 = decideAdditionalProperties(def, refs);
15264
- if (additionalProperties2 !== void 0) {
15265
- result.additionalProperties = additionalProperties2;
15266
- }
15267
- return result;
15268
- }
15269
- function decideAdditionalProperties(def, refs) {
15270
- if (def.catchall._def.typeName !== "ZodNever") {
15271
- return parseDef(def.catchall._def, {
15272
- ...refs,
15273
- currentPath: [...refs.currentPath, "additionalProperties"]
15274
- });
15275
- }
15276
- switch (def.unknownKeys) {
15277
- case "passthrough":
15278
- return refs.allowedAdditionalProperties;
15279
- case "strict":
15280
- return refs.rejectedAdditionalProperties;
15281
- case "strip":
15282
- return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties;
15283
- }
15284
- }
15285
- function safeIsOptional(schema) {
15286
- try {
15287
- return schema.isOptional();
15288
- } catch {
15289
- return true;
15290
- }
15291
- }
15292
- const parseOptionalDef = (def, refs) => {
15293
- var _a;
15294
- if (refs.currentPath.toString() === ((_a = refs.propertyPath) == null ? void 0 : _a.toString())) {
15295
- return parseDef(def.innerType._def, refs);
15296
- }
15297
- const innerSchema = parseDef(def.innerType._def, {
15298
- ...refs,
15299
- currentPath: [...refs.currentPath, "anyOf", "1"]
15300
- });
15301
- return innerSchema ? {
15302
- anyOf: [
15303
- {
15304
- not: parseAnyDef(refs)
15305
- },
15306
- innerSchema
15307
- ]
15308
- } : parseAnyDef(refs);
15309
- };
15310
- const parsePipelineDef = (def, refs) => {
15311
- if (refs.pipeStrategy === "input") {
15312
- return parseDef(def.in._def, refs);
15313
- } else if (refs.pipeStrategy === "output") {
15314
- return parseDef(def.out._def, refs);
15315
- }
15316
- const a = parseDef(def.in._def, {
15317
- ...refs,
15318
- currentPath: [...refs.currentPath, "allOf", "0"]
15319
- });
15320
- const b = parseDef(def.out._def, {
15321
- ...refs,
15322
- currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"]
15323
- });
15324
- return {
15325
- allOf: [a, b].filter((x) => x !== void 0)
15326
- };
15327
- };
15328
- function parsePromiseDef(def, refs) {
15329
- return parseDef(def.type._def, refs);
15330
- }
15331
- function parseSetDef(def, refs) {
15332
- const items2 = parseDef(def.valueType._def, {
15333
- ...refs,
15334
- currentPath: [...refs.currentPath, "items"]
15335
- });
15336
- const schema = {
15337
- type: "array",
15338
- uniqueItems: true,
15339
- items: items2
15340
- };
15341
- if (def.minSize) {
15342
- setResponseValueAndErrors(schema, "minItems", def.minSize.value, def.minSize.message, refs);
15343
- }
15344
- if (def.maxSize) {
15345
- setResponseValueAndErrors(schema, "maxItems", def.maxSize.value, def.maxSize.message, refs);
15346
- }
15347
- return schema;
15348
- }
15349
- function parseTupleDef(def, refs) {
15350
- if (def.rest) {
15351
- return {
15352
- type: "array",
15353
- minItems: def.items.length,
15354
- items: def.items.map((x, i) => parseDef(x._def, {
15355
- ...refs,
15356
- currentPath: [...refs.currentPath, "items", `${i}`]
15357
- })).reduce((acc, x) => x === void 0 ? acc : [...acc, x], []),
15358
- additionalItems: parseDef(def.rest._def, {
15359
- ...refs,
15360
- currentPath: [...refs.currentPath, "additionalItems"]
15361
- })
15362
- };
15363
- } else {
15364
- return {
15365
- type: "array",
15366
- minItems: def.items.length,
15367
- maxItems: def.items.length,
15368
- items: def.items.map((x, i) => parseDef(x._def, {
15369
- ...refs,
15370
- currentPath: [...refs.currentPath, "items", `${i}`]
15371
- })).reduce((acc, x) => x === void 0 ? acc : [...acc, x], [])
15372
- };
15373
- }
15374
- }
15375
- function parseUndefinedDef(refs) {
15376
- return {
15377
- not: parseAnyDef(refs)
15378
- };
15379
- }
15380
- function parseUnknownDef(refs) {
15381
- return parseAnyDef(refs);
15382
- }
15383
- const parseReadonlyDef = (def, refs) => {
15384
- return parseDef(def.innerType._def, refs);
15385
- };
15386
- const selectParser = (def, typeName, refs) => {
15387
- switch (typeName) {
15388
- case ZodFirstPartyTypeKind.ZodString:
15389
- return parseStringDef(def, refs);
15390
- case ZodFirstPartyTypeKind.ZodNumber:
15391
- return parseNumberDef(def, refs);
15392
- case ZodFirstPartyTypeKind.ZodObject:
15393
- return parseObjectDef(def, refs);
15394
- case ZodFirstPartyTypeKind.ZodBigInt:
15395
- return parseBigintDef(def, refs);
15396
- case ZodFirstPartyTypeKind.ZodBoolean:
15397
- return parseBooleanDef();
15398
- case ZodFirstPartyTypeKind.ZodDate:
15399
- return parseDateDef(def, refs);
15400
- case ZodFirstPartyTypeKind.ZodUndefined:
15401
- return parseUndefinedDef(refs);
15402
- case ZodFirstPartyTypeKind.ZodNull:
15403
- return parseNullDef(refs);
15404
- case ZodFirstPartyTypeKind.ZodArray:
15405
- return parseArrayDef(def, refs);
15406
- case ZodFirstPartyTypeKind.ZodUnion:
15407
- case ZodFirstPartyTypeKind.ZodDiscriminatedUnion:
15408
- return parseUnionDef(def, refs);
15409
- case ZodFirstPartyTypeKind.ZodIntersection:
15410
- return parseIntersectionDef(def, refs);
15411
- case ZodFirstPartyTypeKind.ZodTuple:
15412
- return parseTupleDef(def, refs);
15413
- case ZodFirstPartyTypeKind.ZodRecord:
15414
- return parseRecordDef(def, refs);
15415
- case ZodFirstPartyTypeKind.ZodLiteral:
15416
- return parseLiteralDef(def, refs);
15417
- case ZodFirstPartyTypeKind.ZodEnum:
15418
- return parseEnumDef(def);
15419
- case ZodFirstPartyTypeKind.ZodNativeEnum:
15420
- return parseNativeEnumDef(def);
15421
- case ZodFirstPartyTypeKind.ZodNullable:
15422
- return parseNullableDef(def, refs);
15423
- case ZodFirstPartyTypeKind.ZodOptional:
15424
- return parseOptionalDef(def, refs);
15425
- case ZodFirstPartyTypeKind.ZodMap:
15426
- return parseMapDef(def, refs);
15427
- case ZodFirstPartyTypeKind.ZodSet:
15428
- return parseSetDef(def, refs);
15429
- case ZodFirstPartyTypeKind.ZodLazy:
15430
- return () => def.getter()._def;
15431
- case ZodFirstPartyTypeKind.ZodPromise:
15432
- return parsePromiseDef(def, refs);
15433
- case ZodFirstPartyTypeKind.ZodNaN:
15434
- case ZodFirstPartyTypeKind.ZodNever:
15435
- return parseNeverDef(refs);
15436
- case ZodFirstPartyTypeKind.ZodEffects:
15437
- return parseEffectsDef(def, refs);
15438
- case ZodFirstPartyTypeKind.ZodAny:
15439
- return parseAnyDef(refs);
15440
- case ZodFirstPartyTypeKind.ZodUnknown:
15441
- return parseUnknownDef(refs);
15442
- case ZodFirstPartyTypeKind.ZodDefault:
15443
- return parseDefaultDef(def, refs);
15444
- case ZodFirstPartyTypeKind.ZodBranded:
15445
- return parseBrandedDef(def, refs);
15446
- case ZodFirstPartyTypeKind.ZodReadonly:
15447
- return parseReadonlyDef(def, refs);
15448
- case ZodFirstPartyTypeKind.ZodCatch:
15449
- return parseCatchDef(def, refs);
15450
- case ZodFirstPartyTypeKind.ZodPipeline:
15451
- return parsePipelineDef(def, refs);
15452
- case ZodFirstPartyTypeKind.ZodFunction:
15453
- case ZodFirstPartyTypeKind.ZodVoid:
15454
- case ZodFirstPartyTypeKind.ZodSymbol:
15455
- return void 0;
15456
- default:
15457
- return /* @__PURE__ */ ((_) => void 0)();
15458
- }
15459
- };
15460
- function parseDef(def, refs, forceResolution = false) {
15461
- var _a;
15462
- const seenItem = refs.seen.get(def);
15463
- if (refs.override) {
15464
- const overrideResult = (_a = refs.override) == null ? void 0 : _a.call(refs, def, refs, seenItem, forceResolution);
15465
- if (overrideResult !== ignoreOverride) {
15466
- return overrideResult;
15467
- }
15468
- }
15469
- if (seenItem && !forceResolution) {
15470
- const seenSchema = get$ref(seenItem, refs);
15471
- if (seenSchema !== void 0) {
15472
- return seenSchema;
15473
- }
15474
- }
15475
- const newItem = { def, path: refs.currentPath, jsonSchema: void 0 };
15476
- refs.seen.set(def, newItem);
15477
- const jsonSchemaOrGetter = selectParser(def, def.typeName, refs);
15478
- const jsonSchema = typeof jsonSchemaOrGetter === "function" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter;
15479
- if (jsonSchema) {
15480
- addMeta(def, refs, jsonSchema);
15481
- }
15482
- if (refs.postProcess) {
15483
- const postProcessResult = refs.postProcess(jsonSchema, def, refs);
15484
- newItem.jsonSchema = jsonSchema;
15485
- return postProcessResult;
15486
- }
15487
- newItem.jsonSchema = jsonSchema;
15488
- return jsonSchema;
15489
- }
15490
- const get$ref = (item, refs) => {
15491
- switch (refs.$refStrategy) {
15492
- case "root":
15493
- return { $ref: item.path.join("/") };
15494
- case "relative":
15495
- return { $ref: getRelativePath(refs.currentPath, item.path) };
15496
- case "none":
15497
- case "seen": {
15498
- if (item.path.length < refs.currentPath.length && item.path.every((value, index2) => refs.currentPath[index2] === value)) {
15499
- console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`);
15500
- return parseAnyDef(refs);
15501
- }
15502
- return refs.$refStrategy === "seen" ? parseAnyDef(refs) : void 0;
15503
- }
15504
- }
15505
- };
15506
- const addMeta = (def, refs, jsonSchema) => {
15507
- if (def.description) {
15508
- jsonSchema.description = def.description;
15509
- if (refs.markdownDescription) {
15510
- jsonSchema.markdownDescription = def.description;
15511
- }
15512
- }
15513
- return jsonSchema;
15514
- };
15515
- const zodToJsonSchema = (schema, options) => {
15516
- const refs = getRefs(options);
15517
- let definitions2 = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name2, schema2]) => ({
15518
- ...acc,
15519
- [name2]: parseDef(schema2._def, {
15520
- ...refs,
15521
- currentPath: [...refs.basePath, refs.definitionPath, name2]
15522
- }, true) ?? parseAnyDef(refs)
15523
- }), {}) : void 0;
15524
- const name = typeof options === "string" ? options : (options == null ? void 0 : options.nameStrategy) === "title" ? void 0 : options == null ? void 0 : options.name;
15525
- const main = parseDef(schema._def, name === void 0 ? refs : {
15526
- ...refs,
15527
- currentPath: [...refs.basePath, refs.definitionPath, name]
15528
- }, false) ?? parseAnyDef(refs);
15529
- const title2 = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0;
15530
- if (title2 !== void 0) {
15531
- main.title = title2;
15532
- }
15533
- if (refs.flags.hasReferencedOpenAiAnyType) {
15534
- if (!definitions2) {
15535
- definitions2 = {};
15536
- }
15537
- if (!definitions2[refs.openAiAnyTypeName]) {
15538
- definitions2[refs.openAiAnyTypeName] = {
15539
- // Skipping "object" as no properties can be defined and additionalProperties must be "false"
15540
- type: ["string", "number", "integer", "boolean", "array", "null"],
15541
- items: {
15542
- $ref: refs.$refStrategy === "relative" ? "1" : [
15543
- ...refs.basePath,
15544
- refs.definitionPath,
15545
- refs.openAiAnyTypeName
15546
- ].join("/")
15547
- }
15548
- };
15549
- }
15550
- }
15551
- const combined = name === void 0 ? definitions2 ? {
15552
- ...main,
15553
- [refs.definitionPath]: definitions2
15554
- } : main : {
15555
- $ref: [
15556
- ...refs.$refStrategy === "relative" ? [] : refs.basePath,
15557
- refs.definitionPath,
15558
- name
15559
- ].join("/"),
15560
- [refs.definitionPath]: {
15561
- ...definitions2,
15562
- [name]: main
15563
- }
15564
- };
15565
- if (refs.target === "jsonSchema7") {
15566
- combined.$schema = "http://json-schema.org/draft-07/schema#";
15567
- } else if (refs.target === "jsonSchema2019-09" || refs.target === "openAi") {
15568
- combined.$schema = "https://json-schema.org/draft/2019-09/schema#";
15569
- }
15570
- if (refs.target === "openAi" && ("anyOf" in combined || "oneOf" in combined || "allOf" in combined || "type" in combined && Array.isArray(combined.type))) {
15571
- console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");
15572
- }
15573
- return combined;
15574
- };
15575
- var McpZodTypeKind;
15576
- (function(McpZodTypeKind2) {
15577
- McpZodTypeKind2["Completable"] = "McpCompletable";
15578
- })(McpZodTypeKind || (McpZodTypeKind = {}));
15579
- class Completable extends ZodType {
15580
- _parse(input) {
15581
- const { ctx } = this._processInputParams(input);
15582
- const data2 = ctx.data;
15583
- return this._def.type._parse({
15584
- data: data2,
15585
- path: ctx.path,
15586
- parent: ctx
15587
- });
15588
- }
15589
- unwrap() {
15590
- return this._def.type;
15591
- }
15592
- }
15593
- Completable.create = (type2, params) => {
15594
- return new Completable({
15595
- type: type2,
15596
- typeName: McpZodTypeKind.Completable,
15597
- complete: params.complete,
15598
- ...processCreateParams(params)
15599
- });
15600
- };
15601
- function processCreateParams(params) {
15602
- if (!params)
15603
- return {};
15604
- const { errorMap, invalid_type_error, required_error, description: description2 } = params;
15605
- if (errorMap && (invalid_type_error || required_error)) {
15606
- throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
15607
- }
15608
- if (errorMap)
15609
- return { errorMap, description: description2 };
15610
- const customMap = (iss, ctx) => {
15611
- var _a, _b;
15612
- const { message } = params;
15613
- if (iss.code === "invalid_enum_value") {
15614
- return { message: message !== null && message !== void 0 ? message : ctx.defaultError };
15615
- }
15616
- if (typeof ctx.data === "undefined") {
15617
- return { message: (_a = message !== null && message !== void 0 ? message : required_error) !== null && _a !== void 0 ? _a : ctx.defaultError };
15618
- }
15619
- if (iss.code !== "invalid_type")
15620
- return { message: ctx.defaultError };
15621
- return { message: (_b = message !== null && message !== void 0 ? message : invalid_type_error) !== null && _b !== void 0 ? _b : ctx.defaultError };
15622
- };
15623
- return { errorMap: customMap, description: description2 };
15624
- }
15625
- class McpServer {
15626
- constructor(serverInfo, options) {
15627
- this._registeredResources = {};
15628
- this._registeredResourceTemplates = {};
15629
- this._registeredTools = {};
15630
- this._registeredPrompts = {};
15631
- this._toolHandlersInitialized = false;
15632
- this._completionHandlerInitialized = false;
15633
- this._resourceHandlersInitialized = false;
15634
- this._promptHandlersInitialized = false;
15635
- this.server = new Server(serverInfo, options);
15636
- }
15637
- /**
15638
- * Attaches to the given transport, starts it, and starts listening for messages.
15639
- *
15640
- * The `server` object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward.
15641
- */
15642
- async connect(transport) {
15643
- return await this.server.connect(transport);
15644
- }
15645
- /**
15646
- * Closes the connection.
15886
+ * Closes the connection.
15647
15887
  */
15648
15888
  async close() {
15649
15889
  await this.server.close();
@@ -15665,13 +15905,11 @@ class McpServer {
15665
15905
  name,
15666
15906
  title: tool.title,
15667
15907
  description: tool.description,
15668
- inputSchema: tool.inputSchema ? zodToJsonSchema(tool.inputSchema, {
15669
- strictUnions: true
15670
- }) : EMPTY_OBJECT_JSON_SCHEMA,
15908
+ inputSchema: tool.inputSchema ? safeToJSONSchema(tool.inputSchema) : EMPTY_OBJECT_JSON_SCHEMA,
15671
15909
  annotations: tool.annotations
15672
15910
  };
15673
15911
  if (tool.outputSchema) {
15674
- toolDefinition.outputSchema = zodToJsonSchema(tool.outputSchema, { strictUnions: true });
15912
+ toolDefinition.outputSchema = safeToJSONSchema(tool.outputSchema);
15675
15913
  }
15676
15914
  return toolDefinition;
15677
15915
  })
@@ -15769,8 +16007,17 @@ class McpServer {
15769
16007
  if (!(field instanceof Completable)) {
15770
16008
  return EMPTY_COMPLETION_RESULT;
15771
16009
  }
15772
- const def = field._def;
15773
- const suggestions = await def.complete(request.params.argument.value, request.params.context);
16010
+ const suggestions = await field.complete(request.params.argument.value, request.params.context);
16011
+ return createCompletionResult(suggestions);
16012
+ }
16013
+ async getFieldCompletions(field, request) {
16014
+ if (!field) {
16015
+ return EMPTY_COMPLETION_RESULT;
16016
+ }
16017
+ if (!(field instanceof Completable)) {
16018
+ return EMPTY_COMPLETION_RESULT;
16019
+ }
16020
+ const suggestions = await field.complete(request.params.argument.value, request.params.context);
15774
16021
  return createCompletionResult(suggestions);
15775
16022
  }
15776
16023
  async handleResourceCompletion(request, ref2) {
@@ -16038,8 +16285,8 @@ class McpServer {
16038
16285
  const registeredTool = {
16039
16286
  title: title2,
16040
16287
  description: description2,
16041
- inputSchema: inputSchema === void 0 ? void 0 : z.object(inputSchema),
16042
- outputSchema: outputSchema === void 0 ? void 0 : z.object(outputSchema),
16288
+ inputSchema: inputSchema === void 0 ? void 0 : isZodTypeLike(inputSchema) ? inputSchema : z.object(inputSchema),
16289
+ outputSchema: outputSchema === void 0 ? void 0 : isZodTypeLike(outputSchema) ? outputSchema : z.object(outputSchema),
16043
16290
  annotations,
16044
16291
  callback,
16045
16292
  enabled: true,
@@ -16173,32 +16420,72 @@ class McpServer {
16173
16420
  }
16174
16421
  }
16175
16422
  }
16423
+ class ResourceTemplate {
16424
+ constructor(uriTemplate, _callbacks) {
16425
+ this._callbacks = _callbacks;
16426
+ this._uriTemplate = typeof uriTemplate === "string" ? new UriTemplate(uriTemplate) : uriTemplate;
16427
+ }
16428
+ /**
16429
+ * Gets the URI template pattern.
16430
+ */
16431
+ get uriTemplate() {
16432
+ return this._uriTemplate;
16433
+ }
16434
+ /**
16435
+ * Gets the list callback, if one was provided.
16436
+ */
16437
+ get listCallback() {
16438
+ return this._callbacks.list;
16439
+ }
16440
+ /**
16441
+ * Gets the callback for completing a specific URI template variable, if one was provided.
16442
+ */
16443
+ completeCallback(variable) {
16444
+ var _a;
16445
+ return (_a = this._callbacks.complete) === null || _a === void 0 ? void 0 : _a[variable];
16446
+ }
16447
+ }
16176
16448
  const EMPTY_OBJECT_JSON_SCHEMA = {
16177
16449
  type: "object",
16178
16450
  properties: {}
16179
16451
  };
16452
+ function safeToJSONSchema(schema) {
16453
+ try {
16454
+ if (!schema)
16455
+ return EMPTY_OBJECT_JSON_SCHEMA;
16456
+ return z.toJSONSchema(schema);
16457
+ } catch (error) {
16458
+ console.error("JSON Schema generation failed:", error);
16459
+ return EMPTY_OBJECT_JSON_SCHEMA;
16460
+ }
16461
+ }
16180
16462
  function isZodRawShape(obj) {
16181
16463
  if (typeof obj !== "object" || obj === null)
16182
16464
  return false;
16183
16465
  const isEmptyObject = Object.keys(obj).length === 0;
16184
- return isEmptyObject || Object.values(obj).some(isZodTypeLike);
16466
+ const filteredValues = Object.entries(obj).filter(([key]) => key !== "~standard").map(([, value]) => value);
16467
+ return isEmptyObject || filteredValues.some(isZodTypeLike);
16185
16468
  }
16186
16469
  function isZodTypeLike(value) {
16187
16470
  return value !== null && typeof value === "object" && "parse" in value && typeof value.parse === "function" && "safeParse" in value && typeof value.safeParse === "function";
16188
16471
  }
16189
16472
  function promptArgumentsFromSchema(schema) {
16190
- return Object.entries(schema.shape).map(([name, field]) => ({
16191
- name,
16192
- description: field.description,
16193
- required: !field.isOptional()
16194
- }));
16473
+ return Object.entries(schema.shape).map(([name, field]) => {
16474
+ var _a, _b, _c;
16475
+ return {
16476
+ name,
16477
+ description: field.description,
16478
+ required: !((_c = (_b = (_a = field).isOptional) === null || _b === void 0 ? void 0 : _b.call(_a)) !== null && _c !== void 0 ? _c : false)
16479
+ };
16480
+ });
16195
16481
  }
16196
16482
  function createCompletionResult(suggestions) {
16483
+ const filteredSuggestions = suggestions.filter((s) => s !== void 0);
16197
16484
  return {
16198
16485
  completion: {
16199
- values: suggestions.slice(0, 100),
16200
- total: suggestions.length,
16201
- hasMore: suggestions.length > 100
16486
+ values: filteredSuggestions.slice(0, 100),
16487
+ total: filteredSuggestions.length,
16488
+ hasMore: filteredSuggestions.length > 100
16202
16489
  }
16203
16490
  };
16204
16491
  }
@@ -16210,7 +16497,152 @@ const EMPTY_COMPLETION_RESULT = {
16210
16497
  };
16211
16498
  const mcp = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
16212
16499
  __proto__: null,
16213
- McpServer
16500
+ McpServer,
16501
+ ResourceTemplate
16502
+ }, Symbol.toStringTag, { value: "Module" }));
16503
+ class McpLifecycleManager {
16504
+ constructor(events, logger2, serverInfo, argParser) {
16505
+ this.events = events;
16506
+ this.logger = logger2;
16507
+ this.serverInfo = serverInfo;
16508
+ this.argParser = argParser;
16509
+ this.state = {
16510
+ initialized: false,
16511
+ ready: false,
16512
+ shuttingDown: false
16513
+ };
16514
+ this.parsedArgs = {};
16515
+ }
16516
+ /**
16517
+ * Set the parsed arguments for flag access
16518
+ */
16519
+ setParsedArgs(parsedArgs) {
16520
+ this.parsedArgs = parsedArgs;
16521
+ }
16522
+ /**
16523
+ * Get a flag value from parsed arguments or environment variables
16524
+ */
16525
+ getFlag(name) {
16526
+ if (this.parsedArgs && this.parsedArgs[name] !== void 0) {
16527
+ return this.parsedArgs[name];
16528
+ }
16529
+ if (this.argParser) {
16530
+ const flagDef = this.argParser.getFlagDefinition(name);
16531
+ if (flagDef) {
16532
+ if (flagDef.env && process.env[flagDef.env]) {
16533
+ return process.env[flagDef.env];
16534
+ }
16535
+ return flagDef.defaultValue;
16536
+ }
16537
+ }
16538
+ return void 0;
16539
+ }
16540
+ /**
16541
+ * Handle the initialize request
16542
+ */
16543
+ async handleInitialize(clientInfo, protocolVersion, clientCapabilities) {
16544
+ if (this.state.initialized) {
16545
+ this.logger.mcpError("Initialize called multiple times");
16546
+ return;
16547
+ }
16548
+ this.state.clientInfo = clientInfo;
16549
+ this.state.protocolVersion = protocolVersion;
16550
+ this.state.clientCapabilities = clientCapabilities;
16551
+ this.state.initialized = true;
16552
+ if (this.events.onInitialize) {
16553
+ const context = {
16554
+ getFlag: (name) => this.getFlag(name),
16555
+ logger: this.logger,
16556
+ serverInfo: this.serverInfo,
16557
+ clientInfo,
16558
+ protocolVersion,
16559
+ clientCapabilities
16560
+ };
16561
+ try {
16562
+ await this.events.onInitialize(context);
16563
+ this.logger.mcpError("Lifecycle onInitialize completed successfully");
16564
+ } catch (error) {
16565
+ this.logger.mcpError(
16566
+ `Lifecycle onInitialize failed: ${error instanceof Error ? error.message : String(error)}`
16567
+ );
16568
+ throw error;
16569
+ }
16570
+ }
16571
+ }
16572
+ /**
16573
+ * Handle the initialized notification
16574
+ */
16575
+ async handleInitialized() {
16576
+ if (!this.state.initialized) {
16577
+ this.logger.mcpError("Initialized called before initialize");
16578
+ return;
16579
+ }
16580
+ if (this.state.ready) {
16581
+ this.logger.mcpError("Initialized called multiple times");
16582
+ return;
16583
+ }
16584
+ this.state.ready = true;
16585
+ if (this.events.onInitialized && this.state.clientInfo) {
16586
+ const context = {
16587
+ getFlag: (name) => this.getFlag(name),
16588
+ logger: this.logger,
16589
+ serverInfo: this.serverInfo,
16590
+ clientInfo: this.state.clientInfo,
16591
+ protocolVersion: this.state.protocolVersion
16592
+ };
16593
+ try {
16594
+ await this.events.onInitialized(context);
16595
+ this.logger.mcpError("Lifecycle onInitialized completed successfully");
16596
+ } catch (error) {
16597
+ this.logger.mcpError(
16598
+ `Lifecycle onInitialized failed: ${error instanceof Error ? error.message : String(error)}`
16599
+ );
16600
+ throw error;
16601
+ }
16602
+ }
16603
+ }
16604
+ /**
16605
+ * Handle server shutdown
16606
+ */
16607
+ async handleShutdown(reason, error) {
16608
+ if (this.state.shuttingDown) {
16609
+ return;
16610
+ }
16611
+ this.state.shuttingDown = true;
16612
+ if (this.events.onShutdown) {
16613
+ const context = {
16614
+ getFlag: (name) => this.getFlag(name),
16615
+ logger: this.logger,
16616
+ serverInfo: this.serverInfo,
16617
+ reason,
16618
+ error
16619
+ };
16620
+ try {
16621
+ await this.events.onShutdown(context);
16622
+ this.logger.mcpError("Lifecycle onShutdown completed successfully");
16623
+ } catch (shutdownError) {
16624
+ this.logger.mcpError(
16625
+ `Lifecycle onShutdown failed: ${shutdownError instanceof Error ? shutdownError.message : String(shutdownError)}`
16626
+ );
16627
+ }
16628
+ }
16629
+ }
16630
+ /**
16631
+ * Get current lifecycle state
16632
+ */
16633
+ getState() {
16634
+ return { ...this.state };
16635
+ }
16636
+ /**
16637
+ * Check if the server is ready for operations
16638
+ */
16639
+ isReady() {
16640
+ return this.state.ready && !this.state.shuttingDown;
16641
+ }
16642
+ }
16643
+ const mcpLifecycle = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
16644
+ __proto__: null,
16645
+ McpLifecycleManager
16214
16646
  }, Symbol.toStringTag, { value: "Module" }));
16215
16647
  class ReadBuffer {
16216
16648
  append(chunk) {
@@ -24488,6 +24920,7 @@ export {
24488
24920
  createYamlPlugin,
24489
24921
  createYamlPluginAsync,
24490
24922
  cwdRelative,
24923
+ debug,
24491
24924
  detectEntryPoint,
24492
24925
  enableConfigPlugins,
24493
24926
  enableOptionalConfigPlugins,
@@ -24498,9 +24931,11 @@ export {
24498
24931
  getEntryPointFromImportMeta,
24499
24932
  getJsonSchemaTypeFromFlag,
24500
24933
  globalConfigPluginRegistry,
24934
+ isValidMcpToolName,
24501
24935
  legacyCwdPath,
24502
24936
  logger,
24503
24937
  resolveLogPath,
24938
+ sanitizeMcpToolName,
24504
24939
  zodFlagSchema
24505
24940
  };
24506
24941
  //# sourceMappingURL=index.mjs.map