fix(cli): classify MCP launcher arguments once (#12152)

Refs #12129
This commit is contained in:
morluto authored and GitHub committed 2026-11-19 03:59:09 +00:00
1 parent 0b1ab37a33
commit 85ac88fe87
9 files changed
+258 -133

No files matched your search

+8 -23
View File
@@ -37,21 +37,7 @@ const builtinArgumentRuntime = "dist/cli-runtime/cliBuiltinArguments.js";
const builtinArguments = (await compiledRuntimeExists([builtinArgumentRuntime]))
? await import("../dist/cli-runtime/cliBuiltinArguments.js")
: undefined;
const isShellCompletion =
builtinArguments?.cliCompletionShell?.(process.env) !== undefined;
const doctorArguments = isShellCompletion
? undefined
: builtinArguments?.productionMcpDoctorArguments(args);
const isMcpEntry =
!isShellCompletion && (args[0] === "--mcp" || args[0] === "mcp");
const isMcpMode = isMcpEntry && args.length === 1;
const isMcpDoctorMode = doctorArguments !== undefined;
// Only flags may follow the entry: `mcp add --http` stays Incur's `mcp add`,
// while `mcp -h --http` reaches the HTTP entry's own help.
const isMcpHttpMode =
isMcpEntry &&
(args[1]?.startsWith("-") ?? false) &&
args.slice(1).includes("--http");
const entry = builtinArguments?.classifyCliEntrypoint(args, process.env);
/** How long an exiting command may wait for its remaining handles to close. */
const EXIT_DRAIN_GRACE_MS = 1_000;
/** Exit status of a writer terminated by SIGPIPE (128 + 13). */
@@ -60,9 +46,9 @@ const SIGPIPE_EXIT_STATUS = 141;
let stdoutClosed = false;
const runtimeFiles = [
builtinArgumentRuntime,
...(isMcpMode || isMcpHttpMode
...(entry?.kind === "mcp-stdio" || entry?.kind === "mcp-http"
? ["dist/mcp/main.js"]
: isMcpDoctorMode
: entry?.kind === "mcp-doctor"
? ["dist/mcp/main.js", "dist/cli-runtime/mcpDoctor.js"]
: [
"dist/cli-runtime/cli.js",
@@ -76,18 +62,17 @@ if (!(await compiledRuntimeExists(runtimeFiles))) {
`REA's compiled runtime is missing. Run \`npm ci && npm run build:cached\` in ${packageRoot} to install dependencies and build REA, then restart it. If this is an installed package, reinstall rea-agents.\n`,
);
process.exitCode = 1;
} else if (isMcpMode) {
} else if (entry?.kind === "mcp-stdio") {
const { runEntrypoint } = await import("../dist/mcp/main.js");
await runEntrypoint();
} else if (isMcpHttpMode) {
} else if (entry?.kind === "mcp-http") {
const { runMcpHttpEntrypoint } = await import("../dist/mcp/main.js");
await runMcpHttpEntrypoint(args.slice(1));
} else if (isMcpDoctorMode) {
await runMcpHttpEntrypoint(entry.command);
} else if (entry?.kind === "mcp-doctor") {
guardClosedStdout();
// Doctor runs outside the command dispatcher, so the launcher measures its
// timing global, which the global argument reader has taken out.
const { arguments: doctorCliArguments, timings: timingRequested } =
doctorArguments;
const { arguments: doctorCliArguments, timings: timingRequested } = entry;
const started = performance.now();
try {
const { runProductionMcpDoctorCli } =
+130 -4
View File
@@ -9,6 +9,12 @@ export const VALUED_OUTPUT_FLAGS: ReadonlySet<string> = new Set([
"--token-offset",
]);
const spacedOutputValue = (
flag: string,
next: string | undefined,
): string | undefined =>
VALUED_OUTPUT_FLAGS.has(flag) && next ? next : undefined;
export const OUTPUT_SWITCHES: ReadonlySet<string> = new Set([
"--json",
"--full-output",
@@ -80,10 +86,11 @@ const normalizeCliArguments = (arguments_: readonly string[]): string[] => {
let rootUpdate = true;
for (let index = 0; index < arguments_.length; index += 1) {
const argument = arguments_[index]!;
if (VALUED_OUTPUT_FLAGS.has(argument) && arguments_[index + 1]) {
const outputValue = spacedOutputValue(argument, arguments_[index + 1]);
if (outputValue !== undefined) {
// A nonempty spaced value is consumed before looking for more flags.
// Its contents belong to that option, even when they look like a flag.
normalized.push(argument, arguments_[index + 1]!);
normalized.push(argument, outputValue);
index += 1;
continue;
}
@@ -134,7 +141,7 @@ export const parseCliGlobalArguments = (
flags.add(argument);
continue;
}
if (VALUED_OUTPUT_FLAGS.has(argument) && next) {
if (spacedOutputValue(argument, next) !== undefined) {
outputValues.push({ flag: argument, index: index + 1 });
index += 1;
continue;
@@ -275,7 +282,7 @@ export const isProjectScopedAmpRegistration = ({
* the `mcp doctor` words and the timing global the launcher measures. Returns
* undefined for any other command.
*/
export const productionMcpDoctorArguments = (
const productionMcpDoctorArguments = (
arguments_: readonly string[],
):
| { readonly arguments: readonly string[]; readonly timings: boolean }
@@ -336,3 +343,122 @@ export const CLI_COMPLETION_SHELLS = [
] as const;
export const cliCompletionShell = (environment: Readonly<NodeJS.ProcessEnv>) =>
CLI_COMPLETION_SHELLS.find((shell) => shell === environment.COMPLETE);
type McpHttpCommandProblem =
| { readonly kind: "help" }
| { readonly kind: "invalid"; readonly message: string };
export type McpHttpCommand =
| McpHttpCommandProblem
| {
readonly kind: "listen";
readonly host: string | undefined;
readonly port: string | undefined;
readonly allowedHosts: readonly string[];
};
const invalidMcpHttpCommand = (message: string): McpHttpCommandProblem => ({
kind: "invalid",
message,
});
const MCP_HTTP_VALUED_FLAGS: ReadonlySet<string> = new Set([
"--host",
"--port",
"--allowed-hosts",
]);
const MCP_HTTP_HELP_FLAGS: ReadonlySet<string> = new Set(["--help", "-h"]);
const readMcpHttpOption = (argument: string, next: string | undefined) => {
const separator = argument.indexOf("=");
return separator === -1
? {
flag: argument,
inline: false,
value: next?.startsWith("-") ? undefined : next,
}
: {
flag: argument.slice(0, separator),
inline: true,
value: argument.slice(separator + 1),
};
};
/** Read the transport syntax once, retaining the first help or refusal while looking for the mode. */
const readMcpHttpCommand = (
arguments_: readonly string[],
): McpHttpCommand | undefined => {
let mode: "explicit" | "required" | undefined;
const values = new Map<string, string>();
const allowedHosts: string[] = [];
let problem: McpHttpCommandProblem | undefined;
for (let index = 0; index < arguments_.length; index += 1) {
const argument = arguments_[index]!;
if (MCP_HTTP_HELP_FLAGS.has(argument)) {
problem ??= { kind: "help" };
continue;
}
if (argument === "--http") {
mode = "explicit";
continue;
}
const next = arguments_[index + 1];
const { flag, inline, value } = readMcpHttpOption(argument, next);
if (MCP_HTTP_VALUED_FLAGS.has(flag)) {
mode ??= "required";
if (value === undefined) {
problem ??= invalidMcpHttpCommand(`Missing value for ${flag}`);
} else {
if (flag === "--allowed-hosts") allowedHosts.push(value);
else values.set(flag, value);
if (!inline) index += 1;
}
continue;
}
problem ??= invalidMcpHttpCommand(
`Unknown mcp --http argument: ${argument}`,
);
// A subcommand or an option delimiter ends mode selection. Global
// output values belong to the one-shot CLI even if they spell --http.
if (!argument.startsWith("-") || argument === "--") break;
if (!inline && spacedOutputValue(flag, next) !== undefined) index += 1;
}
if (mode === undefined) return undefined;
if (problem !== undefined) return problem;
if (mode === "required")
return invalidMcpHttpCommand("--host and --port require --http");
return {
kind: "listen",
host: values.get("--host"),
port: values.get("--port"),
allowedHosts,
};
};
type CliEntrypoint =
| { readonly kind: "cli" | "mcp-stdio" }
| { readonly kind: "mcp-http"; readonly command: McpHttpCommand }
| {
readonly kind: "mcp-doctor";
readonly arguments: readonly string[];
readonly timings: boolean;
};
/** Select the process entry before loading its runtime, including completion requests. */
export const classifyCliEntrypoint = (
arguments_: readonly string[],
environment: Readonly<NodeJS.ProcessEnv>,
): CliEntrypoint => {
if (cliCompletionShell(environment) !== undefined) return { kind: "cli" };
const entry = arguments_[0];
if (entry === "mcp" || entry === "--mcp") {
if (arguments_.length === 1) return { kind: "mcp-stdio" };
const command = readMcpHttpCommand(arguments_.slice(1));
if (command !== undefined) return { kind: "mcp-http", command };
}
const doctor = productionMcpDoctorArguments(arguments_);
return doctor === undefined
? { kind: "cli" }
: { kind: "mcp-doctor", ...doctor };
};
+5 -4
View File
@@ -10,6 +10,7 @@ import {
import { serveStdio } from "@modelcontextprotocol/server/stdio";
import { parseConfig } from "./config/parseConfig.js";
import type { McpHttpCommand } from "./cliBuiltinArguments.js";
import { projectAnalysisError } from "./domain/analysisErrorProjection.js";
import type { RuntimeDependencies } from "./main/types.js";
import { runDeferred } from "./main/deferredRuntime.js";
@@ -160,14 +161,14 @@ const processIo: EntrypointIo = {
},
};
/** Run `rea mcp --http`: parse its flags, resolve MCP_HOST/MCP_PORT, then serve over HTTP. */
/** Validate the selected HTTP command, resolve MCP_HOST/MCP_PORT, then serve over HTTP. */
export const runMcpHttpEntrypoint = async (
arguments_: readonly string[],
command: McpHttpCommand,
io: EntrypointIo = processIo,
): Promise<void> => {
const { parseMcpHttpArguments, renderMcpHttpHelp } =
const { validateMcpHttpCommand, renderMcpHttpHelp } =
await import("./main/mcpHttpArguments.js");
const parsed = parseMcpHttpArguments(arguments_);
const parsed = validateMcpHttpCommand(command);
if (!parsed.ok) {
if (parsed.help) {
io.writeStdout(`${renderMcpHttpHelp()}\n`);
+11 -41
View File
@@ -1,4 +1,5 @@
import { formatCommandHelp } from "../cli/help.js";
import type { McpHttpCommand } from "../cliBuiltinArguments.js";
import { z } from "zod";
import type { HttpHostname } from "../domain/httpHostname.js";
@@ -39,12 +40,6 @@ const MCP_HTTP_ALIAS = { help: "h" } as const;
const MCP_HTTP_COMMAND = "rea mcp --http";
const MCP_HTTP_DESCRIPTION =
"Serve the MCP server over streamable HTTP for one local client";
const HELP_FLAGS: ReadonlySet<string> = new Set(["--help", "-h"]);
const VALUED_FLAGS: ReadonlySet<string> = new Set([
"--host",
"--port",
"--allowed-hosts",
]);
/** Render help for the dispatcher entry, which accepts no global options. */
export const renderMcpHttpHelp = (): string =>
@@ -72,49 +67,24 @@ const invalid = (message: string): McpHttpArguments => ({
message,
});
/** Split `--flag=value` into its flag and inline value. */
const splitFlag = (argument: string): readonly [string, string | undefined] => {
const separator = argument.indexOf("=");
return separator === -1
? [argument, undefined]
: [argument.slice(0, separator), argument.slice(separator + 1)];
};
/** Parse the dispatcher arguments after `mcp`; help wins only in flag position. */
export const parseMcpHttpArguments = (
arguments_: readonly string[],
/** Validate the transport options selected by the executable dispatcher. */
export const validateMcpHttpCommand = (
command: McpHttpCommand,
): McpHttpArguments => {
const values = new Map<string, string>();
const allowedHostValues: string[] = [];
let http = false;
for (let index = 0; index < arguments_.length; index += 1) {
const argument = arguments_[index] ?? "";
if (HELP_FLAGS.has(argument)) return { ok: false, help: true };
if (argument === "--http") {
http = true;
continue;
}
const [flag, inline] = splitFlag(argument);
if (!VALUED_FLAGS.has(flag))
return invalid(`Unknown mcp --http argument: ${argument}`);
const value = inline ?? arguments_[index + 1];
if (inline === undefined) index += 1;
if (value === undefined || (inline === undefined && value.startsWith("-")))
return invalid(`Missing value for ${flag}`);
if (flag === "--allowed-hosts") allowedHostValues.push(value);
else values.set(flag, value);
}
if (!http) return invalid("--host and --port require --http");
const host = values.get("--host")?.trim();
if (command.kind === "help") return { ok: false, help: true };
if (command.kind === "invalid") return invalid(command.message);
const host = command.host?.trim();
if (host !== undefined && host.length === 0)
return invalid("--host must be a non-empty host name or IP address");
const portText = values.get("--port");
const portText = command.port;
const port =
portText === undefined ? undefined : mcpHttpPortSchema.safeParse(portText);
if (port !== undefined && !port.success)
return invalid(`Invalid --port: ${MCP_HTTP_PORT_CONSTRAINT}`);
const allowedHostsText =
allowedHostValues.length === 0 ? undefined : allowedHostValues.join(",");
command.allowedHosts.length === 0
? undefined
: command.allowedHosts.join(",");
const allowedHosts =
allowedHostsText === undefined
? undefined
+14 -7
View File
@@ -26,7 +26,8 @@ import {
} from "./serveStreamableHttp.js";
import { StreamableHttpListenError } from "./streamableHttpListenError.js";
import { mcpAllowedHostsTextSchema } from "../../config/mcpHttpEndpoint.js";
import { parseMcpHttpArguments } from "../../main/mcpHttpArguments.js";
import { classifyCliEntrypoint } from "../../cliBuiltinArguments.js";
import { validateMcpHttpCommand } from "../../main/mcpHttpArguments.js";
import { RequestTrackingMcpServer } from "../RequestTrackingMcpServer.js";
import { waitFor } from "../../../tests/support/testWait.js";
import { ProviderCleanupError } from "../../domain/providerCleanupError.js";
@@ -354,12 +355,18 @@ it.each([
});
it("serves every declared repeated host while refusing undeclared hosts and origins", async () => {
const parsed = parseMcpHttpArguments([
"--http",
"--allowed-hosts",
"a.example",
"--allowed-hosts=b.example",
]);
const entry = classifyCliEntrypoint(
[
"mcp",
"--http",
"--allowed-hosts",
"a.example",
"--allowed-hosts=b.example",
],
{},
);
if (entry.kind !== "mcp-http") throw new Error("Expected an MCP HTTP entry");
const parsed = validateMcpHttpCommand(entry.command);
if (!parsed.ok || parsed.allowedHosts === undefined)
throw new Error("Expected valid repeated host lists");
const { served } = await start({
+33 -21
View File
@@ -1,7 +1,7 @@
import { it, expect } from "vitest";
import {
classifyCliEntrypoint,
parseCliGlobalArguments,
productionMcpDoctorArguments,
} from "../../../src/cliBuiltinArguments.js";
// Observed with Incur 0.6.1 before removing the dependency.
@@ -81,8 +81,12 @@ it.each([
"--timings=",
])("preserves output values and root alias with %s", (flag) => {
expect(
productionMcpDoctorArguments(["mcp", "doctor", "--format", flag]),
).toEqual({ arguments: ["--format", flag], timings: false });
classifyCliEntrypoint(["mcp", "doctor", "--format", flag], {}),
).toEqual({
kind: "mcp-doctor",
arguments: ["--format", flag],
timings: false,
});
expect(
parseCliGlobalArguments([flag, "--update", "--json"]).arguments,
).toEqual(["update", flag, "--json"]);
@@ -99,25 +103,33 @@ it("retains the separator and its following timing-shaped data", () => {
parseCliGlobalArguments(["--", "--update", "--timings=false"]).arguments,
).toEqual(["--", "--update", "--timings=false"]);
expect(
productionMcpDoctorArguments([
"mcp",
"doctor",
"--format",
"--",
"--timings=true",
]),
).toEqual({ arguments: ["--format", "--"], timings: true });
classifyCliEntrypoint(
["mcp", "doctor", "--format", "--", "--timings=true"],
{},
),
).toEqual({
kind: "mcp-doctor",
arguments: ["--format", "--"],
timings: true,
});
});
it("takes the doctor words and timing global out of the doctor's arguments", () => {
expect(
productionMcpDoctorArguments([
"--timings",
"mcp",
"--format=json",
"doctor",
"--no-timings",
"--verbose",
]),
).toEqual({ arguments: ["--format", "json", "--verbose"], timings: false });
expect(productionMcpDoctorArguments(["mcp", "add"])).toBeUndefined();
classifyCliEntrypoint(
[
"--timings",
"mcp",
"--format=json",
"doctor",
"--no-timings",
"--verbose",
],
{},
),
).toEqual({
kind: "mcp-doctor",
arguments: ["--format", "json", "--verbose"],
timings: false,
});
expect(classifyCliEntrypoint(["mcp", "add"], {})).toEqual({ kind: "cli" });
});
+5 -3
View File
@@ -1,6 +1,5 @@
import { access, cp, symlink } from "node:fs/promises";
import { join, resolve } from "node:path";
import { pathToFileURL } from "node:url";
import { describe, expect } from "vitest";
@@ -292,7 +291,7 @@ describe("executable dispatcher", () => {
await Promise.all([
workspace.write(
"dist/mcp/main.js",
'export const runEntrypoint = () => process.stdout.write(JSON.stringify({ adapter: "mcp" })); export const runMcpHttpEntrypoint = (args) => process.stdout.write(JSON.stringify({ adapter: "mcp-http", args }));\n',
'export const runEntrypoint = () => process.stdout.write(JSON.stringify({ adapter: "mcp" })); export const runMcpHttpEntrypoint = () => process.stdout.write(JSON.stringify({ adapter: "mcp-http" }));\n',
),
workspace.write(
"dist/cli-runtime/mcpDoctor.js",
@@ -343,7 +342,6 @@ describe("executable dispatcher", () => {
])
await expect(invoke(args)).resolves.toEqual({
adapter: "mcp-http",
args: args.slice(1),
});
await expect(invoke(["mcp", "doctor", "--http"])).resolves.toEqual({
adapter: "mcp-doctor",
@@ -354,6 +352,10 @@ describe("executable dispatcher", () => {
adapter: "cli",
args: ["mcp", "add", "--http"],
});
await expect(invoke(["mcp", "--", "--http"])).resolves.toEqual({
adapter: "cli",
args: ["mcp", "--", "--http"],
});
},
);
+50 -7
View File
@@ -7,12 +7,22 @@ import {
mcpAllowedHostsTextSchema,
} from "../../../src/config/mcpHttpEndpoint.js";
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
import { classifyCliEntrypoint } from "../../../src/cliBuiltinArguments.js";
import { runMcpHttpEntrypoint } from "../../../src/main.js";
import {
parseMcpHttpArguments,
renderMcpHttpHelp,
validateMcpHttpCommand,
} from "../../../src/main/mcpHttpArguments.js";
const httpCommand = (args: readonly string[]) => {
const entry = classifyCliEntrypoint(["mcp", ...args], {});
if (entry.kind !== "mcp-http") throw new Error("Expected an MCP HTTP entry");
return entry.command;
};
const parseMcpHttpArguments = (args: readonly string[]) =>
validateMcpHttpCommand(httpCommand(args));
describe("rea mcp --http arguments", () => {
it("accepts --http with optional host and port in either flag spelling", () => {
expect(parseMcpHttpArguments(["--http"])).toEqual({ ok: true });
@@ -39,10 +49,6 @@ describe("rea mcp --http arguments", () => {
ok: false,
message: "Unknown mcp --http argument: add",
});
expect(parseMcpHttpArguments(["--port", "1"])).toMatchObject({
ok: false,
message: "--host and --port require --http",
});
for (const port of ["70000", "08", "-1", "http"])
expect(parseMcpHttpArguments(["--http", `--port=${port}`])).toMatchObject(
{ ok: false, message: expect.stringContaining("Invalid --port") },
@@ -127,18 +133,55 @@ describe("rea mcp --http arguments", () => {
};
};
const help = io();
await runMcpHttpEntrypoint(["--http", "--help"], help);
await runMcpHttpEntrypoint(httpCommand(["--http", "--help"]), help);
expect(help.stdout).toEqual([`${renderMcpHttpHelp()}\n`]);
expect(help.stderr).toEqual([]);
expect(help.exitCodes).toEqual([0]);
const rejected = io();
await runMcpHttpEntrypoint(["--http", "add"], rejected);
await runMcpHttpEntrypoint(httpCommand(["--http", "add"]), rejected);
expect(rejected.stdout).toEqual([]);
expect(rejected.stderr).toEqual(["Unknown mcp --http argument: add\n"]);
expect(rejected.exitCodes).toEqual([1]);
});
});
processTest(
"keeps a flag-shaped output format with the doctor command without starting HTTP",
async ({ processes }) => {
const result = await processes.run(process.execPath, [
fileURLToPath(new URL("../../../scripts/rea.mjs", import.meta.url)),
"mcp",
"--format",
"--http",
"doctor",
"--json",
]);
expect(result.exitCode).toBe(1);
expect(result.stderr).toBe("");
expect(JSON.parse(result.stdout)).toMatchObject({
code: "VALIDATION_ERROR",
message: "Invalid output format: --http",
});
},
);
processTest(
"reports an HTTP option without its mode through the compiled CLI",
async ({ processes }) => {
const result = await processes.run(process.execPath, [
fileURLToPath(new URL("../../../scripts/rea.mjs", import.meta.url)),
"mcp",
"--port",
"8765",
]);
expect(result).toMatchObject({
exitCode: 1,
stdout: "",
stderr: "--host and --port require --http\n",
});
},
);
processTest(
"rejects an invalid earlier host list before the compiled CLI opens a listener",
async ({ processes }) => {
+2 -23
View File
@@ -1,8 +1,7 @@
import { resolve } from "node:path";
import { tmpdir } from "node:os";
import {
cliCompletionShell,
productionMcpDoctorArguments,
classifyCliEntrypoint,
parseCliGlobalArguments,
} from "../../../src/cliBuiltinArguments.js";
import { DEFAULT_INFO_LOGGING_COMMANDS } from "../../../src/contracts/cliCommandNames.js";
@@ -150,26 +149,6 @@ export const cliCompileCacheEnvironment = (
...environment,
});
/**
* Mirror `scripts/rea.mjs` entry routing for invocations handled outside
* `runOneShotCli` (`rea mcp` / `rea --mcp`, `rea mcp ... --http`, and
* production `rea mcp doctor ...`). Subcommands such as `rea mcp add` and
* `rea mcp --help` still dispatch through `runOneShotCli`.
*/
const isDirectMcpLauncherEntry = (
arguments_: readonly string[],
environment: NodeJS.ProcessEnv | undefined,
): boolean => {
if (cliCompletionShell(environment ?? {}) !== undefined) return false;
if (productionMcpDoctorArguments([...arguments_]) !== undefined) return true;
if (arguments_[0] !== "mcp" && arguments_[0] !== "--mcp") return false;
return (
arguments_.length === 1 ||
((arguments_[1]?.startsWith("-") ?? false) &&
arguments_.slice(1).includes("--http"))
);
};
/**
* Whether the file's shared process reports this command exactly as a fresh
* `rea` process would. Stdin and deadlines belong to a process; the launcher
@@ -190,7 +169,7 @@ const sharedProcessCanServe = ({
terminal !== true &&
input === undefined &&
timeoutMs === undefined &&
!isDirectMcpLauncherEntry(arguments_, environment) &&
classifyCliEntrypoint(arguments_, environment ?? {}).kind === "cli" &&
(environment?.NODE_OPTIONS === undefined ||
environment.NODE_OPTIONS ===
environment[REGISTRATION_GUARD_NODE_OPTIONS_ENV]) &&