@ai-ecoverse/mcpcat 0.2.0 → 0.3.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.
@@ -1538,34 +1538,1235 @@ 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
+ }
1546
1801
  return {
1547
- async get(name) {
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/lock.ts
1862
+ var LOCK_STALE_MS = 1e4;
1863
+ var LOCK_POLL_MS = 50;
1864
+ var LOCK_MAX_WAIT_MS = 5e3;
1865
+ function isEexist(err) {
1866
+ if (err instanceof Error && "code" in err)
1867
+ return err.code === "EEXIST";
1868
+ if (err instanceof Error) return err.message.includes("EEXIST");
1869
+ return false;
1870
+ }
1871
+ async function removeStaleLock(fs, lockPath) {
1872
+ try {
1873
+ const s = await fs.stat(lockPath);
1874
+ if (Date.now() - s.mtimeMs > LOCK_STALE_MS) {
1548
1875
  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
- }
1560
- }
1561
- return void 0;
1876
+ await fs.rmdir(lockPath);
1562
1877
  } catch {
1563
- return void 0;
1564
1878
  }
1879
+ return true;
1880
+ }
1881
+ } catch {
1882
+ }
1883
+ return false;
1884
+ }
1885
+ async function acquireLock(fs, configPath) {
1886
+ const lockPath = `${configPath}.lock`;
1887
+ const start = Date.now();
1888
+ while (true) {
1889
+ try {
1890
+ await fs.mkdirExclusive(lockPath);
1891
+ break;
1892
+ } catch (err) {
1893
+ if (!isEexist(err)) throw err;
1894
+ await removeStaleLock(fs, lockPath);
1895
+ }
1896
+ if (Date.now() - start > LOCK_MAX_WAIT_MS) {
1897
+ throw new Error(`mcpcat: could not acquire lock ${lockPath} within ${LOCK_MAX_WAIT_MS}ms`);
1898
+ }
1899
+ await new Promise((r) => setTimeout(r, LOCK_POLL_MS));
1900
+ }
1901
+ let released = false;
1902
+ return async () => {
1903
+ if (released) return;
1904
+ released = true;
1905
+ try {
1906
+ await fs.rmdir(lockPath);
1907
+ } catch {
1565
1908
  }
1566
1909
  };
1567
1910
  }
1568
1911
 
