@ai-ecoverse/mcpcat 0.2.0 → 0.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.
@@ -738,7 +738,7 @@ var DEFAULT_RECONNECT_MAX_DELAY_MS = 3e4;
738
738
  var DEFAULT_RECONNECT_MAX_RETRIES = 5;
739
739
  async function consumeSseStream(stream, options) {
740
740
  const reader = stream.getReader();
741
- const decoder = new TextDecoder();
741
+ const decoder2 = new TextDecoder();
742
742
  let buffered = "";
743
743
  let eventName;
744
744
  let eventId;
@@ -789,7 +789,7 @@ async function consumeSseStream(stream, options) {
789
789
  const { done, value } = await reader.read();
790
790
  if (done)
791
791
  break;
792
- buffered += decoder.decode(value, { stream: true });
792
+ buffered += decoder2.decode(value, { stream: true });
793
793
  let newline = buffered.indexOf("\n");
794
794
  while (newline >= 0) {
795
795
  processLine(buffered.slice(0, newline));
@@ -799,7 +799,7 @@ async function consumeSseStream(stream, options) {
799
799
  if (Buffer.byteLength(buffered) > maxEventBytes)
800
800
  throw new Error(`MCP SSE event exceeds ${maxEventBytes} bytes`);
801
801
  }
802
- buffered += decoder.decode();
802
+ buffered += decoder2.decode();
803
803
  if (buffered)
804
804
  processLine(buffered);
805
805
  dispatch();
@@ -1327,16 +1327,16 @@ async function createStatelessConnection(options) {
1327
1327
  }
1328
1328
  if (res.status >= 400) {
1329
1329
  const text = await res.text();
1330
- let rpcError;
1330
+ let rpcError2;
1331
1331
  try {
1332
1332
  const parsed = JSON.parse(text);
1333
1333
  if (parsed.error && typeof parsed.error.code === "number") {
1334
- rpcError = parsed.error;
1334
+ rpcError2 = parsed.error;
1335
1335
  }
1336
1336
  } catch {
1337
1337
  }
1338
- if (rpcError) {
1339
- throw new StatelessRpcError(rpcError.code, rpcError.message, rpcError.data);
1338
+ if (rpcError2) {
1339
+ throw new StatelessRpcError(rpcError2.code, rpcError2.message, rpcError2.data);
1340
1340
  }
1341
1341
  throw new StatelessHttpError(res.status, res.statusText, method, text.slice(0, 512));
1342
1342
  }
@@ -1353,10 +1353,10 @@ async function createStatelessConnection(options) {
1353
1353
  }
1354
1354
  return frame.result;
1355
1355
  }
1356
- const discoverResult = await request("server/discover", {
1356
+ const discoverResult2 = await request("server/discover", {
1357
1357
  protocolVersion: STATELESS_PROTOCOL_VERSION
1358
1358
  });
1359
- const supported = Array.isArray(discoverResult?.supportedVersions) ? discoverResult.supportedVersions.filter((v) => typeof v === "string") : [];
1359
+ const supported = Array.isArray(discoverResult2?.supportedVersions) ? discoverResult2.supportedVersions.filter((v) => typeof v === "string") : [];
1360
1360
  if (!supported.includes(STATELESS_PROTOCOL_VERSION)) {
1361
1361
  throw new Error(
1362
1362
  `Server does not support ${STATELESS_PROTOCOL_VERSION} (advertised: ${supported.join(", ") || "none"})`
@@ -1367,7 +1367,7 @@ async function createStatelessConnection(options) {
1367
1367
  return {
1368
1368
  async info() {
1369
1369
  if (serverInfoCache) return serverInfoCache;
1370
- const result = discoverResult;
1370
+ const result = discoverResult2;
1371
1371
  serverInfoCache = {
1372
1372
  name: result?.serverInfo?.name,
1373
1373
  version: result?.serverInfo?.version,
@@ -1538,32 +1538,2626 @@ function configToTarget(entry) {
1538
1538
  throw new Error("config entry has neither url nor command");
1539
1539
  }
1540
1540
 
1541
- // src/config/source.ts
1542
- function createConfigSource(platform) {
1543
- const home = platform.env.HOME ?? platform.env.USERPROFILE ?? "";
1544
- const piDir = platform.env.PI_CODING_AGENT_DIR ?? `${home}/.pi/agent`;
1545
- const configPath = `${piDir}/mcp.json`;
1541
+ // src/config/parse.ts
1542
+ var SERVER_NAME = /^[A-Za-z0-9_-]+$/;
1543
+ var EXPOSURES = ["codemode", "deferred", "direct", "hidden"];
1544
+ var EXPOSURE_ALIASES = { "codemode-deferred": "codemode" };
1545
+ function isRecord(value) {
1546
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1547
+ }
1548
+ function isStringRecord(value) {
1549
+ return isRecord(value) && Object.values(value).every((v) => typeof v === "string");
1550
+ }
1551
+ function isExposure(value) {
1552
+ return typeof value === "string" && EXPOSURES.includes(value);
1553
+ }
1554
+ function resolveAlias(value) {
1555
+ return typeof value === "string" ? EXPOSURE_ALIASES[value] ?? value : value;
1556
+ }
1557
+ function resolveAliases(value) {
1558
+ const out = { ...value };
1559
+ if (out.exposure !== void 0) out.exposure = resolveAlias(out.exposure);
1560
+ if (isRecord(out.toolExposure)) {
1561
+ out.toolExposure = Object.fromEntries(
1562
+ Object.entries(out.toolExposure).map(([k, v]) => [k, resolveAlias(v)])
1563
+ );
1564
+ }
1565
+ return out;
1566
+ }
1567
+ function fail(server, message, field) {
1568
+ return { server, ...field ? { field } : {}, message };
1569
+ }
1570
+ function validateCommon(name, value) {
1571
+ const exposures = EXPOSURES.map((e) => `"${e}"`).join(", ");
1572
+ if (value.exposure !== void 0 && !isExposure(value.exposure))
1573
+ return fail(name, `exposure must be one of ${exposures}`, "exposure");
1574
+ if (value.toolExposure !== void 0) {
1575
+ if (!isRecord(value.toolExposure))
1576
+ return fail(name, "toolExposure must map tool names to exposures", "toolExposure");
1577
+ for (const [tool, exp] of Object.entries(value.toolExposure))
1578
+ if (!isExposure(exp))
1579
+ return fail(
1580
+ name,
1581
+ `toolExposure "${tool}" must be one of ${exposures}`,
1582
+ `toolExposure.${tool}`
1583
+ );
1584
+ }
1585
+ if (value.enabled !== void 0 && typeof value.enabled !== "boolean")
1586
+ return fail(name, "enabled must be a boolean", "enabled");
1587
+ if (value.description !== void 0 && typeof value.description !== "string")
1588
+ return fail(name, "description must be a string", "description");
1589
+ if (value.timeout !== void 0 && (typeof value.timeout !== "number" || !(value.timeout > 0)))
1590
+ return fail(name, "timeout must be a positive number of seconds", "timeout");
1591
+ return void 0;
1592
+ }
1593
+ function validateOAuthFields(name, oauth) {
1594
+ if (oauth.clientId !== void 0 && typeof oauth.clientId !== "string")
1595
+ return fail(name, "oauth.clientId must be a string", "oauth.clientId");
1596
+ if (oauth.clientSecret !== void 0 && typeof oauth.clientSecret !== "string")
1597
+ return fail(name, "oauth.clientSecret must be a string", "oauth.clientSecret");
1598
+ const port = oauth.callbackPort;
1599
+ if (port !== void 0 && (typeof port !== "number" || !Number.isInteger(port) || port < 1 || port > 65535))
1600
+ return fail(name, "oauth.callbackPort must be a port number", "oauth.callbackPort");
1601
+ if (oauth.callbackUrl !== void 0 && typeof oauth.callbackUrl !== "string")
1602
+ return fail(name, "oauth.callbackUrl must be a string", "oauth.callbackUrl");
1603
+ if (oauth.scope !== void 0 && typeof oauth.scope !== "string")
1604
+ return fail(name, "oauth.scope must be a string", "oauth.scope");
1605
+ if (oauth.clientName !== void 0 && (typeof oauth.clientName !== "string" || !oauth.clientName.trim()))
1606
+ return fail(name, "oauth.clientName must be a non-empty string", "oauth.clientName");
1607
+ return void 0;
1608
+ }
1609
+ function validateOAuthExtras(name, oauth) {
1610
+ if (oauth.clientRegistration !== void 0 && oauth.clientRegistration !== "dcr" && oauth.clientRegistration !== "cimd")
1611
+ return fail(
1612
+ name,
1613
+ 'oauth.clientRegistration must be "dcr" or "cimd"',
1614
+ "oauth.clientRegistration"
1615
+ );
1616
+ if (oauth.authServerMetadataUrl !== void 0) {
1617
+ const url = typeof oauth.authServerMetadataUrl === "string" && URL.canParse(oauth.authServerMetadataUrl) ? new URL(oauth.authServerMetadataUrl) : void 0;
1618
+ if (!url || url.protocol !== "https:" && !(url.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname)))
1619
+ return fail(
1620
+ name,
1621
+ "oauth.authServerMetadataUrl must be an https URL",
1622
+ "oauth.authServerMetadataUrl"
1623
+ );
1624
+ }
1625
+ return void 0;
1626
+ }
1627
+ function validateOAuth(name, value) {
1628
+ const { oauth } = value;
1629
+ if (oauth === void 0) return void 0;
1630
+ if (!isRecord(oauth)) return fail(name, "oauth must be an object", "oauth");
1631
+ return validateOAuthFields(name, oauth) ?? validateOAuthExtras(name, oauth);
1632
+ }
1633
+ function validateHttpServer(name, value) {
1634
+ if (typeof value.url !== "string" || value.type !== void 0 && value.type !== "http" && value.type !== "streamable-http")
1635
+ return void 0;
1636
+ if (!URL.canParse(value.url) || !/^https?:$/.test(new URL(value.url).protocol))
1637
+ return fail(name, "url must be an http or https URL", "url");
1638
+ if (value.headers !== void 0 && !isStringRecord(value.headers))
1639
+ return fail(name, "headers must map names to strings", "headers");
1640
+ const oauthErr = validateOAuth(name, value);
1641
+ if (oauthErr) return oauthErr;
1642
+ return value;
1643
+ }
1644
+ function validateStdioServer(name, value) {
1645
+ if (typeof value.command !== "string" || value.type !== void 0 && value.type !== "stdio")
1646
+ return void 0;
1647
+ if (value.args !== void 0 && !(Array.isArray(value.args) && value.args.every((a) => typeof a === "string")))
1648
+ return fail(name, "args must be an array of strings", "args");
1649
+ if (value.env !== void 0 && !isStringRecord(value.env))
1650
+ return fail(name, "env must map names to strings", "env");
1651
+ if (value.cwd !== void 0 && typeof value.cwd !== "string")
1652
+ return fail(name, "cwd must be a string", "cwd");
1653
+ return value;
1654
+ }
1655
+ function validateServer(name, raw) {
1656
+ if (!SERVER_NAME.test(name))
1657
+ return fail(name, `invalid server name "${name}" (use letters, digits, "_" and "-")`);
1658
+ if (!isRecord(raw)) return fail(name, "must be an object");
1659
+ const value = resolveAliases(raw);
1660
+ if (value.type === "sse")
1661
+ return fail(name, "legacy SSE transport is not supported; use the streamable HTTP URL", "type");
1662
+ const common = validateCommon(name, value);
1663
+ if (common) return common;
1664
+ const httpResult = validateHttpServer(name, value);
1665
+ if (httpResult) return httpResult;
1666
+ const stdioResult = validateStdioServer(name, value);
1667
+ if (stdioResult) return stdioResult;
1668
+ if (value.type !== void 0 && !["http", "streamable-http", "stdio"].includes(value.type))
1669
+ return fail(name, 'type must be "stdio", "http", or "streamable-http"', "type");
1670
+ return fail(name, 'needs a "url" or "command"');
1671
+ }
1672
+ function isOverride(value) {
1673
+ return value.command === void 0 && value.url === void 0 && value.type === void 0;
1674
+ }
1675
+ function canonical(name) {
1676
+ return name.replace(/-/g, "_");
1677
+ }
1678
+ function parseMcpJson(text) {
1679
+ const result = { servers: [], overrides: [], problems: [] };
1680
+ let parsed;
1681
+ try {
1682
+ parsed = JSON.parse(text);
1683
+ } catch (error) {
1684
+ result.problems.push({ message: `not valid JSON: ${error.message}` });
1685
+ return result;
1686
+ }
1687
+ if (!isRecord(parsed) || parsed.mcpServers !== void 0 && !isRecord(parsed.mcpServers)) {
1688
+ result.problems.push({ message: "mcpServers must be an object" });
1689
+ return result;
1690
+ }
1691
+ if (typeof parsed.autoEnableCodemode === "boolean")
1692
+ result.autoEnableCodemode = parsed.autoEnableCodemode;
1693
+ else if (parsed.autoEnableCodemode !== void 0)
1694
+ result.problems.push({ message: "autoEnableCodemode must be a boolean" });
1695
+ const seen = /* @__PURE__ */ new Set();
1696
+ for (const [name, raw] of Object.entries(parsed.mcpServers ?? {})) {
1697
+ if (!SERVER_NAME.test(name)) {
1698
+ result.problems.push(
1699
+ fail(name, `invalid server name "${name}" (use letters, digits, "_" and "-")`)
1700
+ );
1701
+ continue;
1702
+ }
1703
+ if (seen.has(canonical(name))) {
1704
+ result.problems.push(
1705
+ fail(name, 'names that differ only in "-" and "_" count as the same server')
1706
+ );
1707
+ continue;
1708
+ }
1709
+ seen.add(canonical(name));
1710
+ if (isRecord(raw) && isOverride(raw)) {
1711
+ result.overrides.push({ name, raw });
1712
+ continue;
1713
+ }
1714
+ const checked = validateServer(name, raw);
1715
+ if ("message" in checked) {
1716
+ result.problems.push(checked);
1717
+ continue;
1718
+ }
1719
+ result.servers.push({ name, config: checked });
1720
+ }
1721
+ return result;
1722
+ }
1723
+
1724
+ // src/config/merge.ts
1725
+ var OVERRIDE_KEYS = /* @__PURE__ */ new Set(["enabled", "exposure", "toolExposure"]);
1726
+ async function readFile(fs, path) {
1727
+ try {
1728
+ const data = await fs.readFile(path);
1729
+ return new TextDecoder().decode(data);
1730
+ } catch {
1731
+ return void 0;
1732
+ }
1733
+ }
1734
+ function applyOverride(servers, problems, name, override, projectPath) {
1735
+ const raw = override;
1736
+ const base = servers.get(name);
1737
+ const extra = Object.keys(raw).filter((k) => !OVERRIDE_KEYS.has(k));
1738
+ if (!base) {
1739
+ problems.push({
1740
+ server: name,
1741
+ message: 'needs "command" or "url", or a user server to override'
1742
+ });
1743
+ return;
1744
+ }
1745
+ if (extra.length > 0) {
1746
+ problems.push({
1747
+ server: name,
1748
+ message: "an override can only set enabled, exposure, toolExposure"
1749
+ });
1750
+ return;
1751
+ }
1752
+ const merged = { ...base.config, ...raw };
1753
+ servers.set(name, { ...base, config: merged, override: projectPath });
1754
+ }
1755
+ function applyProjectEntry(servers, problems, name, config, projectPath) {
1756
+ const clash = [...servers.keys()].find(
1757
+ (other) => other !== name && canonical(other) === canonical(name)
1758
+ );
1759
+ if (clash) {
1760
+ problems.push({
1761
+ server: name,
1762
+ message: `conflicts with "${clash}" (names differ only in "-"/"_")`
1763
+ });
1764
+ return;
1765
+ }
1766
+ servers.set(name, { name, config, source: projectPath, scope: "project" });
1767
+ }
1768
+ function loadUserServers(parsed, userPath, servers, problems) {
1769
+ for (const p of parsed.problems) problems.push(p);
1770
+ for (const { name, config } of parsed.servers) {
1771
+ servers.set(name, { name, config, source: userPath, scope: "user" });
1772
+ }
1773
+ }
1774
+ function loadProjectServers(parsed, projectPath, servers, problems) {
1775
+ for (const p of parsed.problems) problems.push(p);
1776
+ for (const { name, raw } of parsed.overrides) {
1777
+ applyOverride(servers, problems, name, raw, projectPath);
1778
+ }
1779
+ for (const { name, config } of parsed.servers) {
1780
+ applyProjectEntry(servers, problems, name, config, projectPath);
1781
+ }
1782
+ }
1783
+ async function loadConfig(input) {
1784
+ const servers = /* @__PURE__ */ new Map();
1785
+ const problems = [];
1786
+ let autoEnableCodemode;
1787
+ const userText = await readFile(input.fs, input.userPath);
1788
+ if (userText !== void 0) {
1789
+ const parsed = parseMcpJson(userText);
1790
+ if (parsed.autoEnableCodemode !== void 0) autoEnableCodemode = parsed.autoEnableCodemode;
1791
+ loadUserServers(parsed, input.userPath, servers, problems);
1792
+ }
1793
+ if (input.projectPath && input.trustProject) {
1794
+ const projectText = await readFile(input.fs, input.projectPath);
1795
+ if (projectText !== void 0) {
1796
+ const parsed = parseMcpJson(projectText);
1797
+ if (parsed.autoEnableCodemode !== void 0) autoEnableCodemode = parsed.autoEnableCodemode;
1798
+ loadProjectServers(parsed, input.projectPath, servers, problems);
1799
+ }
1800
+ }
1801
+ return {
1802
+ servers: [...servers.values()],
1803
+ problems,
1804
+ ...autoEnableCodemode !== void 0 ? { autoEnableCodemode } : {}
1805
+ };
1806
+ }
1807
+
1808
+ // src/config/paths.ts
1809
+ function userConfigDir(platform) {
1810
+ const piDir = platform.env.PI_CODING_AGENT_DIR;
1811
+ if (piDir) return piDir;
1812
+ const home = platform.env.HOME ?? platform.env.USERPROFILE ?? "/";
1813
+ return `${home}/.pi/agent`;
1814
+ }
1815
+ function userConfigPath(platform) {
1816
+ return `${userConfigDir(platform)}/mcp.json`;
1817
+ }
1818
+ function projectConfigPath(platform) {
1819
+ return `${platform.cwd}/.pi/mcp.json`;
1820
+ }
1821
+
1822
+ // src/config/index.ts
1823
+ var MergedConfigSource = class _MergedConfigSource {
1824
+ entries;
1825
+ config;
1826
+ constructor(config) {
1827
+ this.config = config;
1828
+ this.entries = /* @__PURE__ */ new Map();
1829
+ for (const entry of config.servers) {
1830
+ this.entries.set(entry.name, entry);
1831
+ }
1832
+ }
1833
+ async get(name) {
1834
+ const normalizedName = name.replace(/[-_]/g, "").toLowerCase();
1835
+ for (const [key, entry] of this.entries) {
1836
+ if (key.replace(/[-_]/g, "").toLowerCase() === normalizedName) {
1837
+ return entry.config;
1838
+ }
1839
+ }
1840
+ return void 0;
1841
+ }
1842
+ entry(name) {
1843
+ return this.entries.get(name);
1844
+ }
1845
+ list() {
1846
+ return [...this.entries.values()];
1847
+ }
1848
+ static async load(platform, options) {
1849
+ const userPath = options?.configFile ?? userConfigPath(platform);
1850
+ const projectPath = options?.configFile ? void 0 : projectConfigPath(platform);
1851
+ const config = await loadConfig({
1852
+ userPath,
1853
+ projectPath,
1854
+ trustProject: options?.trustProject ?? false,
1855
+ fs: platform.fs
1856
+ });
1857
+ return new _MergedConfigSource(config);
1858
+ }
1859
+ };
1860
+
1861
+ // src/config/expand.ts
1862
+ var PLACEHOLDER = /\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g;
1863
+ var PLACEHOLDER_TEST = /\$\{[A-Za-z_][A-Za-z0-9_]*\}/;
1864
+ function containsPlaceholders(value) {
1865
+ return PLACEHOLDER_TEST.test(value);
1866
+ }
1867
+ function expandPlaceholdersStrict(value, env) {
1868
+ let hasUndefined = false;
1869
+ const result = value.replace(PLACEHOLDER, (_, name) => {
1870
+ if (env[name] === void 0) {
1871
+ hasUndefined = true;
1872
+ return "";
1873
+ }
1874
+ return env[name];
1875
+ });
1876
+ if (hasUndefined) return void 0;
1877
+ return result;
1878
+ }
1879
+
1880
+ // src/serve/catalog.ts
1881
+ var NAME_RE = /^[A-Za-z][\w-]*$/;
1882
+ function sanitizeName(raw) {
1883
+ const cleaned = raw.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "");
1884
+ return cleaned || "cli";
1885
+ }
1886
+ function cliPrefix(help, filePath, explicit) {
1887
+ if (explicit) return sanitizeName(explicit);
1888
+ const fromUsage = usageProgramName(help);
1889
+ if (fromUsage) return sanitizeName(fromUsage);
1890
+ const base = filePath.split("/").pop() ?? filePath;
1891
+ return sanitizeName(base.replace(/\.jsh$/i, ""));
1892
+ }
1893
+ function parseHelp(help) {
1894
+ const block = commandsFromBlock(help);
1895
+ const program = usageProgramName(help);
1896
+ const commands = mergeCommandLists(block.commands, usageCommands(help, program));
1546
1897
  return {
1547
- async get(name) {
1898
+ ...program ? { program } : {},
1899
+ commands: applyScopedFlags(commands, block.scoped),
1900
+ globalFlags: block.globalFlags
1901
+ };
1902
+ }
1903
+ function isGroupCandidate(command) {
1904
+ return command.path.length === 1 && command.positionals.length === 0 && command.flags.length === 0;
1905
+ }
1906
+ function nestGroup(commands, group, nested, topNames) {
1907
+ const children = attachGlobalFlags(nested.commands, nested.globalFlags);
1908
+ if (children.length === 0) return null;
1909
+ const childNames = children.map((child) => child.path[0] ?? "");
1910
+ const same = childNames.length === topNames.size && childNames.every((name) => topNames.has(name));
1911
+ if (same) return null;
1912
+ const nestedCommands = children.map((child) => ({ ...child, path: childPath(group, child) }));
1913
+ return commands.filter((command) => command.path[0] !== group).concat(nestedCommands);
1914
+ }
1915
+ function attachGlobalFlags(commands, globalFlags) {
1916
+ if (globalFlags.length === 0) return commands;
1917
+ return commands.map((command) => ({ ...command, flags: mergeFlags(command.flags, globalFlags) }));
1918
+ }
1919
+ function parseMcpOverride(stdout) {
1920
+ let value;
1921
+ try {
1922
+ value = JSON.parse(stdout);
1923
+ } catch {
1924
+ return null;
1925
+ }
1926
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
1927
+ const commandsValue = Object.getOwnPropertyDescriptor(value, "commands")?.value;
1928
+ if (!Array.isArray(commandsValue)) return null;
1929
+ const commands = [];
1930
+ for (const entry of commandsValue) {
1931
+ const command = readMcpCommand(entry);
1932
+ if (command) commands.push(command);
1933
+ }
1934
+ if (commands.length === 0) return null;
1935
+ return { commands, globalFlags: [] };
1936
+ }
1937
+ function buildTools(prefix, commands) {
1938
+ const tools = [
1939
+ {
1940
+ name: `${prefix}_help`,
1941
+ description: `Show ${prefix} help.`,
1942
+ inputSchema: objectSchema({}),
1943
+ cli: prefix,
1944
+ kind: "help",
1945
+ commandPath: []
1946
+ },
1947
+ {
1948
+ name: `${prefix}_invoke`,
1949
+ description: `Run ${prefix} with an argv array (one element per argument) and optional stdin. A non-zero exit is a tool error.`,
1950
+ inputSchema: invokeSchema(),
1951
+ cli: prefix,
1952
+ kind: "invoke",
1953
+ commandPath: []
1954
+ }
1955
+ ];
1956
+ for (const command of commands) {
1957
+ const leaf = command.path.join("_");
1958
+ tools.push({
1959
+ name: `${prefix}_${leaf}`,
1960
+ description: command.description || `Run ${prefix} ${command.path.join(" ")}`,
1961
+ inputSchema: commandSchema(command),
1962
+ cli: prefix,
1963
+ kind: "command",
1964
+ commandPath: command.path
1965
+ });
1966
+ }
1967
+ return tools;
1968
+ }
1969
+ function readToolArguments(input) {
1970
+ if (input === void 0 || input === null) return { fields: [] };
1971
+ if (typeof input !== "object" || Array.isArray(input)) {
1972
+ return { fields: [], error: "arguments must be an object" };
1973
+ }
1974
+ const fields = [];
1975
+ let stdin;
1976
+ let passthrough;
1977
+ let argv;
1978
+ for (const key of Object.keys(input)) {
1979
+ const value = Object.getOwnPropertyDescriptor(input, key)?.value;
1980
+ const read = readArgument(key, value);
1981
+ if (read.error) return { fields, error: read.error };
1982
+ if (read.stdin !== void 0) stdin = read.stdin;
1983
+ else if (read.passthrough) passthrough = read.passthrough;
1984
+ else if (read.argv) argv = read.argv;
1985
+ else if (read.field) fields.push(read.field);
1986
+ }
1987
+ return {
1988
+ fields,
1989
+ ...stdin !== void 0 ? { stdin } : {},
1990
+ ...passthrough ? { passthrough } : {},
1991
+ ...argv ? { argv } : {}
1992
+ };
1993
+ }
1994
+ function argvForCommand(command, args) {
1995
+ if (args.error) return { error: args.error };
1996
+ const argv = [...command.path];
1997
+ for (const positional of command.positionals) {
1998
+ const found = args.fields.find((field) => field.name === positional.name);
1999
+ if (!found) {
2000
+ if (positional.required) return { error: `missing ${positional.name}` };
2001
+ continue;
2002
+ }
2003
+ if (typeof found.value !== "string" && typeof found.value !== "number") {
2004
+ return { error: `${positional.name} must be a string` };
2005
+ }
2006
+ argv.push(String(found.value));
2007
+ }
2008
+ const flags = appendFlags(command.flags, args.fields);
2009
+ if ("error" in flags) return flags;
2010
+ argv.push(...flags.argv);
2011
+ if (args.passthrough) argv.push(...args.passthrough);
2012
+ return { argv, ...args.stdin !== void 0 ? { stdin: args.stdin } : {} };
2013
+ }
2014
+ function appendFlags(flags, fields) {
2015
+ const argv = [];
2016
+ for (const flag of flags) {
2017
+ const found = fields.find((field) => field.name === flag.name);
2018
+ if (!found || found.value === false) continue;
2019
+ const encoded = encodeFlag(flag, found.value);
2020
+ if ("error" in encoded) return encoded;
2021
+ argv.push(...encoded.argv);
2022
+ }
2023
+ return { argv };
2024
+ }
2025
+ function encodeFlag(flag, value) {
2026
+ if (flag.type === "boolean") {
2027
+ return value === true ? { argv: [`--${flag.name}`] } : { argv: [] };
2028
+ }
2029
+ if (flag.type === "string[]") {
2030
+ if (!Array.isArray(value)) return { error: `${flag.name} must be an array of strings` };
2031
+ const argv = [];
2032
+ for (const item of value) argv.push(`--${flag.name}`, item);
2033
+ return { argv };
2034
+ }
2035
+ if (typeof value !== "string" && typeof value !== "number") {
2036
+ return { error: `${flag.name} must be a string` };
2037
+ }
2038
+ return { argv: [`--${flag.name}`, String(value)] };
2039
+ }
2040
+ function commandsFromBlock(help) {
2041
+ let section = "none";
2042
+ const commands = [];
2043
+ const globalFlags = [];
2044
+ const scoped = [];
2045
+ for (const rawLine of help.split("\n")) {
2046
+ const line = rawLine.replace(/\t/g, " ");
2047
+ const header = classifyHeader(line);
2048
+ if (header) {
2049
+ section = header.kind === "other" ? "none" : header.kind;
2050
+ if (header.kind === "scoped" && header.name) scoped.push({ name: header.name, flags: [] });
2051
+ continue;
2052
+ }
2053
+ pushSectionLine(section, line, commands, globalFlags, scoped);
2054
+ }
2055
+ return { commands, globalFlags, scoped };
2056
+ }
2057
+ function pushSectionLine(section, line, commands, globalFlags, scoped) {
2058
+ if (section === "commands") {
2059
+ const command = parseCommandLine(line);
2060
+ if (command) commands.push(command);
2061
+ return;
2062
+ }
2063
+ const flag = parseFlagLine(line);
2064
+ if (!flag) return;
2065
+ if (section === "options") globalFlags.push(flag);
2066
+ if (section === "scoped") scoped[scoped.length - 1]?.flags.push(flag);
2067
+ }
2068
+ function classifyHeader(line) {
2069
+ const text = line.trim();
2070
+ if (/^commands:?$/i.test(text)) return { kind: "commands" };
2071
+ if (/^options:?$/i.test(text)) return { kind: "options" };
2072
+ const flags = /^([A-Za-z][\w-]*)\s+flags:?$/i.exec(text);
2073
+ if (flags?.[1]) return { kind: "scoped", name: flags[1].toLowerCase() };
2074
+ if (/^[A-Z][A-Z0-9 ]+:$/.test(text)) return { kind: "other" };
2075
+ return null;
2076
+ }
2077
+ function parseCommandLine(line) {
2078
+ if (!/^\s{2,}\S/.test(line)) return null;
2079
+ const parts = line.trim().split(/\s{2,}/);
2080
+ if (parts.length < 2) return null;
2081
+ const tokens = tokenize(parts[0] ?? "");
2082
+ const name = tokens[0] ?? "";
2083
+ if (!NAME_RE.test(name) || name.startsWith("-")) return null;
2084
+ const spec = emptySpec();
2085
+ for (const token of tokens.slice(1)) parseUsageToken(token, spec);
2086
+ return {
2087
+ path: [name],
2088
+ description: parts.slice(1).join(" ").trim(),
2089
+ positionals: spec.positionals,
2090
+ flags: spec.flags
2091
+ };
2092
+ }
2093
+ function usageProgramName(help) {
2094
+ for (const raw of help.split("\n")) {
2095
+ if (!/^[\s>*]*usage:/i.test(raw)) continue;
2096
+ const tokens = tokenize(raw);
2097
+ const name = tokens[0];
2098
+ if (name && NAME_RE.test(name)) return name;
2099
+ }
2100
+ return void 0;
2101
+ }
2102
+ function usageCommands(help, program) {
2103
+ const commands = [];
2104
+ for (const raw of help.split("\n")) {
2105
+ const command = usageCommand(raw, program);
2106
+ if (command) commands.push(command);
2107
+ }
2108
+ return commands;
2109
+ }
2110
+ function isCommandSlot(token) {
2111
+ const inner = token.replace(/^\[|\]$/g, "").replace(/^<|>$/g, "").toLowerCase();
2112
+ return inner === "command" || inner === "cmd" || inner === "subcommand" || inner === "verb";
2113
+ }
2114
+ function usageCommand(raw, program) {
2115
+ const line = raw.trim();
2116
+ const tokens = tokenize(line);
2117
+ if (tokens.length < 2) return null;
2118
+ const isUsage = /^usage:/i.test(line);
2119
+ if (!isUsage && tokens[0] !== program) return null;
2120
+ const path = [];
2121
+ let index = 1;
2122
+ while (index < tokens.length && path.length < 2 && NAME_RE.test(tokens[index] ?? "")) {
2123
+ path.push(tokens[index] ?? "");
2124
+ index++;
2125
+ }
2126
+ if (path.length === 0) return null;
2127
+ if (isCommandSlot(tokens[index] ?? "")) return null;
2128
+ const spec = emptySpec();
2129
+ for (const token of tokens.slice(index)) parseUsageToken(token, spec);
2130
+ return { path, description: "", positionals: spec.positionals, flags: spec.flags };
2131
+ }
2132
+ function emptySpec() {
2133
+ return { positionals: [], flags: [] };
2134
+ }
2135
+ function parseUsageToken(token, into) {
2136
+ const optional = token.startsWith("[") && token.endsWith("]");
2137
+ const inner = optional ? token.slice(1, -1).trim() : token;
2138
+ if (inner.startsWith("--")) {
2139
+ const flag = parseFlagToken(inner);
2140
+ if (flag) into.flags.push(flag);
2141
+ return;
2142
+ }
2143
+ if (inner.startsWith("<") && inner.endsWith(">")) {
2144
+ into.positionals.push({
2145
+ name: cleanName(inner.slice(1, -1)),
2146
+ required: !optional,
2147
+ description: ""
2148
+ });
2149
+ return;
2150
+ }
2151
+ if (NAME_RE.test(inner)) {
2152
+ into.positionals.push({ name: cleanName(inner), required: !optional, description: "" });
2153
+ }
2154
+ }
2155
+ function parseFlagToken(inner) {
2156
+ const match = /^--([A-Za-z][\w-]*)(?:(?:=|\s+)(\S+))?$/.exec(inner.trim());
2157
+ if (!match?.[1]) return null;
2158
+ const value = match[2] ?? "";
2159
+ if (!value) return { name: match[1], type: "boolean", description: "" };
2160
+ return { name: match[1], type: value.includes("...") ? "string[]" : "string", description: "" };
2161
+ }
2162
+ function parseFlagLine(line) {
2163
+ const trimmed = line.trim();
2164
+ if (!trimmed.includes("--")) return null;
2165
+ const match = /--([A-Za-z][\w-]*)(?:=(\S+)|(?:\s+(<[^>]+>|\[[^\]]+\]|[A-Z][A-Z0-9_-]+)))?/.exec(
2166
+ trimmed
2167
+ );
2168
+ if (!match?.[1]) return null;
2169
+ const value = match[2] || match[3] || "";
2170
+ const repeatable = /\brepeat|\.\.\.|one or more/i.test(trimmed);
2171
+ const description = flagDescription(trimmed);
2172
+ if (!value && !repeatable) return { name: match[1], type: "boolean", description };
2173
+ return { name: match[1], type: repeatable ? "string[]" : "string", description };
2174
+ }
2175
+ function flagDescription(line) {
2176
+ const parts = line.trim().split(/\s{2,}/);
2177
+ return parts.length > 1 ? parts.slice(1).join(" ").trim() : "";
2178
+ }
2179
+ function tokenize(line) {
2180
+ const source = line.trim().replace(/^usage:\s*/i, "");
2181
+ const tokens = [];
2182
+ let index = 0;
2183
+ while (index < source.length) {
2184
+ if (source[index] === " ") {
2185
+ index++;
2186
+ continue;
2187
+ }
2188
+ const closer = source[index] === "[" ? "]" : source[index] === "<" ? ">" : "";
2189
+ if (closer) {
2190
+ const end = source.indexOf(closer, index);
2191
+ if (end === -1) {
2192
+ tokens.push(source.slice(index));
2193
+ break;
2194
+ }
2195
+ tokens.push(source.slice(index, end + 1));
2196
+ index = end + 1;
2197
+ continue;
2198
+ }
2199
+ const next = source.indexOf(" ", index);
2200
+ if (next === -1) {
2201
+ tokens.push(source.slice(index));
2202
+ break;
2203
+ }
2204
+ tokens.push(source.slice(index, next));
2205
+ index = next;
2206
+ }
2207
+ return tokens;
2208
+ }
2209
+ function mergeCommandLists(primary, extra) {
2210
+ const merged = primary.map((command) => ({ ...command }));
2211
+ for (const command of extra) {
2212
+ const existing = merged.find((item) => samePath(item.path, command.path));
2213
+ if (!existing) {
2214
+ merged.push(command);
2215
+ continue;
2216
+ }
2217
+ if (existing.positionals.length === 0) existing.positionals = command.positionals;
2218
+ if (!existing.description) existing.description = command.description;
2219
+ existing.flags = mergeFlags(existing.flags, command.flags);
2220
+ }
2221
+ return merged;
2222
+ }
2223
+ function applyScopedFlags(commands, scoped) {
2224
+ return commands.map((command) => {
2225
+ const extra = scoped.find((scope) => scope.name === (command.path[0] ?? "").toLowerCase());
2226
+ if (!extra) return command;
2227
+ return { ...command, flags: mergeFlags(command.flags, extra.flags) };
2228
+ });
2229
+ }
2230
+ function mergeFlags(left, right) {
2231
+ const merged = [...left];
2232
+ for (const flag of right) {
2233
+ if (!merged.some((existing) => existing.name === flag.name)) merged.push(flag);
2234
+ }
2235
+ return merged;
2236
+ }
2237
+ function samePath(left, right) {
2238
+ return left.length === right.length && left.every((part, index) => part === right[index]);
2239
+ }
2240
+ function childPath(group, child) {
2241
+ if (child.path[0] === group) return child.path.slice(0, 2);
2242
+ return [group, child.path[0] ?? ""].filter((part) => part.length > 0).slice(0, 2);
2243
+ }
2244
+ function cleanName(raw) {
2245
+ const cleaned = raw.replace(/[^A-Za-z0-9_-]+/g, "").replace(/^-+/, "");
2246
+ return cleaned || "arg";
2247
+ }
2248
+ function readMcpCommand(value) {
2249
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
2250
+ const name = ownString(value, "name");
2251
+ if (!name) return null;
2252
+ const path = name.split(/\s+/).filter((part) => NAME_RE.test(part)).slice(0, 2);
2253
+ if (path.length === 0) return null;
2254
+ return {
2255
+ path,
2256
+ description: ownString(value, "description") ?? "",
2257
+ positionals: readMcpPositionals(Object.getOwnPropertyDescriptor(value, "positionals")?.value),
2258
+ flags: readMcpFlags(Object.getOwnPropertyDescriptor(value, "flags")?.value)
2259
+ };
2260
+ }
2261
+ function readMcpPositionals(value) {
2262
+ if (!Array.isArray(value)) return [];
2263
+ const positionals = [];
2264
+ for (const entry of value) {
2265
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
2266
+ const name = ownString(entry, "name");
2267
+ if (!name) continue;
2268
+ const required = Object.getOwnPropertyDescriptor(entry, "required")?.value;
2269
+ positionals.push({ name, required: required !== false, description: "" });
2270
+ }
2271
+ return positionals;
2272
+ }
2273
+ function readMcpFlags(value) {
2274
+ if (!Array.isArray(value)) return [];
2275
+ const flags = [];
2276
+ for (const entry of value) {
2277
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
2278
+ const name = ownString(entry, "name");
2279
+ const type = ownString(entry, "type");
2280
+ if (!name || type !== "boolean" && type !== "string" && type !== "string[]") continue;
2281
+ flags.push({ name, type, description: "" });
2282
+ }
2283
+ return flags;
2284
+ }
2285
+ function ownString(value, key) {
2286
+ const found = Object.getOwnPropertyDescriptor(value, key)?.value;
2287
+ return typeof found === "string" && found.length > 0 ? found : void 0;
2288
+ }
2289
+ function objectSchema(properties, required) {
2290
+ return {
2291
+ type: "object",
2292
+ properties,
2293
+ additionalProperties: false,
2294
+ ...required && required.length > 0 ? { required } : {}
2295
+ };
2296
+ }
2297
+ function invokeSchema() {
2298
+ return objectSchema(
2299
+ {
2300
+ argv: {
2301
+ type: "array",
2302
+ items: { type: "string" },
2303
+ description: "Arguments, one element per argument. Never a shell string."
2304
+ },
2305
+ stdin: { type: "string", description: "Optional standard input." }
2306
+ },
2307
+ ["argv"]
2308
+ );
2309
+ }
2310
+ function commandSchema(command) {
2311
+ const properties = {};
2312
+ const required = [];
2313
+ for (const positional of command.positionals) {
2314
+ properties[positional.name] = {
2315
+ type: "string",
2316
+ description: positional.description || positional.name
2317
+ };
2318
+ if (positional.required) required.push(positional.name);
2319
+ }
2320
+ for (const flag of command.flags) {
2321
+ properties[flag.name] = flagProperty(flag);
2322
+ }
2323
+ properties.stdin = { type: "string", description: "Optional standard input." };
2324
+ properties.passthrough = {
2325
+ type: "array",
2326
+ items: { type: "string" },
2327
+ description: "Extra arguments appended as-is."
2328
+ };
2329
+ return objectSchema(properties, required);
2330
+ }
2331
+ function flagProperty(flag) {
2332
+ if (flag.type === "boolean")
2333
+ return { type: "boolean", description: flag.description || flag.name };
2334
+ if (flag.type === "string[]") {
2335
+ return { type: "array", items: { type: "string" }, description: flag.description || flag.name };
2336
+ }
2337
+ return { type: "string", description: flag.description || flag.name };
2338
+ }
2339
+ function readArgument(key, value) {
2340
+ if (key === "stdin") {
2341
+ return typeof value === "string" ? { stdin: value } : { error: "stdin must be a string" };
2342
+ }
2343
+ if (key === "passthrough") return readStringArray(value, "passthrough");
2344
+ if (key === "argv") {
2345
+ const read = readStringArray(value, "argv");
2346
+ return read.passthrough ? { argv: read.passthrough } : read;
2347
+ }
2348
+ if (!isArgValue(value)) return { error: `${key} has an unsupported type` };
2349
+ return { field: { name: key, value } };
2350
+ }
2351
+ function readStringArray(value, label) {
2352
+ if (!Array.isArray(value) || !value.every((item) => typeof item === "string")) {
2353
+ return { error: `${label} must be an array of strings` };
2354
+ }
2355
+ return { passthrough: value };
2356
+ }
2357
+ function isArgValue(value) {
2358
+ if (typeof value === "string" || typeof value === "boolean" || typeof value === "number")
2359
+ return true;
2360
+ return Array.isArray(value) && value.every((item) => typeof item === "string");
2361
+ }
2362
+ function parseToolTemplate(spec) {
2363
+ const colonIdx = spec.indexOf(":");
2364
+ if (colonIdx <= 0) return null;
2365
+ const name = spec.slice(0, colonIdx).trim();
2366
+ const template = spec.slice(colonIdx + 1).trim();
2367
+ if (!name || !template) return null;
2368
+ const placeholders = [];
2369
+ const re = /\{(\w+)\}/g;
2370
+ let m;
2371
+ while ((m = re.exec(template)) !== null) {
2372
+ if (!placeholders.includes(m[1])) placeholders.push(m[1]);
2373
+ }
2374
+ const properties = {};
2375
+ for (const ph of placeholders) {
2376
+ properties[ph] = { type: "string", description: ph };
2377
+ }
2378
+ return {
2379
+ name,
2380
+ description: template,
2381
+ inputSchema: {
2382
+ type: "object",
2383
+ properties,
2384
+ required: placeholders,
2385
+ additionalProperties: false
2386
+ },
2387
+ cli: "",
2388
+ kind: "command",
2389
+ commandPath: []
2390
+ };
2391
+ }
2392
+ function templateToArgv(template, args) {
2393
+ let expanded = template;
2394
+ for (const [key, value] of Object.entries(args)) {
2395
+ expanded = expanded.replaceAll(`{${key}}`, value);
2396
+ }
2397
+ return expanded.split(/\s+/).filter(Boolean);
2398
+ }
2399
+
2400
+ // src/serve/http.ts
2401
+ var encoder = new TextEncoder();
2402
+ var decoder = new TextDecoder();
2403
+ var MAX_HEADER_SIZE = 16384;
2404
+ var MAX_BODY_SIZE = 10485760;
2405
+ async function readUntil(reader, buf, bufLen, sentinel, maxSize) {
2406
+ for (; ; ) {
2407
+ const text = decoder.decode(new Uint8Array(buf.buffer, buf.byteOffset, bufLen));
2408
+ const pos = text.indexOf(sentinel);
2409
+ if (pos >= 0) return { buf, bufLen, pos };
2410
+ if (bufLen >= maxSize) return null;
2411
+ const { done, value } = await reader.read();
2412
+ if (done) return null;
2413
+ if (bufLen + value.length > buf.length) {
2414
+ const newBuf = new Uint8Array(Math.max(buf.length * 2, bufLen + value.length));
2415
+ newBuf.set(new Uint8Array(buf.buffer, buf.byteOffset, bufLen));
2416
+ buf = newBuf;
2417
+ }
2418
+ buf.set(value, bufLen);
2419
+ bufLen += value.length;
2420
+ }
2421
+ }
2422
+ async function readExact(reader, buf, bufLen, needed) {
2423
+ while (bufLen < needed) {
2424
+ const { done, value } = await reader.read();
2425
+ if (done) return null;
2426
+ if (bufLen + value.length > buf.length) {
2427
+ const newBuf = new Uint8Array(Math.max(buf.length * 2, bufLen + value.length));
2428
+ newBuf.set(new Uint8Array(buf.buffer, buf.byteOffset, bufLen));
2429
+ buf = newBuf;
2430
+ }
2431
+ buf.set(value, bufLen);
2432
+ bufLen += value.length;
2433
+ }
2434
+ return { buf, bufLen };
2435
+ }
2436
+ function parseRequestLine(buf, endPos) {
2437
+ const headText = decoder.decode(new Uint8Array(buf.buffer, buf.byteOffset, endPos));
2438
+ const lines = headText.split("\r\n");
2439
+ const requestLine = lines[0];
2440
+ if (!requestLine) return null;
2441
+ const parts = requestLine.split(" ");
2442
+ if (parts.length < 2) return null;
2443
+ const method = parts[0];
2444
+ const target = parts[1];
2445
+ const headers = {};
2446
+ for (let i = 1; i < lines.length; i++) {
2447
+ const line = lines[i];
2448
+ if (!line) continue;
2449
+ const colonIdx = line.indexOf(":");
2450
+ if (colonIdx <= 0) continue;
2451
+ headers[line.slice(0, colonIdx).trim().toLowerCase()] = line.slice(colonIdx + 1).trim();
2452
+ }
2453
+ return { method, target, headers, headerEnd: endPos + 4 };
2454
+ }
2455
+ async function handleConnection(readable, writable, handler) {
2456
+ const reader = readable.getReader();
2457
+ const writer = writable.getWriter();
2458
+ let buf = new Uint8Array(4096);
2459
+ let bufLen = 0;
2460
+ try {
2461
+ for (; ; ) {
2462
+ const headerResult = await readUntil(reader, buf, bufLen, "\r\n\r\n", MAX_HEADER_SIZE);
2463
+ if (!headerResult) break;
2464
+ buf = headerResult.buf;
2465
+ bufLen = headerResult.bufLen;
2466
+ const parsed = parseRequestLine(buf, headerResult.pos);
2467
+ if (!parsed) {
2468
+ await writeResponse(writer, {
2469
+ status: 400,
2470
+ reason: "Bad Request",
2471
+ headers: { "content-type": "text/plain" },
2472
+ body: "Bad Request"
2473
+ });
2474
+ break;
2475
+ }
2476
+ const contentLength = Number(parsed.headers["content-length"] ?? 0);
2477
+ if (contentLength > MAX_BODY_SIZE) {
2478
+ await writeResponse(writer, {
2479
+ status: 413,
2480
+ reason: "Payload Too Large",
2481
+ headers: { "content-type": "text/plain" },
2482
+ body: "Payload Too Large"
2483
+ });
2484
+ break;
2485
+ }
2486
+ const bodyStart = parsed.headerEnd;
2487
+ const totalNeeded = bodyStart + contentLength;
2488
+ const bodyResult = await readExact(reader, buf, bufLen, totalNeeded);
2489
+ if (!bodyResult && contentLength > 0) break;
2490
+ if (bodyResult) {
2491
+ buf = bodyResult.buf;
2492
+ bufLen = bodyResult.bufLen;
2493
+ }
2494
+ const bodyBytes = buf.slice(bodyStart, bodyStart + contentLength);
2495
+ const body = decoder.decode(bodyBytes);
2496
+ const request = {
2497
+ method: parsed.method,
2498
+ target: parsed.target,
2499
+ headers: parsed.headers,
2500
+ body
2501
+ };
2502
+ const response = await handler(request);
2503
+ await writeResponse(writer, response);
2504
+ const connectionHeader = (parsed.headers.connection ?? "").toLowerCase();
2505
+ if (connectionHeader === "close") break;
2506
+ const consumed = bodyStart + contentLength;
2507
+ const remaining = bufLen - consumed;
2508
+ if (remaining > 0) {
2509
+ const newBuf = new Uint8Array(Math.max(4096, remaining));
2510
+ newBuf.set(new Uint8Array(buf.buffer, buf.byteOffset + consumed, remaining));
2511
+ buf = newBuf;
2512
+ bufLen = remaining;
2513
+ } else {
2514
+ buf = new Uint8Array(4096);
2515
+ bufLen = 0;
2516
+ }
2517
+ }
2518
+ } finally {
2519
+ reader.releaseLock();
2520
+ try {
2521
+ await writer.close();
2522
+ } catch {
2523
+ }
2524
+ }
2525
+ }
2526
+ async function writeResponse(writer, response) {
2527
+ const bodyLength = new TextEncoder().encode(response.body).length;
2528
+ const headers = { ...response.headers, "content-length": String(bodyLength) };
2529
+ const lines = [`HTTP/1.1 ${response.status} ${response.reason}`];
2530
+ for (const [name, value] of Object.entries(headers)) {
2531
+ lines.push(`${name}: ${value}`);
2532
+ }
2533
+ lines.push("", "");
2534
+ const headBytes = encoder.encode(lines.join("\r\n"));
2535
+ await writer.write(headBytes);
2536
+ if (response.body.length > 0) {
2537
+ const bodyBytes = encoder.encode(response.body);
2538
+ await writer.write(bodyBytes);
2539
+ }
2540
+ }
2541
+
2542
+ // src/serve/jsonrpc.ts
2543
+ var PROTOCOL_VERSIONS = ["2026-07-28", "2025-11-25", "2025-06-18"];
2544
+ var OUTPUT_CAP = 1048576;
2545
+ var JSON_CT = "application/json; charset=utf-8";
2546
+ async function handleJsonRpc(raw, tools, call, serverName, serverVersion) {
2547
+ let parsed;
2548
+ try {
2549
+ parsed = JSON.parse(raw);
2550
+ } catch {
2551
+ return rpcError(null, -32700, "Parse error");
2552
+ }
2553
+ if (Array.isArray(parsed)) return rpcError(null, -32600, "Batch requests are not supported");
2554
+ if (!parsed || typeof parsed !== "object") return rpcError(null, -32600, "Invalid request");
2555
+ const method = readString(parsed, "method");
2556
+ if (!method) return rpcError(readId(parsed), -32600, "Invalid request");
2557
+ if (!hasOwn(parsed, "id")) return { status: 202, contentType: "text/plain", body: "" };
2558
+ const id = readId(parsed);
2559
+ const params = Object.getOwnPropertyDescriptor(parsed, "params")?.value;
2560
+ if (method === "initialize")
2561
+ return rpcOk(id, initializeResult(params, serverName, serverVersion));
2562
+ if (method === "server/discover") return rpcOk(id, discoverResult(serverName, serverVersion));
2563
+ if (method === "tools/list") return rpcOk(id, { tools });
2564
+ if (method === "ping") return rpcOk(id, {});
2565
+ if (method === "tools/call") return toolCall(id, params, tools, call);
2566
+ return rpcError(id, -32601, `Method not found: ${method}`);
2567
+ }
2568
+ async function toolCall(id, params, tools, call) {
2569
+ const name = params && typeof params === "object" ? readString(params, "name") : void 0;
2570
+ if (!name) return rpcError(id, -32602, "tools/call requires a name");
2571
+ if (!tools.some((tool) => tool.name === name))
2572
+ return rpcError(id, -32602, `Unknown tool: ${name}`);
2573
+ const args = params && typeof params === "object" ? Object.getOwnPropertyDescriptor(params, "arguments")?.value : void 0;
2574
+ try {
2575
+ const result = await call(name, args);
2576
+ return rpcOk(id, toolResult(result));
2577
+ } catch (err) {
2578
+ const message = err instanceof Error ? err.message : "tool call failed";
2579
+ return rpcError(id, -32e3, message);
2580
+ }
2581
+ }
2582
+ function toolResult(result) {
2583
+ const stdout = cap(result.stdout);
2584
+ const stderr = cap(result.stderr);
2585
+ const text = stderr ? stdout ? `${stdout}
2586
+ ${stderr}` : stderr : stdout;
2587
+ return {
2588
+ content: [{ type: "text", text }],
2589
+ isError: result.exitCode !== 0,
2590
+ structuredContent: { stdout, stderr, exitCode: result.exitCode }
2591
+ };
2592
+ }
2593
+ function initializeResult(params, serverName, serverVersion) {
2594
+ const requested = params && typeof params === "object" ? readString(params, "protocolVersion") : void 0;
2595
+ const protocolVersion = PROTOCOL_VERSIONS.find((version) => version === requested) ?? PROTOCOL_VERSIONS[0];
2596
+ return {
2597
+ protocolVersion,
2598
+ capabilities: { tools: { listChanged: false } },
2599
+ serverInfo: { name: serverName, version: serverVersion }
2600
+ };
2601
+ }
2602
+ function discoverResult(serverName, serverVersion) {
2603
+ return {
2604
+ protocolVersion: PROTOCOL_VERSIONS[0],
2605
+ supportedVersions: PROTOCOL_VERSIONS,
2606
+ capabilities: { tools: { listChanged: false } },
2607
+ serverInfo: { name: serverName, version: serverVersion }
2608
+ };
2609
+ }
2610
+ function cap(value) {
2611
+ if (value.length <= OUTPUT_CAP) return value;
2612
+ const half = Math.floor(OUTPUT_CAP / 2);
2613
+ const cut = value.length - OUTPUT_CAP;
2614
+ return `${value.slice(0, half)}
2615
+ \u2026 ${cut} characters cut \u2026
2616
+ ${value.slice(value.length - half)}`;
2617
+ }
2618
+ function rpcOk(id, result) {
2619
+ return {
2620
+ status: 200,
2621
+ contentType: JSON_CT,
2622
+ body: JSON.stringify({ jsonrpc: "2.0", id, result })
2623
+ };
2624
+ }
2625
+ function rpcError(id, code, message) {
2626
+ return {
2627
+ status: 200,
2628
+ contentType: JSON_CT,
2629
+ body: JSON.stringify({ jsonrpc: "2.0", id, error: { code, message } })
2630
+ };
2631
+ }
2632
+ function readId(value) {
2633
+ const id = Object.getOwnPropertyDescriptor(value, "id")?.value;
2634
+ if (typeof id === "string" || typeof id === "number" || id === null) return id;
2635
+ return null;
2636
+ }
2637
+ function readString(value, key) {
2638
+ const found = Object.getOwnPropertyDescriptor(value, key)?.value;
2639
+ return typeof found === "string" ? found : void 0;
2640
+ }
2641
+ function hasOwn(value, key) {
2642
+ return Object.prototype.hasOwnProperty.call(value, key);
2643
+ }
2644
+
2645
+ // src/serve/origin.ts
2646
+ var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]"]);
2647
+ function isLoopbackOrigin(origin) {
2648
+ try {
2649
+ const url = new URL(origin);
2650
+ const hostname = url.hostname;
2651
+ if (LOOPBACK_HOSTS.has(hostname)) return true;
2652
+ if (hostname === "::1") return true;
2653
+ if (hostname.endsWith(".localhost")) return true;
2654
+ return false;
2655
+ } catch {
2656
+ return false;
2657
+ }
2658
+ }
2659
+ function isLoopbackHost(host) {
2660
+ const hostname = host.replace(/:\d+$/, "");
2661
+ if (LOOPBACK_HOSTS.has(hostname)) return true;
2662
+ if (hostname === "::1") return true;
2663
+ if (hostname.endsWith(".localhost")) return true;
2664
+ return false;
2665
+ }
2666
+ function checkOrigin(origin, allowedOrigins, boundLoopback) {
2667
+ if (origin === void 0) return { ok: true };
2668
+ if (allowedOrigins.has(origin)) return { ok: true };
2669
+ if (isLoopbackOrigin(origin)) return { ok: true };
2670
+ if (!boundLoopback) return { ok: true };
2671
+ return { ok: false, reason: `origin ${origin} is not allowed` };
2672
+ }
2673
+ function checkHost(host, boundLoopback) {
2674
+ if (!boundLoopback) return { ok: true };
2675
+ if (!host) return { ok: false, reason: "missing Host header" };
2676
+ if (isLoopbackHost(host)) return { ok: true };
2677
+ return { ok: false, reason: `host ${host} is not loopback` };
2678
+ }
2679
+
2680
+ // src/serve/runtime.ts
2681
+ var CALL_TIMEOUT_MS = 12e4;
2682
+ var MAX_OUTPUT_DEFAULT = 1048576;
2683
+ var ALLOWED_ENV_KEYS = /* @__PURE__ */ new Set(["PATH", "HOME", "LANG"]);
2684
+ function parseHttpFlag(args, i) {
2685
+ const next = args[i + 1];
2686
+ if (!next || next.startsWith("-")) return { host: "127.0.0.1", port: 0, next: i };
2687
+ const colonIdx = next.lastIndexOf(":");
2688
+ if (colonIdx > 0 && colonIdx < next.length - 1) {
2689
+ return { host: next.slice(0, colonIdx), port: Number(next.slice(colonIdx + 1)), next: i + 1 };
2690
+ }
2691
+ return { host: "127.0.0.1", port: Number(next), next: i + 1 };
2692
+ }
2693
+ function parseCommandTarget(arg) {
2694
+ const eqIdx = arg.indexOf("=");
2695
+ if (eqIdx > 0 && !arg.slice(0, eqIdx).includes("/")) {
2696
+ return { name: arg.slice(0, eqIdx), path: arg.slice(eqIdx + 1) };
2697
+ }
2698
+ return { path: arg };
2699
+ }
2700
+ function parseSingleFlag(args, i, opts) {
2701
+ const arg = args[i];
2702
+ if (arg === "--stdio") {
2703
+ opts.transport = "stdio";
2704
+ } else if (arg === "--http") {
2705
+ opts.transport = "http";
2706
+ const parsed = parseHttpFlag(args, i);
2707
+ opts.host = parsed.host;
2708
+ opts.port = parsed.port;
2709
+ return parsed.next;
2710
+ } else if (arg === "--bearer" && args[i + 1]) {
2711
+ opts.bearer = args[++i];
2712
+ } else if (arg === "--allow-origin" && args[i + 1]) {
2713
+ opts.allowOrigins.push(args[++i]);
2714
+ } else if (arg === "--env" && args[i + 1]) {
2715
+ opts.envAllow.push(args[++i]);
2716
+ } else if (arg === "--tool" && args[i + 1]) {
2717
+ opts.toolTemplates.push(args[++i]);
2718
+ } else if (arg === "--call-timeout" && args[i + 1]) {
2719
+ opts.callTimeout = Number(args[++i]) * 1e3;
2720
+ } else if (arg === "--concurrency" && args[i + 1]) {
2721
+ opts.concurrency = Number(args[++i]);
2722
+ } else if (arg === "--max-output" && args[i + 1]) {
2723
+ opts.maxOutput = Number(args[++i]);
2724
+ } else if (arg === "--cwd" && args[i + 1]) {
2725
+ opts.cwd = args[++i];
2726
+ } else if (arg === "--json") {
2727
+ opts.json = true;
2728
+ } else if (!arg.startsWith("-")) {
2729
+ opts.commands.push(parseCommandTarget(arg));
2730
+ }
2731
+ return i;
2732
+ }
2733
+ function parseServeFlags(args) {
2734
+ const opts = {
2735
+ transport: "stdio",
2736
+ host: "127.0.0.1",
2737
+ port: 0,
2738
+ bearer: void 0,
2739
+ allowOrigins: [],
2740
+ envAllow: [],
2741
+ toolTemplates: [],
2742
+ callTimeout: CALL_TIMEOUT_MS,
2743
+ concurrency: 1,
2744
+ maxOutput: MAX_OUTPUT_DEFAULT,
2745
+ cwd: void 0,
2746
+ json: false,
2747
+ commands: []
2748
+ };
2749
+ for (let i = 0; i < args.length; i++) {
2750
+ i = parseSingleFlag(args, i, opts);
2751
+ }
2752
+ return opts;
2753
+ }
2754
+ function expandBearerToken(template, env) {
2755
+ if (!containsPlaceholders(template)) return void 0;
2756
+ return expandPlaceholdersStrict(template, env);
2757
+ }
2758
+ function constantTimeEqual(a, b) {
2759
+ if (a.length !== b.length) return false;
2760
+ let mismatch = 0;
2761
+ for (let i = 0; i < a.length; i++) {
2762
+ mismatch |= a.charCodeAt(i) ^ b.charCodeAt(i);
2763
+ }
2764
+ return mismatch === 0;
2765
+ }
2766
+ function buildChildEnv(platform, envAllow) {
2767
+ const env = {};
2768
+ for (const key of ALLOWED_ENV_KEYS) {
2769
+ if (platform.env[key]) env[key] = platform.env[key];
2770
+ }
2771
+ for (const entry of envAllow) {
2772
+ const eqIdx = entry.indexOf("=");
2773
+ if (eqIdx > 0) {
2774
+ env[entry.slice(0, eqIdx)] = entry.slice(eqIdx + 1);
2775
+ } else if (platform.env[entry]) {
2776
+ env[entry] = platform.env[entry];
2777
+ }
2778
+ }
2779
+ return env;
2780
+ }
2781
+ function capOutput(value, limit) {
2782
+ if (value.length <= limit) return value;
2783
+ const half = Math.floor(limit / 2);
2784
+ const cut = value.length - limit;
2785
+ return `${value.slice(0, half)}
2786
+ \u2026 ${cut} characters cut \u2026
2787
+ ${value.slice(value.length - half)}`;
2788
+ }
2789
+ var inflightProcs = /* @__PURE__ */ new Set();
2790
+ async function runCommand(platform, cmdPath, argv, childEnv, stdin, timeoutMs, maxOutput, cwd) {
2791
+ let proc;
2792
+ try {
2793
+ proc = await platform.spawn({
2794
+ argv: [cmdPath, ...argv],
2795
+ env: childEnv,
2796
+ cwd
2797
+ });
2798
+ } catch (err) {
2799
+ return { stdout: "", stderr: `spawn failed: ${err.message}`, exitCode: 127 };
2800
+ }
2801
+ inflightProcs.add(proc);
2802
+ if (stdin !== void 0) {
2803
+ const writer = proc.stdin.getWriter();
2804
+ await writer.write(new TextEncoder().encode(stdin));
2805
+ await writer.close();
2806
+ } else {
2807
+ try {
2808
+ await proc.stdin.getWriter().close();
2809
+ } catch {
2810
+ }
2811
+ }
2812
+ const stdoutChunks = [];
2813
+ const stderrChunks = [];
2814
+ const readStream = async (stream, into) => {
2815
+ const r = stream.getReader();
2816
+ try {
2817
+ for (; ; ) {
2818
+ const { done, value } = await r.read();
2819
+ if (done) break;
2820
+ into.push(value);
2821
+ }
2822
+ } finally {
2823
+ r.releaseLock();
2824
+ }
2825
+ };
2826
+ const timer = new Promise(
2827
+ (resolve) => setTimeout(() => resolve("timeout"), timeoutMs)
2828
+ );
2829
+ const work = Promise.all([
2830
+ readStream(proc.stdout, stdoutChunks),
2831
+ readStream(proc.stderr, stderrChunks),
2832
+ proc.wait()
2833
+ ]);
2834
+ const result = await Promise.race([work, timer]);
2835
+ if (result === "timeout") {
2836
+ proc.kill("SIGTERM");
2837
+ await new Promise((resolve) => setTimeout(resolve, 5e3));
2838
+ try {
2839
+ proc.kill("SIGKILL");
2840
+ } catch {
2841
+ }
2842
+ inflightProcs.delete(proc);
2843
+ return { stdout: "", stderr: "timed out", exitCode: 124 };
2844
+ }
2845
+ inflightProcs.delete(proc);
2846
+ const [, , exitResult] = result;
2847
+ const dec = new TextDecoder();
2848
+ return {
2849
+ stdout: capOutput(dec.decode(concat(stdoutChunks)), maxOutput),
2850
+ stderr: capOutput(dec.decode(concat(stderrChunks)), maxOutput),
2851
+ exitCode: exitResult.status
2852
+ };
2853
+ }
2854
+ function concat(chunks) {
2855
+ const total = chunks.reduce((s, c) => s + c.length, 0);
2856
+ const out = new Uint8Array(total);
2857
+ let offset = 0;
2858
+ for (const c of chunks) {
2859
+ out.set(c, offset);
2860
+ offset += c.length;
2861
+ }
2862
+ return out;
2863
+ }
2864
+ async function killInflight() {
2865
+ for (const proc of inflightProcs) {
2866
+ try {
2867
+ proc.kill("SIGTERM");
2868
+ } catch {
2869
+ }
2870
+ }
2871
+ if (inflightProcs.size > 0) {
2872
+ await new Promise((resolve) => setTimeout(resolve, 5e3));
2873
+ for (const proc of inflightProcs) {
1548
2874
  try {
1549
- const exists = await platform.fs.exists(configPath);
1550
- if (!exists) return void 0;
1551
- const data = await platform.fs.readFile(configPath);
1552
- const text = new TextDecoder().decode(data);
1553
- const parsed = JSON.parse(text);
1554
- if (!parsed.mcpServers) return void 0;
1555
- const normalizedName = name.replace(/[-_]/g, "").toLowerCase();
1556
- for (const [key, value] of Object.entries(parsed.mcpServers)) {
1557
- if (key.replace(/[-_]/g, "").toLowerCase() === normalizedName) {
1558
- return value;
1559
- }
2875
+ proc.kill("SIGKILL");
2876
+ } catch {
2877
+ }
2878
+ }
2879
+ }
2880
+ inflightProcs.clear();
2881
+ }
2882
+ async function runHelpForCli(platform, filePath, childEnv, cwd) {
2883
+ const dashed = await runCommand(
2884
+ platform,
2885
+ filePath,
2886
+ ["--help"],
2887
+ childEnv,
2888
+ void 0,
2889
+ 1e4,
2890
+ MAX_OUTPUT_DEFAULT,
2891
+ cwd
2892
+ );
2893
+ if (dashed.exitCode === 0 && dashed.stdout.trim()) return dashed.stdout;
2894
+ const plain = await runCommand(
2895
+ platform,
2896
+ filePath,
2897
+ ["help"],
2898
+ childEnv,
2899
+ void 0,
2900
+ 1e4,
2901
+ MAX_OUTPUT_DEFAULT,
2902
+ cwd
2903
+ );
2904
+ if (plain.exitCode === 0 && plain.stdout.trim()) return plain.stdout;
2905
+ return dashed.stdout.trim() ? dashed.stdout : "";
2906
+ }
2907
+ async function expandGroupCommands(platform, filePath, commands, childEnv, cwd) {
2908
+ const topNames = new Set(commands.map((c) => c.path[0] ?? ""));
2909
+ let current = commands;
2910
+ for (const command of commands) {
2911
+ if (!isGroupCandidate(command)) continue;
2912
+ const group = command.path[0] ?? "";
2913
+ const nested = await runCommand(
2914
+ platform,
2915
+ filePath,
2916
+ [group, "--help"],
2917
+ childEnv,
2918
+ void 0,
2919
+ 1e4,
2920
+ MAX_OUTPUT_DEFAULT,
2921
+ cwd
2922
+ );
2923
+ if (nested.exitCode !== 0 || !nested.stdout.trim()) continue;
2924
+ const replaced = nestGroup(current, group, parseHelp(nested.stdout), topNames);
2925
+ if (replaced) current = replaced;
2926
+ }
2927
+ return current;
2928
+ }
2929
+ async function discoverCli(platform, filePath, explicitName, childEnv, cwd) {
2930
+ const mcp = await runCommand(
2931
+ platform,
2932
+ filePath,
2933
+ ["--mcp"],
2934
+ childEnv,
2935
+ void 0,
2936
+ 1e4,
2937
+ MAX_OUTPUT_DEFAULT,
2938
+ cwd
2939
+ );
2940
+ const override = mcp.exitCode === 0 ? parseMcpOverride(mcp.stdout) : null;
2941
+ const helpText2 = override ? "" : await runHelpForCli(platform, filePath, childEnv, cwd);
2942
+ if (!override && !helpText2.trim()) {
2943
+ throw new Error(`${filePath} did not print help or --mcp descriptor`);
2944
+ }
2945
+ const parsed = override ?? parseHelp(helpText2);
2946
+ let commands = parsed.commands;
2947
+ if (!override) {
2948
+ commands = attachGlobalFlags(commands, parsed.globalFlags);
2949
+ commands = await expandGroupCommands(platform, filePath, commands, childEnv, cwd);
2950
+ }
2951
+ return { name: cliPrefix(helpText2, filePath, explicitName), path: filePath, commands };
2952
+ }
2953
+ function createToolExecutor(platform, clis, allTools, childEnv, options, serveCwd) {
2954
+ const rpcTools = allTools.map((t) => ({
2955
+ name: t.name,
2956
+ description: t.description,
2957
+ inputSchema: t.inputSchema
2958
+ }));
2959
+ const queues = /* @__PURE__ */ new Map();
2960
+ function enqueue(key, job) {
2961
+ const previous = queues.get(key) ?? Promise.resolve();
2962
+ const run2 = previous.then(job, job);
2963
+ queues.set(
2964
+ key,
2965
+ run2.then(
2966
+ () => void 0,
2967
+ () => void 0
2968
+ )
2969
+ );
2970
+ return run2;
2971
+ }
2972
+ function invokeTemplateTool(tool, args) {
2973
+ const templateArgs = {};
2974
+ if (args && typeof args === "object") {
2975
+ for (const [k, v] of Object.entries(args)) {
2976
+ templateArgs[k] = String(v);
2977
+ }
2978
+ }
2979
+ const argv = templateToArgv(tool.description, templateArgs);
2980
+ return enqueue(
2981
+ "__template__",
2982
+ () => runCommand(
2983
+ platform,
2984
+ argv[0],
2985
+ argv.slice(1),
2986
+ childEnv,
2987
+ void 0,
2988
+ options.callTimeout,
2989
+ options.maxOutput,
2990
+ serveCwd
2991
+ )
2992
+ );
2993
+ }
2994
+ async function executeTool(tool, cli, args) {
2995
+ if (tool.kind === "help") {
2996
+ const result = await runCommand(
2997
+ platform,
2998
+ cli.path,
2999
+ ["--help"],
3000
+ childEnv,
3001
+ void 0,
3002
+ options.callTimeout,
3003
+ options.maxOutput,
3004
+ serveCwd
3005
+ );
3006
+ if (result.exitCode === 0) return result;
3007
+ return runCommand(
3008
+ platform,
3009
+ cli.path,
3010
+ ["help"],
3011
+ childEnv,
3012
+ void 0,
3013
+ options.callTimeout,
3014
+ options.maxOutput,
3015
+ serveCwd
3016
+ );
3017
+ }
3018
+ if (tool.kind === "invoke") {
3019
+ const parsed2 = readToolArguments(args ?? {});
3020
+ if (parsed2.error) return { stdout: "", stderr: parsed2.error, exitCode: 2 };
3021
+ if (!parsed2.argv) return { stdout: "", stderr: "argv is required", exitCode: 2 };
3022
+ return runCommand(
3023
+ platform,
3024
+ cli.path,
3025
+ parsed2.argv,
3026
+ childEnv,
3027
+ parsed2.stdin,
3028
+ options.callTimeout,
3029
+ options.maxOutput,
3030
+ serveCwd
3031
+ );
3032
+ }
3033
+ const parsed = readToolArguments(args ?? {});
3034
+ const command = cli.commands.find((c) => c.path.join("_") === tool.commandPath.join("_"));
3035
+ if (!command) return { stdout: "", stderr: `unknown command ${tool.name}`, exitCode: 2 };
3036
+ const planned = argvForCommand(command, parsed);
3037
+ if ("error" in planned) return { stdout: "", stderr: planned.error, exitCode: 2 };
3038
+ return runCommand(
3039
+ platform,
3040
+ cli.path,
3041
+ planned.argv,
3042
+ childEnv,
3043
+ planned.stdin,
3044
+ options.callTimeout,
3045
+ options.maxOutput,
3046
+ serveCwd
3047
+ );
3048
+ }
3049
+ async function invoke(name, args) {
3050
+ const tool = allTools.find((t) => t.name === name);
3051
+ if (!tool) return { stdout: "", stderr: `unknown tool ${name}`, exitCode: 1 };
3052
+ if (tool.cli === "" && tool.commandPath.length === 0) {
3053
+ return invokeTemplateTool(tool, args);
3054
+ }
3055
+ const cli = clis.find((c) => c.name === tool.cli);
3056
+ if (!cli) return { stdout: "", stderr: `unknown cli ${tool.cli}`, exitCode: 1 };
3057
+ return enqueue(cli.name, () => executeTool(tool, cli, args));
3058
+ }
3059
+ return { invoke, rpcTools };
3060
+ }
3061
+ async function runServe(platform, options, version) {
3062
+ let resolvedBearer;
3063
+ if (options.bearer) {
3064
+ const expanded = expandBearerToken(options.bearer, platform.env);
3065
+ if (!expanded) {
3066
+ await platform.write(
3067
+ 2,
3068
+ "mcpcat serve: --bearer requires a ${NAME} variable reference, not a literal token. Use --bearer '${MY_TOKEN}' and set MY_TOKEN in the environment.\n"
3069
+ );
3070
+ return 2;
3071
+ }
3072
+ resolvedBearer = expanded;
3073
+ }
3074
+ const serveCwd = options.cwd ?? platform.cwd;
3075
+ const childEnv = buildChildEnv(platform, options.envAllow);
3076
+ const clis = [];
3077
+ for (const cmd of options.commands) {
3078
+ try {
3079
+ const cli = await discoverCli(platform, cmd.path, cmd.name, childEnv, serveCwd);
3080
+ clis.push(cli);
3081
+ } catch (err) {
3082
+ await platform.write(2, `mcpcat serve: ${err.message}
3083
+ `);
3084
+ return 2;
3085
+ }
3086
+ }
3087
+ const allTools = clis.flatMap((cli) => buildTools(cli.name, cli.commands));
3088
+ for (const spec of options.toolTemplates) {
3089
+ const tool = parseToolTemplate(spec);
3090
+ if (!tool) {
3091
+ await platform.write(2, `mcpcat serve: invalid --tool spec: ${spec}
3092
+ `);
3093
+ return 2;
3094
+ }
3095
+ allTools.push(tool);
3096
+ }
3097
+ const executor = createToolExecutor(platform, clis, allTools, childEnv, options, serveCwd);
3098
+ const serverName = "mcpcat-serve";
3099
+ if (options.transport === "stdio") {
3100
+ return runStdioServer(platform, executor.rpcTools, executor.invoke, serverName, version);
3101
+ }
3102
+ return runHttpServer(
3103
+ platform,
3104
+ options,
3105
+ executor.rpcTools,
3106
+ executor.invoke,
3107
+ serverName,
3108
+ version,
3109
+ resolvedBearer
3110
+ );
3111
+ }
3112
+ async function runStdioServer(platform, tools, call, serverName, version) {
3113
+ const reader = platform.stdin.getReader();
3114
+ let buffer = "";
3115
+ const dec = new TextDecoder();
3116
+ const enc = new TextEncoder();
3117
+ try {
3118
+ for (; ; ) {
3119
+ const { done, value } = await reader.read();
3120
+ if (done) break;
3121
+ buffer += dec.decode(value, { stream: true });
3122
+ let nlIdx;
3123
+ while ((nlIdx = buffer.indexOf("\n")) >= 0) {
3124
+ const line = buffer.slice(0, nlIdx).trim();
3125
+ buffer = buffer.slice(nlIdx + 1);
3126
+ if (!line) continue;
3127
+ const outcome = await handleJsonRpc(line, tools, call, serverName, version);
3128
+ if (outcome.status === 202) continue;
3129
+ const writer = platform.stdout.getWriter();
3130
+ await writer.write(enc.encode(`${outcome.body}
3131
+ `));
3132
+ writer.releaseLock();
3133
+ }
3134
+ }
3135
+ } finally {
3136
+ reader.releaseLock();
3137
+ }
3138
+ return 0;
3139
+ }
3140
+ async function runHttpServer(platform, options, tools, call, serverName, version, resolvedBearer) {
3141
+ if (!platform.listen) {
3142
+ await platform.write(2, "mcpcat serve: HTTP transport requires platform.listen\n");
3143
+ return 3;
3144
+ }
3145
+ const boundLoopback = options.host === "127.0.0.1" || options.host === "localhost" || options.host === "::1";
3146
+ if (!boundLoopback && !resolvedBearer) {
3147
+ await platform.write(2, "mcpcat serve: --bearer is required when binding off loopback\n");
3148
+ return 2;
3149
+ }
3150
+ const allowedOrigins = new Set(options.allowOrigins);
3151
+ const listener = await platform.listen({ host: options.host, port: options.port });
3152
+ const actualPort = listener.port;
3153
+ const listenUrl = `http://${options.host}:${actualPort}/mcp`;
3154
+ if (options.json) {
3155
+ await platform.write(1, `${JSON.stringify({ url: listenUrl })}
3156
+ `);
3157
+ }
3158
+ await platform.write(2, `mcpcat serve: listening on ${listenUrl}
3159
+ `);
3160
+ let shutdownRequested = false;
3161
+ const shutdown = () => {
3162
+ if (shutdownRequested) return;
3163
+ shutdownRequested = true;
3164
+ listener.close();
3165
+ void killInflight();
3166
+ };
3167
+ if (platform.onSignal) {
3168
+ platform.onSignal("SIGINT", shutdown);
3169
+ platform.onSignal("SIGTERM", shutdown);
3170
+ }
3171
+ const handler = (request) => handleMcpRequest(
3172
+ request,
3173
+ tools,
3174
+ call,
3175
+ serverName,
3176
+ version,
3177
+ allowedOrigins,
3178
+ boundLoopback,
3179
+ resolvedBearer
3180
+ );
3181
+ try {
3182
+ for await (const connection of listener) {
3183
+ if (shutdownRequested) break;
3184
+ const conn = connection;
3185
+ handleConnection(conn.readable, conn.writable, handler).catch(() => {
3186
+ }).finally(() => {
3187
+ try {
3188
+ conn.close();
3189
+ } catch {
1560
3190
  }
1561
- return void 0;
3191
+ });
3192
+ }
3193
+ } catch {
3194
+ if (!shutdownRequested) throw new Error("listener closed unexpectedly");
3195
+ }
3196
+ return 0;
3197
+ }
3198
+ async function handleMcpRequest(request, tools, call, serverName, version, allowedOrigins, boundLoopback, resolvedBearer) {
3199
+ if (resolvedBearer) {
3200
+ const authHeader = request.headers.authorization;
3201
+ const provided = authHeader?.startsWith("Bearer ") ? authHeader.slice(7) : "";
3202
+ if (!provided || !constantTimeEqual(provided, resolvedBearer)) {
3203
+ return {
3204
+ status: 401,
3205
+ reason: "Unauthorized",
3206
+ headers: { "content-type": "text/plain" },
3207
+ body: "Unauthorized"
3208
+ };
3209
+ }
3210
+ }
3211
+ const originCheck = checkOrigin(request.headers.origin, allowedOrigins, boundLoopback);
3212
+ if (!originCheck.ok) {
3213
+ return {
3214
+ status: 403,
3215
+ reason: "Forbidden",
3216
+ headers: { "content-type": "text/plain" },
3217
+ body: originCheck.reason ?? "Forbidden"
3218
+ };
3219
+ }
3220
+ const hostCheck = checkHost(request.headers.host, boundLoopback);
3221
+ if (!hostCheck.ok) {
3222
+ return {
3223
+ status: 403,
3224
+ reason: "Forbidden",
3225
+ headers: { "content-type": "text/plain" },
3226
+ body: hostCheck.reason ?? "Forbidden"
3227
+ };
3228
+ }
3229
+ if (request.target !== "/mcp") {
3230
+ return {
3231
+ status: 404,
3232
+ reason: "Not Found",
3233
+ headers: { "content-type": "text/plain" },
3234
+ body: "Not Found"
3235
+ };
3236
+ }
3237
+ if (request.method !== "POST") {
3238
+ return {
3239
+ status: 405,
3240
+ reason: "Method Not Allowed",
3241
+ headers: { "content-type": "text/plain", allow: "POST" },
3242
+ body: "Method Not Allowed"
3243
+ };
3244
+ }
3245
+ const outcome = await handleJsonRpc(request.body, tools, call, serverName, version);
3246
+ return {
3247
+ status: outcome.status,
3248
+ reason: outcome.status === 200 ? "OK" : "Accepted",
3249
+ headers: { "content-type": outcome.contentType },
3250
+ body: outcome.body
3251
+ };
3252
+ }
3253
+
3254
+ // src/config/lock.ts
3255
+ var LOCK_STALE_MS = 1e4;
3256
+ var LOCK_POLL_MS = 50;
3257
+ var LOCK_MAX_WAIT_MS = 5e3;
3258
+ function isEexist(err) {
3259
+ if (err instanceof Error && "code" in err)
3260
+ return err.code === "EEXIST";
3261
+ if (err instanceof Error) return err.message.includes("EEXIST");
3262
+ return false;
3263
+ }
3264
+ async function removeStaleLock(fs, lockPath) {
3265
+ try {
3266
+ const s = await fs.stat(lockPath);
3267
+ if (Date.now() - s.mtimeMs > LOCK_STALE_MS) {
3268
+ try {
3269
+ await fs.rmdir(lockPath);
1562
3270
  } catch {
1563
- return void 0;
3271
+ }
3272
+ return true;
3273
+ }
3274
+ } catch {
3275
+ }
3276
+ return false;
3277
+ }
3278
+ async function acquireLock(fs, configPath) {
3279
+ const lockPath = `${configPath}.lock`;
3280
+ const start = Date.now();
3281
+ while (true) {
3282
+ try {
3283
+ await fs.mkdirExclusive(lockPath);
3284
+ break;
3285
+ } catch (err) {
3286
+ if (!isEexist(err)) throw err;
3287
+ await removeStaleLock(fs, lockPath);
3288
+ }
3289
+ if (Date.now() - start > LOCK_MAX_WAIT_MS) {
3290
+ throw new Error(`mcpcat: could not acquire lock ${lockPath} within ${LOCK_MAX_WAIT_MS}ms`);
3291
+ }
3292
+ await new Promise((r) => setTimeout(r, LOCK_POLL_MS));
3293
+ }
3294
+ let released = false;
3295
+ return async () => {
3296
+ if (released) return;
3297
+ released = true;
3298
+ try {
3299
+ await fs.rmdir(lockPath);
3300
+ } catch {
3301
+ }
3302
+ };
3303
+ }
3304
+
3305
+ // src/config/edit.ts
3306
+ function isRecord2(value) {
3307
+ return typeof value === "object" && value !== null && !Array.isArray(value);
3308
+ }
3309
+ function detectIndent(text) {
3310
+ const match = /^([ \t]+)\S/m.exec(text);
3311
+ return match ? match[1] : " ";
3312
+ }
3313
+ async function readText(fs, path) {
3314
+ try {
3315
+ const data = await fs.readFile(path);
3316
+ return new TextDecoder().decode(data);
3317
+ } catch {
3318
+ return void 0;
3319
+ }
3320
+ }
3321
+ async function editMcpServers(fs, path, edit) {
3322
+ const release = await acquireLock(fs, path);
3323
+ try {
3324
+ const text = await readText(fs, path);
3325
+ const parsed = text === void 0 ? {} : JSON.parse(text);
3326
+ if (!isRecord2(parsed) || parsed.mcpServers !== void 0 && !isRecord2(parsed.mcpServers))
3327
+ throw new Error(`${path}: expected an object with an "mcpServers" object`);
3328
+ const servers = isRecord2(parsed.mcpServers) ? parsed.mcpServers : void 0;
3329
+ if (!edit(servers, parsed)) return { changed: false };
3330
+ const indent = text ? detectIndent(text) : " ";
3331
+ const output = `${JSON.stringify(parsed, null, indent)}
3332
+ `;
3333
+ const dir = path.slice(0, path.lastIndexOf("/"));
3334
+ if (dir) {
3335
+ try {
3336
+ await fs.mkdir(dir);
3337
+ } catch {
3338
+ }
3339
+ }
3340
+ const tmpPath = `${path}.tmp.${Date.now()}`;
3341
+ await fs.writeFile(tmpPath, output);
3342
+ await fs.rename(tmpPath, path);
3343
+ return { changed: true };
3344
+ } finally {
3345
+ await release();
3346
+ }
3347
+ }
3348
+ async function addServer(fs, path, name, config) {
3349
+ let replaced = false;
3350
+ await editMcpServers(fs, path, (servers, parsed) => {
3351
+ const target = servers ?? {};
3352
+ replaced = target[name] !== void 0;
3353
+ target[name] = config;
3354
+ parsed.mcpServers = target;
3355
+ return true;
3356
+ });
3357
+ return { replaced };
3358
+ }
3359
+ async function removeServer(fs, path, name) {
3360
+ let removed = false;
3361
+ await editMcpServers(fs, path, (servers) => {
3362
+ if (!servers || servers[name] === void 0) return false;
3363
+ delete servers[name];
3364
+ removed = true;
3365
+ return true;
3366
+ });
3367
+ return removed;
3368
+ }
3369
+ async function updateServer(fs, path, name, patch) {
3370
+ let updated = false;
3371
+ await editMcpServers(fs, path, (servers) => {
3372
+ if (!servers || !isRecord2(servers[name])) return false;
3373
+ const entry = servers[name];
3374
+ if (patch.enabled !== void 0) entry.enabled = patch.enabled;
3375
+ if (patch.exposure !== void 0) entry.exposure = patch.exposure;
3376
+ if (patch.toolExposure !== void 0) entry.toolExposure = patch.toolExposure;
3377
+ updated = true;
3378
+ return true;
3379
+ });
3380
+ return updated;
3381
+ }
3382
+ async function setExposure(fs, path, name, exposure, toolGlob) {
3383
+ let updated = false;
3384
+ await editMcpServers(fs, path, (servers) => {
3385
+ if (!servers || !isRecord2(servers[name])) return false;
3386
+ const entry = servers[name];
3387
+ if (toolGlob) {
3388
+ const te = isRecord2(entry.toolExposure) ? { ...entry.toolExposure } : {};
3389
+ te[toolGlob] = exposure;
3390
+ entry.toolExposure = te;
3391
+ } else {
3392
+ entry.exposure = exposure;
3393
+ }
3394
+ updated = true;
3395
+ return true;
3396
+ });
3397
+ return updated;
3398
+ }
3399
+
3400
+ // src/config/import.ts
3401
+ function isRecord3(value) {
3402
+ return typeof value === "object" && value !== null && !Array.isArray(value);
3403
+ }
3404
+ function isStringRecord2(value) {
3405
+ return isRecord3(value) && Object.values(value).every((v) => typeof v === "string");
3406
+ }
3407
+ function tryParse(text) {
3408
+ try {
3409
+ return { parsed: JSON.parse(text) };
3410
+ } catch (e) {
3411
+ return { parsed: void 0, error: `not valid JSON: ${e.message}` };
3412
+ }
3413
+ }
3414
+ function filterNames(entries, names) {
3415
+ const result = [];
3416
+ for (const [name, value] of entries) {
3417
+ if (names && names.length > 0 && !names.includes(name)) continue;
3418
+ result.push([name, value]);
3419
+ }
3420
+ return result;
3421
+ }
3422
+ function replaceInputVars(value) {
3423
+ return value.replace(
3424
+ /\$\{input:([^}]+)\}/g,
3425
+ (_, name) => `\${${name.toUpperCase().replace(/[^A-Z0-9]/g, "_")}}`
3426
+ );
3427
+ }
3428
+ function importClaude(text, names) {
3429
+ const result = { servers: [], errors: [] };
3430
+ const { parsed, error } = tryParse(text);
3431
+ if (error) {
3432
+ result.errors.push(error);
3433
+ return result;
3434
+ }
3435
+ if (!isRecord3(parsed)) {
3436
+ result.errors.push("expected an object");
3437
+ return result;
3438
+ }
3439
+ const mcpServers = parsed.mcpServers;
3440
+ if (!isRecord3(mcpServers)) {
3441
+ result.errors.push('no "mcpServers" object');
3442
+ return result;
3443
+ }
3444
+ for (const [name, entry] of filterNames(Object.entries(mcpServers), names)) {
3445
+ if (!isRecord3(entry)) {
3446
+ result.errors.push(`${name}: not an object`);
3447
+ continue;
3448
+ }
3449
+ result.servers.push({ name, config: entry });
3450
+ }
3451
+ return result;
3452
+ }
3453
+ function importVSCode(text, names) {
3454
+ const result = { servers: [], errors: [] };
3455
+ const { parsed, error } = tryParse(text);
3456
+ if (error) {
3457
+ result.errors.push(error);
3458
+ return result;
3459
+ }
3460
+ if (!isRecord3(parsed)) {
3461
+ result.errors.push("expected an object");
3462
+ return result;
3463
+ }
3464
+ const servers = parsed.servers ?? parsed.mcpServers;
3465
+ if (!isRecord3(servers)) {
3466
+ result.errors.push('no "servers" or "mcpServers" object');
3467
+ return result;
3468
+ }
3469
+ for (const [name, entry] of filterNames(Object.entries(servers), names)) {
3470
+ if (!isRecord3(entry)) {
3471
+ result.errors.push(`${name}: not an object`);
3472
+ continue;
3473
+ }
3474
+ result.servers.push({ name, config: convertVSCodeEntry(entry) });
3475
+ }
3476
+ return result;
3477
+ }
3478
+ function convertVSCodeEntry(entry) {
3479
+ const config = {};
3480
+ for (const [key, value] of Object.entries(entry)) {
3481
+ if (key === "type" || key === "command" || key === "args" || key === "cwd" || key === "url") {
3482
+ config[key] = value;
3483
+ } else if (key === "headers" && isStringRecord2(value)) {
3484
+ const headers = {};
3485
+ for (const [h, v] of Object.entries(value)) headers[h] = replaceInputVars(v);
3486
+ config.headers = headers;
3487
+ } else if (key === "env" && isStringRecord2(value)) {
3488
+ const env = {};
3489
+ for (const [k, v] of Object.entries(value)) env[k] = replaceInputVars(v);
3490
+ config.env = env;
3491
+ } else {
3492
+ config[key] = value;
3493
+ }
3494
+ }
3495
+ return config;
3496
+ }
3497
+ function importSixServers(text, names) {
3498
+ const result = { servers: [], errors: [] };
3499
+ const { parsed, error } = tryParse(text);
3500
+ if (error) {
3501
+ result.errors.push(error);
3502
+ return result;
3503
+ }
3504
+ if (!isRecord3(parsed)) {
3505
+ result.errors.push("expected an object");
3506
+ return result;
3507
+ }
3508
+ const servers = parsed.servers;
3509
+ if (!isRecord3(servers)) {
3510
+ result.errors.push('no "servers" object');
3511
+ return result;
3512
+ }
3513
+ for (const [name, entry] of filterNames(Object.entries(servers), names)) {
3514
+ if (!isRecord3(entry)) {
3515
+ result.errors.push(`${name}: not an object`);
3516
+ continue;
3517
+ }
3518
+ const config = {};
3519
+ if (typeof entry.url === "string") config.url = entry.url;
3520
+ if (isStringRecord2(entry.headers)) config.headers = entry.headers;
3521
+ if (typeof entry.exposure === "string") config.exposure = entry.exposure;
3522
+ if (isRecord3(entry.toolExposure)) config.toolExposure = entry.toolExposure;
3523
+ result.servers.push({ name, config });
3524
+ }
3525
+ return result;
3526
+ }
3527
+ function importCodexToml(text, names) {
3528
+ const result = { servers: [], errors: [] };
3529
+ const sections = parseTomlSections(text);
3530
+ for (const [sectionName, fields] of sections) {
3531
+ const prefix = "mcp_servers.";
3532
+ if (!sectionName.startsWith(prefix)) continue;
3533
+ const name = sectionName.slice(prefix.length);
3534
+ if (names && names.length > 0 && !names.includes(name)) continue;
3535
+ const config = {};
3536
+ if (fields.command) config.command = fields.command;
3537
+ if (fields.args) config.args = fields.args;
3538
+ if (fields.url) config.url = fields.url;
3539
+ if (fields.env && isRecord3(fields.env)) config.env = fields.env;
3540
+ result.servers.push({ name, config });
3541
+ }
3542
+ return result;
3543
+ }
3544
+ function parseTomlSections(text) {
3545
+ const sections = [];
3546
+ let current;
3547
+ let currentName = "";
3548
+ for (const line of text.split("\n")) {
3549
+ const trimmed = line.trim();
3550
+ if (trimmed.startsWith("#") || trimmed === "") continue;
3551
+ const sectionMatch = /^\[([^\]]+)\]/.exec(trimmed);
3552
+ if (sectionMatch) {
3553
+ if (current) sections.push([currentName, current]);
3554
+ currentName = sectionMatch[1].trim();
3555
+ current = {};
3556
+ continue;
3557
+ }
3558
+ if (!current) continue;
3559
+ const kvMatch = /^(\w+)\s*=\s*(.+)/.exec(trimmed);
3560
+ if (kvMatch) {
3561
+ current[kvMatch[1]] = parseTomlValue(kvMatch[2].trim());
3562
+ }
3563
+ }
3564
+ if (current) sections.push([currentName, current]);
3565
+ return sections;
3566
+ }
3567
+ function parseTomlValue(raw) {
3568
+ if (raw.startsWith('"') && raw.endsWith('"')) return raw.slice(1, -1);
3569
+ if (raw.startsWith("'") && raw.endsWith("'")) return raw.slice(1, -1);
3570
+ if (raw.startsWith("[")) {
3571
+ try {
3572
+ return JSON.parse(raw.replace(/'/g, '"'));
3573
+ } catch {
3574
+ return raw;
3575
+ }
3576
+ }
3577
+ if (raw === "true") return true;
3578
+ if (raw === "false") return false;
3579
+ const num = Number(raw);
3580
+ if (!Number.isNaN(num)) return num;
3581
+ return raw;
3582
+ }
3583
+ function convertOpenCodeLocal(entry) {
3584
+ const config = {};
3585
+ if (Array.isArray(entry.command) && entry.command.length > 0) {
3586
+ config.command = entry.command[0];
3587
+ if (entry.command.length > 1) config.args = entry.command.slice(1);
3588
+ } else if (typeof entry.command === "string") {
3589
+ config.command = entry.command;
3590
+ }
3591
+ if (isRecord3(entry.environment)) {
3592
+ const env = {};
3593
+ for (const [k, v] of Object.entries(entry.environment)) {
3594
+ if (typeof v === "string")
3595
+ env[k] = v.replace(/\{env:([^}]+)\}/g, (_, n) => `\${${n}}`);
3596
+ }
3597
+ config.env = env;
3598
+ }
3599
+ return config;
3600
+ }
3601
+ function convertOpenCodeRemote(entry) {
3602
+ const config = {};
3603
+ config.url = entry.url;
3604
+ if (isStringRecord2(entry.headers)) config.headers = entry.headers;
3605
+ return config;
3606
+ }
3607
+ function importOpenCode(text, names) {
3608
+ const result = { servers: [], errors: [] };
3609
+ const { parsed, error } = tryParse(text);
3610
+ if (error) {
3611
+ result.errors.push(error);
3612
+ return result;
3613
+ }
3614
+ if (!isRecord3(parsed)) {
3615
+ result.errors.push("expected an object");
3616
+ return result;
3617
+ }
3618
+ const mcpServers = parsed.mcpServers ?? parsed.mcp;
3619
+ if (!isRecord3(mcpServers)) {
3620
+ result.errors.push("no mcp servers found");
3621
+ return result;
3622
+ }
3623
+ for (const [name, entry] of filterNames(Object.entries(mcpServers), names)) {
3624
+ if (!isRecord3(entry)) {
3625
+ result.errors.push(`${name}: not an object`);
3626
+ continue;
3627
+ }
3628
+ const isLocal = entry.type === "local" || entry.command;
3629
+ const config = isLocal ? convertOpenCodeLocal(entry) : convertOpenCodeRemote(entry);
3630
+ result.servers.push({ name, config });
3631
+ }
3632
+ return result;
3633
+ }
3634
+ function detectFormat(text, filename) {
3635
+ if (filename.endsWith(".toml")) return "codex";
3636
+ if (filename.includes("servers.json")) return "six";
3637
+ if (filename.includes(".vscode")) return "vscode";
3638
+ try {
3639
+ const parsed = JSON.parse(text);
3640
+ if (isRecord3(parsed)) {
3641
+ if (parsed.servers && isRecord3(parsed.servers) && parsed.version !== void 0) return "six";
3642
+ if (parsed.servers && isRecord3(parsed.servers)) return "vscode";
3643
+ if (parsed.mcpServers) return "claude";
3644
+ if (parsed.mcp) return "opencode";
3645
+ }
3646
+ } catch {
3647
+ }
3648
+ if (text.includes("[mcp_servers.")) return "codex";
3649
+ return "claude";
3650
+ }
3651
+ function importFile(text, filename, names) {
3652
+ const format = detectFormat(text, filename);
3653
+ switch (format) {
3654
+ case "claude":
3655
+ return importClaude(text, names);
3656
+ case "vscode":
3657
+ return importVSCode(text, names);
3658
+ case "six":
3659
+ return importSixServers(text, names);
3660
+ case "codex":
3661
+ return importCodexToml(text, names);
3662
+ case "opencode":
3663
+ return importOpenCode(text, names);
3664
+ default:
3665
+ return importClaude(text, names);
3666
+ }
3667
+ }
3668
+
3669
+ // src/config/warnings.ts
3670
+ var SECRET_HEADER = /authorization|cookie|token|key|secret|password|session/i;
3671
+ var PLACEHOLDER2 = /\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g;
3672
+ var SCHEME = /^\s*(?:bearer|basic|token|apikey|api-key)\s+/i;
3673
+ var SECRET_PARAM = /token|key|secret|password|signature|sig|auth|code/i;
3674
+ function literalSecret(header, value) {
3675
+ if (!SECRET_HEADER.test(header)) return false;
3676
+ return value.replace(PLACEHOLDER2, "").replace(SCHEME, "").trim() !== "";
3677
+ }
3678
+ function urlHasSecret(url) {
3679
+ if (!URL.canParse(url)) return void 0;
3680
+ const parsed = new URL(url);
3681
+ if (parsed.username || parsed.password) return "url";
3682
+ for (const name of parsed.searchParams.keys()) if (SECRET_PARAM.test(name)) return `url ?${name}`;
3683
+ return void 0;
3684
+ }
3685
+ var SLICC_OAUTH_REFUSED = {
3686
+ clientSecret: "a client secret would have to live in mcp.json; SLICC signs in as a public client",
3687
+ callbackPort: "SLICC signs in through its own page, not a loopback port",
3688
+ callbackUrl: "SLICC signs in through its own page, not a loopback URL",
3689
+ clientRegistration: "SLICC registers dynamically or uses oauth.clientId"
3690
+ };
3691
+ function checkAgentWarnings(name, config) {
3692
+ const warnings = [];
3693
+ if ("command" in config && config.command) {
3694
+ warnings.push({
3695
+ server: name,
3696
+ message: "stdio servers need slicc-kernel#68, so the agent will skip this entry",
3697
+ advice: "use mcpcat serve --proxy to bridge it as HTTP"
3698
+ });
3699
+ }
3700
+ if ("headers" in config && config.headers) {
3701
+ for (const [h, v] of Object.entries(config.headers)) {
3702
+ if (v.trim().startsWith("!")) {
3703
+ warnings.push({
3704
+ server: name,
3705
+ message: `headers.${h} runs a command, which the agent can't do`,
3706
+ advice: "use ${NAME} and set the value in Settings > MCP servers"
3707
+ });
3708
+ }
3709
+ if (literalSecret(h, v)) {
3710
+ warnings.push({
3711
+ server: name,
3712
+ message: `headers.${h} holds a literal secret`,
3713
+ advice: "write ${NAME} instead, and add the value in Settings > MCP servers"
3714
+ });
1564
3715
  }
1565
3716
  }
3717
+ }
3718
+ if ("url" in config && config.url) {
3719
+ const secret = urlHasSecret(config.url);
3720
+ if (secret) {
3721
+ warnings.push({
3722
+ server: name,
3723
+ message: `${secret} holds a literal secret`,
3724
+ advice: "put it in a header as ${NAME}"
3725
+ });
3726
+ }
3727
+ }
3728
+ if ("oauth" in config && config.oauth) {
3729
+ for (const key of Object.keys(config.oauth)) {
3730
+ const reason = SLICC_OAUTH_REFUSED[key];
3731
+ if (reason) {
3732
+ warnings.push({
3733
+ server: name,
3734
+ message: `oauth.${key} is not supported by the agent: ${reason}`,
3735
+ advice: `remove oauth.${key}`
3736
+ });
3737
+ }
3738
+ }
3739
+ }
3740
+ return warnings;
3741
+ }
3742
+
3743
+ // src/cli/config-verbs.ts
3744
+ function parseHeader(hdr) {
3745
+ const colonIdx = hdr.indexOf(":");
3746
+ if (colonIdx < 1) return `invalid header '${hdr}'`;
3747
+ return [hdr.slice(0, colonIdx).trim(), hdr.slice(colonIdx + 1).trim()];
3748
+ }
3749
+ function parseEnvPair(pair) {
3750
+ const eqIdx = pair.indexOf("=");
3751
+ if (eqIdx < 1) return `invalid --env '${pair}'`;
3752
+ return [pair.slice(0, eqIdx), pair.slice(eqIdx + 1)];
3753
+ }
3754
+ function parseAddFlagAt(flagArgs, i, flags) {
3755
+ const arg = flagArgs[i];
3756
+ if (arg === "-l" || arg === "--local") {
3757
+ flags.local = true;
3758
+ return { next: i + 1 };
3759
+ }
3760
+ if (arg === "--no-probe") {
3761
+ flags.noProbe = true;
3762
+ return { next: i + 1 };
3763
+ }
3764
+ if (arg === "--config" && i + 1 < flagArgs.length) {
3765
+ flags.configFile = flagArgs[i + 1];
3766
+ return { next: i + 2 };
3767
+ }
3768
+ if (arg === "--description" && i + 1 < flagArgs.length) {
3769
+ flags.description = flagArgs[i + 1];
3770
+ return { next: i + 2 };
3771
+ }
3772
+ if (arg === "--exposure" && i + 1 < flagArgs.length) {
3773
+ flags.exposure = flagArgs[i + 1];
3774
+ return { next: i + 2 };
3775
+ }
3776
+ if ((arg === "-H" || arg === "--header") && i + 1 < flagArgs.length) {
3777
+ const result = parseHeader(flagArgs[i + 1]);
3778
+ if (typeof result === "string") return { next: i + 2, error: result };
3779
+ flags.headers.push(result);
3780
+ return { next: i + 2 };
3781
+ }
3782
+ if (arg === "--env" && i + 1 < flagArgs.length) {
3783
+ const result = parseEnvPair(flagArgs[i + 1]);
3784
+ if (typeof result === "string") return { next: i + 2, error: result };
3785
+ flags.envPairs.push(result);
3786
+ return { next: i + 2 };
3787
+ }
3788
+ if (arg === "--cwd" && i + 1 < flagArgs.length) {
3789
+ flags.cwd = flagArgs[i + 1];
3790
+ return { next: i + 2 };
3791
+ }
3792
+ if (arg.startsWith("-")) return { next: i + 1, error: `unknown option '${arg}'` };
3793
+ flags.positional.push(arg);
3794
+ return { next: i + 1 };
3795
+ }
3796
+ function parseAddFlags(args) {
3797
+ const flags = {
3798
+ local: false,
3799
+ noProbe: false,
3800
+ headers: [],
3801
+ envPairs: [],
3802
+ positional: [],
3803
+ cmdArgs: []
3804
+ };
3805
+ const dashDashIdx = args.indexOf("--");
3806
+ const flagArgs = dashDashIdx >= 0 ? args.slice(0, dashDashIdx) : args;
3807
+ flags.cmdArgs = dashDashIdx >= 0 ? args.slice(dashDashIdx + 1) : [];
3808
+ let i = 0;
3809
+ while (i < flagArgs.length) {
3810
+ const step = parseAddFlagAt(flagArgs, i, flags);
3811
+ if (step.error) return step.error;
3812
+ i = step.next;
3813
+ }
3814
+ return flags;
3815
+ }
3816
+ function buildStdioConfig(flags) {
3817
+ const config = {
3818
+ command: flags.cmdArgs[0],
3819
+ ...flags.cmdArgs.length > 1 ? { args: flags.cmdArgs.slice(1) } : {}
1566
3820
  };
3821
+ if (flags.envPairs.length > 0) {
3822
+ const env = {};
3823
+ for (const [k, v] of flags.envPairs) env[k] = v;
3824
+ config.env = env;
3825
+ }
3826
+ if (flags.cwd) config.cwd = flags.cwd;
3827
+ if (flags.description) config.description = flags.description;
3828
+ if (flags.exposure) config.exposure = flags.exposure;
3829
+ return config;
3830
+ }
3831
+ function buildHttpConfig(urlStr, flags) {
3832
+ const config = { url: urlStr };
3833
+ if (flags.headers.length > 0) {
3834
+ const hdrs = {};
3835
+ for (const [k, v] of flags.headers) {
3836
+ if (literalSecret(k, v)) return `header '${k}' holds a literal secret; use \${NAME} instead`;
3837
+ hdrs[k] = v;
3838
+ }
3839
+ config.headers = hdrs;
3840
+ }
3841
+ if (flags.description) config.description = flags.description;
3842
+ if (flags.exposure) config.exposure = flags.exposure;
3843
+ return config;
3844
+ }
3845
+ async function runAdd(platform, args, probe) {
3846
+ const flags = parseAddFlags(args);
3847
+ if (typeof flags === "string") {
3848
+ await platform.write(2, `mcpcat add: ${flags}
3849
+ `);
3850
+ return 2;
3851
+ }
3852
+ if (flags.positional.length < 1) {
3853
+ await platform.write(2, "mcpcat add: requires a server name\n");
3854
+ return 2;
3855
+ }
3856
+ let name;
3857
+ let config;
3858
+ if (flags.cmdArgs.length > 0) {
3859
+ name = flags.positional[0];
3860
+ config = buildStdioConfig(flags);
3861
+ } else if (flags.positional.length >= 2) {
3862
+ let urlStr;
3863
+ if (URL.canParse(flags.positional[0]) && !URL.canParse(flags.positional[1])) {
3864
+ urlStr = flags.positional[0];
3865
+ name = flags.positional[1];
3866
+ } else {
3867
+ name = flags.positional[0];
3868
+ urlStr = flags.positional[1];
3869
+ }
3870
+ if (!URL.canParse(urlStr)) {
3871
+ await platform.write(2, `mcpcat add: '${urlStr}' is not a valid URL
3872
+ `);
3873
+ return 2;
3874
+ }
3875
+ const secret = urlHasSecret(urlStr);
3876
+ if (secret) {
3877
+ await platform.write(
3878
+ 2,
3879
+ `mcpcat add: ${secret} holds a literal secret; use \${NAME} in a header instead
3880
+ `
3881
+ );
3882
+ return 2;
3883
+ }
3884
+ const httpResult = buildHttpConfig(urlStr, flags);
3885
+ if (typeof httpResult === "string") {
3886
+ await platform.write(2, `mcpcat add: ${httpResult}
3887
+ `);
3888
+ return 2;
3889
+ }
3890
+ config = httpResult;
3891
+ } else {
3892
+ await platform.write(2, "mcpcat add: requires a URL or -- <command>\n");
3893
+ return 2;
3894
+ }
3895
+ const validation = validateServer(name, config);
3896
+ if ("message" in validation) {
3897
+ await platform.write(2, `mcpcat add: ${validation.message}
3898
+ `);
3899
+ return 2;
3900
+ }
3901
+ const path = flags.configFile ?? (flags.local ? projectConfigPath(platform) : userConfigPath(platform));
3902
+ const { replaced } = await addServer(platform.fs, path, name, config);
3903
+ const warnings = checkAgentWarnings(name, config);
3904
+ for (const w of warnings) {
3905
+ await platform.write(2, `mcpcat add: warning: ${w.message}; ${w.advice}
3906
+ `);
3907
+ }
3908
+ await platform.write(1, `${replaced ? "replaced" : "added"} ${name} in ${path}
3909
+ `);
3910
+ if (!flags.noProbe && probe) {
3911
+ const reason = await probe(name, config, platform);
3912
+ if (reason) {
3913
+ await platform.write(2, `mcpcat add: probe failed: ${reason}
3914
+ `);
3915
+ return 3;
3916
+ }
3917
+ }
3918
+ return 0;
3919
+ }
3920
+ async function runRm(platform, args) {
3921
+ let configFile;
3922
+ let local = false;
3923
+ const names = [];
3924
+ for (let i = 0; i < args.length; i++) {
3925
+ const arg = args[i];
3926
+ if (arg === "--config" && i + 1 < args.length) {
3927
+ configFile = args[++i];
3928
+ continue;
3929
+ }
3930
+ if (arg === "-l" || arg === "--local") {
3931
+ local = true;
3932
+ continue;
3933
+ }
3934
+ if (arg === "--logout") continue;
3935
+ if (arg.startsWith("-")) {
3936
+ await platform.write(2, `mcpcat rm: unknown option '${arg}'
3937
+ `);
3938
+ return 2;
3939
+ }
3940
+ names.push(arg);
3941
+ }
3942
+ if (names.length === 0) {
3943
+ await platform.write(2, "mcpcat rm: requires a server name\n");
3944
+ return 2;
3945
+ }
3946
+ const path = configFile ?? (local ? projectConfigPath(platform) : userConfigPath(platform));
3947
+ for (const name of names) {
3948
+ const removed = await removeServer(platform.fs, path, name);
3949
+ if (!removed) {
3950
+ await platform.write(2, `mcpcat rm: '${name}' not found in ${path}
3951
+ `);
3952
+ return 1;
3953
+ }
3954
+ await platform.write(1, `removed ${name} from ${path}
3955
+ `);
3956
+ }
3957
+ return 0;
3958
+ }
3959
+ function formatListEntry(entry) {
3960
+ const c = entry.config;
3961
+ const transport = "url" in c ? "http" : "stdio";
3962
+ const target = "url" in c ? c.url : c.command;
3963
+ const enabled = "enabled" in c && c.enabled === false ? " (disabled)" : "";
3964
+ const exp = c.exposure ? ` [${c.exposure}]` : "";
3965
+ return `${entry.name} ${transport} ${target}${enabled}${exp} (${entry.source})`;
3966
+ }
3967
+ async function printListJson(platform, config) {
3968
+ const entries = {};
3969
+ for (const entry of config.servers) {
3970
+ entries[entry.name] = {
3971
+ ...entry.config,
3972
+ source: entry.source,
3973
+ ...entry.scope ? { scope: entry.scope } : {},
3974
+ ...entry.override ? { override: entry.override } : {}
3975
+ };
3976
+ }
3977
+ await platform.write(1, `${JSON.stringify(entries, null, 2)}
3978
+ `);
3979
+ }
3980
+ async function printListText(platform, config) {
3981
+ if (config.servers.length === 0 && config.problems.length === 0) {
3982
+ await platform.write(1, "no servers configured\n");
3983
+ return;
3984
+ }
3985
+ for (const entry of config.servers) {
3986
+ await platform.write(1, `${formatListEntry(entry)}
3987
+ `);
3988
+ }
3989
+ }
3990
+ async function runList(platform, args) {
3991
+ let json = false;
3992
+ let configFile;
3993
+ let trustProject = false;
3994
+ for (let i = 0; i < args.length; i++) {
3995
+ const arg = args[i];
3996
+ if (arg === "--json") {
3997
+ json = true;
3998
+ continue;
3999
+ }
4000
+ if (arg === "--config" && i + 1 < args.length) {
4001
+ configFile = args[++i];
4002
+ continue;
4003
+ }
4004
+ if (arg === "--trust-project") {
4005
+ trustProject = true;
4006
+ }
4007
+ }
4008
+ const source = await MergedConfigSource.load(platform, { trustProject, configFile });
4009
+ const { config } = source;
4010
+ if (json) {
4011
+ await printListJson(platform, config);
4012
+ } else {
4013
+ await printListText(platform, config);
4014
+ }
4015
+ let hasProblems = false;
4016
+ for (const p of config.problems) {
4017
+ hasProblems = true;
4018
+ const prefix = p.server ? `${p.server}: ` : "";
4019
+ await platform.write(2, `mcpcat list: ${prefix}${p.message}
4020
+ `);
4021
+ }
4022
+ return hasProblems ? 1 : 0;
4023
+ }
4024
+ async function runEnable(platform, args, enable) {
4025
+ let configFile;
4026
+ let local = false;
4027
+ const names = [];
4028
+ for (let i = 0; i < args.length; i++) {
4029
+ const arg = args[i];
4030
+ if (arg === "--config" && i + 1 < args.length) {
4031
+ configFile = args[++i];
4032
+ continue;
4033
+ }
4034
+ if (arg === "-l" || arg === "--local") {
4035
+ local = true;
4036
+ continue;
4037
+ }
4038
+ if (arg.startsWith("-")) continue;
4039
+ names.push(arg);
4040
+ }
4041
+ if (names.length === 0) {
4042
+ await platform.write(2, `mcpcat ${enable ? "enable" : "disable"}: requires a server name
4043
+ `);
4044
+ return 2;
4045
+ }
4046
+ const path = configFile ?? (local ? projectConfigPath(platform) : userConfigPath(platform));
4047
+ for (const name of names) {
4048
+ const ok = await updateServer(platform.fs, path, name, { enabled: enable });
4049
+ if (!ok) {
4050
+ await platform.write(
4051
+ 2,
4052
+ `mcpcat ${enable ? "enable" : "disable"}: '${name}' not found in ${path}
4053
+ `
4054
+ );
4055
+ return 1;
4056
+ }
4057
+ await platform.write(1, `${enable ? "enabled" : "disabled"} ${name} in ${path}
4058
+ `);
4059
+ }
4060
+ return 0;
4061
+ }
4062
+ async function runExposure(platform, args) {
4063
+ let configFile;
4064
+ let local = false;
4065
+ let toolGlob;
4066
+ const positional = [];
4067
+ for (let i = 0; i < args.length; i++) {
4068
+ const arg = args[i];
4069
+ if (arg === "--config" && i + 1 < args.length) {
4070
+ configFile = args[++i];
4071
+ continue;
4072
+ }
4073
+ if (arg === "-l" || arg === "--local") {
4074
+ local = true;
4075
+ continue;
4076
+ }
4077
+ if (arg === "--tool" && i + 1 < args.length) {
4078
+ toolGlob = args[++i];
4079
+ continue;
4080
+ }
4081
+ if (arg.startsWith("-")) continue;
4082
+ positional.push(arg);
4083
+ }
4084
+ if (positional.length < 2) {
4085
+ await platform.write(2, "mcpcat exposure: requires <name> <mode>\n");
4086
+ return 2;
4087
+ }
4088
+ const [name, mode] = positional;
4089
+ const validModes = ["codemode", "deferred", "direct", "hidden"];
4090
+ if (!validModes.includes(mode)) {
4091
+ await platform.write(2, `mcpcat exposure: mode must be one of ${validModes.join(", ")}
4092
+ `);
4093
+ return 2;
4094
+ }
4095
+ const path = configFile ?? (local ? projectConfigPath(platform) : userConfigPath(platform));
4096
+ const ok = await setExposure(platform.fs, path, name, mode, toolGlob);
4097
+ if (!ok) {
4098
+ await platform.write(2, `mcpcat exposure: '${name}' not found in ${path}
4099
+ `);
4100
+ return 1;
4101
+ }
4102
+ const what = toolGlob ? `${name} tool ${toolGlob}` : name;
4103
+ await platform.write(1, `set ${what} to ${mode} in ${path}
4104
+ `);
4105
+ return 0;
4106
+ }
4107
+ async function runImport(platform, args) {
4108
+ let configFile;
4109
+ let local = false;
4110
+ const positional = [];
4111
+ for (let i = 0; i < args.length; i++) {
4112
+ const arg = args[i];
4113
+ if (arg === "--config" && i + 1 < args.length) {
4114
+ configFile = args[++i];
4115
+ continue;
4116
+ }
4117
+ if (arg === "-l" || arg === "--local") {
4118
+ local = true;
4119
+ continue;
4120
+ }
4121
+ if (arg.startsWith("-")) continue;
4122
+ positional.push(arg);
4123
+ }
4124
+ if (positional.length < 1) {
4125
+ await platform.write(2, "mcpcat import: requires a file path\n");
4126
+ return 2;
4127
+ }
4128
+ const filePath = positional[0];
4129
+ const names = positional.slice(1);
4130
+ let text;
4131
+ try {
4132
+ const data = await platform.fs.readFile(filePath);
4133
+ text = new TextDecoder().decode(data);
4134
+ } catch {
4135
+ await platform.write(2, `mcpcat import: cannot read '${filePath}'
4136
+ `);
4137
+ return 2;
4138
+ }
4139
+ const result = importFile(text, filePath, names.length > 0 ? names : void 0);
4140
+ for (const err of result.errors) {
4141
+ await platform.write(2, `mcpcat import: ${err}
4142
+ `);
4143
+ }
4144
+ if (result.servers.length === 0) {
4145
+ await platform.write(2, "mcpcat import: no servers found\n");
4146
+ return 1;
4147
+ }
4148
+ const destPath = configFile ?? (local ? projectConfigPath(platform) : userConfigPath(platform));
4149
+ for (const { name, config } of result.servers) {
4150
+ const validation = validateServer(name, config);
4151
+ if ("message" in validation) {
4152
+ await platform.write(2, `mcpcat import: ${name}: ${validation.message}
4153
+ `);
4154
+ continue;
4155
+ }
4156
+ const { replaced } = await addServer(platform.fs, destPath, name, config);
4157
+ await platform.write(1, `${replaced ? "replaced" : "imported"} ${name}
4158
+ `);
4159
+ }
4160
+ return 0;
1567
4161
  }
1568
4162
 
1569
4163
  // src/cli/main.ts
@@ -1595,6 +4189,15 @@ var VERBS = [
1595
4189
  "inbox",
1596
4190
  "help"
1597
4191
  ];
4192
+ var CONFIG_VERBS = {
4193
+ add: true,
4194
+ rm: true,
4195
+ list: true,
4196
+ enable: true,
4197
+ disable: true,
4198
+ exposure: true,
4199
+ import: true
4200
+ };
1598
4201
  var UNIMPLEMENTED_VERBS = /* @__PURE__ */ new Set([
1599
4202
  "resources",
1600
4203
  "read",
@@ -1603,21 +4206,13 @@ var UNIMPLEMENTED_VERBS = /* @__PURE__ */ new Set([
1603
4206
  "grep",
1604
4207
  "complete",
1605
4208
  "task",
1606
- "add",
1607
- "rm",
1608
- "list",
1609
- "enable",
1610
- "disable",
1611
- "exposure",
1612
- "import",
1613
4209
  "login",
1614
4210
  "logout",
1615
- "serve",
1616
4211
  "code",
1617
4212
  "discover",
1618
4213
  "inbox"
1619
4214
  ]);
1620
- var CLIENT_VERBS = /* @__PURE__ */ new Set(["info", "tools", "call", "describe"]);
4215
+ var CLIENT_VERBS = /* @__PURE__ */ new Set(["info", "tools", "call", "describe", "serve"]);
1621
4216
  function helpText(version) {
1622
4217
  return `mcpcat ${version} \u2013 a curl for the Model Context Protocol
1623
4218
 
@@ -1631,17 +4226,17 @@ Client verbs:
1631
4226
  describe <target> [tool] Tool schema and help
1632
4227
 
1633
4228
  Configuration verbs:
1634
- add <name> <url> Add a server to mcp.json (not implemented yet)
1635
- rm <name> Remove a server (not implemented yet)
1636
- list List configured servers (not implemented yet)
1637
- enable|disable <name> Toggle a server (not implemented yet)
1638
- exposure <name> <mode> Set exposure mode (not implemented yet)
1639
- import <file> Import from other configs (not implemented yet)
4229
+ add <name> <url> Add a server to mcp.json
4230
+ rm <name> Remove a server
4231
+ list List configured servers
4232
+ enable|disable <name> Toggle a server
4233
+ exposure <name> <mode> Set exposure mode
4234
+ import <file> Import from other configs
1640
4235
  login <target> OAuth sign-in (not implemented yet)
1641
4236
  logout <target> Remove tokens (not implemented yet)
1642
4237
 
1643
4238
  Server and code verbs:
1644
- serve [--stdio|--http] \u2026 Expose commands as MCP server (not implemented yet)
4239
+ serve [--stdio|--http] \u2026 Expose commands as MCP server
1645
4240
  code [-e src|file.js] Run a codemode script (not implemented yet)
1646
4241
  discover <url> Find MCP servers (not implemented yet)
1647
4242
  inbox Discovery inbox (not implemented yet)
@@ -1895,6 +4490,55 @@ async function runVerb(platform, parsed, conn) {
1895
4490
  return 2;
1896
4491
  }
1897
4492
  }
4493
+ async function probeServer(_name, config, platform) {
4494
+ try {
4495
+ const opts = { version: "probe" };
4496
+ if ("url" in config && config.url) {
4497
+ opts.url = config.url;
4498
+ if ("headers" in config) opts.headers = config.headers;
4499
+ } else if ("command" in config && config.command) {
4500
+ opts.command = config.command;
4501
+ if ("args" in config) opts.args = config.args;
4502
+ if ("env" in config) opts.env = config.env;
4503
+ if ("cwd" in config) opts.cwd = config.cwd;
4504
+ } else {
4505
+ return void 0;
4506
+ }
4507
+ const conn = await connect(platform, opts);
4508
+ try {
4509
+ await conn.info();
4510
+ } finally {
4511
+ try {
4512
+ await conn.close();
4513
+ } catch {
4514
+ }
4515
+ }
4516
+ return void 0;
4517
+ } catch (err) {
4518
+ return err.message;
4519
+ }
4520
+ }
4521
+ async function dispatchConfigVerb(platform, verb, args) {
4522
+ const rest = args.slice(1);
4523
+ switch (verb) {
4524
+ case "add":
4525
+ return runAdd(platform, rest, probeServer);
4526
+ case "rm":
4527
+ return runRm(platform, rest);
4528
+ case "list":
4529
+ return runList(platform, rest);
4530
+ case "enable":
4531
+ return runEnable(platform, rest, true);
4532
+ case "disable":
4533
+ return runEnable(platform, rest, false);
4534
+ case "exposure":
4535
+ return runExposure(platform, rest);
4536
+ case "import":
4537
+ return runImport(platform, rest);
4538
+ default:
4539
+ return 1;
4540
+ }
4541
+ }
1898
4542
  async function run(platform, version, args) {
1899
4543
  if (args.includes("--version") || args.includes("-V")) {
1900
4544
  await platform.write(1, `${version}
@@ -1914,11 +4558,23 @@ async function run(platform, version, args) {
1914
4558
  await platform.write(2, "mcpcat: no verb or target given\n");
1915
4559
  return 2;
1916
4560
  }
4561
+ if (parsed.verb in CONFIG_VERBS) {
4562
+ return dispatchConfigVerb(platform, parsed.verb, args);
4563
+ }
1917
4564
  if (UNIMPLEMENTED_VERBS.has(parsed.verb)) {
1918
4565
  await platform.write(2, `mcpcat: '${parsed.verb}' is not implemented yet
1919
4566
  `);
1920
4567
  return 1;
1921
4568
  }
4569
+ if (parsed.verb === "serve") {
4570
+ const serveArgs = args.slice(args.indexOf("serve") + 1);
4571
+ const serveOptions = parseServeFlags(serveArgs);
4572
+ if (serveOptions.commands.length === 0 && serveOptions.toolTemplates.length === 0) {
4573
+ await platform.write(2, "mcpcat serve: no commands or --tool templates given\n");
4574
+ return 2;
4575
+ }
4576
+ return runServe(platform, serveOptions, version);
4577
+ }
1922
4578
  if (!CLIENT_VERBS.has(parsed.verb)) {
1923
4579
  await platform.write(2, `mcpcat: unknown command '${parsed.verb}'
1924
4580
  `);
@@ -1933,7 +4589,7 @@ async function run(platform, version, args) {
1933
4589
  `);
1934
4590
  return 2;
1935
4591
  }
1936
- const config = createConfigSource(platform);
4592
+ const config = await MergedConfigSource.load(platform);
1937
4593
  let resolved;
1938
4594
  try {
1939
4595
  resolved = await resolveTarget(
@@ -1986,7 +4642,17 @@ function kernelFs(ctx) {
1986
4642
  mkdir: (path) => ctx.fs.mkdir(path),
1987
4643
  rename: (from, to) => ctx.fs.rename(from, to),
1988
4644
  stat: (path) => ctx.fs.stat(path),
1989
- exists: (path) => ctx.fs.exists(path)
4645
+ exists: (path) => ctx.fs.exists(path),
4646
+ async mkdirExclusive(path) {
4647
+ const exists = await ctx.fs.exists(path);
4648
+ if (exists) {
4649
+ const err = new Error(`EEXIST: directory already exists, mkdir '${path}'`);
4650
+ err.code = "EEXIST";
4651
+ throw err;
4652
+ }
4653
+ await ctx.fs.mkdir(path);
4654
+ },
4655
+ rmdir: (path) => ctx.fs.rm(path)
1990
4656
  };
1991
4657
  }
1992
4658
  async function kernelSpawn(ctx, options) {
@@ -2006,11 +4672,46 @@ async function kernelSpawn(ctx, options) {
2006
4672
  kill: (signal) => result.kill(signal)
2007
4673
  };
2008
4674
  }
4675
+ async function kernelListen(ctx, options) {
4676
+ const raw = await ctx.net.listen({ port: options.port, host: options.host });
4677
+ let closed = false;
4678
+ async function accept() {
4679
+ const conn = await raw.accept();
4680
+ return {
4681
+ readable: conn.readable,
4682
+ writable: conn.writable,
4683
+ remoteAddress: conn.remote.host,
4684
+ close() {
4685
+ conn.close();
4686
+ }
4687
+ };
4688
+ }
4689
+ return {
4690
+ get port() {
4691
+ return raw.port;
4692
+ },
4693
+ accept,
4694
+ close() {
4695
+ closed = true;
4696
+ raw.close();
4697
+ },
4698
+ async *[Symbol.asyncIterator]() {
4699
+ while (!closed) {
4700
+ try {
4701
+ yield await accept();
4702
+ } catch {
4703
+ break;
4704
+ }
4705
+ }
4706
+ }
4707
+ };
4708
+ }
2009
4709
  function createKernelPlatform(ctx) {
2010
- const encoder = new TextEncoder();
4710
+ const encoder2 = new TextEncoder();
2011
4711
  return {
2012
4712
  fetch: ctx.fetch,
2013
4713
  spawn: (options) => kernelSpawn(ctx, options),
4714
+ listen: (options) => kernelListen(ctx, options),
2014
4715
  fs: kernelFs(ctx),
2015
4716
  env: ctx.env,
2016
4717
  cwd: ctx.cwd,
@@ -2019,10 +4720,13 @@ function createKernelPlatform(ctx) {
2019
4720
  stdout: ctx.stdout,
2020
4721
  stderr: ctx.stderr,
2021
4722
  async write(fd, data) {
2022
- await ctx.write(fd, typeof data === "string" ? encoder.encode(data) : data);
4723
+ await ctx.write(fd, typeof data === "string" ? encoder2.encode(data) : data);
2023
4724
  },
2024
4725
  exit(code) {
2025
4726
  ctx.exit(code);
4727
+ },
4728
+ onSignal(signal, handler) {
4729
+ ctx.signals.on(signal, handler);
2026
4730
  }
2027
4731
  };
2028
4732
  }
@@ -2031,7 +4735,7 @@ function createKernelPlatform(ctx) {
2031
4735
  async function main(ctx) {
2032
4736
  const platform = createKernelPlatform(ctx);
2033
4737
  const args = ctx.argv.slice(1);
2034
- return run(platform, "0.2.0", args);
4738
+ return run(platform, "0.4.0", args);
2035
4739
  }
2036
4740
  export {
2037
4741
  main as default