Skip to content

OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security

fix(cli)!: make MCP targets and launchers explicit (#2591)

Michael D'Angelo721cfce6308d
diff --git a/sdk/typescript/docs/cli.md b/sdk/typescript/docs/cli.md
index 4d8779927..d63838715 100644
--- a/sdk/typescript/docs/cli.md
+++ b/sdk/typescript/docs/cli.md
@@ -156,7 +156,7 @@ If Codex Security reports that the refresh token was already used, run
`codex-security logout`, then `codex-security login`. If your Codex CLI or app
reports that error, sign out and sign back in there.
-Use `codex-security login status --json` in automation. Its stdout reports `authenticated`, the effective authentication `method`, and the environment variable name when an API key takes precedence. Native diagnostics go to stderr. The command keeps the exit status of the human-readable status check.
+Use `codex-security login status --json` in automation. Its stdout reports `authenticated`, the effective authentication `method`, and the environment variable name when an API key takes precedence. When an API key takes precedence, stderr names the variable that configures it. This offline status check also labels the separate stored sign-in diagnostic. The command keeps the exit status of the human-readable status check.
For other refresh errors, check `codex-security login status`. Retry if the
sign-in recently changed. Otherwise run `codex-security logout`, then
@@ -2770,23 +2770,39 @@ only read-only `info` because the transport cannot cancel scans. For the plugin'
scan, triage, patch, and verification workflows, see the
[agent workflow guide](https://github.com/openai/codex-security/blob/main/docs/agent-workflows.md).
-Use `skills add --no-global` to write generated guidance to the current project.
-`--depth 0` creates a single skill; the default depth of 1 groups guidance by
-top-level command. `skills list` checks installation status at depth 1 by
-default. To inspect a different grouping, pass the installation depth, for
-example `skills list --depth 0 --json`. Installation status uses the paths
-recorded by the most recent `skills add` for this user, including project installs.
-For both installers, `--help`, `--schema`, and `--version` can be inspected
-before writing any configuration.
-
-`mcp add` registers in the user profile by default. `mcp add --no-global`
-selects project-capable clients. Registration uses the client adapters installed
-with the SDK. Selecting a user-only client in project scope fails before the
-CLI writes configuration. For example, use
-`mcp add --no-global --agent cursor` to target Cursor. The built-in Amp
-registration supports only user settings. `mcp doctor` checks the current CLI's
-server startup and tool catalog. To verify a registered launcher, connect from
-the client where it was registered.
+Both installers default to `--scope user`. Use `--scope project` for the current
+directory. Existing scripts can continue using `--no-global` for project scope.
+Inspect either command with `--help`, `--schema`, or `--version` before installing.
+
+`skills add --depth 0` creates a single skill. The default depth of 1 groups
+guidance by top-level command. To check the installed files, use the same
+depth with `skills list`, for example `skills list --depth 0 --json`. Each
+entry includes its canonical `SKILL.md` locations in the current project and
+user profile.
+
+`mcp add` registers detected compatible clients. If it finds none in the
+selected scope, choose a client with `--agent NAME` (repeatable), or register
+every compatible client with `--all`. For example, `mcp add --scope project
+--agent cursor` writes Cursor's project configuration. In user scope, Codex
+detection and registration use `CODEX_HOME` when set. Amp supports user
+registration only.
+
+The default launcher runs `npx --yes @openai/codex-security --mcp`. To register
+an installed executable, use its name or path with `--exec` and repeat
+`--arg=VALUE` for each argument. Each value is stored literally, including
+spaces, empty arguments, and leading dashes. To run an npm package, select
+`--package NAME`. The existing `--command` accepts a command line or HTTP(S)
+URL. Quotes group command-line words, and backslashes are literal. A bare
+executable name is stored directly. Use `--exec` for a path with
+spaces, including when the executable will be installed on another machine.
+
+```bash
+codex-security mcp add --agent cursor --exec "/opt/My Tools/server" --arg=--mcp
+codex-security mcp add --agent cursor --package @openai/codex-security --arg=--mcp
+```
+
+`mcp doctor` checks the current CLI's server startup and tool catalog. To
+verify a registered launcher, connect from the client where it was registered.
For local findings storage, deduplication, and custom endpoints, see the
[findings guide](findings-service.md).
diff --git a/sdk/typescript/scripts/package-dist-files.mjs b/sdk/typescript/scripts/package-dist-files.mjs
index 8b1a02e3e..6dc154a36 100644
--- a/sdk/typescript/scripts/package-dist-files.mjs
+++ b/sdk/typescript/scripts/package-dist-files.mjs
@@ -78,6 +78,7 @@ const distModules = [
"config",
"config-path",
"contract",
+ "command-words",
"cost",
"cost-model",
"bedrock-pricing",
diff --git a/sdk/typescript/src/cli-integrations.ts b/sdk/typescript/src/cli-integrations.ts
index 0e8f7aa48..e0a627790 100644
--- a/sdk/typescript/src/cli-integrations.ts
+++ b/sdk/typescript/src/cli-integrations.ts
@@ -1,4 +1,7 @@
import { Cli, Completions, Help, SyncSkills, z } from "incur";
+import { statSync } from "node:fs";
+import { homedir } from "node:os";
+import { join } from "node:path";
import { parseArgs } from "node:util";
import { registerMcp } from "./cli-mcp.js";
@@ -10,10 +13,23 @@ const depth = z
.nonnegative()
.optional()
.describe("Grouping depth for generated skill files (default: 1).");
+const scope = z
+ .enum(["project", "user"])
+ .optional()
+ .describe("Installation scope (default: user).");
const noGlobal = z
.boolean()
.optional()
- .describe("Install to the current project instead of the user profile.");
+ .describe("Compatibility spelling for --scope project.");
+function projectScope(options: {
+ scope?: "project" | "user" | undefined;
+ noGlobal?: boolean | undefined;
+}) {
+ if (options.noGlobal && options.scope === "user")
+ throw new Error("--scope user conflicts with --no-global.");
+ return options.noGlobal === true || options.scope === "project";
+}
+
const descriptions = {
skills:
"Manage generated CLI command guidance. The Codex Security plugin provides scan and remediation workflows.",
@@ -44,6 +60,11 @@ const outputOptions = {
const options = {
...outputOptions,
depth: string,
+ scope: string,
+ all: boolean,
+ exec: string,
+ package: string,
+ arg: { ...string, multiple: true },
"no-global": boolean,
command: { ...string, short: "c" },
agent: { ...string, multiple: true },
@@ -81,18 +102,20 @@ function integrationGroups(
.command("add", {
description:
"Install generated CLI command guidance in the user profile or current project.",
- options: z.object({ depth, noGlobal }),
- async run({ options: { depth, noGlobal } }) {
+ options: z.object({ depth, scope, noGlobal }),
+ async run({ options }) {
+ const { depth } = options;
+ const local = projectScope(options);
if (plain)
return builtin([
"skills",
"add",
- ...(noGlobal ? ["--no-global"] : []),
+ ...(local ? ["--no-global"] : []),
...(depth === undefined ? [] : ["--depth", String(depth)]),
]);
const result = await SyncSkills.sync(cliName, commands, {
depth,
- global: !noGlobal,
+ global: !local,
description: cliOptions.description,
});
return {
@@ -107,14 +130,38 @@ function integrationGroups(
"List generated CLI guidance for one grouping depth. Use the same depth as skills add to check an installation.",
options: z.object({ depth }),
async run({ options: { depth } }) {
- if (plain) {
- cliOptions.sync = { ...(cliOptions.sync || {}), depth };
- return `Skill grouping depth: ${depth ?? 1}\n${await builtin(["skills", "list"])}`;
- }
- return SyncSkills.list(cliName, commands, {
+ const entries = await SyncSkills.list(cliName, commands, {
depth,
description: cliOptions.description,
});
+ const roots = { project: process.cwd(), user: homedir() };
+ const skills = entries.map((skill) => {
+ const locations = Object.entries(roots).flatMap(([scope, root]) => {
+ const path = join(
+ root,
+ ".agents",
+ "skills",
+ skill.name,
+ "SKILL.md",
+ );
+ return statSync(path, { throwIfNoEntry: false })?.isFile()
+ ? [{ scope, path }]
+ : [];
+ });
+ return { ...skill, installed: locations.length > 0, locations };
+ });
+ if (!plain) return skills;
+ return [
+ `Skill grouping depth: ${depth ?? 1}`,
+ ...skills.map(({ name, installed, description, locations }) =>
+ [
+ ` ${installed ? "✓" : "✗"} ${name} ${description ?? ""}`,
+ ...locations.map(({ scope, path }) => ` ${scope}: ${path}`),
+ ].join("\n"),
+ ),
+ "",
+ `${skills.length} skill${skills.length === 1 ? "" : "s"} (${skills.filter((skill) => skill.installed).length} installed)`,
+ ].join("\n");
},
});
const mcp = Cli.create(prefix + "mcp", {
@@ -128,32 +175,49 @@ function integrationGroups(
})
.command("add", {
description:
- "Register this CLI’s read-only info tool with an agent. Registers in the user profile by default; Amp supports only user registration.",
+ "Register the read-only info tool with detected clients. Use --agent NAME or --all when no clients are detected. Amp supports user scope only.",
options: z.object({
agent: z
.array(z.string().min(1))
.optional()
.describe("Target a specific agent. Repeat to select more agents."),
+ all: z
+ .boolean()
+ .optional()
+ .describe("Register all compatible clients in the selected scope."),
+ exec: z
+ .string()
+ .min(1)
+ .optional()
+ .describe("Literal executable name or path."),
+ package: z
+ .string()
+ .min(1)
+ .optional()
+ .describe("Run this npm package with npx."),
+ arg: z
+ .array(z.string())
+ .optional()
+ .describe(
+ "Literal argument to --exec or --package. Repeat in order. Use --arg=VALUE for flags.",
+ ),
command: z
.string()
.min(1)
.optional()
- .describe("Override the command agents will run."),
+ .describe(
+ "Launcher command line or HTTP(S) URL. For literal arguments use --exec and --arg.",
+ ),
+ scope,
noGlobal,
}),
alias: { command: "c" },
async run({ options }) {
- const agents = [...new Set(options.agent)];
- if (options.noGlobal && agents.includes("amp"))
- throw new Error(
- "The MCP installer can register Amp only in the user profile. For a project installation, select a project-capable client with --no-global --agent NAME.",
- );
- const launch = options.command ?? cliOptions.mcp!.command!;
const result = await registerMcp(
cliName,
- launch,
- agents,
- options.noGlobal === true,
+ options,
+ cliOptions.mcp!.command!,
+ projectScope(options),
);
if (plain)
return [
diff --git a/sdk/typescript/src/cli-mcp.ts b/sdk/typescript/src/cli-mcp.ts
index 76f69aa02..9da28ca32 100644
--- a/sdk/typescript/src/cli-mcp.ts
+++ b/sdk/typescript/src/cli-mcp.ts
@@ -1,7 +1,17 @@
import type { AgentType, McpServerConfig } from "add-mcp";
-import { SyncMcp } from "incur";
-import { lstat, realpath, stat } from "node:fs/promises";
+import { existsSync } from "node:fs";
+import {
+ lstat,
+ mkdir,
+ readFile,
+ realpath,
+ stat,
+ writeFile,
+} from "node:fs/promises";
+import { homedir } from "node:os";
import { dirname, join } from "node:path";
+import { splitCommand } from "./command-words.js";
+import { isRecord } from "./record.js";
import { isWithin } from "./trusted-executable.js";
// These CLI aliases are accepted by add-mcp in addition to its exported agent IDs.
@@ -23,18 +33,66 @@ const agentAliases: Readonly<Record<string, AgentType>> = {
"pi-agent": "pi",
};
-function mcpServerConfig(launch: string): McpServerConfig {
- const value = launch.trim();
+type Launcher = {
+ command?: string | undefined;
+ exec?: string | undefined;
+ package?: string | undefined;
+ arg?: string[] | undefined;
+};
+
+function mcpServerConfig(
+ options: Launcher,
+ defaultCommand: string,
+): McpServerConfig {
+ const { command, exec, package: pkg, arg = [] } = options;
+ if ([command, exec, pkg].filter((value) => value !== undefined).length > 1)
+ throw new Error("Choose one of --exec, --package or --command.");
+ if (exec !== undefined) return { command: exec, args: arg };
+ if (pkg !== undefined)
+ return { command: "npx", args: ["--yes", "--", pkg, ...arg] };
+ if (arg.length) throw new Error("Use --arg with --exec or --package.");
+ const value = (command ?? defaultCommand).trim();
if (!value) throw new Error("--command requires a launcher.");
if (/^https?:\/\//u.test(value)) return { url: value, type: "http" };
- // Preserve add-mcp's handling of literal executable paths, command lines,
- // and bare npm package specifiers.
- if (/^(?:\/|~(?:\/|$)|\.{1,2}\/|[A-Za-z]:[\\/]|\\\\)/u.test(value))
+ // Preserve an existing literal path with spaces. Otherwise a path starts
+ // a command line and can be followed by positional arguments or flags.
+ const isPath = /^(?:\/|~(?:\/|$)|\.{1,2}\/|[A-Za-z]:[\\/]|\\\\)/u.test(value);
+ const argsAt = isPath ? value.search(/\s/u) : 0;
+ if (argsAt === -1 || (isPath && existsSync(value)))
return { command: value, args: [] };
- const [command, ...args] = value.split(" ");
- return args.length
- ? { command: command!, args }
- : { command: "npx", args: ["-y", value] };
+ const words = value.slice(argsAt).trim();
+ // Quotes group launcher words. Keep backslashes literal, including in
+ // unquoted Windows paths that occur alongside a quoted argument.
+ const tokens = splitCommand(words, "literal");
+ if (!tokens?.length)
+ throw new Error(
+ "Invalid --command quoting. Use --exec and --arg for literal values.",
+ );
+ return isPath
+ ? { command: value.slice(0, argsAt), args: tokens }
+ : { command: tokens[0]!, args: tokens.slice(1) };
+}
+
+async function ampSettings(
+ path: string,
+ cliName: string,
+ config: McpServerConfig,
+) {
+ const text = await readFile(path, "utf8").catch(
+ (error: NodeJS.ErrnoException) => {
+ if (error.code !== "ENOENT") throw error;
+ return "{}";
+ },
+ );
+ const settings: unknown = JSON.parse(text);
+ if (!isRecord(settings) || !isRecord(settings["amp.mcpServers"] ?? {}))
+ throw new Error(`Invalid Amp settings in ${path}.`);
+ const servers = (settings["amp.mcpServers"] ?? {}) as Record<string, unknown>;
+ settings["amp.mcpServers"] = {
+ ...servers,
+ [cliName]: config.url ? { url: config.url } : config,
+ };
+ return JSON.stringify(settings, null, 2) + "\n";
}
async function checkProjectConfig(root: string, file: string) {
@@ -61,10 +119,17 @@ async function checkProjectConfig(root: string, file: string) {
export async function registerMcp(
cliName: string,
- command: string,
- requested: string[],
+ options: Launcher & {
+ agent?: string[] | undefined;
+ all?: boolean | undefined;
+ },
+ defaultCommand: string,
local: boolean,
-): Promise<SyncMcp.register.Result> {
+) {
+ const requested = options.agent ?? [];
+ const config = mcpServerConfig(options, defaultCommand);
+ if (options.all && requested.length)
+ throw new Error("Choose --all or --agent NAME.");
// Import from the SDK installation. Never resolve or launch a package manager
// or installer from the project being configured.
const {
@@ -77,10 +142,16 @@ export async function registerMcp(
const cwd = await realpath(process.cwd());
const all = getAgentTypes();
const targets = new Set<AgentType>();
+ const ampDir = join(homedir(), ".config", "amp");
+ let amp = false;
if (requested.length) {
for (const target of requested) {
- if (target === "amp") continue;
const key = target.toLowerCase();
+ if (key === "amp") {
+ if (local) throw new Error("Amp supports only --scope user.");
+ amp = true;
+ continue;
+ }
const type =
all.find((type) => type === key) ??
(Object.hasOwn(agentAliases, key) ? agentAliases[key] : undefined);
@@ -91,15 +162,31 @@ export async function registerMcp(
targets.add(type);
}
} else {
- const detected = local
- ? detectProjectAgents(cwd)
- : await detectGlobalAgents();
- for (const type of detected.length
- ? detected
- : all.filter((type) => !local || agents[type].localConfigPath))
- targets.add(type);
+ const candidates = new Set(
+ options.all
+ ? all
+ : local
+ ? detectProjectAgents(cwd)
+ : await detectGlobalAgents(),
+ );
+ // add-mcp detects ~/.codex even when its writer uses a custom CODEX_HOME.
+ if (!local && !options.all && process.env["CODEX_HOME"]) {
+ if (existsSync(dirname(agents.codex.configPath))) candidates.add("codex");
+ else candidates.delete("codex");
+ }
+ for (const type of candidates) {
+ if (
+ (!local || agents[type].localConfigPath) &&
+ agents[type].supportedTransports.includes(config.type ?? "stdio")
+ )
+ targets.add(type);
+ }
+ amp = !local && (options.all === true || existsSync(ampDir));
+ if (!targets.size && !amp)
+ throw new Error(
+ `No compatible MCP clients detected in ${local ? "project" : "user"} scope. Select --agent NAME or use --all to register every compatible client in this scope.`,
+ );
}
- const config = mcpServerConfig(command);
for (const type of targets) {
const agent = agents[type];
if (!agent.supportedTransports.includes(config.type ?? "stdio"))
@@ -117,6 +204,10 @@ export async function registerMcp(
await checkProjectConfig(cwd, path);
}
}
+ const ampPath = join(ampDir, "settings.json");
+ const settings = amp
+ ? await ampSettings(ampPath, cliName, config)
+ : undefined;
const installed = [];
for (const type of targets) {
const result = upsertServer(type, cliName, config, { local, cwd });
@@ -124,14 +215,18 @@ export async function registerMcp(
throw new Error(`${agents[type].displayName}: ${result.error}`);
installed.push(agents[type].displayName);
}
- if (!local && (!requested.length || requested.includes("amp"))) {
- // With Amp as the sole target Incur writes its settings directly.
- const amp = await SyncMcp.register(cliName, { agents: ["amp"], command });
- if (requested.includes("amp") && !amp.agents.length)
- throw new Error(
- "The Amp settings file could not be updated. Check its JSON and retry.",
- );
- installed.push(...amp.agents);
+ if (settings !== undefined) {
+ await mkdir(ampDir, { recursive: true });
+ await writeFile(ampPath, settings, { mode: 0o600 });
+ installed.push("Amp");
}
+ const command =
+ options.command ??
+ (config.url ||
+ [config.command!, ...(config.args ?? [])]
+ .map((word) =>
+ word && !/\s|["']/u.test(word) ? word : JSON.stringify(word),
+ )
+ .join(" "));
return { command, agents: installed };
}
diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.ts
index 7dec91a46..17919e6dd 100644
--- a/sdk/typescript/src/cli.ts
+++ b/sdk/typescript/src/cli.ts
@@ -7749,6 +7749,12 @@ export async function main(
async run({ format }) {
const structured = !useDefaultOutput(format);
const authentication = scanAuthentication(dependencies.environment);
+ if (authentication.method === "api_key") {
+ errorOutput.write(
+ `API key configured via ${authentication.source} (offline check).\n`,
+ );
+ errorOutput.write("Stored sign-in status:\n");
+ }
exitCode = await withLoginEnvironment(async (environment) => {
if (authentication.method !== "api_key")
await initialCredentialsAvailable(
@@ -7781,9 +7787,6 @@ export async function main(
(exitCode === 0 || exitCode === 1)
) {
exitCode = 0;
- errorOutput.write(
- `Effective scan authentication: API key from ${authentication.source}.\n`,
- );
errorOutput.write(
`To use a ChatGPT sign-in, ${formatEnvironmentVariableRemovalGuidance(["OPENAI_API_KEY", "CODEX_API_KEY"])}.\n`,
);
diff --git a/sdk/typescript/src/command-words.ts b/sdk/typescript/src/command-words.ts
new file mode 100644
index 000000000..481921d64
--- /dev/null
+++ b/sdk/typescript/src/command-words.ts
@@ -0,0 +1,37 @@
+/** Split quoted command words without evaluating shell expansions. */
+export function splitCommand(
+ command: string,
+ backslashes: "escape" | "literal" = "escape",
+): string[] | null {
+ const words: string[] = [];
+ let word = "";
+ let started = false;
+ let quote: "'" | '"' | null = null;
+ for (let index = 0; index < command.length; index++) {
+ const character = command[index]!;
+ if (character === "\\" && quote !== "'" && backslashes === "escape") {
+ const next = command[++index];
+ if (next === undefined) return null;
+ if (quote === '"' && !["$", "`", '"', "\\", "\n"].includes(next))
+ word += "\\";
+ if (next !== "\n") word += next;
+ started = true;
+ } else if (quote !== null) {
+ if (character === quote) quote = null;
+ else word += character;
+ } else if (character === "'" || character === '"') {
+ quote = character;
+ started = true;
+ } else if (" \t\r\n".includes(character)) {
+ if (started) words.push(word);
+ word = "";
+ started = false;
+ } else {
+ word += character;
+ started = true;
+ }
+ }
+ if (quote !== null) return null;
+ if (started) words.push(word);
+ return words;
+}
diff --git a/sdk/typescript/src/cost.ts b/sdk/typescript/src/cost.ts
index dfa362db5..e83431f30 100644
--- a/sdk/typescript/src/cost.ts
+++ b/sdk/typescript/src/cost.ts
@@ -1,3 +1,4 @@
+import { splitCommand } from "./command-words.js";
import { isSafeNonNegativeInteger, parseJson } from "./value.js";
import type { JsonObject } from "./config.js";
import { workbenchArgs } from "./workbench-arguments.js";
@@ -4077,41 +4078,6 @@ function takeFirstIndex(heap: number[]): number {
return first;
}
-/** Decode the quoted argv rendering emitted by native command completions. */
-function splitCommand(command: string): string[] | null {
- const words: string[] = [];
- let word = "";
- let started = false;
- let quote: "'" | '"' | null = null;
- for (let index = 0; index < command.length; index++) {
- const character = command[index]!;
- if (character === "\\" && quote !== "'") {
- const next = command[++index];
- if (next === undefined) return null;
- if (quote === '"' && !["$", "`", '"', "\\", "\n"].includes(next))
- word += "\\";
- if (next !== "\n") word += next;
- started = true;
- } else if (quote !== null) {
- if (character === quote) quote = null;
- else word += character;
- } else if (character === "'" || character === '"') {
- quote = character;
- started = true;
- } else if (" \t\r\n".includes(character)) {
- if (started) words.push(word);
- word = "";
- started = false;
- } else {
- word += character;
- started = true;
- }
- }
- if (quote !== null) return null;
- if (started) words.push(word);
- return words;
-}
-
function sessionProgressUpdates(
payload: Readonly<Record<string, unknown>>,
): ScanProgress[] {
diff --git a/sdk/typescript/tests-ts/cli-authentication.test.ts b/sdk/typescript/tests-ts/cli-authentication.test.ts
index 7f112e51d..079e68a87 100644
--- a/sdk/typescript/tests-ts/cli-authentication.test.ts
+++ b/sdk/typescript/tests-ts/cli-authentication.test.ts
@@ -101,7 +101,7 @@ async function createCredentialHome() {
describe("CLI authentication", () => {
test("login status JSON uses an isolated home and returns the effective authentication source", async () => {
- const { stdout, runCli } = createCliTest(main, { stderr: true });
+ const { stdout, stderr, runCli } = createCliTest(main, { stderr: true });
const environment = {
HOME: stateDirectory,
USERPROFILE: stateDirectory,
@@ -113,6 +113,9 @@ describe("CLI authentication", () => {
dependencies({ environment }),
),
).toBe(0);
+ expect(stderr.text()).toStartWith(
+ "API key configured via CODEX_API_KEY (offline check).\nStored sign-in status:\n",
+ );
expect(JSON.parse(stdout.text())).toEqual({
authenticated: true,
method: "api_key",
@@ -449,7 +452,7 @@ describe("CLI authentication", () => {
await runCli(["login", "status"], dependencies({ environment })),
).toBe(0);
expect(stderr.text()).toContain(
- `Effective scan authentication: API key from ${expectedSource}.`,
+ `API key configured via ${expectedSource} (offline check).`,
);
expect(stderr.text()).toContain(
"To use a ChatGPT sign-in, remove OPENAI_API_KEY and CODEX_API_KEY from the environment.",
@@ -1121,7 +1124,7 @@ describe("CLI authentication", () => {
dependencies({ environment, onCodex: () => 1 }),
),
).toBe(0);
- expect(stderr.text()).toContain("API key from OPENAI_API_KEY");
+ expect(stderr.text()).toContain("API key configured via OPENAI_API_KEY");
expect(stderr.text()).not.toContain("synthetic");
delete environment["OPENAI_API_KEY"];
@@ -1132,7 +1135,7 @@ describe("CLI authentication", () => {
dependencies({ environment, onCodex: () => 1 }),
),
).toBe(0);
- expect(rotated.text()).toContain("API key from CODEX_API_KEY");
+ expect(rotated.text()).toContain("API key configured via CODEX_API_KEY");
expect(
await runCapturedCli(
diff --git a/sdk/typescript/tests-ts/cli-integrations.test.ts b/sdk/typescript/tests-ts/cli-integrations.test.ts
index f57ea9034..ce5e867ff 100644
--- a/sdk/typescript/tests-ts/cli-integrations.test.ts
+++ b/sdk/typescript/tests-ts/cli-integrations.test.ts
@@ -20,6 +20,8 @@ async function isolatedCli(root: string, environment: NodeJS.ProcessEnv = {}) {
...process.env,
HOME: home,
USERPROFILE: home,
+ APPDATA: join(home, "AppData", "Roaming"),
+ LOCALAPPDATA: join(home, "AppData", "Local"),
XDG_CACHE_HOME: join(root, "cache"),
XDG_CONFIG_HOME: join(root, "config"),
XDG_DATA_HOME: join(root, "data"),
@@ -27,15 +29,17 @@ async function isolatedCli(root: string, environment: NodeJS.ProcessEnv = {}) {
CI: "1",
...environment,
};
+ const runFrom = (cwd: string, ...args: string[]) =>
+ runCommand(
+ process.execPath,
+ [join(import.meta.dir, "../src/cli.ts"), ...args],
+ { env, cwd, timeout: 30_000 },
+ );
return {
home,
project,
- run: (...args: string[]) =>
- runCommand(
- process.execPath,
- [join(import.meta.dir, "../src/cli.ts"), ...args],
- { env, cwd: project, timeout: 30_000 },
- ),
+ runFrom,
+ run: (...args: string[]) => runFrom(project, ...args),
};
}
@@ -61,6 +65,19 @@ describe("integration command dispatch", () => {
},
{ args: ["mcp", "add", "--command", "--no-global"], mode: "error" },
{ args: ["skills", "add", "surplus"], mode: "error" },
+ { args: ["skills", "add", "--scope=user", "--no-global"], mode: "error" },
+ { args: ["mcp", "add", "--agent=cursor", "--all"], mode: "error" },
+ {
+ args: [
+ "mcp",
+ "add",
+ "--agent=cursor",
+ "--exec=server",
+ "--package=server",
+ ],
+ mode: "error",
+ },
+ { args: ["mcp", "add", "--agent=cursor", "--arg=--mcp"], mode: "error" },
{
args: ["mcp", "add", "--agent=amp", "--filter-output", "--llms"],
mode: "error",
@@ -296,6 +313,109 @@ describe("integration command dispatch", () => {
});
}, 30_000);
+ test("empty scopes require explicit targets and --all registers compatible project clients", async () => {
+ await using temp = await scopedTemporaryDirectory("cli-mcp-targets-");
+ const { project, home, run } = await isolatedCli(temp.path, {
+ PATH: join(temp.path, "no-executables"),
+ });
+ for (const scope of ["project", "user"]) {
+ const result = await run("mcp", "add", "--scope", scope);
+ expect(result.status).toBe(2);
+ expect(result.stderr).toContain("--agent");
+ expect(result.stderr).toContain("--all");
+ expect(await readdir(project)).toEqual([]);
+ expect(await readdir(home)).toEqual([]);
+ }
+ const result = await run(
+ "mcp",
+ "add",
+ "--scope=project",
+ "--all",
+ "--json",
+ );
+ expect(result.status, result.stderr).toBe(0);
+ expect(JSON.parse(result.stdout).agents).toContain("Cursor");
+ expect(JSON.parse(result.stdout).agents.length).toBeGreaterThan(1);
+ expect(await readdir(home)).toEqual([]);
+ }, 30_000);
+
+ test("user detection follows the configured Codex profile", async () => {
+ await using temp = await scopedTemporaryDirectory("cli-mcp-codex-home-");
+ const profile = join(temp.path, "custom-profile");
+ const { home, run } = await isolatedCli(temp.path, { CODEX_HOME: profile });
+ await mkdir(profile);
+ const result = await run("mcp", "add", "--json");
+ expect(result.status, result.stderr).toBe(0);
+ expect(JSON.parse(result.stdout).agents).toEqual(["Codex"]);
+ expect(await readFile(join(profile, "config.toml"), "utf8")).toContain(
+ "mcp_servers.codex-security",
+ );
+ expect(await readdir(home)).toEqual([]);
+ }, 30_000);
+
+ test("MCP launchers preserve literal arguments and use npm only when selected", async () => {
+ await using temp = await scopedTemporaryDirectory("cli-mcp-launcher-");
+ const { home, run } = await isolatedCli(temp.path);
+ const executable = String.raw`C:\Program Files\tool's "server".exe`;
+ const existingExecutable = join(temp.path, "server with spaces");
+ await writeFile(existingExecutable, "", { mode: 0o700 });
+ const args = ["--mcp", "", "two words", "--json", "one=two"];
+ for (const [launcher, expected] of [
+ [
+ ["--exec", executable, ...args.map((value) => `--arg=${value}`)],
+ { command: executable, args },
+ ],
+ [
+ ["--package=@acme/server", "--arg=--mcp"],
+ { command: "npx", args: ["--yes", "--", "@acme/server", "--mcp"] },
+ ],
+ [
+ [
+ String.raw`--command=node C:\tools\server.js --label="two words" --mcp`,
+ ],
+ {
+ command: "node",
+ args: [String.raw`C:\tools\server.js`, "--label=two words", "--mcp"],
+ },
+ ],
+ [["--command=local-server"], { command: "local-server", args: [] }],
+ [
+ [`--command=${existingExecutable}`],
+ { command: existingExecutable, args: [] },
+ ],
+ [
+ ["--command=/usr/bin/node /opt/server.js --mcp"],
+ { command: "/usr/bin/node", args: ["/opt/server.js", "--mcp"] },
+ ],
+ [
+ ['--command=/usr/bin/node "server entry.js"'],
+ { command: "/usr/bin/node", args: ["server entry.js"] },
+ ],
+ [
+ ["--command=/opt/tools/server --mcp"],
+ { command: "/opt/tools/server", args: ["--mcp"] },
+ ],
+ ] as const) {
+ const result = await run(
+ "mcp",
+ "add",
+ "--agent=cursor",
+ "--agent=amp",
+ "--json",
+ ...launcher,
+ );
+ expect(result.status, result.stderr).toBe(0);
+ const cursor = JSON.parse(
+ await readFile(join(home, ".cursor", "mcp.json"), "utf8"),
+ );
+ const amp = JSON.parse(
+ await readFile(join(home, ".config", "amp", "settings.json"), "utf8"),
+ );
+ expect(cursor.mcpServers["codex-security"]).toEqual(expected);
+ expect(amp["amp.mcpServers"]["codex-security"]).toEqual(expected);
+ }
+ }, 30_000);
+
test("project registration keeps linked configurations inside the project", async () => {
await using temp = await scopedTemporaryDirectory("cli-project-links-");
const { home, project, run } = await isolatedCli(temp.path);
@@ -342,7 +462,7 @@ describe("integration command dispatch", () => {
test("lists installed guidance at the selected grouping depth", async () => {
await using temp = await scopedTemporaryDirectory("cli-skill-grouping-");
- const { project, run } = await isolatedCli(temp.path);
+ const { project, home, run, runFrom } = await isolatedCli(temp.path);
const skills = await run(
"skill",
"add",
@@ -357,11 +477,43 @@ describe("integration command dispatch", () => {
const list = await run("skill", "ls", "--depth=0", "--json");
expect(list.status).toBe(0);
expect(JSON.parse(list.stdout)).toMatchObject([
- { name: "codex-security", installed: true },
+ {
+ name: "codex-security",
+ installed: true,
+ locations: [{ scope: "project", path: join(installed[0], "SKILL.md") }],
+ },
]);
const human = await run("skills", "list", "--depth", "0");
expect(human.status).toBe(0);
expect(human.stdout).toContain("1 skill (1 installed)");
+ const other = join(temp.path, "other-project");
+ await mkdir(other);
+ const elsewhere = await runFrom(
+ other,
+ "skills",
+ "list",
+ "--depth=0",
+ "--json",
+ );
+ expect(JSON.parse(elsewhere.stdout)).toMatchObject([
+ { installed: false, locations: [] },
+ ]);
+ const user = await run(
+ "skills",
+ "add",
+ "--scope=user",
+ "--depth=0",
+ "--json",
+ );
+ expect(user.status, user.stderr).toBe(0);
+ const combined = await run("skills", "list", "--depth=0", "--json");
+ expect(JSON.parse(combined.stdout)[0].locations).toEqual([
+ { scope: "project", path: join(installed[0], "SKILL.md") },
+ {
+ scope: "user",
+ path: join(home, ".agents", "skills", "codex-security", "SKILL.md"),
+ },
+ ]);
const defaultList = await run("skills", "list");
expect(defaultList.stdout).toContain("Skill grouping depth: 1");
}, 30_000);