@ai-ecoverse/mcpcat 0.3.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,
@@ -1858,6 +1858,1399 @@ var MergedConfigSource = class _MergedConfigSource {
1858
1858
  }
1859
1859
  };
1860
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));
1897
+ return {
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) {
2874
+ try {
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 {
3190
+ }
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
+
1861
3254
  // src/config/lock.ts
1862
3255
  var LOCK_STALE_MS = 1e4;
1863
3256
  var LOCK_POLL_MS = 50;
@@ -2275,12 +3668,12 @@ function importFile(text, filename, names) {
2275
3668
 
2276
3669
  // src/config/warnings.ts
2277
3670
  var SECRET_HEADER = /authorization|cookie|token|key|secret|password|session/i;
2278
- var PLACEHOLDER = /\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g;
3671
+ var PLACEHOLDER2 = /\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g;
2279
3672
  var SCHEME = /^\s*(?:bearer|basic|token|apikey|api-key)\s+/i;
2280
3673
  var SECRET_PARAM = /token|key|secret|password|signature|sig|auth|code/i;
2281
3674
  function literalSecret(header, value) {
2282
3675
  if (!SECRET_HEADER.test(header)) return false;
2283
- return value.replace(PLACEHOLDER, "").replace(SCHEME, "").trim() !== "";
3676
+ return value.replace(PLACEHOLDER2, "").replace(SCHEME, "").trim() !== "";
2284
3677
  }
2285
3678
  function urlHasSecret(url) {
2286
3679
  if (!URL.canParse(url)) return void 0;
@@ -2815,12 +4208,11 @@ var UNIMPLEMENTED_VERBS = /* @__PURE__ */ new Set([
2815
4208
  "task",
2816
4209
  "login",
2817
4210
  "logout",
2818
- "serve",
2819
4211
  "code",
2820
4212
  "discover",
2821
4213
  "inbox"
2822
4214
  ]);
2823
- var CLIENT_VERBS = /* @__PURE__ */ new Set(["info", "tools", "call", "describe"]);
4215
+ var CLIENT_VERBS = /* @__PURE__ */ new Set(["info", "tools", "call", "describe", "serve"]);
2824
4216
  function helpText(version) {
2825
4217
  return `mcpcat ${version} \u2013 a curl for the Model Context Protocol
2826
4218
 
@@ -2844,7 +4236,7 @@ Configuration verbs:
2844
4236
  logout <target> Remove tokens (not implemented yet)
2845
4237
 
2846
4238
  Server and code verbs:
2847
- serve [--stdio|--http] \u2026 Expose commands as MCP server (not implemented yet)
4239
+ serve [--stdio|--http] \u2026 Expose commands as MCP server
2848
4240
  code [-e src|file.js] Run a codemode script (not implemented yet)
2849
4241
  discover <url> Find MCP servers (not implemented yet)
2850
4242
  inbox Discovery inbox (not implemented yet)
@@ -3174,6 +4566,15 @@ async function run(platform, version, args) {
3174
4566
  `);
3175
4567
  return 1;
3176
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
+ }
3177
4578
  if (!CLIENT_VERBS.has(parsed.verb)) {
3178
4579
  await platform.write(2, `mcpcat: unknown command '${parsed.verb}'
3179
4580
  `);
@@ -3271,11 +4672,46 @@ async function kernelSpawn(ctx, options) {
3271
4672
  kill: (signal) => result.kill(signal)
3272
4673
  };
3273
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
+ }
3274
4709
  function createKernelPlatform(ctx) {
3275
- const encoder = new TextEncoder();
4710
+ const encoder2 = new TextEncoder();
3276
4711
  return {
3277
4712
  fetch: ctx.fetch,
3278
4713
  spawn: (options) => kernelSpawn(ctx, options),
4714
+ listen: (options) => kernelListen(ctx, options),
3279
4715
  fs: kernelFs(ctx),
3280
4716
  env: ctx.env,
3281
4717
  cwd: ctx.cwd,
@@ -3284,10 +4720,13 @@ function createKernelPlatform(ctx) {
3284
4720
  stdout: ctx.stdout,
3285
4721
  stderr: ctx.stderr,
3286
4722
  async write(fd, data) {
3287
- await ctx.write(fd, typeof data === "string" ? encoder.encode(data) : data);
4723
+ await ctx.write(fd, typeof data === "string" ? encoder2.encode(data) : data);
3288
4724
  },
3289
4725
  exit(code) {
3290
4726
  ctx.exit(code);
4727
+ },
4728
+ onSignal(signal, handler) {
4729
+ ctx.signals.on(signal, handler);
3291
4730
  }
3292
4731
  };
3293
4732
  }
@@ -3296,7 +4735,7 @@ function createKernelPlatform(ctx) {
3296
4735
  async function main(ctx) {
3297
4736
  const platform = createKernelPlatform(ctx);
3298
4737
  const args = ctx.argv.slice(1);
3299
- return run(platform, "0.3.0", args);
4738
+ return run(platform, "0.4.0", args);
3300
4739
  }
3301
4740
  export {
3302
4741
  main as default