1912
+ // src/config/edit.ts
1913
+ function isRecord2(value) {
1914
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1915
+ }
1916
+ function detectIndent(text) {
1917
+ const match = /^([ \t]+)\S/m.exec(text);
1918
+ return match ? match[1] : " ";
1919
+ }
1920
+ async function readText(fs, path) {
1921
+ try {
1922
+ const data = await fs.readFile(path);
1923
+ return new TextDecoder().decode(data);
1924
+ } catch {
1925
+ return void 0;
1926
+ }
1927
+ }
1928
+ async function editMcpServers(fs, path, edit) {
1929
+ const release = await acquireLock(fs, path);
1930
+ try {
1931
+ const text = await readText(fs, path);
1932
+ const parsed = text === void 0 ? {} : JSON.parse(text);
1933
+ if (!isRecord2(parsed) || parsed.mcpServers !== void 0 && !isRecord2(parsed.mcpServers))
1934
+ throw new Error(`${path}: expected an object with an "mcpServers" object`);
1935
+ const servers = isRecord2(parsed.mcpServers) ? parsed.mcpServers : void 0;
1936
+ if (!edit(servers, parsed)) return { changed: false };
1937
+ const indent = text ? detectIndent(text) : " ";
1938
+ const output = `${JSON.stringify(parsed, null, indent)}
1939
+ `;
1940
+ const dir = path.slice(0, path.lastIndexOf("/"));
1941
+ if (dir) {
1942
+ try {
1943
+ await fs.mkdir(dir);
1944
+ } catch {
1945
+ }
1946
+ }
1947
+ const tmpPath = `${path}.tmp.${Date.now()}`;
1948
+ await fs.writeFile(tmpPath, output);
1949
+ await fs.rename(tmpPath, path);
1950
+ return { changed: true };
1951
+ } finally {
1952
+ await release();
1953
+ }
1954
+ }
1955
+ async function addServer(fs, path, name, config) {
1956
+ let replaced = false;
1957
+ await editMcpServers(fs, path, (servers, parsed) => {
1958
+ const target = servers ?? {};
1959
+ replaced = target[name] !== void 0;
1960
+ target[name] = config;
1961
+ parsed.mcpServers = target;
1962
+ return true;
1963
+ });
1964
+ return { replaced };
1965
+ }
1966
+ async function removeServer(fs, path, name) {
1967
+ let removed = false;
1968
+ await editMcpServers(fs, path, (servers) => {
1969
+ if (!servers || servers[name] === void 0) return false;
1970
+ delete servers[name];
1971
+ removed = true;
1972
+ return true;
1973
+ });
1974
+ return removed;
1975
+ }
1976
+ async function updateServer(fs, path, name, patch) {
1977
+ let updated = false;
1978
+ await editMcpServers(fs, path, (servers) => {
1979
+ if (!servers || !isRecord2(servers[name])) return false;
1980
+ const entry = servers[name];
1981
+ if (patch.enabled !== void 0) entry.enabled = patch.enabled;
1982
+ if (patch.exposure !== void 0) entry.exposure = patch.exposure;
1983
+ if (patch.toolExposure !== void 0) entry.toolExposure = patch.toolExposure;
1984
+ updated = true;
1985
+ return true;
1986
+ });
1987
+ return updated;
1988
+ }
1989
+ async function setExposure(fs, path, name, exposure, toolGlob) {
1990
+ let updated = false;
1991
+ await editMcpServers(fs, path, (servers) => {
1992
+ if (!servers || !isRecord2(servers[name])) return false;
1993
+ const entry = servers[name];
1994
+ if (toolGlob) {
1995
+ const te = isRecord2(entry.toolExposure) ? { ...entry.toolExposure } : {};
1996
+ te[toolGlob] = exposure;
1997
+ entry.toolExposure = te;
1998
+ } else {
1999
+ entry.exposure = exposure;
2000
+ }
2001
+ updated = true;
2002
+ return true;
2003
+ });
2004
+ return updated;
2005
+ }
2006
+
2007
+ // src/config/import.ts
2008
+ function isRecord3(value) {
2009
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2010
+ }
2011
+ function isStringRecord2(value) {
2012
+ return isRecord3(value) && Object.values(value).every((v) => typeof v === "string");
2013
+ }
2014
+ function tryParse(text) {
2015
+ try {
2016
+ return { parsed: JSON.parse(text) };
2017
+ } catch (e) {
2018
+ return { parsed: void 0, error: `not valid JSON: ${e.message}` };
2019
+ }
2020
+ }
2021
+ function filterNames(entries, names) {
2022
+ const result = [];
2023
+ for (const [name, value] of entries) {
2024
+ if (names && names.length > 0 && !names.includes(name)) continue;
2025
+ result.push([name, value]);
2026
+ }
2027
+ return result;
2028
+ }
2029
+ function replaceInputVars(value) {
2030
+ return value.replace(
2031
+ /\$\{input:([^}]+)\}/g,
2032
+ (_, name) => `\${${name.toUpperCase().replace(/[^A-Z0-9]/g, "_")}}`
2033
+ );
2034
+ }
2035
+ function importClaude(text, names) {
2036
+ const result = { servers: [], errors: [] };
2037
+ const { parsed, error } = tryParse(text);
2038
+ if (error) {
2039
+ result.errors.push(error);
2040
+ return result;
2041
+ }
2042
+ if (!isRecord3(parsed)) {
2043
+ result.errors.push("expected an object");
2044
+ return result;
2045
+ }
2046
+ const mcpServers = parsed.mcpServers;
2047
+ if (!isRecord3(mcpServers)) {
2048
+ result.errors.push('no "mcpServers" object');
2049
+ return result;
2050
+ }
2051
+ for (const [name, entry] of filterNames(Object.entries(mcpServers), names)) {
2052
+ if (!isRecord3(entry)) {
2053
+ result.errors.push(`${name}: not an object`);
2054
+ continue;
2055
+ }
2056
+ result.servers.push({ name, config: entry });
2057
+ }
2058
+ return result;
2059
+ }
2060
+ function importVSCode(text, names) {
2061
+ const result = { servers: [], errors: [] };
2062
+ const { parsed, error } = tryParse(text);
2063
+ if (error) {
2064
+ result.errors.push(error);
2065
+ return result;
2066
+ }
2067
+ if (!isRecord3(parsed)) {
2068
+ result.errors.push("expected an object");
2069
+ return result;
2070
+ }
2071
+ const servers = parsed.servers ?? parsed.mcpServers;
2072
+ if (!isRecord3(servers)) {
2073
+ result.errors.push('no "servers" or "mcpServers" object');
2074
+ return result;
2075
+ }
2076
+ for (const [name, entry] of filterNames(Object.entries(servers), names)) {
2077
+ if (!isRecord3(entry)) {
2078
+ result.errors.push(`${name}: not an object`);
2079
+ continue;
2080
+ }
2081
+ result.servers.push({ name, config: convertVSCodeEntry(entry) });
2082
+ }
2083
+ return result;
2084
+ }
2085
+ function convertVSCodeEntry(entry) {
2086
+ const config = {};
2087
+ for (const [key, value] of Object.entries(entry)) {
2088
+ if (key === "type" || key === "command" || key === "args" || key === "cwd" || key === "url") {
2089
+ config[key] = value;
2090
+ } else if (key === "headers" && isStringRecord2(value)) {
2091
+ const headers = {};
2092
+ for (const [h, v] of Object.entries(value)) headers[h] = replaceInputVars(v);
2093
+ config.headers = headers;
2094
+ } else if (key === "env" && isStringRecord2(value)) {
2095
+ const env = {};
2096
+ for (const [k, v] of Object.entries(value)) env[k] = replaceInputVars(v);
2097
+ config.env = env;
2098
+ } else {
2099
+ config[key] = value;
2100
+ }
2101
+ }
2102
+ return config;
2103
+ }
2104
+ function importSixServers(text, names) {
2105
+ const result = { servers: [], errors: [] };
2106
+ const { parsed, error } = tryParse(text);
2107
+ if (error) {
2108
+ result.errors.push(error);
2109
+ return result;
2110
+ }
2111
+ if (!isRecord3(parsed)) {
2112
+ result.errors.push("expected an object");
2113
+ return result;
2114
+ }
2115
+ const servers = parsed.servers;
2116
+ if (!isRecord3(servers)) {
2117
+ result.errors.push('no "servers" object');
2118
+ return result;
2119
+ }
2120
+ for (const [name, entry] of filterNames(Object.entries(servers), names)) {
2121
+ if (!isRecord3(entry)) {
2122
+ result.errors.push(`${name}: not an object`);
2123
+ continue;
2124
+ }
2125
+ const config = {};
2126
+ if (typeof entry.url === "string") config.url = entry.url;
2127
+ if (isStringRecord2(entry.headers)) config.headers = entry.headers;
2128
+ if (typeof entry.exposure === "string") config.exposure = entry.exposure;
2129
+ if (isRecord3(entry.toolExposure)) config.toolExposure = entry.toolExposure;
2130
+ result.servers.push({ name, config });
2131
+ }
2132
+ return result;
2133
+ }
2134
+ function importCodexToml(text, names) {
2135
+ const result = { servers: [], errors: [] };
2136
+ const sections = parseTomlSections(text);
2137
+ for (const [sectionName, fields] of sections) {
2138
+ const prefix = "mcp_servers.";
2139
+ if (!sectionName.startsWith(prefix)) continue;
2140
+ const name = sectionName.slice(prefix.length);
2141
+ if (names && names.length > 0 && !names.includes(name)) continue;
2142
+ const config = {};
2143
+ if (fields.command) config.command = fields.command;
2144
+ if (fields.args) config.args = fields.args;
2145
+ if (fields.url) config.url = fields.url;
2146
+ if (fields.env && isRecord3(fields.env)) config.env = fields.env;
2147
+ result.servers.push({ name, config });
2148
+ }
2149
+ return result;
2150
+ }
2151
+ function parseTomlSections(text) {
2152
+ const sections = [];
2153
+ let current;
2154
+ let currentName = "";
2155
+ for (const line of text.split("\n")) {
2156
+ const trimmed = line.trim();
2157
+ if (trimmed.startsWith("#") || trimmed === "") continue;
2158
+ const sectionMatch = /^\[([^\]]+)\]/.exec(trimmed);
2159
+ if (sectionMatch) {
2160
+ if (current) sections.push([currentName, current]);
2161
+ currentName = sectionMatch[1].trim();
2162
+ current = {};
2163
+ continue;
2164
+ }
2165
+ if (!current) continue;
2166
+ const kvMatch = /^(\w+)\s*=\s*(.+)/.exec(trimmed);
2167
+ if (kvMatch) {
2168
+ current[kvMatch[1]] = parseTomlValue(kvMatch[2].trim());
2169
+ }
2170
+ }
2171
+ if (current) sections.push([currentName, current]);
2172
+ return sections;
2173
+ }
2174
+ function parseTomlValue(raw) {
2175
+ if (raw.startsWith('"') && raw.endsWith('"')) return raw.slice(1, -1);
2176
+ if (raw.startsWith("'") && raw.endsWith("'")) return raw.slice(1, -1);
2177
+ if (raw.startsWith("[")) {
2178
+ try {
2179
+ return JSON.parse(raw.replace(/'/g, '"'));
2180
+ } catch {
2181
+ return raw;
2182
+ }
2183
+ }
2184
+ if (raw === "true") return true;
2185
+ if (raw === "false") return false;
2186
+ const num = Number(raw);
2187
+ if (!Number.isNaN(num)) return num;
2188
+ return raw;
2189
+ }
2190
+ function convertOpenCodeLocal(entry) {
2191
+ const config = {};
2192
+ if (Array.isArray(entry.command) && entry.command.length > 0) {
2193
+ config.command = entry.command[0];
2194
+ if (entry.command.length > 1) config.args = entry.command.slice(1);
2195
+ } else if (typeof entry.command === "string") {
2196
+ config.command = entry.command;
2197
+ }
2198
+ if (isRecord3(entry.environment)) {
2199
+ const env = {};
2200
+ for (const [k, v] of Object.entries(entry.environment)) {
2201
+ if (typeof v === "string")
2202
+ env[k] = v.replace(/\{env:([^}]+)\}/g, (_, n) => `\${${n}}`);
2203
+ }
2204
+ config.env = env;
2205
+ }
2206
+ return config;
2207
+ }
2208
+ function convertOpenCodeRemote(entry) {
2209
+ const config = {};
2210
+ config.url = entry.url;
2211
+ if (isStringRecord2(entry.headers)) config.headers = entry.headers;
2212
+ return config;
2213
+ }
2214
+ function importOpenCode(text, names) {
2215
+ const result = { servers: [], errors: [] };
2216
+ const { parsed, error } = tryParse(text);
2217
+ if (error) {
2218
+ result.errors.push(error);
2219
+ return result;
2220
+ }
2221
+ if (!isRecord3(parsed)) {
2222
+ result.errors.push("expected an object");
2223
+ return result;
2224
+ }
2225
+ const mcpServers = parsed.mcpServers ?? parsed.mcp;
2226
+ if (!isRecord3(mcpServers)) {
2227
+ result.errors.push("no mcp servers found");
2228
+ return result;
2229
+ }
2230
+ for (const [name, entry] of filterNames(Object.entries(mcpServers), names)) {
2231
+ if (!isRecord3(entry)) {
2232
+ result.errors.push(`${name}: not an object`);
2233
+ continue;
2234
+ }
2235
+ const isLocal = entry.type === "local" || entry.command;
2236
+ const config = isLocal ? convertOpenCodeLocal(entry) : convertOpenCodeRemote(entry);
2237
+ result.servers.push({ name, config });
2238
+ }
2239
+ return result;
2240
+ }
2241
+ function detectFormat(text, filename) {
2242
+ if (filename.endsWith(".toml")) return "codex";
2243
+ if (filename.includes("servers.json")) return "six";
2244
+ if (filename.includes(".vscode")) return "vscode";
2245
+ try {
2246
+ const parsed = JSON.parse(text);
2247
+ if (isRecord3(parsed)) {
2248
+ if (parsed.servers && isRecord3(parsed.servers) && parsed.version !== void 0) return "six";
2249
+ if (parsed.servers && isRecord3(parsed.servers)) return "vscode";
2250
+ if (parsed.mcpServers) return "claude";
2251
+ if (parsed.mcp) return "opencode";
2252
+ }
2253
+ } catch {
2254
+ }
2255
+ if (text.includes("[mcp_servers.")) return "codex";
2256
+ return "claude";
2257
+ }
2258
+ function importFile(text, filename, names) {
2259
+ const format = detectFormat(text, filename);
2260
+ switch (format) {
2261
+ case "claude":
2262
+ return importClaude(text, names);
2263
+ case "vscode":
2264
+ return importVSCode(text, names);
2265
+ case "six":
2266
+ return importSixServers(text, names);
2267
+ case "codex":
2268
+ return importCodexToml(text, names);
2269
+ case "opencode":
2270
+ return importOpenCode(text, names);
2271
+ default:
2272
+ return importClaude(text, names);
2273
+ }
2274
+ }
2275
+
2276
+ // src/config/warnings.ts
2277
+ var SECRET_HEADER = /authorization|cookie|token|key|secret|password|session/i;
2278
+ var PLACEHOLDER = /\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g;
2279
+ var SCHEME = /^\s*(?:bearer|basic|token|apikey|api-key)\s+/i;
2280
+ var SECRET_PARAM = /token|key|secret|password|signature|sig|auth|code/i;
2281
+ function literalSecret(header, value) {
2282
+ if (!SECRET_HEADER.test(header)) return false;
2283
+ return value.replace(PLACEHOLDER, "").replace(SCHEME, "").trim() !== "";
2284
+ }
2285
+ function urlHasSecret(url) {
2286
+ if (!URL.canParse(url)) return void 0;
2287
+ const parsed = new URL(url);
2288
+ if (parsed.username || parsed.password) return "url";
2289
+ for (const name of parsed.searchParams.keys()) if (SECRET_PARAM.test(name)) return `url ?${name}`;
2290
+ return void 0;
2291
+ }
2292
+ var SLICC_OAUTH_REFUSED = {
2293
+ clientSecret: "a client secret would have to live in mcp.json; SLICC signs in as a public client",
2294
+ callbackPort: "SLICC signs in through its own page, not a loopback port",
2295
+ callbackUrl: "SLICC signs in through its own page, not a loopback URL",
2296
+ clientRegistration: "SLICC registers dynamically or uses oauth.clientId"
2297
+ };
2298
+ function checkAgentWarnings(name, config) {
2299
+ const warnings = [];
2300
+ if ("command" in config && config.command) {
2301
+ warnings.push({
2302
+ server: name,
2303
+ message: "stdio servers need slicc-kernel#68, so the agent will skip this entry",
2304
+ advice: "use mcpcat serve --proxy to bridge it as HTTP"
2305
+ });
2306
+ }
2307
+ if ("headers" in config && config.headers) {
2308
+ for (const [h, v] of Object.entries(config.headers)) {
2309
+ if (v.trim().startsWith("!")) {
2310
+ warnings.push({
2311
+ server: name,
2312
+ message: `headers.${h} runs a command, which the agent can't do`,
2313
+ advice: "use ${NAME} and set the value in Settings > MCP servers"
2314
+ });
2315
+ }
2316
+ if (literalSecret(h, v)) {
2317
+ warnings.push({
2318
+ server: name,
2319
+ message: `headers.${h} holds a literal secret`,
2320
+ advice: "write ${NAME} instead, and add the value in Settings > MCP servers"
2321
+ });
2322
+ }
2323
+ }
2324
+ }
2325
+ if ("url" in config && config.url) {
2326
+ const secret = urlHasSecret(config.url);
2327
+ if (secret) {
2328
+ warnings.push({
2329
+ server: name,
2330
+ message: `${secret} holds a literal secret`,
2331
+ advice: "put it in a header as ${NAME}"
2332
+ });
2333
+ }
2334
+ }
2335
+ if ("oauth" in config && config.oauth) {
2336
+ for (const key of Object.keys(config.oauth)) {
2337
+ const reason = SLICC_OAUTH_REFUSED[key];
2338
+ if (reason) {
2339
+ warnings.push({
2340
+ server: name,
2341
+ message: `oauth.${key} is not supported by the agent: ${reason}`,
2342
+ advice: `remove oauth.${key}`
2343
+ });
2344
+ }
2345
+ }
2346
+ }
2347
+ return warnings;
2348
+ }
2349
+
2350
+ // src/cli/config-verbs.ts
2351
+ function parseHeader(hdr) {
2352
+ const colonIdx = hdr.indexOf(":");
2353
+ if (colonIdx < 1) return `invalid header '${hdr}'`;
2354
+ return [hdr.slice(0, colonIdx).trim(), hdr.slice(colonIdx + 1).trim()];
2355
+ }
2356
+ function parseEnvPair(pair) {
2357
+ const eqIdx = pair.indexOf("=");
2358
+ if (eqIdx < 1) return `invalid --env '${pair}'`;
2359
+ return [pair.slice(0, eqIdx), pair.slice(eqIdx + 1)];
2360
+ }
2361
+ function parseAddFlagAt(flagArgs, i, flags) {
2362
+ const arg = flagArgs[i];
2363
+ if (arg === "-l" || arg === "--local") {
2364
+ flags.local = true;
2365
+ return { next: i + 1 };
2366
+ }
2367
+ if (arg === "--no-probe") {
2368
+ flags.noProbe = true;
2369
+ return { next: i + 1 };
2370
+ }
2371
+ if (arg === "--config" && i + 1 < flagArgs.length) {
2372
+ flags.configFile = flagArgs[i + 1];
2373
+ return { next: i + 2 };
2374
+ }
2375
+ if (arg === "--description" && i + 1 < flagArgs.length) {
2376
+ flags.description = flagArgs[i + 1];
2377
+ return { next: i + 2 };
2378
+ }
2379
+ if (arg === "--exposure" && i + 1 < flagArgs.length) {
2380
+ flags.exposure = flagArgs[i + 1];
2381
+ return { next: i + 2 };
2382
+ }
2383
+ if ((arg === "-H" || arg === "--header") && i + 1 < flagArgs.length) {
2384
+ const result = parseHeader(flagArgs[i + 1]);
2385
+ if (typeof result === "string") return { next: i + 2, error: result };
2386
+ flags.headers.push(result);
2387
+ return { next: i + 2 };
2388
+ }
2389
+ if (arg === "--env" && i + 1 < flagArgs.length) {
2390
+ const result = parseEnvPair(flagArgs[i + 1]);
2391
+ if (typeof result === "string") return { next: i + 2, error: result };
2392
+ flags.envPairs.push(result);
2393
+ return { next: i + 2 };
2394
+ }
2395
+ if (arg === "--cwd" && i + 1 < flagArgs.length) {
2396
+ flags.cwd = flagArgs[i + 1];
2397
+ return { next: i + 2 };
2398
+ }
2399
+ if (arg.startsWith("-")) return { next: i + 1, error: `unknown option '${arg}'` };
2400
+ flags.positional.push(arg);
2401
+ return { next: i + 1 };
2402
+ }
2403
+ function parseAddFlags(args) {
2404
+ const flags = {
2405
+ local: false,
2406
+ noProbe: false,
2407
+ headers: [],
2408
+ envPairs: [],
2409
+ positional: [],
2410
+ cmdArgs: []
2411
+ };
2412
+ const dashDashIdx = args.indexOf("--");
2413
+ const flagArgs = dashDashIdx >= 0 ? args.slice(0, dashDashIdx) : args;
2414
+ flags.cmdArgs = dashDashIdx >= 0 ? args.slice(dashDashIdx + 1) : [];
2415
+ let i = 0;
2416
+ while (i < flagArgs.length) {
2417
+ const step = parseAddFlagAt(flagArgs, i, flags);
2418
+ if (step.error) return step.error;
2419
+ i = step.next;
2420
+ }
2421
+ return flags;
2422
+ }
2423
+ function buildStdioConfig(flags) {
2424
+ const config = {
2425
+ command: flags.cmdArgs[0],
2426
+ ...flags.cmdArgs.length > 1 ? { args: flags.cmdArgs.slice(1) } : {}
2427
+ };
2428
+ if (flags.envPairs.length > 0) {
2429
+ const env = {};
2430
+ for (const [k, v] of flags.envPairs) env[k] = v;
2431
+ config.env = env;
2432
+ }
2433
+ if (flags.cwd) config.cwd = flags.cwd;
2434
+ if (flags.description) config.description = flags.description;
2435
+ if (flags.exposure) config.exposure = flags.exposure;
2436
+ return config;
2437
+ }
2438
+ function buildHttpConfig(urlStr, flags) {
2439
+ const config = { url: urlStr };
2440
+ if (flags.headers.length > 0) {
2441
+ const hdrs = {};
2442
+ for (const [k, v] of flags.headers) {
2443
+ if (literalSecret(k, v)) return `header '${k}' holds a literal secret; use \${NAME} instead`;
2444
+ hdrs[k] = v;
2445
+ }
2446
+ config.headers = hdrs;
2447
+ }
2448
+ if (flags.description) config.description = flags.description;
2449
+ if (flags.exposure) config.exposure = flags.exposure;
2450
+ return config;
2451
+ }
2452
+ async function runAdd(platform, args, probe) {
2453
+ const flags = parseAddFlags(args);
2454
+ if (typeof flags === "string") {
2455
+ await platform.write(2, `mcpcat add: ${flags}
2456
+ `);
2457
+ return 2;
2458
+ }
2459
+ if (flags.positional.length < 1) {
2460
+ await platform.write(2, "mcpcat add: requires a server name\n");
2461
+ return 2;
2462
+ }
2463
+ let name;
2464
+ let config;
2465
+ if (flags.cmdArgs.length > 0) {
2466
+ name = flags.positional[0];
2467
+ config = buildStdioConfig(flags);
2468
+ } else if (flags.positional.length >= 2) {
2469
+ let urlStr;
2470
+ if (URL.canParse(flags.positional[0]) && !URL.canParse(flags.positional[1])) {
2471
+ urlStr = flags.positional[0];
2472
+ name = flags.positional[1];
2473
+ } else {
2474
+ name = flags.positional[0];
2475
+ urlStr = flags.positional[1];
2476
+ }
2477
+ if (!URL.canParse(urlStr)) {
2478
+ await platform.write(2, `mcpcat add: '${urlStr}' is not a valid URL
2479
+ `);
2480
+ return 2;
2481
+ }
2482
+ const secret = urlHasSecret(urlStr);
2483
+ if (secret) {
2484
+ await platform.write(
2485
+ 2,
2486
+ `mcpcat add: ${secret} holds a literal secret; use \${NAME} in a header instead
2487
+ `
2488
+ );
2489
+ return 2;
2490
+ }
2491
+ const httpResult = buildHttpConfig(urlStr, flags);
2492
+ if (typeof httpResult === "string") {
2493
+ await platform.write(2, `mcpcat add: ${httpResult}
2494
+ `);
2495
+ return 2;
2496
+ }
2497
+ config = httpResult;
2498
+ } else {
2499
+ await platform.write(2, "mcpcat add: requires a URL or -- <command>\n");
2500
+ return 2;
2501
+ }
2502
+ const validation = validateServer(name, config);
2503
+ if ("message" in validation) {
2504
+ await platform.write(2, `mcpcat add: ${validation.message}
2505
+ `);
2506
+ return 2;
2507
+ }
2508
+ const path = flags.configFile ?? (flags.local ? projectConfigPath(platform) : userConfigPath(platform));
2509
+ const { replaced } = await addServer(platform.fs, path, name, config);
2510
+ const warnings = checkAgentWarnings(name, config);
2511
+ for (const w of warnings) {
2512
+ await platform.write(2, `mcpcat add: warning: ${w.message}; ${w.advice}
2513
+ `);
2514
+ }
2515
+ await platform.write(1, `${replaced ? "replaced" : "added"} ${name} in ${path}
2516
+ `);
2517
+ if (!flags.noProbe && probe) {
2518
+ const reason = await probe(name, config, platform);
2519
+ if (reason) {
2520
+ await platform.write(2, `mcpcat add: probe failed: ${reason}
2521
+ `);
2522
+ return 3;
2523
+ }
2524
+ }
2525
+ return 0;
2526
+ }
2527
+ async function runRm(platform, args) {
2528
+ let configFile;
2529
+ let local = false;
2530
+ const names = [];
2531
+ for (let i = 0; i < args.length; i++) {
2532
+ const arg = args[i];
2533
+ if (arg === "--config" && i + 1 < args.length) {
2534
+ configFile = args[++i];
2535
+ continue;
2536
+ }
2537
+ if (arg === "-l" || arg === "--local") {
2538
+ local = true;
2539
+ continue;
2540
+ }
2541
+ if (arg === "--logout") continue;
2542
+ if (arg.startsWith("-")) {
2543
+ await platform.write(2, `mcpcat rm: unknown option '${arg}'
2544
+ `);
2545
+ return 2;
2546
+ }
2547
+ names.push(arg);
2548
+ }
2549
+ if (names.length === 0) {
2550
+ await platform.write(2, "mcpcat rm: requires a server name\n");
2551
+ return 2;
2552
+ }
2553
+ const path = configFile ?? (local ? projectConfigPath(platform) : userConfigPath(platform));
2554
+ for (const name of names) {
2555
+ const removed = await removeServer(platform.fs, path, name);
2556
+ if (!removed) {
2557
+ await platform.write(2, `mcpcat rm: '${name}' not found in ${path}
2558
+ `);
2559
+ return 1;
2560
+ }
2561
+ await platform.write(1, `removed ${name} from ${path}
2562
+ `);
2563
+ }
2564
+ return 0;
2565
+ }
2566
+ function formatListEntry(entry) {
2567
+ const c = entry.config;
2568
+ const transport = "url" in c ? "http" : "stdio";
2569
+ const target = "url" in c ? c.url : c.command;
2570
+ const enabled = "enabled" in c && c.enabled === false ? " (disabled)" : "";
2571
+ const exp = c.exposure ? ` [${c.exposure}]` : "";
2572
+ return `${entry.name} ${transport} ${target}${enabled}${exp} (${entry.source})`;
2573
+ }
2574
+ async function printListJson(platform, config) {
2575
+ const entries = {};
2576
+ for (const entry of config.servers) {
2577
+ entries[entry.name] = {
2578
+ ...entry.config,
2579
+ source: entry.source,
2580
+ ...entry.scope ? { scope: entry.scope } : {},
2581
+ ...entry.override ? { override: entry.override } : {}
2582
+ };
2583
+ }
2584
+ await platform.write(1, `${JSON.stringify(entries, null, 2)}
2585
+ `);
2586
+ }
2587
+ async function printListText(platform, config) {
2588
+ if (config.servers.length === 0 && config.problems.length === 0) {
2589
+ await platform.write(1, "no servers configured\n");
2590
+ return;
2591
+ }
2592
+ for (const entry of config.servers) {
2593
+ await platform.write(1, `${formatListEntry(entry)}
2594
+ `);
2595
+ }
2596
+ }
2597
+ async function runList(platform, args) {
2598
+ let json = false;
2599
+ let configFile;
2600
+ let trustProject = false;
2601
+ for (let i = 0; i < args.length; i++) {
2602
+ const arg = args[i];
2603
+ if (arg === "--json") {
2604
+ json = true;
2605
+ continue;
2606
+ }
2607
+ if (arg === "--config" && i + 1 < args.length) {
2608
+ configFile = args[++i];
2609
+ continue;
2610
+ }
2611
+ if (arg === "--trust-project") {
2612
+ trustProject = true;
2613
+ }
2614
+ }
2615
+ const source = await MergedConfigSource.load(platform, { trustProject, configFile });
2616
+ const { config } = source;
2617
+ if (json) {
2618
+ await printListJson(platform, config);
2619
+ } else {
2620
+ await printListText(platform, config);
2621
+ }
2622
+ let hasProblems = false;
2623
+ for (const p of config.problems) {
2624
+ hasProblems = true;
2625
+ const prefix = p.server ? `${p.server}: ` : "";
2626
+ await platform.write(2, `mcpcat list: ${prefix}${p.message}
2627
+ `);
2628
+ }
2629
+ return hasProblems ? 1 : 0;
2630
+ }
2631
+ async function runEnable(platform, args, enable) {
2632
+ let configFile;
2633
+ let local = false;
2634
+ const names = [];
2635
+ for (let i = 0; i < args.length; i++) {
2636
+ const arg = args[i];
2637
+ if (arg === "--config" && i + 1 < args.length) {
2638
+ configFile = args[++i];
2639
+ continue;
2640
+ }
2641
+ if (arg === "-l" || arg === "--local") {
2642
+ local = true;
2643
+ continue;
2644
+ }
2645
+ if (arg.startsWith("-")) continue;
2646
+ names.push(arg);
2647
+ }
2648
+ if (names.length === 0) {
2649
+ await platform.write(2, `mcpcat ${enable ? "enable" : "disable"}: requires a server name
2650
+ `);
2651
+ return 2;
2652
+ }
2653
+ const path = configFile ?? (local ? projectConfigPath(platform) : userConfigPath(platform));
2654
+ for (const name of names) {
2655
+ const ok = await updateServer(platform.fs, path, name, { enabled: enable });
2656
+ if (!ok) {
2657
+ await platform.write(
2658
+ 2,
2659
+ `mcpcat ${enable ? "enable" : "disable"}: '${name}' not found in ${path}
2660
+ `
2661
+ );
2662
+ return 1;
2663
+ }
2664
+ await platform.write(1, `${enable ? "enabled" : "disabled"} ${name} in ${path}
2665
+ `);
2666
+ }
2667
+ return 0;
2668
+ }
2669
+ async function runExposure(platform, args) {
2670
+ let configFile;
2671
+ let local = false;
2672
+ let toolGlob;
2673
+ const positional = [];
2674
+ for (let i = 0; i < args.length; i++) {
2675
+ const arg = args[i];
2676
+ if (arg === "--config" && i + 1 < args.length) {
2677
+ configFile = args[++i];
2678
+ continue;
2679
+ }
2680
+ if (arg === "-l" || arg === "--local") {
2681
+ local = true;
2682
+ continue;
2683
+ }
2684
+ if (arg === "--tool" && i + 1 < args.length) {
2685
+ toolGlob = args[++i];
2686
+ continue;
2687
+ }
2688
+ if (arg.startsWith("-")) continue;
2689
+ positional.push(arg);
2690
+ }
2691
+ if (positional.length < 2) {
2692
+ await platform.write(2, "mcpcat exposure: requires <name> <mode>\n");
2693
+ return 2;
2694
+ }
2695
+ const [name, mode] = positional;
2696
+ const validModes = ["codemode", "deferred", "direct", "hidden"];
2697
+ if (!validModes.includes(mode)) {
2698
+ await platform.write(2, `mcpcat exposure: mode must be one of ${validModes.join(", ")}
2699
+ `);
2700
+ return 2;
2701
+ }
2702
+ const path = configFile ?? (local ? projectConfigPath(platform) : userConfigPath(platform));
2703
+ const ok = await setExposure(platform.fs, path, name, mode, toolGlob);
2704
+ if (!ok) {
2705
+ await platform.write(2, `mcpcat exposure: '${name}' not found in ${path}
2706
+ `);
2707
+ return 1;
2708
+ }
2709
+ const what = toolGlob ? `${name} tool ${toolGlob}` : name;
2710
+ await platform.write(1, `set ${what} to ${mode} in ${path}
2711
+ `);
2712
+ return 0;
2713
+ }
2714
+ async function runImport(platform, args) {
2715
+ let configFile;
2716
+ let local = false;
2717
+ const positional = [];
2718
+ for (let i = 0; i < args.length; i++) {
2719
+ const arg = args[i];
2720
+ if (arg === "--config" && i + 1 < args.length) {
2721
+ configFile = args[++i];
2722
+ continue;
2723
+ }
2724
+ if (arg === "-l" || arg === "--local") {
2725
+ local = true;
2726
+ continue;
2727
+ }
2728
+ if (arg.startsWith("-")) continue;
2729
+ positional.push(arg);
2730
+ }
2731
+ if (positional.length < 1) {
2732
+ await platform.write(2, "mcpcat import: requires a file path\n");
2733
+ return 2;
2734
+ }
2735
+ const filePath = positional[0];
2736
+ const names = positional.slice(1);
2737
+ let text;
2738
+ try {
2739
+ const data = await platform.fs.readFile(filePath);
2740
+ text = new TextDecoder().decode(data);
2741
+ } catch {
2742
+ await platform.write(2, `mcpcat import: cannot read '${filePath}'
2743
+ `);
2744
+ return 2;
2745
+ }
2746
+ const result = importFile(text, filePath, names.length > 0 ? names : void 0);
2747
+ for (const err of result.errors) {
2748
+ await platform.write(2, `mcpcat import: ${err}
2749
+ `);
2750
+ }
2751
+ if (result.servers.length === 0) {
2752
+ await platform.write(2, "mcpcat import: no servers found\n");
2753
+ return 1;
2754
+ }
2755
+ const destPath = configFile ?? (local ? projectConfigPath(platform) : userConfigPath(platform));
2756
+ for (const { name, config } of result.servers) {
2757
+ const validation = validateServer(name, config);
2758
+ if ("message" in validation) {
2759
+ await platform.write(2, `mcpcat import: ${name}: ${validation.message}
2760
+ `);
2761
+ continue;
2762
+ }
2763
+ const { replaced } = await addServer(platform.fs, destPath, name, config);
2764
+ await platform.write(1, `${replaced ? "replaced" : "imported"} ${name}
2765
+ `);
2766
+ }
2767
+ return 0;
2768
+ }
2769
+
1569
2770
  // src/cli/main.ts
1570
2771
  var VERBS = [
1571
2772
  "info",
@@ -1595,6 +2796,15 @@ var VERBS = [
1595
2796
  "inbox",
1596
2797
  "help"
1597
2798
  ];
2799
+ var CONFIG_VERBS = {
2800
+ add: true,
2801
+ rm: true,
2802
+ list: true,
2803
+ enable: true,
2804
+ disable: true,
2805
+ exposure: true,
2806
+ import: true
2807
+ };
1598
2808
  var UNIMPLEMENTED_VERBS = /* @__PURE__ */ new Set([
1599
2809
  "resources",
1600
2810
  "read",
@@ -1603,13 +2813,6 @@ var UNIMPLEMENTED_VERBS = /* @__PURE__ */ new Set([
1603
2813
  "grep",
1604
2814
  "complete",
1605
2815
  "task",
1606
- "add",
1607
- "rm",
1608
- "list",
1609
- "enable",
1610
- "disable",
1611
- "exposure",
1612
- "import",
1613
2816
  "login",
1614
2817
  "logout",
1615
2818
  "serve",
@@ -1631,12 +2834,12 @@ Client verbs:
1631
2834
  describe <target> [tool] Tool schema and help
1632
2835
 
1633
2836
  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)
2837
+ add <name> <url> Add a server to mcp.json
2838
+ rm <name> Remove a server
2839
+ list List configured servers
2840
+ enable|disable <name> Toggle a server
2841
+ exposure <name> <mode> Set exposure mode
2842
+ import <file> Import from other configs
1640
2843
  login <target> OAuth sign-in (not implemented yet)
1641
2844
  logout <target> Remove tokens (not implemented yet)
1642
2845
 
@@ -1895,6 +3098,55 @@ async function runVerb(platform, parsed, conn) {
1895
3098
  return 2;
1896
3099
  }
1897
3100
  }
3101
+ async function probeServer(_name, config, platform) {
3102
+ try {
3103
+ const opts = { version: "probe" };
3104
+ if ("url" in config && config.url) {
3105
+ opts.url = config.url;
3106
+ if ("headers" in config) opts.headers = config.headers;
3107
+ } else if ("command" in config && config.command) {
3108
+ opts.command = config.command;
3109
+ if ("args" in config) opts.args = config.args;
3110
+ if ("env" in config) opts.env = config.env;
3111
+ if ("cwd" in config) opts.cwd = config.cwd;
3112
+ } else {
3113
+ return void 0;
3114
+ }
3115
+ const conn = await connect(platform, opts);
3116
+ try {
3117
+ await conn.info();
3118
+ } finally {
3119
+ try {
3120
+ await conn.close();
3121
+ } catch {
3122
+ }
3123
+ }
3124
+ return void 0;
3125
+ } catch (err) {
3126
+ return err.message;
3127
+ }
3128
+ }
3129
+ async function dispatchConfigVerb(platform, verb, args) {
3130
+ const rest = args.slice(1);
3131
+ switch (verb) {
3132
+ case "add":
3133
+ return runAdd(platform, rest, probeServer);
3134
+ case "rm":
3135
+ return runRm(platform, rest);
3136
+ case "list":
3137
+ return runList(platform, rest);
3138
+ case "enable":
3139
+ return runEnable(platform, rest, true);
3140
+ case "disable":
3141
+ return runEnable(platform, rest, false);
3142
+ case "exposure":
3143
+ return runExposure(platform, rest);
3144
+ case "import":
3145
+ return runImport(platform, rest);
3146
+ default:
3147
+ return 1;
3148
+ }
3149
+ }
1898
3150
  async function run(platform, version, args) {
1899
3151
  if (args.includes("--version") || args.includes("-V")) {
1900
3152
  await platform.write(1, `${version}
@@ -1914,6 +3166,9 @@ async function run(platform, version, args) {
1914
3166
  await platform.write(2, "mcpcat: no verb or target given\n");
1915
3167
  return 2;
1916
3168
  }
3169
+ if (parsed.verb in CONFIG_VERBS) {
3170
+ return dispatchConfigVerb(platform, parsed.verb, args);
3171
+ }
1917
3172
  if (UNIMPLEMENTED_VERBS.has(parsed.verb)) {
1918
3173
  await platform.write(2, `mcpcat: '${parsed.verb}' is not implemented yet
1919
3174
  `);
@@ -1933,7 +3188,7 @@ async function run(platform, version, args) {
1933
3188
  `);
1934
3189
  return 2;
1935
3190
  }
1936
- const config = createConfigSource(platform);
3191
+ const config = await MergedConfigSource.load(platform);
1937
3192
  let resolved;
1938
3193
  try {
1939
3194
  resolved = await resolveTarget(
@@ -1986,7 +3241,17 @@ function kernelFs(ctx) {
1986
3241
  mkdir: (path) => ctx.fs.mkdir(path),
1987
3242
  rename: (from, to) => ctx.fs.rename(from, to),
1988
3243
  stat: (path) => ctx.fs.stat(path),
1989
- exists: (path) => ctx.fs.exists(path)
3244
+ exists: (path) => ctx.fs.exists(path),
3245
+ async mkdirExclusive(path) {
3246
+ const exists = await ctx.fs.exists(path);
3247
+ if (exists) {
3248
+ const err = new Error(`EEXIST: directory already exists, mkdir '${path}'`);
3249
+ err.code = "EEXIST";
3250
+ throw err;
3251
+ }
3252
+ await ctx.fs.mkdir(path);
3253
+ },
3254
+ rmdir: (path) => ctx.fs.rm(path)
1990
3255
  };
1991
3256
  }
1992
3257
  async function kernelSpawn(ctx, options) {
@@ -2031,7 +3296,7 @@ function createKernelPlatform(ctx) {
2031
3296
  async function main(ctx) {
2032
3297
  const platform = createKernelPlatform(ctx);
2033
3298
  const args = ctx.argv.slice(1);
2034
- return run(platform, "0.2.0", args);
3299
+ return run(platform, "0.3.0", args);
2035
3300
  }
2036
3301
  export {
2037
3302
  main as default