@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.
- package/dist/host/mcpcat.mjs +1489 -18
- package/dist/kernel/mcpcat.mjs +1457 -18
- package/package.json +5 -2
package/dist/host/mcpcat.mjs
CHANGED
|
@@ -1273,7 +1273,7 @@ var DEFAULT_RECONNECT_MAX_DELAY_MS = 3e4;
|
|
|
1273
1273
|
var DEFAULT_RECONNECT_MAX_RETRIES = 5;
|
|
1274
1274
|
async function consumeSseStream(stream, options) {
|
|
1275
1275
|
const reader = stream.getReader();
|
|
1276
|
-
const
|
|
1276
|
+
const decoder2 = new TextDecoder();
|
|
1277
1277
|
let buffered = "";
|
|
1278
1278
|
let eventName;
|
|
1279
1279
|
let eventId;
|
|
@@ -1324,7 +1324,7 @@ async function consumeSseStream(stream, options) {
|
|
|
1324
1324
|
const { done, value } = await reader.read();
|
|
1325
1325
|
if (done)
|
|
1326
1326
|
break;
|
|
1327
|
-
buffered +=
|
|
1327
|
+
buffered += decoder2.decode(value, { stream: true });
|
|
1328
1328
|
let newline = buffered.indexOf("\n");
|
|
1329
1329
|
while (newline >= 0) {
|
|
1330
1330
|
processLine(buffered.slice(0, newline));
|
|
@@ -1334,7 +1334,7 @@ async function consumeSseStream(stream, options) {
|
|
|
1334
1334
|
if (Buffer.byteLength(buffered) > maxEventBytes)
|
|
1335
1335
|
throw new Error(`MCP SSE event exceeds ${maxEventBytes} bytes`);
|
|
1336
1336
|
}
|
|
1337
|
-
buffered +=
|
|
1337
|
+
buffered += decoder2.decode();
|
|
1338
1338
|
if (buffered)
|
|
1339
1339
|
processLine(buffered);
|
|
1340
1340
|
dispatch();
|
|
@@ -1862,16 +1862,16 @@ async function createStatelessConnection(options) {
|
|
|
1862
1862
|
}
|
|
1863
1863
|
if (res.status >= 400) {
|
|
1864
1864
|
const text = await res.text();
|
|
1865
|
-
let
|
|
1865
|
+
let rpcError2;
|
|
1866
1866
|
try {
|
|
1867
1867
|
const parsed = JSON.parse(text);
|
|
1868
1868
|
if (parsed.error && typeof parsed.error.code === "number") {
|
|
1869
|
-
|
|
1869
|
+
rpcError2 = parsed.error;
|
|
1870
1870
|
}
|
|
1871
1871
|
} catch {
|
|
1872
1872
|
}
|
|
1873
|
-
if (
|
|
1874
|
-
throw new StatelessRpcError(
|
|
1873
|
+
if (rpcError2) {
|
|
1874
|
+
throw new StatelessRpcError(rpcError2.code, rpcError2.message, rpcError2.data);
|
|
1875
1875
|
}
|
|
1876
1876
|
throw new StatelessHttpError(res.status, res.statusText, method, text.slice(0, 512));
|
|
1877
1877
|
}
|
|
@@ -1888,10 +1888,10 @@ async function createStatelessConnection(options) {
|
|
|
1888
1888
|
}
|
|
1889
1889
|
return frame.result;
|
|
1890
1890
|
}
|
|
1891
|
-
const
|
|
1891
|
+
const discoverResult2 = await request("server/discover", {
|
|
1892
1892
|
protocolVersion: STATELESS_PROTOCOL_VERSION
|
|
1893
1893
|
});
|
|
1894
|
-
const supported = Array.isArray(
|
|
1894
|
+
const supported = Array.isArray(discoverResult2?.supportedVersions) ? discoverResult2.supportedVersions.filter((v) => typeof v === "string") : [];
|
|
1895
1895
|
if (!supported.includes(STATELESS_PROTOCOL_VERSION)) {
|
|
1896
1896
|
throw new Error(
|
|
1897
1897
|
`Server does not support ${STATELESS_PROTOCOL_VERSION} (advertised: ${supported.join(", ") || "none"})`
|
|
@@ -1902,7 +1902,7 @@ async function createStatelessConnection(options) {
|
|
|
1902
1902
|
return {
|
|
1903
1903
|
async info() {
|
|
1904
1904
|
if (serverInfoCache) return serverInfoCache;
|
|
1905
|
-
const result =
|
|
1905
|
+
const result = discoverResult2;
|
|
1906
1906
|
serverInfoCache = {
|
|
1907
1907
|
name: result?.serverInfo?.name,
|
|
1908
1908
|
version: result?.serverInfo?.version,
|
|
@@ -2393,6 +2393,1399 @@ var MergedConfigSource = class _MergedConfigSource {
|
|
|
2393
2393
|
}
|
|
2394
2394
|
};
|
|
2395
2395
|
|
|
2396
|
+
// src/config/expand.ts
|
|
2397
|
+
var PLACEHOLDER = /\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g;
|
|
2398
|
+
var PLACEHOLDER_TEST = /\$\{[A-Za-z_][A-Za-z0-9_]*\}/;
|
|
2399
|
+
function containsPlaceholders(value) {
|
|
2400
|
+
return PLACEHOLDER_TEST.test(value);
|
|
2401
|
+
}
|
|
2402
|
+
function expandPlaceholdersStrict(value, env) {
|
|
2403
|
+
let hasUndefined = false;
|
|
2404
|
+
const result = value.replace(PLACEHOLDER, (_, name) => {
|
|
2405
|
+
if (env[name] === void 0) {
|
|
2406
|
+
hasUndefined = true;
|
|
2407
|
+
return "";
|
|
2408
|
+
}
|
|
2409
|
+
return env[name];
|
|
2410
|
+
});
|
|
2411
|
+
if (hasUndefined) return void 0;
|
|
2412
|
+
return result;
|
|
2413
|
+
}
|
|
2414
|
+
|
|
2415
|
+
// src/serve/catalog.ts
|
|
2416
|
+
var NAME_RE = /^[A-Za-z][\w-]*$/;
|
|
2417
|
+
function sanitizeName(raw) {
|
|
2418
|
+
const cleaned = raw.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "");
|
|
2419
|
+
return cleaned || "cli";
|
|
2420
|
+
}
|
|
2421
|
+
function cliPrefix(help, filePath, explicit) {
|
|
2422
|
+
if (explicit) return sanitizeName(explicit);
|
|
2423
|
+
const fromUsage = usageProgramName(help);
|
|
2424
|
+
if (fromUsage) return sanitizeName(fromUsage);
|
|
2425
|
+
const base = filePath.split("/").pop() ?? filePath;
|
|
2426
|
+
return sanitizeName(base.replace(/\.jsh$/i, ""));
|
|
2427
|
+
}
|
|
2428
|
+
function parseHelp(help) {
|
|
2429
|
+
const block = commandsFromBlock(help);
|
|
2430
|
+
const program = usageProgramName(help);
|
|
2431
|
+
const commands = mergeCommandLists(block.commands, usageCommands(help, program));
|
|
2432
|
+
return {
|
|
2433
|
+
...program ? { program } : {},
|
|
2434
|
+
commands: applyScopedFlags(commands, block.scoped),
|
|
2435
|
+
globalFlags: block.globalFlags
|
|
2436
|
+
};
|
|
2437
|
+
}
|
|
2438
|
+
function isGroupCandidate(command) {
|
|
2439
|
+
return command.path.length === 1 && command.positionals.length === 0 && command.flags.length === 0;
|
|
2440
|
+
}
|
|
2441
|
+
function nestGroup(commands, group, nested, topNames) {
|
|
2442
|
+
const children = attachGlobalFlags(nested.commands, nested.globalFlags);
|
|
2443
|
+
if (children.length === 0) return null;
|
|
2444
|
+
const childNames = children.map((child) => child.path[0] ?? "");
|
|
2445
|
+
const same = childNames.length === topNames.size && childNames.every((name) => topNames.has(name));
|
|
2446
|
+
if (same) return null;
|
|
2447
|
+
const nestedCommands = children.map((child) => ({ ...child, path: childPath(group, child) }));
|
|
2448
|
+
return commands.filter((command) => command.path[0] !== group).concat(nestedCommands);
|
|
2449
|
+
}
|
|
2450
|
+
function attachGlobalFlags(commands, globalFlags) {
|
|
2451
|
+
if (globalFlags.length === 0) return commands;
|
|
2452
|
+
return commands.map((command) => ({ ...command, flags: mergeFlags(command.flags, globalFlags) }));
|
|
2453
|
+
}
|
|
2454
|
+
function parseMcpOverride(stdout) {
|
|
2455
|
+
let value;
|
|
2456
|
+
try {
|
|
2457
|
+
value = JSON.parse(stdout);
|
|
2458
|
+
} catch {
|
|
2459
|
+
return null;
|
|
2460
|
+
}
|
|
2461
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
|
|
2462
|
+
const commandsValue = Object.getOwnPropertyDescriptor(value, "commands")?.value;
|
|
2463
|
+
if (!Array.isArray(commandsValue)) return null;
|
|
2464
|
+
const commands = [];
|
|
2465
|
+
for (const entry of commandsValue) {
|
|
2466
|
+
const command = readMcpCommand(entry);
|
|
2467
|
+
if (command) commands.push(command);
|
|
2468
|
+
}
|
|
2469
|
+
if (commands.length === 0) return null;
|
|
2470
|
+
return { commands, globalFlags: [] };
|
|
2471
|
+
}
|
|
2472
|
+
function buildTools(prefix, commands) {
|
|
2473
|
+
const tools = [
|
|
2474
|
+
{
|
|
2475
|
+
name: `${prefix}_help`,
|
|
2476
|
+
description: `Show ${prefix} help.`,
|
|
2477
|
+
inputSchema: objectSchema({}),
|
|
2478
|
+
cli: prefix,
|
|
2479
|
+
kind: "help",
|
|
2480
|
+
commandPath: []
|
|
2481
|
+
},
|
|
2482
|
+
{
|
|
2483
|
+
name: `${prefix}_invoke`,
|
|
2484
|
+
description: `Run ${prefix} with an argv array (one element per argument) and optional stdin. A non-zero exit is a tool error.`,
|
|
2485
|
+
inputSchema: invokeSchema(),
|
|
2486
|
+
cli: prefix,
|
|
2487
|
+
kind: "invoke",
|
|
2488
|
+
commandPath: []
|
|
2489
|
+
}
|
|
2490
|
+
];
|
|
2491
|
+
for (const command of commands) {
|
|
2492
|
+
const leaf = command.path.join("_");
|
|
2493
|
+
tools.push({
|
|
2494
|
+
name: `${prefix}_${leaf}`,
|
|
2495
|
+
description: command.description || `Run ${prefix} ${command.path.join(" ")}`,
|
|
2496
|
+
inputSchema: commandSchema(command),
|
|
2497
|
+
cli: prefix,
|
|
2498
|
+
kind: "command",
|
|
2499
|
+
commandPath: command.path
|
|
2500
|
+
});
|
|
2501
|
+
}
|
|
2502
|
+
return tools;
|
|
2503
|
+
}
|
|
2504
|
+
function readToolArguments(input) {
|
|
2505
|
+
if (input === void 0 || input === null) return { fields: [] };
|
|
2506
|
+
if (typeof input !== "object" || Array.isArray(input)) {
|
|
2507
|
+
return { fields: [], error: "arguments must be an object" };
|
|
2508
|
+
}
|
|
2509
|
+
const fields = [];
|
|
2510
|
+
let stdin;
|
|
2511
|
+
let passthrough;
|
|
2512
|
+
let argv;
|
|
2513
|
+
for (const key of Object.keys(input)) {
|
|
2514
|
+
const value = Object.getOwnPropertyDescriptor(input, key)?.value;
|
|
2515
|
+
const read = readArgument(key, value);
|
|
2516
|
+
if (read.error) return { fields, error: read.error };
|
|
2517
|
+
if (read.stdin !== void 0) stdin = read.stdin;
|
|
2518
|
+
else if (read.passthrough) passthrough = read.passthrough;
|
|
2519
|
+
else if (read.argv) argv = read.argv;
|
|
2520
|
+
else if (read.field) fields.push(read.field);
|
|
2521
|
+
}
|
|
2522
|
+
return {
|
|
2523
|
+
fields,
|
|
2524
|
+
...stdin !== void 0 ? { stdin } : {},
|
|
2525
|
+
...passthrough ? { passthrough } : {},
|
|
2526
|
+
...argv ? { argv } : {}
|
|
2527
|
+
};
|
|
2528
|
+
}
|
|
2529
|
+
function argvForCommand(command, args2) {
|
|
2530
|
+
if (args2.error) return { error: args2.error };
|
|
2531
|
+
const argv = [...command.path];
|
|
2532
|
+
for (const positional of command.positionals) {
|
|
2533
|
+
const found = args2.fields.find((field) => field.name === positional.name);
|
|
2534
|
+
if (!found) {
|
|
2535
|
+
if (positional.required) return { error: `missing ${positional.name}` };
|
|
2536
|
+
continue;
|
|
2537
|
+
}
|
|
2538
|
+
if (typeof found.value !== "string" && typeof found.value !== "number") {
|
|
2539
|
+
return { error: `${positional.name} must be a string` };
|
|
2540
|
+
}
|
|
2541
|
+
argv.push(String(found.value));
|
|
2542
|
+
}
|
|
2543
|
+
const flags = appendFlags(command.flags, args2.fields);
|
|
2544
|
+
if ("error" in flags) return flags;
|
|
2545
|
+
argv.push(...flags.argv);
|
|
2546
|
+
if (args2.passthrough) argv.push(...args2.passthrough);
|
|
2547
|
+
return { argv, ...args2.stdin !== void 0 ? { stdin: args2.stdin } : {} };
|
|
2548
|
+
}
|
|
2549
|
+
function appendFlags(flags, fields) {
|
|
2550
|
+
const argv = [];
|
|
2551
|
+
for (const flag of flags) {
|
|
2552
|
+
const found = fields.find((field) => field.name === flag.name);
|
|
2553
|
+
if (!found || found.value === false) continue;
|
|
2554
|
+
const encoded = encodeFlag(flag, found.value);
|
|
2555
|
+
if ("error" in encoded) return encoded;
|
|
2556
|
+
argv.push(...encoded.argv);
|
|
2557
|
+
}
|
|
2558
|
+
return { argv };
|
|
2559
|
+
}
|
|
2560
|
+
function encodeFlag(flag, value) {
|
|
2561
|
+
if (flag.type === "boolean") {
|
|
2562
|
+
return value === true ? { argv: [`--${flag.name}`] } : { argv: [] };
|
|
2563
|
+
}
|
|
2564
|
+
if (flag.type === "string[]") {
|
|
2565
|
+
if (!Array.isArray(value)) return { error: `${flag.name} must be an array of strings` };
|
|
2566
|
+
const argv = [];
|
|
2567
|
+
for (const item of value) argv.push(`--${flag.name}`, item);
|
|
2568
|
+
return { argv };
|
|
2569
|
+
}
|
|
2570
|
+
if (typeof value !== "string" && typeof value !== "number") {
|
|
2571
|
+
return { error: `${flag.name} must be a string` };
|
|
2572
|
+
}
|
|
2573
|
+
return { argv: [`--${flag.name}`, String(value)] };
|
|
2574
|
+
}
|
|
2575
|
+
function commandsFromBlock(help) {
|
|
2576
|
+
let section = "none";
|
|
2577
|
+
const commands = [];
|
|
2578
|
+
const globalFlags = [];
|
|
2579
|
+
const scoped = [];
|
|
2580
|
+
for (const rawLine of help.split("\n")) {
|
|
2581
|
+
const line = rawLine.replace(/\t/g, " ");
|
|
2582
|
+
const header = classifyHeader(line);
|
|
2583
|
+
if (header) {
|
|
2584
|
+
section = header.kind === "other" ? "none" : header.kind;
|
|
2585
|
+
if (header.kind === "scoped" && header.name) scoped.push({ name: header.name, flags: [] });
|
|
2586
|
+
continue;
|
|
2587
|
+
}
|
|
2588
|
+
pushSectionLine(section, line, commands, globalFlags, scoped);
|
|
2589
|
+
}
|
|
2590
|
+
return { commands, globalFlags, scoped };
|
|
2591
|
+
}
|
|
2592
|
+
function pushSectionLine(section, line, commands, globalFlags, scoped) {
|
|
2593
|
+
if (section === "commands") {
|
|
2594
|
+
const command = parseCommandLine(line);
|
|
2595
|
+
if (command) commands.push(command);
|
|
2596
|
+
return;
|
|
2597
|
+
}
|
|
2598
|
+
const flag = parseFlagLine(line);
|
|
2599
|
+
if (!flag) return;
|
|
2600
|
+
if (section === "options") globalFlags.push(flag);
|
|
2601
|
+
if (section === "scoped") scoped[scoped.length - 1]?.flags.push(flag);
|
|
2602
|
+
}
|
|
2603
|
+
function classifyHeader(line) {
|
|
2604
|
+
const text = line.trim();
|
|
2605
|
+
if (/^commands:?$/i.test(text)) return { kind: "commands" };
|
|
2606
|
+
if (/^options:?$/i.test(text)) return { kind: "options" };
|
|
2607
|
+
const flags = /^([A-Za-z][\w-]*)\s+flags:?$/i.exec(text);
|
|
2608
|
+
if (flags?.[1]) return { kind: "scoped", name: flags[1].toLowerCase() };
|
|
2609
|
+
if (/^[A-Z][A-Z0-9 ]+:$/.test(text)) return { kind: "other" };
|
|
2610
|
+
return null;
|
|
2611
|
+
}
|
|
2612
|
+
function parseCommandLine(line) {
|
|
2613
|
+
if (!/^\s{2,}\S/.test(line)) return null;
|
|
2614
|
+
const parts = line.trim().split(/\s{2,}/);
|
|
2615
|
+
if (parts.length < 2) return null;
|
|
2616
|
+
const tokens = tokenize(parts[0] ?? "");
|
|
2617
|
+
const name = tokens[0] ?? "";
|
|
2618
|
+
if (!NAME_RE.test(name) || name.startsWith("-")) return null;
|
|
2619
|
+
const spec = emptySpec();
|
|
2620
|
+
for (const token of tokens.slice(1)) parseUsageToken(token, spec);
|
|
2621
|
+
return {
|
|
2622
|
+
path: [name],
|
|
2623
|
+
description: parts.slice(1).join(" ").trim(),
|
|
2624
|
+
positionals: spec.positionals,
|
|
2625
|
+
flags: spec.flags
|
|
2626
|
+
};
|
|
2627
|
+
}
|
|
2628
|
+
function usageProgramName(help) {
|
|
2629
|
+
for (const raw of help.split("\n")) {
|
|
2630
|
+
if (!/^[\s>*]*usage:/i.test(raw)) continue;
|
|
2631
|
+
const tokens = tokenize(raw);
|
|
2632
|
+
const name = tokens[0];
|
|
2633
|
+
if (name && NAME_RE.test(name)) return name;
|
|
2634
|
+
}
|
|
2635
|
+
return void 0;
|
|
2636
|
+
}
|
|
2637
|
+
function usageCommands(help, program) {
|
|
2638
|
+
const commands = [];
|
|
2639
|
+
for (const raw of help.split("\n")) {
|
|
2640
|
+
const command = usageCommand(raw, program);
|
|
2641
|
+
if (command) commands.push(command);
|
|
2642
|
+
}
|
|
2643
|
+
return commands;
|
|
2644
|
+
}
|
|
2645
|
+
function isCommandSlot(token) {
|
|
2646
|
+
const inner = token.replace(/^\[|\]$/g, "").replace(/^<|>$/g, "").toLowerCase();
|
|
2647
|
+
return inner === "command" || inner === "cmd" || inner === "subcommand" || inner === "verb";
|
|
2648
|
+
}
|
|
2649
|
+
function usageCommand(raw, program) {
|
|
2650
|
+
const line = raw.trim();
|
|
2651
|
+
const tokens = tokenize(line);
|
|
2652
|
+
if (tokens.length < 2) return null;
|
|
2653
|
+
const isUsage = /^usage:/i.test(line);
|
|
2654
|
+
if (!isUsage && tokens[0] !== program) return null;
|
|
2655
|
+
const path = [];
|
|
2656
|
+
let index = 1;
|
|
2657
|
+
while (index < tokens.length && path.length < 2 && NAME_RE.test(tokens[index] ?? "")) {
|
|
2658
|
+
path.push(tokens[index] ?? "");
|
|
2659
|
+
index++;
|
|
2660
|
+
}
|
|
2661
|
+
if (path.length === 0) return null;
|
|
2662
|
+
if (isCommandSlot(tokens[index] ?? "")) return null;
|
|
2663
|
+
const spec = emptySpec();
|
|
2664
|
+
for (const token of tokens.slice(index)) parseUsageToken(token, spec);
|
|
2665
|
+
return { path, description: "", positionals: spec.positionals, flags: spec.flags };
|
|
2666
|
+
}
|
|
2667
|
+
function emptySpec() {
|
|
2668
|
+
return { positionals: [], flags: [] };
|
|
2669
|
+
}
|
|
2670
|
+
function parseUsageToken(token, into) {
|
|
2671
|
+
const optional = token.startsWith("[") && token.endsWith("]");
|
|
2672
|
+
const inner = optional ? token.slice(1, -1).trim() : token;
|
|
2673
|
+
if (inner.startsWith("--")) {
|
|
2674
|
+
const flag = parseFlagToken(inner);
|
|
2675
|
+
if (flag) into.flags.push(flag);
|
|
2676
|
+
return;
|
|
2677
|
+
}
|
|
2678
|
+
if (inner.startsWith("<") && inner.endsWith(">")) {
|
|
2679
|
+
into.positionals.push({
|
|
2680
|
+
name: cleanName(inner.slice(1, -1)),
|
|
2681
|
+
required: !optional,
|
|
2682
|
+
description: ""
|
|
2683
|
+
});
|
|
2684
|
+
return;
|
|
2685
|
+
}
|
|
2686
|
+
if (NAME_RE.test(inner)) {
|
|
2687
|
+
into.positionals.push({ name: cleanName(inner), required: !optional, description: "" });
|
|
2688
|
+
}
|
|
2689
|
+
}
|
|
2690
|
+
function parseFlagToken(inner) {
|
|
2691
|
+
const match = /^--([A-Za-z][\w-]*)(?:(?:=|\s+)(\S+))?$/.exec(inner.trim());
|
|
2692
|
+
if (!match?.[1]) return null;
|
|
2693
|
+
const value = match[2] ?? "";
|
|
2694
|
+
if (!value) return { name: match[1], type: "boolean", description: "" };
|
|
2695
|
+
return { name: match[1], type: value.includes("...") ? "string[]" : "string", description: "" };
|
|
2696
|
+
}
|
|
2697
|
+
function parseFlagLine(line) {
|
|
2698
|
+
const trimmed = line.trim();
|
|
2699
|
+
if (!trimmed.includes("--")) return null;
|
|
2700
|
+
const match = /--([A-Za-z][\w-]*)(?:=(\S+)|(?:\s+(<[^>]+>|\[[^\]]+\]|[A-Z][A-Z0-9_-]+)))?/.exec(
|
|
2701
|
+
trimmed
|
|
2702
|
+
);
|
|
2703
|
+
if (!match?.[1]) return null;
|
|
2704
|
+
const value = match[2] || match[3] || "";
|
|
2705
|
+
const repeatable = /\brepeat|\.\.\.|one or more/i.test(trimmed);
|
|
2706
|
+
const description = flagDescription(trimmed);
|
|
2707
|
+
if (!value && !repeatable) return { name: match[1], type: "boolean", description };
|
|
2708
|
+
return { name: match[1], type: repeatable ? "string[]" : "string", description };
|
|
2709
|
+
}
|
|
2710
|
+
function flagDescription(line) {
|
|
2711
|
+
const parts = line.trim().split(/\s{2,}/);
|
|
2712
|
+
return parts.length > 1 ? parts.slice(1).join(" ").trim() : "";
|
|
2713
|
+
}
|
|
2714
|
+
function tokenize(line) {
|
|
2715
|
+
const source = line.trim().replace(/^usage:\s*/i, "");
|
|
2716
|
+
const tokens = [];
|
|
2717
|
+
let index = 0;
|
|
2718
|
+
while (index < source.length) {
|
|
2719
|
+
if (source[index] === " ") {
|
|
2720
|
+
index++;
|
|
2721
|
+
continue;
|
|
2722
|
+
}
|
|
2723
|
+
const closer = source[index] === "[" ? "]" : source[index] === "<" ? ">" : "";
|
|
2724
|
+
if (closer) {
|
|
2725
|
+
const end = source.indexOf(closer, index);
|
|
2726
|
+
if (end === -1) {
|
|
2727
|
+
tokens.push(source.slice(index));
|
|
2728
|
+
break;
|
|
2729
|
+
}
|
|
2730
|
+
tokens.push(source.slice(index, end + 1));
|
|
2731
|
+
index = end + 1;
|
|
2732
|
+
continue;
|
|
2733
|
+
}
|
|
2734
|
+
const next = source.indexOf(" ", index);
|
|
2735
|
+
if (next === -1) {
|
|
2736
|
+
tokens.push(source.slice(index));
|
|
2737
|
+
break;
|
|
2738
|
+
}
|
|
2739
|
+
tokens.push(source.slice(index, next));
|
|
2740
|
+
index = next;
|
|
2741
|
+
}
|
|
2742
|
+
return tokens;
|
|
2743
|
+
}
|
|
2744
|
+
function mergeCommandLists(primary, extra) {
|
|
2745
|
+
const merged = primary.map((command) => ({ ...command }));
|
|
2746
|
+
for (const command of extra) {
|
|
2747
|
+
const existing = merged.find((item) => samePath(item.path, command.path));
|
|
2748
|
+
if (!existing) {
|
|
2749
|
+
merged.push(command);
|
|
2750
|
+
continue;
|
|
2751
|
+
}
|
|
2752
|
+
if (existing.positionals.length === 0) existing.positionals = command.positionals;
|
|
2753
|
+
if (!existing.description) existing.description = command.description;
|
|
2754
|
+
existing.flags = mergeFlags(existing.flags, command.flags);
|
|
2755
|
+
}
|
|
2756
|
+
return merged;
|
|
2757
|
+
}
|
|
2758
|
+
function applyScopedFlags(commands, scoped) {
|
|
2759
|
+
return commands.map((command) => {
|
|
2760
|
+
const extra = scoped.find((scope) => scope.name === (command.path[0] ?? "").toLowerCase());
|
|
2761
|
+
if (!extra) return command;
|
|
2762
|
+
return { ...command, flags: mergeFlags(command.flags, extra.flags) };
|
|
2763
|
+
});
|
|
2764
|
+
}
|
|
2765
|
+
function mergeFlags(left, right) {
|
|
2766
|
+
const merged = [...left];
|
|
2767
|
+
for (const flag of right) {
|
|
2768
|
+
if (!merged.some((existing) => existing.name === flag.name)) merged.push(flag);
|
|
2769
|
+
}
|
|
2770
|
+
return merged;
|
|
2771
|
+
}
|
|
2772
|
+
function samePath(left, right) {
|
|
2773
|
+
return left.length === right.length && left.every((part, index) => part === right[index]);
|
|
2774
|
+
}
|
|
2775
|
+
function childPath(group, child) {
|
|
2776
|
+
if (child.path[0] === group) return child.path.slice(0, 2);
|
|
2777
|
+
return [group, child.path[0] ?? ""].filter((part) => part.length > 0).slice(0, 2);
|
|
2778
|
+
}
|
|
2779
|
+
function cleanName(raw) {
|
|
2780
|
+
const cleaned = raw.replace(/[^A-Za-z0-9_-]+/g, "").replace(/^-+/, "");
|
|
2781
|
+
return cleaned || "arg";
|
|
2782
|
+
}
|
|
2783
|
+
function readMcpCommand(value) {
|
|
2784
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
|
|
2785
|
+
const name = ownString(value, "name");
|
|
2786
|
+
if (!name) return null;
|
|
2787
|
+
const path = name.split(/\s+/).filter((part) => NAME_RE.test(part)).slice(0, 2);
|
|
2788
|
+
if (path.length === 0) return null;
|
|
2789
|
+
return {
|
|
2790
|
+
path,
|
|
2791
|
+
description: ownString(value, "description") ?? "",
|
|
2792
|
+
positionals: readMcpPositionals(Object.getOwnPropertyDescriptor(value, "positionals")?.value),
|
|
2793
|
+
flags: readMcpFlags(Object.getOwnPropertyDescriptor(value, "flags")?.value)
|
|
2794
|
+
};
|
|
2795
|
+
}
|
|
2796
|
+
function readMcpPositionals(value) {
|
|
2797
|
+
if (!Array.isArray(value)) return [];
|
|
2798
|
+
const positionals = [];
|
|
2799
|
+
for (const entry of value) {
|
|
2800
|
+
if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
|
|
2801
|
+
const name = ownString(entry, "name");
|
|
2802
|
+
if (!name) continue;
|
|
2803
|
+
const required = Object.getOwnPropertyDescriptor(entry, "required")?.value;
|
|
2804
|
+
positionals.push({ name, required: required !== false, description: "" });
|
|
2805
|
+
}
|
|
2806
|
+
return positionals;
|
|
2807
|
+
}
|
|
2808
|
+
function readMcpFlags(value) {
|
|
2809
|
+
if (!Array.isArray(value)) return [];
|
|
2810
|
+
const flags = [];
|
|
2811
|
+
for (const entry of value) {
|
|
2812
|
+
if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
|
|
2813
|
+
const name = ownString(entry, "name");
|
|
2814
|
+
const type = ownString(entry, "type");
|
|
2815
|
+
if (!name || type !== "boolean" && type !== "string" && type !== "string[]") continue;
|
|
2816
|
+
flags.push({ name, type, description: "" });
|
|
2817
|
+
}
|
|
2818
|
+
return flags;
|
|
2819
|
+
}
|
|
2820
|
+
function ownString(value, key) {
|
|
2821
|
+
const found = Object.getOwnPropertyDescriptor(value, key)?.value;
|
|
2822
|
+
return typeof found === "string" && found.length > 0 ? found : void 0;
|
|
2823
|
+
}
|
|
2824
|
+
function objectSchema(properties, required) {
|
|
2825
|
+
return {
|
|
2826
|
+
type: "object",
|
|
2827
|
+
properties,
|
|
2828
|
+
additionalProperties: false,
|
|
2829
|
+
...required && required.length > 0 ? { required } : {}
|
|
2830
|
+
};
|
|
2831
|
+
}
|
|
2832
|
+
function invokeSchema() {
|
|
2833
|
+
return objectSchema(
|
|
2834
|
+
{
|
|
2835
|
+
argv: {
|
|
2836
|
+
type: "array",
|
|
2837
|
+
items: { type: "string" },
|
|
2838
|
+
description: "Arguments, one element per argument. Never a shell string."
|
|
2839
|
+
},
|
|
2840
|
+
stdin: { type: "string", description: "Optional standard input." }
|
|
2841
|
+
},
|
|
2842
|
+
["argv"]
|
|
2843
|
+
);
|
|
2844
|
+
}
|
|
2845
|
+
function commandSchema(command) {
|
|
2846
|
+
const properties = {};
|
|
2847
|
+
const required = [];
|
|
2848
|
+
for (const positional of command.positionals) {
|
|
2849
|
+
properties[positional.name] = {
|
|
2850
|
+
type: "string",
|
|
2851
|
+
description: positional.description || positional.name
|
|
2852
|
+
};
|
|
2853
|
+
if (positional.required) required.push(positional.name);
|
|
2854
|
+
}
|
|
2855
|
+
for (const flag of command.flags) {
|
|
2856
|
+
properties[flag.name] = flagProperty(flag);
|
|
2857
|
+
}
|
|
2858
|
+
properties.stdin = { type: "string", description: "Optional standard input." };
|
|
2859
|
+
properties.passthrough = {
|
|
2860
|
+
type: "array",
|
|
2861
|
+
items: { type: "string" },
|
|
2862
|
+
description: "Extra arguments appended as-is."
|
|
2863
|
+
};
|
|
2864
|
+
return objectSchema(properties, required);
|
|
2865
|
+
}
|
|
2866
|
+
function flagProperty(flag) {
|
|
2867
|
+
if (flag.type === "boolean")
|
|
2868
|
+
return { type: "boolean", description: flag.description || flag.name };
|
|
2869
|
+
if (flag.type === "string[]") {
|
|
2870
|
+
return { type: "array", items: { type: "string" }, description: flag.description || flag.name };
|
|
2871
|
+
}
|
|
2872
|
+
return { type: "string", description: flag.description || flag.name };
|
|
2873
|
+
}
|
|
2874
|
+
function readArgument(key, value) {
|
|
2875
|
+
if (key === "stdin") {
|
|
2876
|
+
return typeof value === "string" ? { stdin: value } : { error: "stdin must be a string" };
|
|
2877
|
+
}
|
|
2878
|
+
if (key === "passthrough") return readStringArray(value, "passthrough");
|
|
2879
|
+
if (key === "argv") {
|
|
2880
|
+
const read = readStringArray(value, "argv");
|
|
2881
|
+
return read.passthrough ? { argv: read.passthrough } : read;
|
|
2882
|
+
}
|
|
2883
|
+
if (!isArgValue(value)) return { error: `${key} has an unsupported type` };
|
|
2884
|
+
return { field: { name: key, value } };
|
|
2885
|
+
}
|
|
2886
|
+
function readStringArray(value, label) {
|
|
2887
|
+
if (!Array.isArray(value) || !value.every((item) => typeof item === "string")) {
|
|
2888
|
+
return { error: `${label} must be an array of strings` };
|
|
2889
|
+
}
|
|
2890
|
+
return { passthrough: value };
|
|
2891
|
+
}
|
|
2892
|
+
function isArgValue(value) {
|
|
2893
|
+
if (typeof value === "string" || typeof value === "boolean" || typeof value === "number")
|
|
2894
|
+
return true;
|
|
2895
|
+
return Array.isArray(value) && value.every((item) => typeof item === "string");
|
|
2896
|
+
}
|
|
2897
|
+
function parseToolTemplate(spec) {
|
|
2898
|
+
const colonIdx = spec.indexOf(":");
|
|
2899
|
+
if (colonIdx <= 0) return null;
|
|
2900
|
+
const name = spec.slice(0, colonIdx).trim();
|
|
2901
|
+
const template = spec.slice(colonIdx + 1).trim();
|
|
2902
|
+
if (!name || !template) return null;
|
|
2903
|
+
const placeholders = [];
|
|
2904
|
+
const re = /\{(\w+)\}/g;
|
|
2905
|
+
let m;
|
|
2906
|
+
while ((m = re.exec(template)) !== null) {
|
|
2907
|
+
if (!placeholders.includes(m[1])) placeholders.push(m[1]);
|
|
2908
|
+
}
|
|
2909
|
+
const properties = {};
|
|
2910
|
+
for (const ph of placeholders) {
|
|
2911
|
+
properties[ph] = { type: "string", description: ph };
|
|
2912
|
+
}
|
|
2913
|
+
return {
|
|
2914
|
+
name,
|
|
2915
|
+
description: template,
|
|
2916
|
+
inputSchema: {
|
|
2917
|
+
type: "object",
|
|
2918
|
+
properties,
|
|
2919
|
+
required: placeholders,
|
|
2920
|
+
additionalProperties: false
|
|
2921
|
+
},
|
|
2922
|
+
cli: "",
|
|
2923
|
+
kind: "command",
|
|
2924
|
+
commandPath: []
|
|
2925
|
+
};
|
|
2926
|
+
}
|
|
2927
|
+
function templateToArgv(template, args2) {
|
|
2928
|
+
let expanded = template;
|
|
2929
|
+
for (const [key, value] of Object.entries(args2)) {
|
|
2930
|
+
expanded = expanded.replaceAll(`{${key}}`, value);
|
|
2931
|
+
}
|
|
2932
|
+
return expanded.split(/\s+/).filter(Boolean);
|
|
2933
|
+
}
|
|
2934
|
+
|
|
2935
|
+
// src/serve/http.ts
|
|
2936
|
+
var encoder = new TextEncoder();
|
|
2937
|
+
var decoder = new TextDecoder();
|
|
2938
|
+
var MAX_HEADER_SIZE = 16384;
|
|
2939
|
+
var MAX_BODY_SIZE = 10485760;
|
|
2940
|
+
async function readUntil(reader, buf, bufLen, sentinel, maxSize) {
|
|
2941
|
+
for (; ; ) {
|
|
2942
|
+
const text = decoder.decode(new Uint8Array(buf.buffer, buf.byteOffset, bufLen));
|
|
2943
|
+
const pos = text.indexOf(sentinel);
|
|
2944
|
+
if (pos >= 0) return { buf, bufLen, pos };
|
|
2945
|
+
if (bufLen >= maxSize) return null;
|
|
2946
|
+
const { done, value } = await reader.read();
|
|
2947
|
+
if (done) return null;
|
|
2948
|
+
if (bufLen + value.length > buf.length) {
|
|
2949
|
+
const newBuf = new Uint8Array(Math.max(buf.length * 2, bufLen + value.length));
|
|
2950
|
+
newBuf.set(new Uint8Array(buf.buffer, buf.byteOffset, bufLen));
|
|
2951
|
+
buf = newBuf;
|
|
2952
|
+
}
|
|
2953
|
+
buf.set(value, bufLen);
|
|
2954
|
+
bufLen += value.length;
|
|
2955
|
+
}
|
|
2956
|
+
}
|
|
2957
|
+
async function readExact(reader, buf, bufLen, needed) {
|
|
2958
|
+
while (bufLen < needed) {
|
|
2959
|
+
const { done, value } = await reader.read();
|
|
2960
|
+
if (done) return null;
|
|
2961
|
+
if (bufLen + value.length > buf.length) {
|
|
2962
|
+
const newBuf = new Uint8Array(Math.max(buf.length * 2, bufLen + value.length));
|
|
2963
|
+
newBuf.set(new Uint8Array(buf.buffer, buf.byteOffset, bufLen));
|
|
2964
|
+
buf = newBuf;
|
|
2965
|
+
}
|
|
2966
|
+
buf.set(value, bufLen);
|
|
2967
|
+
bufLen += value.length;
|
|
2968
|
+
}
|
|
2969
|
+
return { buf, bufLen };
|
|
2970
|
+
}
|
|
2971
|
+
function parseRequestLine(buf, endPos) {
|
|
2972
|
+
const headText = decoder.decode(new Uint8Array(buf.buffer, buf.byteOffset, endPos));
|
|
2973
|
+
const lines = headText.split("\r\n");
|
|
2974
|
+
const requestLine = lines[0];
|
|
2975
|
+
if (!requestLine) return null;
|
|
2976
|
+
const parts = requestLine.split(" ");
|
|
2977
|
+
if (parts.length < 2) return null;
|
|
2978
|
+
const method = parts[0];
|
|
2979
|
+
const target = parts[1];
|
|
2980
|
+
const headers = {};
|
|
2981
|
+
for (let i = 1; i < lines.length; i++) {
|
|
2982
|
+
const line = lines[i];
|
|
2983
|
+
if (!line) continue;
|
|
2984
|
+
const colonIdx = line.indexOf(":");
|
|
2985
|
+
if (colonIdx <= 0) continue;
|
|
2986
|
+
headers[line.slice(0, colonIdx).trim().toLowerCase()] = line.slice(colonIdx + 1).trim();
|
|
2987
|
+
}
|
|
2988
|
+
return { method, target, headers, headerEnd: endPos + 4 };
|
|
2989
|
+
}
|
|
2990
|
+
async function handleConnection(readable, writable, handler) {
|
|
2991
|
+
const reader = readable.getReader();
|
|
2992
|
+
const writer = writable.getWriter();
|
|
2993
|
+
let buf = new Uint8Array(4096);
|
|
2994
|
+
let bufLen = 0;
|
|
2995
|
+
try {
|
|
2996
|
+
for (; ; ) {
|
|
2997
|
+
const headerResult = await readUntil(reader, buf, bufLen, "\r\n\r\n", MAX_HEADER_SIZE);
|
|
2998
|
+
if (!headerResult) break;
|
|
2999
|
+
buf = headerResult.buf;
|
|
3000
|
+
bufLen = headerResult.bufLen;
|
|
3001
|
+
const parsed = parseRequestLine(buf, headerResult.pos);
|
|
3002
|
+
if (!parsed) {
|
|
3003
|
+
await writeResponse(writer, {
|
|
3004
|
+
status: 400,
|
|
3005
|
+
reason: "Bad Request",
|
|
3006
|
+
headers: { "content-type": "text/plain" },
|
|
3007
|
+
body: "Bad Request"
|
|
3008
|
+
});
|
|
3009
|
+
break;
|
|
3010
|
+
}
|
|
3011
|
+
const contentLength = Number(parsed.headers["content-length"] ?? 0);
|
|
3012
|
+
if (contentLength > MAX_BODY_SIZE) {
|
|
3013
|
+
await writeResponse(writer, {
|
|
3014
|
+
status: 413,
|
|
3015
|
+
reason: "Payload Too Large",
|
|
3016
|
+
headers: { "content-type": "text/plain" },
|
|
3017
|
+
body: "Payload Too Large"
|
|
3018
|
+
});
|
|
3019
|
+
break;
|
|
3020
|
+
}
|
|
3021
|
+
const bodyStart = parsed.headerEnd;
|
|
3022
|
+
const totalNeeded = bodyStart + contentLength;
|
|
3023
|
+
const bodyResult = await readExact(reader, buf, bufLen, totalNeeded);
|
|
3024
|
+
if (!bodyResult && contentLength > 0) break;
|
|
3025
|
+
if (bodyResult) {
|
|
3026
|
+
buf = bodyResult.buf;
|
|
3027
|
+
bufLen = bodyResult.bufLen;
|
|
3028
|
+
}
|
|
3029
|
+
const bodyBytes = buf.slice(bodyStart, bodyStart + contentLength);
|
|
3030
|
+
const body = decoder.decode(bodyBytes);
|
|
3031
|
+
const request = {
|
|
3032
|
+
method: parsed.method,
|
|
3033
|
+
target: parsed.target,
|
|
3034
|
+
headers: parsed.headers,
|
|
3035
|
+
body
|
|
3036
|
+
};
|
|
3037
|
+
const response = await handler(request);
|
|
3038
|
+
await writeResponse(writer, response);
|
|
3039
|
+
const connectionHeader = (parsed.headers.connection ?? "").toLowerCase();
|
|
3040
|
+
if (connectionHeader === "close") break;
|
|
3041
|
+
const consumed = bodyStart + contentLength;
|
|
3042
|
+
const remaining = bufLen - consumed;
|
|
3043
|
+
if (remaining > 0) {
|
|
3044
|
+
const newBuf = new Uint8Array(Math.max(4096, remaining));
|
|
3045
|
+
newBuf.set(new Uint8Array(buf.buffer, buf.byteOffset + consumed, remaining));
|
|
3046
|
+
buf = newBuf;
|
|
3047
|
+
bufLen = remaining;
|
|
3048
|
+
} else {
|
|
3049
|
+
buf = new Uint8Array(4096);
|
|
3050
|
+
bufLen = 0;
|
|
3051
|
+
}
|
|
3052
|
+
}
|
|
3053
|
+
} finally {
|
|
3054
|
+
reader.releaseLock();
|
|
3055
|
+
try {
|
|
3056
|
+
await writer.close();
|
|
3057
|
+
} catch {
|
|
3058
|
+
}
|
|
3059
|
+
}
|
|
3060
|
+
}
|
|
3061
|
+
async function writeResponse(writer, response) {
|
|
3062
|
+
const bodyLength = new TextEncoder().encode(response.body).length;
|
|
3063
|
+
const headers = { ...response.headers, "content-length": String(bodyLength) };
|
|
3064
|
+
const lines = [`HTTP/1.1 ${response.status} ${response.reason}`];
|
|
3065
|
+
for (const [name, value] of Object.entries(headers)) {
|
|
3066
|
+
lines.push(`${name}: ${value}`);
|
|
3067
|
+
}
|
|
3068
|
+
lines.push("", "");
|
|
3069
|
+
const headBytes = encoder.encode(lines.join("\r\n"));
|
|
3070
|
+
await writer.write(headBytes);
|
|
3071
|
+
if (response.body.length > 0) {
|
|
3072
|
+
const bodyBytes = encoder.encode(response.body);
|
|
3073
|
+
await writer.write(bodyBytes);
|
|
3074
|
+
}
|
|
3075
|
+
}
|
|
3076
|
+
|
|
3077
|
+
// src/serve/jsonrpc.ts
|
|
3078
|
+
var PROTOCOL_VERSIONS = ["2026-07-28", "2025-11-25", "2025-06-18"];
|
|
3079
|
+
var OUTPUT_CAP = 1048576;
|
|
3080
|
+
var JSON_CT = "application/json; charset=utf-8";
|
|
3081
|
+
async function handleJsonRpc(raw, tools, call, serverName, serverVersion) {
|
|
3082
|
+
let parsed;
|
|
3083
|
+
try {
|
|
3084
|
+
parsed = JSON.parse(raw);
|
|
3085
|
+
} catch {
|
|
3086
|
+
return rpcError(null, -32700, "Parse error");
|
|
3087
|
+
}
|
|
3088
|
+
if (Array.isArray(parsed)) return rpcError(null, -32600, "Batch requests are not supported");
|
|
3089
|
+
if (!parsed || typeof parsed !== "object") return rpcError(null, -32600, "Invalid request");
|
|
3090
|
+
const method = readString(parsed, "method");
|
|
3091
|
+
if (!method) return rpcError(readId(parsed), -32600, "Invalid request");
|
|
3092
|
+
if (!hasOwn(parsed, "id")) return { status: 202, contentType: "text/plain", body: "" };
|
|
3093
|
+
const id = readId(parsed);
|
|
3094
|
+
const params = Object.getOwnPropertyDescriptor(parsed, "params")?.value;
|
|
3095
|
+
if (method === "initialize")
|
|
3096
|
+
return rpcOk(id, initializeResult(params, serverName, serverVersion));
|
|
3097
|
+
if (method === "server/discover") return rpcOk(id, discoverResult(serverName, serverVersion));
|
|
3098
|
+
if (method === "tools/list") return rpcOk(id, { tools });
|
|
3099
|
+
if (method === "ping") return rpcOk(id, {});
|
|
3100
|
+
if (method === "tools/call") return toolCall(id, params, tools, call);
|
|
3101
|
+
return rpcError(id, -32601, `Method not found: ${method}`);
|
|
3102
|
+
}
|
|
3103
|
+
async function toolCall(id, params, tools, call) {
|
|
3104
|
+
const name = params && typeof params === "object" ? readString(params, "name") : void 0;
|
|
3105
|
+
if (!name) return rpcError(id, -32602, "tools/call requires a name");
|
|
3106
|
+
if (!tools.some((tool) => tool.name === name))
|
|
3107
|
+
return rpcError(id, -32602, `Unknown tool: ${name}`);
|
|
3108
|
+
const args2 = params && typeof params === "object" ? Object.getOwnPropertyDescriptor(params, "arguments")?.value : void 0;
|
|
3109
|
+
try {
|
|
3110
|
+
const result = await call(name, args2);
|
|
3111
|
+
return rpcOk(id, toolResult(result));
|
|
3112
|
+
} catch (err) {
|
|
3113
|
+
const message = err instanceof Error ? err.message : "tool call failed";
|
|
3114
|
+
return rpcError(id, -32e3, message);
|
|
3115
|
+
}
|
|
3116
|
+
}
|
|
3117
|
+
function toolResult(result) {
|
|
3118
|
+
const stdout = cap(result.stdout);
|
|
3119
|
+
const stderr = cap(result.stderr);
|
|
3120
|
+
const text = stderr ? stdout ? `${stdout}
|
|
3121
|
+
${stderr}` : stderr : stdout;
|
|
3122
|
+
return {
|
|
3123
|
+
content: [{ type: "text", text }],
|
|
3124
|
+
isError: result.exitCode !== 0,
|
|
3125
|
+
structuredContent: { stdout, stderr, exitCode: result.exitCode }
|
|
3126
|
+
};
|
|
3127
|
+
}
|
|
3128
|
+
function initializeResult(params, serverName, serverVersion) {
|
|
3129
|
+
const requested = params && typeof params === "object" ? readString(params, "protocolVersion") : void 0;
|
|
3130
|
+
const protocolVersion = PROTOCOL_VERSIONS.find((version) => version === requested) ?? PROTOCOL_VERSIONS[0];
|
|
3131
|
+
return {
|
|
3132
|
+
protocolVersion,
|
|
3133
|
+
capabilities: { tools: { listChanged: false } },
|
|
3134
|
+
serverInfo: { name: serverName, version: serverVersion }
|
|
3135
|
+
};
|
|
3136
|
+
}
|
|
3137
|
+
function discoverResult(serverName, serverVersion) {
|
|
3138
|
+
return {
|
|
3139
|
+
protocolVersion: PROTOCOL_VERSIONS[0],
|
|
3140
|
+
supportedVersions: PROTOCOL_VERSIONS,
|
|
3141
|
+
capabilities: { tools: { listChanged: false } },
|
|
3142
|
+
serverInfo: { name: serverName, version: serverVersion }
|
|
3143
|
+
};
|
|
3144
|
+
}
|
|
3145
|
+
function cap(value) {
|
|
3146
|
+
if (value.length <= OUTPUT_CAP) return value;
|
|
3147
|
+
const half = Math.floor(OUTPUT_CAP / 2);
|
|
3148
|
+
const cut = value.length - OUTPUT_CAP;
|
|
3149
|
+
return `${value.slice(0, half)}
|
|
3150
|
+
\u2026 ${cut} characters cut \u2026
|
|
3151
|
+
${value.slice(value.length - half)}`;
|
|
3152
|
+
}
|
|
3153
|
+
function rpcOk(id, result) {
|
|
3154
|
+
return {
|
|
3155
|
+
status: 200,
|
|
3156
|
+
contentType: JSON_CT,
|
|
3157
|
+
body: JSON.stringify({ jsonrpc: "2.0", id, result })
|
|
3158
|
+
};
|
|
3159
|
+
}
|
|
3160
|
+
function rpcError(id, code2, message) {
|
|
3161
|
+
return {
|
|
3162
|
+
status: 200,
|
|
3163
|
+
contentType: JSON_CT,
|
|
3164
|
+
body: JSON.stringify({ jsonrpc: "2.0", id, error: { code: code2, message } })
|
|
3165
|
+
};
|
|
3166
|
+
}
|
|
3167
|
+
function readId(value) {
|
|
3168
|
+
const id = Object.getOwnPropertyDescriptor(value, "id")?.value;
|
|
3169
|
+
if (typeof id === "string" || typeof id === "number" || id === null) return id;
|
|
3170
|
+
return null;
|
|
3171
|
+
}
|
|
3172
|
+
function readString(value, key) {
|
|
3173
|
+
const found = Object.getOwnPropertyDescriptor(value, key)?.value;
|
|
3174
|
+
return typeof found === "string" ? found : void 0;
|
|
3175
|
+
}
|
|
3176
|
+
function hasOwn(value, key) {
|
|
3177
|
+
return Object.prototype.hasOwnProperty.call(value, key);
|
|
3178
|
+
}
|
|
3179
|
+
|
|
3180
|
+
// src/serve/origin.ts
|
|
3181
|
+
var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]"]);
|
|
3182
|
+
function isLoopbackOrigin(origin) {
|
|
3183
|
+
try {
|
|
3184
|
+
const url = new URL(origin);
|
|
3185
|
+
const hostname = url.hostname;
|
|
3186
|
+
if (LOOPBACK_HOSTS.has(hostname)) return true;
|
|
3187
|
+
if (hostname === "::1") return true;
|
|
3188
|
+
if (hostname.endsWith(".localhost")) return true;
|
|
3189
|
+
return false;
|
|
3190
|
+
} catch {
|
|
3191
|
+
return false;
|
|
3192
|
+
}
|
|
3193
|
+
}
|
|
3194
|
+
function isLoopbackHost(host) {
|
|
3195
|
+
const hostname = host.replace(/:\d+$/, "");
|
|
3196
|
+
if (LOOPBACK_HOSTS.has(hostname)) return true;
|
|
3197
|
+
if (hostname === "::1") return true;
|
|
3198
|
+
if (hostname.endsWith(".localhost")) return true;
|
|
3199
|
+
return false;
|
|
3200
|
+
}
|
|
3201
|
+
function checkOrigin(origin, allowedOrigins, boundLoopback) {
|
|
3202
|
+
if (origin === void 0) return { ok: true };
|
|
3203
|
+
if (allowedOrigins.has(origin)) return { ok: true };
|
|
3204
|
+
if (isLoopbackOrigin(origin)) return { ok: true };
|
|
3205
|
+
if (!boundLoopback) return { ok: true };
|
|
3206
|
+
return { ok: false, reason: `origin ${origin} is not allowed` };
|
|
3207
|
+
}
|
|
3208
|
+
function checkHost(host, boundLoopback) {
|
|
3209
|
+
if (!boundLoopback) return { ok: true };
|
|
3210
|
+
if (!host) return { ok: false, reason: "missing Host header" };
|
|
3211
|
+
if (isLoopbackHost(host)) return { ok: true };
|
|
3212
|
+
return { ok: false, reason: `host ${host} is not loopback` };
|
|
3213
|
+
}
|
|
3214
|
+
|
|
3215
|
+
// src/serve/runtime.ts
|
|
3216
|
+
var CALL_TIMEOUT_MS = 12e4;
|
|
3217
|
+
var MAX_OUTPUT_DEFAULT = 1048576;
|
|
3218
|
+
var ALLOWED_ENV_KEYS = /* @__PURE__ */ new Set(["PATH", "HOME", "LANG"]);
|
|
3219
|
+
function parseHttpFlag(args2, i) {
|
|
3220
|
+
const next = args2[i + 1];
|
|
3221
|
+
if (!next || next.startsWith("-")) return { host: "127.0.0.1", port: 0, next: i };
|
|
3222
|
+
const colonIdx = next.lastIndexOf(":");
|
|
3223
|
+
if (colonIdx > 0 && colonIdx < next.length - 1) {
|
|
3224
|
+
return { host: next.slice(0, colonIdx), port: Number(next.slice(colonIdx + 1)), next: i + 1 };
|
|
3225
|
+
}
|
|
3226
|
+
return { host: "127.0.0.1", port: Number(next), next: i + 1 };
|
|
3227
|
+
}
|
|
3228
|
+
function parseCommandTarget(arg) {
|
|
3229
|
+
const eqIdx = arg.indexOf("=");
|
|
3230
|
+
if (eqIdx > 0 && !arg.slice(0, eqIdx).includes("/")) {
|
|
3231
|
+
return { name: arg.slice(0, eqIdx), path: arg.slice(eqIdx + 1) };
|
|
3232
|
+
}
|
|
3233
|
+
return { path: arg };
|
|
3234
|
+
}
|
|
3235
|
+
function parseSingleFlag(args2, i, opts) {
|
|
3236
|
+
const arg = args2[i];
|
|
3237
|
+
if (arg === "--stdio") {
|
|
3238
|
+
opts.transport = "stdio";
|
|
3239
|
+
} else if (arg === "--http") {
|
|
3240
|
+
opts.transport = "http";
|
|
3241
|
+
const parsed = parseHttpFlag(args2, i);
|
|
3242
|
+
opts.host = parsed.host;
|
|
3243
|
+
opts.port = parsed.port;
|
|
3244
|
+
return parsed.next;
|
|
3245
|
+
} else if (arg === "--bearer" && args2[i + 1]) {
|
|
3246
|
+
opts.bearer = args2[++i];
|
|
3247
|
+
} else if (arg === "--allow-origin" && args2[i + 1]) {
|
|
3248
|
+
opts.allowOrigins.push(args2[++i]);
|
|
3249
|
+
} else if (arg === "--env" && args2[i + 1]) {
|
|
3250
|
+
opts.envAllow.push(args2[++i]);
|
|
3251
|
+
} else if (arg === "--tool" && args2[i + 1]) {
|
|
3252
|
+
opts.toolTemplates.push(args2[++i]);
|
|
3253
|
+
} else if (arg === "--call-timeout" && args2[i + 1]) {
|
|
3254
|
+
opts.callTimeout = Number(args2[++i]) * 1e3;
|
|
3255
|
+
} else if (arg === "--concurrency" && args2[i + 1]) {
|
|
3256
|
+
opts.concurrency = Number(args2[++i]);
|
|
3257
|
+
} else if (arg === "--max-output" && args2[i + 1]) {
|
|
3258
|
+
opts.maxOutput = Number(args2[++i]);
|
|
3259
|
+
} else if (arg === "--cwd" && args2[i + 1]) {
|
|
3260
|
+
opts.cwd = args2[++i];
|
|
3261
|
+
} else if (arg === "--json") {
|
|
3262
|
+
opts.json = true;
|
|
3263
|
+
} else if (!arg.startsWith("-")) {
|
|
3264
|
+
opts.commands.push(parseCommandTarget(arg));
|
|
3265
|
+
}
|
|
3266
|
+
return i;
|
|
3267
|
+
}
|
|
3268
|
+
function parseServeFlags(args2) {
|
|
3269
|
+
const opts = {
|
|
3270
|
+
transport: "stdio",
|
|
3271
|
+
host: "127.0.0.1",
|
|
3272
|
+
port: 0,
|
|
3273
|
+
bearer: void 0,
|
|
3274
|
+
allowOrigins: [],
|
|
3275
|
+
envAllow: [],
|
|
3276
|
+
toolTemplates: [],
|
|
3277
|
+
callTimeout: CALL_TIMEOUT_MS,
|
|
3278
|
+
concurrency: 1,
|
|
3279
|
+
maxOutput: MAX_OUTPUT_DEFAULT,
|
|
3280
|
+
cwd: void 0,
|
|
3281
|
+
json: false,
|
|
3282
|
+
commands: []
|
|
3283
|
+
};
|
|
3284
|
+
for (let i = 0; i < args2.length; i++) {
|
|
3285
|
+
i = parseSingleFlag(args2, i, opts);
|
|
3286
|
+
}
|
|
3287
|
+
return opts;
|
|
3288
|
+
}
|
|
3289
|
+
function expandBearerToken(template, env) {
|
|
3290
|
+
if (!containsPlaceholders(template)) return void 0;
|
|
3291
|
+
return expandPlaceholdersStrict(template, env);
|
|
3292
|
+
}
|
|
3293
|
+
function constantTimeEqual(a, b) {
|
|
3294
|
+
if (a.length !== b.length) return false;
|
|
3295
|
+
let mismatch = 0;
|
|
3296
|
+
for (let i = 0; i < a.length; i++) {
|
|
3297
|
+
mismatch |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
|
3298
|
+
}
|
|
3299
|
+
return mismatch === 0;
|
|
3300
|
+
}
|
|
3301
|
+
function buildChildEnv(platform2, envAllow) {
|
|
3302
|
+
const env = {};
|
|
3303
|
+
for (const key of ALLOWED_ENV_KEYS) {
|
|
3304
|
+
if (platform2.env[key]) env[key] = platform2.env[key];
|
|
3305
|
+
}
|
|
3306
|
+
for (const entry of envAllow) {
|
|
3307
|
+
const eqIdx = entry.indexOf("=");
|
|
3308
|
+
if (eqIdx > 0) {
|
|
3309
|
+
env[entry.slice(0, eqIdx)] = entry.slice(eqIdx + 1);
|
|
3310
|
+
} else if (platform2.env[entry]) {
|
|
3311
|
+
env[entry] = platform2.env[entry];
|
|
3312
|
+
}
|
|
3313
|
+
}
|
|
3314
|
+
return env;
|
|
3315
|
+
}
|
|
3316
|
+
function capOutput(value, limit) {
|
|
3317
|
+
if (value.length <= limit) return value;
|
|
3318
|
+
const half = Math.floor(limit / 2);
|
|
3319
|
+
const cut = value.length - limit;
|
|
3320
|
+
return `${value.slice(0, half)}
|
|
3321
|
+
\u2026 ${cut} characters cut \u2026
|
|
3322
|
+
${value.slice(value.length - half)}`;
|
|
3323
|
+
}
|
|
3324
|
+
var inflightProcs = /* @__PURE__ */ new Set();
|
|
3325
|
+
async function runCommand(platform2, cmdPath, argv, childEnv, stdin, timeoutMs, maxOutput, cwd) {
|
|
3326
|
+
let proc;
|
|
3327
|
+
try {
|
|
3328
|
+
proc = await platform2.spawn({
|
|
3329
|
+
argv: [cmdPath, ...argv],
|
|
3330
|
+
env: childEnv,
|
|
3331
|
+
cwd
|
|
3332
|
+
});
|
|
3333
|
+
} catch (err) {
|
|
3334
|
+
return { stdout: "", stderr: `spawn failed: ${err.message}`, exitCode: 127 };
|
|
3335
|
+
}
|
|
3336
|
+
inflightProcs.add(proc);
|
|
3337
|
+
if (stdin !== void 0) {
|
|
3338
|
+
const writer = proc.stdin.getWriter();
|
|
3339
|
+
await writer.write(new TextEncoder().encode(stdin));
|
|
3340
|
+
await writer.close();
|
|
3341
|
+
} else {
|
|
3342
|
+
try {
|
|
3343
|
+
await proc.stdin.getWriter().close();
|
|
3344
|
+
} catch {
|
|
3345
|
+
}
|
|
3346
|
+
}
|
|
3347
|
+
const stdoutChunks = [];
|
|
3348
|
+
const stderrChunks = [];
|
|
3349
|
+
const readStream = async (stream, into) => {
|
|
3350
|
+
const r = stream.getReader();
|
|
3351
|
+
try {
|
|
3352
|
+
for (; ; ) {
|
|
3353
|
+
const { done, value } = await r.read();
|
|
3354
|
+
if (done) break;
|
|
3355
|
+
into.push(value);
|
|
3356
|
+
}
|
|
3357
|
+
} finally {
|
|
3358
|
+
r.releaseLock();
|
|
3359
|
+
}
|
|
3360
|
+
};
|
|
3361
|
+
const timer = new Promise(
|
|
3362
|
+
(resolve) => setTimeout(() => resolve("timeout"), timeoutMs)
|
|
3363
|
+
);
|
|
3364
|
+
const work = Promise.all([
|
|
3365
|
+
readStream(proc.stdout, stdoutChunks),
|
|
3366
|
+
readStream(proc.stderr, stderrChunks),
|
|
3367
|
+
proc.wait()
|
|
3368
|
+
]);
|
|
3369
|
+
const result = await Promise.race([work, timer]);
|
|
3370
|
+
if (result === "timeout") {
|
|
3371
|
+
proc.kill("SIGTERM");
|
|
3372
|
+
await new Promise((resolve) => setTimeout(resolve, 5e3));
|
|
3373
|
+
try {
|
|
3374
|
+
proc.kill("SIGKILL");
|
|
3375
|
+
} catch {
|
|
3376
|
+
}
|
|
3377
|
+
inflightProcs.delete(proc);
|
|
3378
|
+
return { stdout: "", stderr: "timed out", exitCode: 124 };
|
|
3379
|
+
}
|
|
3380
|
+
inflightProcs.delete(proc);
|
|
3381
|
+
const [, , exitResult] = result;
|
|
3382
|
+
const dec = new TextDecoder();
|
|
3383
|
+
return {
|
|
3384
|
+
stdout: capOutput(dec.decode(concat(stdoutChunks)), maxOutput),
|
|
3385
|
+
stderr: capOutput(dec.decode(concat(stderrChunks)), maxOutput),
|
|
3386
|
+
exitCode: exitResult.status
|
|
3387
|
+
};
|
|
3388
|
+
}
|
|
3389
|
+
function concat(chunks) {
|
|
3390
|
+
const total = chunks.reduce((s, c) => s + c.length, 0);
|
|
3391
|
+
const out = new Uint8Array(total);
|
|
3392
|
+
let offset = 0;
|
|
3393
|
+
for (const c of chunks) {
|
|
3394
|
+
out.set(c, offset);
|
|
3395
|
+
offset += c.length;
|
|
3396
|
+
}
|
|
3397
|
+
return out;
|
|
3398
|
+
}
|
|
3399
|
+
async function killInflight() {
|
|
3400
|
+
for (const proc of inflightProcs) {
|
|
3401
|
+
try {
|
|
3402
|
+
proc.kill("SIGTERM");
|
|
3403
|
+
} catch {
|
|
3404
|
+
}
|
|
3405
|
+
}
|
|
3406
|
+
if (inflightProcs.size > 0) {
|
|
3407
|
+
await new Promise((resolve) => setTimeout(resolve, 5e3));
|
|
3408
|
+
for (const proc of inflightProcs) {
|
|
3409
|
+
try {
|
|
3410
|
+
proc.kill("SIGKILL");
|
|
3411
|
+
} catch {
|
|
3412
|
+
}
|
|
3413
|
+
}
|
|
3414
|
+
}
|
|
3415
|
+
inflightProcs.clear();
|
|
3416
|
+
}
|
|
3417
|
+
async function runHelpForCli(platform2, filePath, childEnv, cwd) {
|
|
3418
|
+
const dashed = await runCommand(
|
|
3419
|
+
platform2,
|
|
3420
|
+
filePath,
|
|
3421
|
+
["--help"],
|
|
3422
|
+
childEnv,
|
|
3423
|
+
void 0,
|
|
3424
|
+
1e4,
|
|
3425
|
+
MAX_OUTPUT_DEFAULT,
|
|
3426
|
+
cwd
|
|
3427
|
+
);
|
|
3428
|
+
if (dashed.exitCode === 0 && dashed.stdout.trim()) return dashed.stdout;
|
|
3429
|
+
const plain = await runCommand(
|
|
3430
|
+
platform2,
|
|
3431
|
+
filePath,
|
|
3432
|
+
["help"],
|
|
3433
|
+
childEnv,
|
|
3434
|
+
void 0,
|
|
3435
|
+
1e4,
|
|
3436
|
+
MAX_OUTPUT_DEFAULT,
|
|
3437
|
+
cwd
|
|
3438
|
+
);
|
|
3439
|
+
if (plain.exitCode === 0 && plain.stdout.trim()) return plain.stdout;
|
|
3440
|
+
return dashed.stdout.trim() ? dashed.stdout : "";
|
|
3441
|
+
}
|
|
3442
|
+
async function expandGroupCommands(platform2, filePath, commands, childEnv, cwd) {
|
|
3443
|
+
const topNames = new Set(commands.map((c) => c.path[0] ?? ""));
|
|
3444
|
+
let current = commands;
|
|
3445
|
+
for (const command of commands) {
|
|
3446
|
+
if (!isGroupCandidate(command)) continue;
|
|
3447
|
+
const group = command.path[0] ?? "";
|
|
3448
|
+
const nested = await runCommand(
|
|
3449
|
+
platform2,
|
|
3450
|
+
filePath,
|
|
3451
|
+
[group, "--help"],
|
|
3452
|
+
childEnv,
|
|
3453
|
+
void 0,
|
|
3454
|
+
1e4,
|
|
3455
|
+
MAX_OUTPUT_DEFAULT,
|
|
3456
|
+
cwd
|
|
3457
|
+
);
|
|
3458
|
+
if (nested.exitCode !== 0 || !nested.stdout.trim()) continue;
|
|
3459
|
+
const replaced = nestGroup(current, group, parseHelp(nested.stdout), topNames);
|
|
3460
|
+
if (replaced) current = replaced;
|
|
3461
|
+
}
|
|
3462
|
+
return current;
|
|
3463
|
+
}
|
|
3464
|
+
async function discoverCli(platform2, filePath, explicitName, childEnv, cwd) {
|
|
3465
|
+
const mcp = await runCommand(
|
|
3466
|
+
platform2,
|
|
3467
|
+
filePath,
|
|
3468
|
+
["--mcp"],
|
|
3469
|
+
childEnv,
|
|
3470
|
+
void 0,
|
|
3471
|
+
1e4,
|
|
3472
|
+
MAX_OUTPUT_DEFAULT,
|
|
3473
|
+
cwd
|
|
3474
|
+
);
|
|
3475
|
+
const override = mcp.exitCode === 0 ? parseMcpOverride(mcp.stdout) : null;
|
|
3476
|
+
const helpText2 = override ? "" : await runHelpForCli(platform2, filePath, childEnv, cwd);
|
|
3477
|
+
if (!override && !helpText2.trim()) {
|
|
3478
|
+
throw new Error(`${filePath} did not print help or --mcp descriptor`);
|
|
3479
|
+
}
|
|
3480
|
+
const parsed = override ?? parseHelp(helpText2);
|
|
3481
|
+
let commands = parsed.commands;
|
|
3482
|
+
if (!override) {
|
|
3483
|
+
commands = attachGlobalFlags(commands, parsed.globalFlags);
|
|
3484
|
+
commands = await expandGroupCommands(platform2, filePath, commands, childEnv, cwd);
|
|
3485
|
+
}
|
|
3486
|
+
return { name: cliPrefix(helpText2, filePath, explicitName), path: filePath, commands };
|
|
3487
|
+
}
|
|
3488
|
+
function createToolExecutor(platform2, clis, allTools, childEnv, options, serveCwd) {
|
|
3489
|
+
const rpcTools = allTools.map((t) => ({
|
|
3490
|
+
name: t.name,
|
|
3491
|
+
description: t.description,
|
|
3492
|
+
inputSchema: t.inputSchema
|
|
3493
|
+
}));
|
|
3494
|
+
const queues = /* @__PURE__ */ new Map();
|
|
3495
|
+
function enqueue(key, job) {
|
|
3496
|
+
const previous = queues.get(key) ?? Promise.resolve();
|
|
3497
|
+
const run2 = previous.then(job, job);
|
|
3498
|
+
queues.set(
|
|
3499
|
+
key,
|
|
3500
|
+
run2.then(
|
|
3501
|
+
() => void 0,
|
|
3502
|
+
() => void 0
|
|
3503
|
+
)
|
|
3504
|
+
);
|
|
3505
|
+
return run2;
|
|
3506
|
+
}
|
|
3507
|
+
function invokeTemplateTool(tool, args2) {
|
|
3508
|
+
const templateArgs = {};
|
|
3509
|
+
if (args2 && typeof args2 === "object") {
|
|
3510
|
+
for (const [k, v] of Object.entries(args2)) {
|
|
3511
|
+
templateArgs[k] = String(v);
|
|
3512
|
+
}
|
|
3513
|
+
}
|
|
3514
|
+
const argv = templateToArgv(tool.description, templateArgs);
|
|
3515
|
+
return enqueue(
|
|
3516
|
+
"__template__",
|
|
3517
|
+
() => runCommand(
|
|
3518
|
+
platform2,
|
|
3519
|
+
argv[0],
|
|
3520
|
+
argv.slice(1),
|
|
3521
|
+
childEnv,
|
|
3522
|
+
void 0,
|
|
3523
|
+
options.callTimeout,
|
|
3524
|
+
options.maxOutput,
|
|
3525
|
+
serveCwd
|
|
3526
|
+
)
|
|
3527
|
+
);
|
|
3528
|
+
}
|
|
3529
|
+
async function executeTool(tool, cli, args2) {
|
|
3530
|
+
if (tool.kind === "help") {
|
|
3531
|
+
const result = await runCommand(
|
|
3532
|
+
platform2,
|
|
3533
|
+
cli.path,
|
|
3534
|
+
["--help"],
|
|
3535
|
+
childEnv,
|
|
3536
|
+
void 0,
|
|
3537
|
+
options.callTimeout,
|
|
3538
|
+
options.maxOutput,
|
|
3539
|
+
serveCwd
|
|
3540
|
+
);
|
|
3541
|
+
if (result.exitCode === 0) return result;
|
|
3542
|
+
return runCommand(
|
|
3543
|
+
platform2,
|
|
3544
|
+
cli.path,
|
|
3545
|
+
["help"],
|
|
3546
|
+
childEnv,
|
|
3547
|
+
void 0,
|
|
3548
|
+
options.callTimeout,
|
|
3549
|
+
options.maxOutput,
|
|
3550
|
+
serveCwd
|
|
3551
|
+
);
|
|
3552
|
+
}
|
|
3553
|
+
if (tool.kind === "invoke") {
|
|
3554
|
+
const parsed2 = readToolArguments(args2 ?? {});
|
|
3555
|
+
if (parsed2.error) return { stdout: "", stderr: parsed2.error, exitCode: 2 };
|
|
3556
|
+
if (!parsed2.argv) return { stdout: "", stderr: "argv is required", exitCode: 2 };
|
|
3557
|
+
return runCommand(
|
|
3558
|
+
platform2,
|
|
3559
|
+
cli.path,
|
|
3560
|
+
parsed2.argv,
|
|
3561
|
+
childEnv,
|
|
3562
|
+
parsed2.stdin,
|
|
3563
|
+
options.callTimeout,
|
|
3564
|
+
options.maxOutput,
|
|
3565
|
+
serveCwd
|
|
3566
|
+
);
|
|
3567
|
+
}
|
|
3568
|
+
const parsed = readToolArguments(args2 ?? {});
|
|
3569
|
+
const command = cli.commands.find((c) => c.path.join("_") === tool.commandPath.join("_"));
|
|
3570
|
+
if (!command) return { stdout: "", stderr: `unknown command ${tool.name}`, exitCode: 2 };
|
|
3571
|
+
const planned = argvForCommand(command, parsed);
|
|
3572
|
+
if ("error" in planned) return { stdout: "", stderr: planned.error, exitCode: 2 };
|
|
3573
|
+
return runCommand(
|
|
3574
|
+
platform2,
|
|
3575
|
+
cli.path,
|
|
3576
|
+
planned.argv,
|
|
3577
|
+
childEnv,
|
|
3578
|
+
planned.stdin,
|
|
3579
|
+
options.callTimeout,
|
|
3580
|
+
options.maxOutput,
|
|
3581
|
+
serveCwd
|
|
3582
|
+
);
|
|
3583
|
+
}
|
|
3584
|
+
async function invoke(name, args2) {
|
|
3585
|
+
const tool = allTools.find((t) => t.name === name);
|
|
3586
|
+
if (!tool) return { stdout: "", stderr: `unknown tool ${name}`, exitCode: 1 };
|
|
3587
|
+
if (tool.cli === "" && tool.commandPath.length === 0) {
|
|
3588
|
+
return invokeTemplateTool(tool, args2);
|
|
3589
|
+
}
|
|
3590
|
+
const cli = clis.find((c) => c.name === tool.cli);
|
|
3591
|
+
if (!cli) return { stdout: "", stderr: `unknown cli ${tool.cli}`, exitCode: 1 };
|
|
3592
|
+
return enqueue(cli.name, () => executeTool(tool, cli, args2));
|
|
3593
|
+
}
|
|
3594
|
+
return { invoke, rpcTools };
|
|
3595
|
+
}
|
|
3596
|
+
async function runServe(platform2, options, version) {
|
|
3597
|
+
let resolvedBearer;
|
|
3598
|
+
if (options.bearer) {
|
|
3599
|
+
const expanded = expandBearerToken(options.bearer, platform2.env);
|
|
3600
|
+
if (!expanded) {
|
|
3601
|
+
await platform2.write(
|
|
3602
|
+
2,
|
|
3603
|
+
"mcpcat serve: --bearer requires a ${NAME} variable reference, not a literal token. Use --bearer '${MY_TOKEN}' and set MY_TOKEN in the environment.\n"
|
|
3604
|
+
);
|
|
3605
|
+
return 2;
|
|
3606
|
+
}
|
|
3607
|
+
resolvedBearer = expanded;
|
|
3608
|
+
}
|
|
3609
|
+
const serveCwd = options.cwd ?? platform2.cwd;
|
|
3610
|
+
const childEnv = buildChildEnv(platform2, options.envAllow);
|
|
3611
|
+
const clis = [];
|
|
3612
|
+
for (const cmd of options.commands) {
|
|
3613
|
+
try {
|
|
3614
|
+
const cli = await discoverCli(platform2, cmd.path, cmd.name, childEnv, serveCwd);
|
|
3615
|
+
clis.push(cli);
|
|
3616
|
+
} catch (err) {
|
|
3617
|
+
await platform2.write(2, `mcpcat serve: ${err.message}
|
|
3618
|
+
`);
|
|
3619
|
+
return 2;
|
|
3620
|
+
}
|
|
3621
|
+
}
|
|
3622
|
+
const allTools = clis.flatMap((cli) => buildTools(cli.name, cli.commands));
|
|
3623
|
+
for (const spec of options.toolTemplates) {
|
|
3624
|
+
const tool = parseToolTemplate(spec);
|
|
3625
|
+
if (!tool) {
|
|
3626
|
+
await platform2.write(2, `mcpcat serve: invalid --tool spec: ${spec}
|
|
3627
|
+
`);
|
|
3628
|
+
return 2;
|
|
3629
|
+
}
|
|
3630
|
+
allTools.push(tool);
|
|
3631
|
+
}
|
|
3632
|
+
const executor = createToolExecutor(platform2, clis, allTools, childEnv, options, serveCwd);
|
|
3633
|
+
const serverName = "mcpcat-serve";
|
|
3634
|
+
if (options.transport === "stdio") {
|
|
3635
|
+
return runStdioServer(platform2, executor.rpcTools, executor.invoke, serverName, version);
|
|
3636
|
+
}
|
|
3637
|
+
return runHttpServer(
|
|
3638
|
+
platform2,
|
|
3639
|
+
options,
|
|
3640
|
+
executor.rpcTools,
|
|
3641
|
+
executor.invoke,
|
|
3642
|
+
serverName,
|
|
3643
|
+
version,
|
|
3644
|
+
resolvedBearer
|
|
3645
|
+
);
|
|
3646
|
+
}
|
|
3647
|
+
async function runStdioServer(platform2, tools, call, serverName, version) {
|
|
3648
|
+
const reader = platform2.stdin.getReader();
|
|
3649
|
+
let buffer = "";
|
|
3650
|
+
const dec = new TextDecoder();
|
|
3651
|
+
const enc = new TextEncoder();
|
|
3652
|
+
try {
|
|
3653
|
+
for (; ; ) {
|
|
3654
|
+
const { done, value } = await reader.read();
|
|
3655
|
+
if (done) break;
|
|
3656
|
+
buffer += dec.decode(value, { stream: true });
|
|
3657
|
+
let nlIdx;
|
|
3658
|
+
while ((nlIdx = buffer.indexOf("\n")) >= 0) {
|
|
3659
|
+
const line = buffer.slice(0, nlIdx).trim();
|
|
3660
|
+
buffer = buffer.slice(nlIdx + 1);
|
|
3661
|
+
if (!line) continue;
|
|
3662
|
+
const outcome = await handleJsonRpc(line, tools, call, serverName, version);
|
|
3663
|
+
if (outcome.status === 202) continue;
|
|
3664
|
+
const writer = platform2.stdout.getWriter();
|
|
3665
|
+
await writer.write(enc.encode(`${outcome.body}
|
|
3666
|
+
`));
|
|
3667
|
+
writer.releaseLock();
|
|
3668
|
+
}
|
|
3669
|
+
}
|
|
3670
|
+
} finally {
|
|
3671
|
+
reader.releaseLock();
|
|
3672
|
+
}
|
|
3673
|
+
return 0;
|
|
3674
|
+
}
|
|
3675
|
+
async function runHttpServer(platform2, options, tools, call, serverName, version, resolvedBearer) {
|
|
3676
|
+
if (!platform2.listen) {
|
|
3677
|
+
await platform2.write(2, "mcpcat serve: HTTP transport requires platform.listen\n");
|
|
3678
|
+
return 3;
|
|
3679
|
+
}
|
|
3680
|
+
const boundLoopback = options.host === "127.0.0.1" || options.host === "localhost" || options.host === "::1";
|
|
3681
|
+
if (!boundLoopback && !resolvedBearer) {
|
|
3682
|
+
await platform2.write(2, "mcpcat serve: --bearer is required when binding off loopback\n");
|
|
3683
|
+
return 2;
|
|
3684
|
+
}
|
|
3685
|
+
const allowedOrigins = new Set(options.allowOrigins);
|
|
3686
|
+
const listener = await platform2.listen({ host: options.host, port: options.port });
|
|
3687
|
+
const actualPort = listener.port;
|
|
3688
|
+
const listenUrl = `http://${options.host}:${actualPort}/mcp`;
|
|
3689
|
+
if (options.json) {
|
|
3690
|
+
await platform2.write(1, `${JSON.stringify({ url: listenUrl })}
|
|
3691
|
+
`);
|
|
3692
|
+
}
|
|
3693
|
+
await platform2.write(2, `mcpcat serve: listening on ${listenUrl}
|
|
3694
|
+
`);
|
|
3695
|
+
let shutdownRequested = false;
|
|
3696
|
+
const shutdown = () => {
|
|
3697
|
+
if (shutdownRequested) return;
|
|
3698
|
+
shutdownRequested = true;
|
|
3699
|
+
listener.close();
|
|
3700
|
+
void killInflight();
|
|
3701
|
+
};
|
|
3702
|
+
if (platform2.onSignal) {
|
|
3703
|
+
platform2.onSignal("SIGINT", shutdown);
|
|
3704
|
+
platform2.onSignal("SIGTERM", shutdown);
|
|
3705
|
+
}
|
|
3706
|
+
const handler = (request) => handleMcpRequest(
|
|
3707
|
+
request,
|
|
3708
|
+
tools,
|
|
3709
|
+
call,
|
|
3710
|
+
serverName,
|
|
3711
|
+
version,
|
|
3712
|
+
allowedOrigins,
|
|
3713
|
+
boundLoopback,
|
|
3714
|
+
resolvedBearer
|
|
3715
|
+
);
|
|
3716
|
+
try {
|
|
3717
|
+
for await (const connection of listener) {
|
|
3718
|
+
if (shutdownRequested) break;
|
|
3719
|
+
const conn = connection;
|
|
3720
|
+
handleConnection(conn.readable, conn.writable, handler).catch(() => {
|
|
3721
|
+
}).finally(() => {
|
|
3722
|
+
try {
|
|
3723
|
+
conn.close();
|
|
3724
|
+
} catch {
|
|
3725
|
+
}
|
|
3726
|
+
});
|
|
3727
|
+
}
|
|
3728
|
+
} catch {
|
|
3729
|
+
if (!shutdownRequested) throw new Error("listener closed unexpectedly");
|
|
3730
|
+
}
|
|
3731
|
+
return 0;
|
|
3732
|
+
}
|
|
3733
|
+
async function handleMcpRequest(request, tools, call, serverName, version, allowedOrigins, boundLoopback, resolvedBearer) {
|
|
3734
|
+
if (resolvedBearer) {
|
|
3735
|
+
const authHeader = request.headers.authorization;
|
|
3736
|
+
const provided = authHeader?.startsWith("Bearer ") ? authHeader.slice(7) : "";
|
|
3737
|
+
if (!provided || !constantTimeEqual(provided, resolvedBearer)) {
|
|
3738
|
+
return {
|
|
3739
|
+
status: 401,
|
|
3740
|
+
reason: "Unauthorized",
|
|
3741
|
+
headers: { "content-type": "text/plain" },
|
|
3742
|
+
body: "Unauthorized"
|
|
3743
|
+
};
|
|
3744
|
+
}
|
|
3745
|
+
}
|
|
3746
|
+
const originCheck = checkOrigin(request.headers.origin, allowedOrigins, boundLoopback);
|
|
3747
|
+
if (!originCheck.ok) {
|
|
3748
|
+
return {
|
|
3749
|
+
status: 403,
|
|
3750
|
+
reason: "Forbidden",
|
|
3751
|
+
headers: { "content-type": "text/plain" },
|
|
3752
|
+
body: originCheck.reason ?? "Forbidden"
|
|
3753
|
+
};
|
|
3754
|
+
}
|
|
3755
|
+
const hostCheck = checkHost(request.headers.host, boundLoopback);
|
|
3756
|
+
if (!hostCheck.ok) {
|
|
3757
|
+
return {
|
|
3758
|
+
status: 403,
|
|
3759
|
+
reason: "Forbidden",
|
|
3760
|
+
headers: { "content-type": "text/plain" },
|
|
3761
|
+
body: hostCheck.reason ?? "Forbidden"
|
|
3762
|
+
};
|
|
3763
|
+
}
|
|
3764
|
+
if (request.target !== "/mcp") {
|
|
3765
|
+
return {
|
|
3766
|
+
status: 404,
|
|
3767
|
+
reason: "Not Found",
|
|
3768
|
+
headers: { "content-type": "text/plain" },
|
|
3769
|
+
body: "Not Found"
|
|
3770
|
+
};
|
|
3771
|
+
}
|
|
3772
|
+
if (request.method !== "POST") {
|
|
3773
|
+
return {
|
|
3774
|
+
status: 405,
|
|
3775
|
+
reason: "Method Not Allowed",
|
|
3776
|
+
headers: { "content-type": "text/plain", allow: "POST" },
|
|
3777
|
+
body: "Method Not Allowed"
|
|
3778
|
+
};
|
|
3779
|
+
}
|
|
3780
|
+
const outcome = await handleJsonRpc(request.body, tools, call, serverName, version);
|
|
3781
|
+
return {
|
|
3782
|
+
status: outcome.status,
|
|
3783
|
+
reason: outcome.status === 200 ? "OK" : "Accepted",
|
|
3784
|
+
headers: { "content-type": outcome.contentType },
|
|
3785
|
+
body: outcome.body
|
|
3786
|
+
};
|
|
3787
|
+
}
|
|
3788
|
+
|
|
2396
3789
|
// src/config/lock.ts
|
|
2397
3790
|
var LOCK_STALE_MS = 1e4;
|
|
2398
3791
|
var LOCK_POLL_MS = 50;
|
|
@@ -2810,12 +4203,12 @@ function importFile(text, filename, names) {
|
|
|
2810
4203
|
|
|
2811
4204
|
// src/config/warnings.ts
|
|
2812
4205
|
var SECRET_HEADER = /authorization|cookie|token|key|secret|password|session/i;
|
|
2813
|
-
var
|
|
4206
|
+
var PLACEHOLDER2 = /\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g;
|
|
2814
4207
|
var SCHEME = /^\s*(?:bearer|basic|token|apikey|api-key)\s+/i;
|
|
2815
4208
|
var SECRET_PARAM = /token|key|secret|password|signature|sig|auth|code/i;
|
|
2816
4209
|
function literalSecret(header, value) {
|
|
2817
4210
|
if (!SECRET_HEADER.test(header)) return false;
|
|
2818
|
-
return value.replace(
|
|
4211
|
+
return value.replace(PLACEHOLDER2, "").replace(SCHEME, "").trim() !== "";
|
|
2819
4212
|
}
|
|
2820
4213
|
function urlHasSecret(url) {
|
|
2821
4214
|
if (!URL.canParse(url)) return void 0;
|
|
@@ -3350,12 +4743,11 @@ var UNIMPLEMENTED_VERBS = /* @__PURE__ */ new Set([
|
|
|
3350
4743
|
"task",
|
|
3351
4744
|
"login",
|
|
3352
4745
|
"logout",
|
|
3353
|
-
"serve",
|
|
3354
4746
|
"code",
|
|
3355
4747
|
"discover",
|
|
3356
4748
|
"inbox"
|
|
3357
4749
|
]);
|
|
3358
|
-
var CLIENT_VERBS = /* @__PURE__ */ new Set(["info", "tools", "call", "describe"]);
|
|
4750
|
+
var CLIENT_VERBS = /* @__PURE__ */ new Set(["info", "tools", "call", "describe", "serve"]);
|
|
3359
4751
|
function helpText(version) {
|
|
3360
4752
|
return `mcpcat ${version} \u2013 a curl for the Model Context Protocol
|
|
3361
4753
|
|
|
@@ -3379,7 +4771,7 @@ Configuration verbs:
|
|
|
3379
4771
|
logout <target> Remove tokens (not implemented yet)
|
|
3380
4772
|
|
|
3381
4773
|
Server and code verbs:
|
|
3382
|
-
serve [--stdio|--http] \u2026 Expose commands as MCP server
|
|
4774
|
+
serve [--stdio|--http] \u2026 Expose commands as MCP server
|
|
3383
4775
|
code [-e src|file.js] Run a codemode script (not implemented yet)
|
|
3384
4776
|
discover <url> Find MCP servers (not implemented yet)
|
|
3385
4777
|
inbox Discovery inbox (not implemented yet)
|
|
@@ -3709,6 +5101,15 @@ async function run(platform2, version, args2) {
|
|
|
3709
5101
|
`);
|
|
3710
5102
|
return 1;
|
|
3711
5103
|
}
|
|
5104
|
+
if (parsed.verb === "serve") {
|
|
5105
|
+
const serveArgs = args2.slice(args2.indexOf("serve") + 1);
|
|
5106
|
+
const serveOptions = parseServeFlags(serveArgs);
|
|
5107
|
+
if (serveOptions.commands.length === 0 && serveOptions.toolTemplates.length === 0) {
|
|
5108
|
+
await platform2.write(2, "mcpcat serve: no commands or --tool templates given\n");
|
|
5109
|
+
return 2;
|
|
5110
|
+
}
|
|
5111
|
+
return runServe(platform2, serveOptions, version);
|
|
5112
|
+
}
|
|
3712
5113
|
if (!CLIENT_VERBS.has(parsed.verb)) {
|
|
3713
5114
|
await platform2.write(2, `mcpcat: unknown command '${parsed.verb}'
|
|
3714
5115
|
`);
|
|
@@ -3772,6 +5173,7 @@ async function run(platform2, version, args2) {
|
|
|
3772
5173
|
import { spawn as cpSpawn } from "node:child_process";
|
|
3773
5174
|
import { constants } from "node:fs";
|
|
3774
5175
|
import { access, mkdir, readFile as readFile2, rename, rmdir, stat, writeFile } from "node:fs/promises";
|
|
5176
|
+
import { createServer } from "node:net";
|
|
3775
5177
|
import { Readable, Writable } from "node:stream";
|
|
3776
5178
|
import * as tty from "node:tty";
|
|
3777
5179
|
function nodeSpawn(options) {
|
|
@@ -3853,11 +5255,77 @@ function createStdoutStream() {
|
|
|
3853
5255
|
function createStderrStream() {
|
|
3854
5256
|
return Writable.toWeb(process.stderr);
|
|
3855
5257
|
}
|
|
5258
|
+
function nodeListen(options) {
|
|
5259
|
+
return new Promise((resolve, reject) => {
|
|
5260
|
+
const server = createServer();
|
|
5261
|
+
const pending = [];
|
|
5262
|
+
const ready = [];
|
|
5263
|
+
let closed = false;
|
|
5264
|
+
server.on("connection", (socket) => {
|
|
5265
|
+
const conn = {
|
|
5266
|
+
readable: Readable.toWeb(socket),
|
|
5267
|
+
writable: Writable.toWeb(socket),
|
|
5268
|
+
remoteAddress: socket.remoteAddress ?? "",
|
|
5269
|
+
close() {
|
|
5270
|
+
socket.destroy();
|
|
5271
|
+
}
|
|
5272
|
+
};
|
|
5273
|
+
const waiter = pending.shift();
|
|
5274
|
+
if (waiter) {
|
|
5275
|
+
waiter.resolve(conn);
|
|
5276
|
+
} else {
|
|
5277
|
+
ready.push(conn);
|
|
5278
|
+
}
|
|
5279
|
+
});
|
|
5280
|
+
server.on("error", (err) => {
|
|
5281
|
+
if (!closed) reject(err);
|
|
5282
|
+
for (const waiter of pending) waiter.reject(err);
|
|
5283
|
+
pending.length = 0;
|
|
5284
|
+
});
|
|
5285
|
+
server.listen(options.port, options.host ?? "127.0.0.1", () => {
|
|
5286
|
+
const addr = server.address();
|
|
5287
|
+
const actualPort = typeof addr === "object" && addr ? addr.port : options.port;
|
|
5288
|
+
const listener = {
|
|
5289
|
+
get port() {
|
|
5290
|
+
return actualPort;
|
|
5291
|
+
},
|
|
5292
|
+
accept() {
|
|
5293
|
+
const queued = ready.shift();
|
|
5294
|
+
if (queued) return Promise.resolve(queued);
|
|
5295
|
+
return new Promise((res, rej) => {
|
|
5296
|
+
if (closed) {
|
|
5297
|
+
rej(new Error("listener closed"));
|
|
5298
|
+
return;
|
|
5299
|
+
}
|
|
5300
|
+
pending.push({ resolve: res, reject: rej });
|
|
5301
|
+
});
|
|
5302
|
+
},
|
|
5303
|
+
close() {
|
|
5304
|
+
closed = true;
|
|
5305
|
+
server.close();
|
|
5306
|
+
for (const waiter of pending) waiter.reject(new Error("listener closed"));
|
|
5307
|
+
pending.length = 0;
|
|
5308
|
+
},
|
|
5309
|
+
async *[Symbol.asyncIterator]() {
|
|
5310
|
+
while (!closed) {
|
|
5311
|
+
try {
|
|
5312
|
+
yield await this.accept();
|
|
5313
|
+
} catch {
|
|
5314
|
+
break;
|
|
5315
|
+
}
|
|
5316
|
+
}
|
|
5317
|
+
}
|
|
5318
|
+
};
|
|
5319
|
+
resolve(listener);
|
|
5320
|
+
});
|
|
5321
|
+
});
|
|
5322
|
+
}
|
|
3856
5323
|
function createHostPlatform() {
|
|
3857
|
-
const
|
|
5324
|
+
const encoder2 = new TextEncoder();
|
|
3858
5325
|
return {
|
|
3859
5326
|
fetch: globalThis.fetch,
|
|
3860
5327
|
spawn: nodeSpawn,
|
|
5328
|
+
listen: nodeListen,
|
|
3861
5329
|
fs: hostFs,
|
|
3862
5330
|
env: process.env,
|
|
3863
5331
|
cwd: process.cwd(),
|
|
@@ -3868,7 +5336,7 @@ function createHostPlatform() {
|
|
|
3868
5336
|
stdout: createStdoutStream(),
|
|
3869
5337
|
stderr: createStderrStream(),
|
|
3870
5338
|
async write(fd, data) {
|
|
3871
|
-
const bytes = typeof data === "string" ?
|
|
5339
|
+
const bytes = typeof data === "string" ? encoder2.encode(data) : data;
|
|
3872
5340
|
const stream = fd === 1 ? process.stdout : process.stderr;
|
|
3873
5341
|
return new Promise((resolve, reject) => {
|
|
3874
5342
|
stream.write(bytes, (err) => err ? reject(err) : resolve());
|
|
@@ -3876,6 +5344,9 @@ function createHostPlatform() {
|
|
|
3876
5344
|
},
|
|
3877
5345
|
exit(code2) {
|
|
3878
5346
|
process.exit(code2);
|
|
5347
|
+
},
|
|
5348
|
+
onSignal(signal, handler) {
|
|
5349
|
+
process.on(signal, handler);
|
|
3879
5350
|
}
|
|
3880
5351
|
};
|
|
3881
5352
|
}
|
|
@@ -3883,5 +5354,5 @@ function createHostPlatform() {
|
|
|
3883
5354
|
// src/host.ts
|
|
3884
5355
|
var platform = createHostPlatform();
|
|
3885
5356
|
var args = process.argv.slice(2);
|
|
3886
|
-
var code = await run(platform, "0.
|
|
5357
|
+
var code = await run(platform, "0.4.0", args);
|
|
3887
5358
|
process.exit(code);
|