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): inspect integration commands before installation (#2582)

Michael D'Angelo83c9c9196b8a
diff --git a/sdk/typescript/docs/cli.md b/sdk/typescript/docs/cli.md
index d71a9c527..e741dd7af 100644
--- a/sdk/typescript/docs/cli.md
+++ b/sdk/typescript/docs/cli.md
@@ -2735,6 +2735,24 @@ 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.
+
For local findings storage, deduplication, and custom endpoints, see the
[findings guide](findings-service.md).
diff --git a/sdk/typescript/package.json b/sdk/typescript/package.json
index 729454a11..c5154c96d 100644
--- a/sdk/typescript/package.json
+++ b/sdk/typescript/package.json
@@ -91,6 +91,7 @@
"@octokit/core": "7.0.8",
"@openai/codex": "0.167.0",
"@openai/codex-sdk": "0.167.0",
+ "add-mcp": "2.6.1",
"ajv": "8.20.0",
"fflate": "0.8.3",
"incur": "0.7.1",
diff --git a/sdk/typescript/pnpm-lock.yaml b/sdk/typescript/pnpm-lock.yaml
index 0b7261f83..f15029bdf 100644
--- a/sdk/typescript/pnpm-lock.yaml
+++ b/sdk/typescript/pnpm-lock.yaml
@@ -32,6 +32,9 @@ importers:
'@openai/codex-sdk':
specifier: 0.167.0
version: 0.167.0
+ add-mcp:
+ specifier: 2.6.1
+ version: 2.6.1
ajv:
specifier: 8.20.0
version: 8.20.0
@@ -134,6 +137,12 @@ packages:
'@cfworker/[email protected]':
resolution: {integrity: sha512-gAmrUZSGtKc3AiBL71iNWxDsyUC5uMaKKGdvzYsBoTW/xi42JQHl7eKV2OYzCUqvc+D2RCcf7EXY2iCyFIk6og==}
+ '@clack/[email protected]':
+ resolution: {integrity: sha512-Pxhij4UXg8KSr7rPek6Zowm+5M22rbd2g1nfojHJkxp5YkFqiZ2+YLEM/XGVIzvGOcM0nqjIFxrpDwWRZYWYjA==}
+
+ '@clack/[email protected]':
+ resolution: {integrity: sha512-JIpyaboYZeWYlyP0H+OoPPxd6nqueG/CmN6ixBiNFsIDHREevjIf0n0Ohh5gr5C8pEDknzgvz+pIJ8dMhzWIeg==}
+
'@esbuild/[email protected]':
resolution: {integrity: sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==}
engines: {node: '>=18'}
@@ -295,6 +304,9 @@ packages:
peerDependencies:
graphql: ^0.8.0 || ^0.9.0 || ^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^14.0.0 || ^15.0.0 || ^16.0.0 || ^17.0.0
+ '@iarna/[email protected]':
+ resolution: {integrity: sha512-trnsAYxU3xnS1gPHPyU961coFyLkh4gAD/0zQ5mymY4yOZ+CYvsPqUbOFSw0aDM4y0tV7tiFxL/1XfXPNC6IPg==}
+
'@inquirer/[email protected]':
resolution: {integrity: sha512-dwrc+1aqVZpHNkNDswXGtn1typ+Pxpo5FHZRyBw1le7onEJUkPUkYOY1FIFC1LvFMYUqqLuWBwElhAmencL7MQ==}
engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'}
@@ -669,6 +681,11 @@ packages:
cpu: [x64]
os: [win32]
+ resolution: {integrity: sha512-Jimza7/1JLaC3RVoaImX+CJSYKrQZkKuBZoV77zdo5yZwl/ZI66ba2uBVz690VSiqXR3yWKIPaw6Ou4ntzuRwg==}
+ engines: {node: '>=18'}
+ hasBin: true
+
resolution: {integrity: sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==}
@@ -704,6 +721,10 @@ packages:
resolution: {integrity: sha512-yjrJh5oGX7mMPKGd19YXyIjmEuj4G4zNC30bs7PM9Az7NQ3ndF3j6hbeRdvJTRQEhJ/FYQwW0a2moweEi2hMxQ==}
+ resolution: {integrity: sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==}
+ engines: {node: ^12.17.0 || ^14.13 || >=16.0.0}
+
resolution: {integrity: sha512-/Ce6KNm3vIbWdMlNna6RVIZ/ICQxnJxCicet5LBKK9ZffBkqzDw0xh9EiKSljdRtiIQ1S1z4YgcscUUGzNCWrA==}
engines: {node: '>=22'}
@@ -728,6 +749,10 @@ packages:
resolution: {integrity: sha512-xxodCmBen3iy2i0WtAK8FlFNrRzjUqjRsMfho58xT/wvZU1YTM3fCnRjcy1gJPMepaRlgm/0e6w8SpWHpn3/cA==}
engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}
+ resolution: {integrity: sha512-/rFeCpNJQbhSZjGVwO9RFV3xPqbnERS8MmIQzCtD/zl6gpJuV/bMLuN92oG3F7d8oDEHHRrujSXNUr8fpjntKw==}
+ engines: {node: '>=18'}
+
resolution: {integrity: sha512-AIi5H6p0xk5uknXcN3/rmhP8jgp69OfSe/JuKiQAFprJ7UGw7mwj7m4XcmDzlrnJDG+cGpphAINGdU3g3g7kDw==}
engines: {node: '>=22'}
@@ -861,6 +886,9 @@ packages:
engines: {node: '>=6'}
hasBin: true
+ resolution: {integrity: sha512-HUgH65KyejrUFPvHFPbqOY0rsFip3Bo5wb4ngvdi1EpCYWUQDC5V+Y7mZws+DLkr4M//zQJoanu1SP+87Dv1oQ==}
+
resolution: {integrity: sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==}
@@ -893,6 +921,9 @@ packages:
resolution: {integrity: sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg==}
+ resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==}
+
resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==}
engines: {node: '>=12'}
@@ -946,6 +977,9 @@ packages:
resolution: {integrity: sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==}
engines: {node: '>=14'}
+ resolution: {integrity: sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==}
+
resolution: {integrity: sha512-SO/3iYL5S3W57LLEniscOGPZgOqZUPCx6d3dB+52B80yJ0XstzsC/eV8gnA4tM3MHDrKz+OCFSLNjswdSC+/bA==}
engines: {node: '>=22'}
@@ -1037,6 +1071,17 @@ snapshots:
'@cfworker/[email protected]': {}
+ '@clack/[email protected]':
+ dependencies:
+ picocolors: 1.1.1
+ sisteransi: 1.0.5
+
+ '@clack/[email protected]':
+ dependencies:
+ '@clack/core': 0.4.1
+ picocolors: 1.1.1
+ sisteransi: 1.0.5
+
'@esbuild/[email protected]':
optional: true
@@ -1119,6 +1164,8 @@ snapshots:
dependencies:
graphql: 17.0.2
+ '@iarna/[email protected]': {}
+
'@inquirer/[email protected]': {}
@@ -1393,6 +1440,15 @@ snapshots:
'@typescript/[email protected]':
optional: true
+ dependencies:
+ '@clack/prompts': 0.9.1
+ '@iarna/toml': 2.2.5
+ chalk: 5.6.2
+ commander: 13.1.0
+ jsonc-parser: 3.3.1
+ yaml: 2.9.1
+
dependencies:
fast-deep-equal: 3.1.3
@@ -1423,6 +1479,8 @@ snapshots:
'@types/node': 26.6.6
undici-types: 8.9.0
+
@@ -1442,6 +1500,8 @@ snapshots:
dependencies:
convert-to-spaces: 2.0.1
+
@@ -1591,6 +1651,8 @@ snapshots:
+
@@ -1613,6 +1675,8 @@ snapshots:
+
@@ -1647,6 +1711,8 @@ snapshots:
+
dependencies:
ansi-styles: 6.2.3
diff --git a/sdk/typescript/scripts/package-dist-files.mjs b/sdk/typescript/scripts/package-dist-files.mjs
index 75fa06a19..8b1a02e3e 100644
--- a/sdk/typescript/scripts/package-dist-files.mjs
+++ b/sdk/typescript/scripts/package-dist-files.mjs
@@ -13,6 +13,8 @@ const distModules = [
"cli-argument",
"cli-daybreak",
"cli-help",
+ "cli-integrations",
+ "cli-mcp",
"cli-scan-logs-json",
"cli-signals",
"classify-severity",
diff --git a/sdk/typescript/src/cli-integrations.ts b/sdk/typescript/src/cli-integrations.ts
new file mode 100644
index 000000000..0e8f7aa48
--- /dev/null
+++ b/sdk/typescript/src/cli-integrations.ts
@@ -0,0 +1,319 @@
+import { Cli, Completions, Help, SyncSkills, z } from "incur";
+import { parseArgs } from "node:util";
+import { registerMcp } from "./cli-mcp.js";
+
+const cliName = "codex-security";
+export const completionShell = z.enum(["bash", "fish", "nushell", "zsh"]);
+const depth = z
+ .number()
+ .int()
+ .nonnegative()
+ .optional()
+ .describe("Grouping depth for generated skill files (default: 1).");
+const noGlobal = z
+ .boolean()
+ .optional()
+ .describe("Install to the current project instead of the user profile.");
+const descriptions = {
+ skills:
+ "Manage generated CLI command guidance. The Codex Security plugin provides scan and remediation workflows.",
+ mcp: "Register the read-only info tool or check its server startup and catalog.",
+};
+
+// Node's tokenizer rejects surplus positionals and missing values such as
+// --command --no-global before an installer can consume the scope switch.
+const boolean = { type: "boolean" } as const;
+const string = { type: "string" } as const;
+const formatOptions = {
+ json: boolean,
+ format: string,
+ "full-output": boolean,
+ "filter-output": string,
+ "token-count": boolean,
+ "token-limit": string,
+ "token-offset": string,
+};
+const outputOptions = {
+ ...formatOptions,
+ help: { ...boolean, short: "h" },
+ schema: boolean,
+ version: boolean,
+ llms: boolean,
+ "llms-full": boolean,
+};
+const options = {
+ ...outputOptions,
+ depth: string,
+ "no-global": boolean,
+ command: { ...string, short: "c" },
+ agent: { ...string, multiple: true },
+} as const;
+
+function integrationGroups(
+ cli: Cli.Cli,
+ cliOptions: Cli.create.Options,
+ invocation?: { output: Cli.serve.Options; plain: boolean; full?: boolean },
+) {
+ const { output, plain, full } = invocation ?? {};
+ const commands = Cli.toCommands.get(cli)!;
+ const config = {
+ sync: false,
+ update: false,
+ version: cliOptions.version,
+ } as const;
+ const prefix = invocation ? cliName + " " : "";
+ async function builtin(args: string[]) {
+ let text = "";
+ await cli.serve(args, {
+ ...output,
+ stdout: (chunk) => {
+ text += chunk;
+ },
+ });
+ return text.trimEnd();
+ }
+
+ const skills = Cli.create(prefix + "skills", {
+ ...config,
+ description: descriptions.skills,
+ aliases: ["skill"],
+ })
+ .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 } }) {
+ if (plain)
+ return builtin([
+ "skills",
+ "add",
+ ...(noGlobal ? ["--no-global"] : []),
+ ...(depth === undefined ? [] : ["--depth", String(depth)]),
+ ]);
+ const result = await SyncSkills.sync(cliName, commands, {
+ depth,
+ global: !noGlobal,
+ description: cliOptions.description,
+ });
+ return {
+ skills: result.paths,
+ ...(full ? { agents: result.agents } : {}),
+ };
+ },
+ })
+ .command("list", {
+ aliases: ["ls"],
+ description:
+ "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, {
+ depth,
+ description: cliOptions.description,
+ });
+ },
+ });
+ const mcp = Cli.create(prefix + "mcp", {
+ ...config,
+ description: descriptions.mcp,
+ })
+ .command("doctor", {
+ description:
+ "Check the current CLI's MCP startup and tool catalog. Connect from your client to test its registered launcher.",
+ run: async () => JSON.parse(await builtin(["mcp", "doctor", "--json"])),
+ })
+ .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.",
+ options: z.object({
+ agent: z
+ .array(z.string().min(1))
+ .optional()
+ .describe("Target a specific agent. Repeat to select more agents."),
+ command: z
+ .string()
+ .min(1)
+ .optional()
+ .describe("Override the command agents will run."),
+ 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,
+ );
+ if (plain)
+ return [
+ `✓ Registered ${cliName} as MCP server`,
+ ...(result.agents.length
+ ? [` Agents: ${result.agents.join(", ")}`]
+ : []),
+ ].join("\n");
+ return { name: cliName, ...result };
+ },
+ });
+ if (!invocation) {
+ cli
+ .command(skills)
+ .command(mcp)
+ .command("completions", {
+ description: "Generate a shell completion script.",
+ args: z.object({ shell: completionShell }),
+ run: () => undefined,
+ });
+ // Incur mounts aliases for leaf commands, but not for a whole group.
+ commands.set("skill", { _alias: true, target: "skills" });
+ }
+ return { skills, mcp };
+}
+
+/** Complete shell words without dispatching or validating any command. */
+export function completeCli(
+ cli: Cli.Cli,
+ cliOptions: Cli.create.Options,
+ shell: z.infer<typeof completionShell>,
+ argv: readonly string[],
+) {
+ const words = argv[0] === "--" ? argv.slice(1) : [...argv];
+ if (words.length === 0)
+ return [cliName, ...(cliOptions.aliases ?? [])]
+ .map((name) => Completions.register(shell, name))
+ .join("\n");
+ const index = Number(process.env["_COMPLETE_INDEX"] ?? words.length - 1);
+ if (!Number.isSafeInteger(index) || index < 0 || index > words.length)
+ return "";
+ integrationGroups(cli, cliOptions);
+ const candidates = Completions.complete(
+ Cli.toCommands.get(cli)!,
+ undefined,
+ words,
+ index,
+ {
+ schema: z.object({
+ format: z.enum(["toon", "json", "yaml", "md", "jsonl"]),
+ }),
+ },
+ );
+ return Completions.format(shell, candidates);
+}
+
+/** Incur dispatches its built-in writers before schema and version. Serve
+ * ordinary command groups so its normal parser and metadata handling run first. */
+export async function serveIntegration(
+ argv: string[],
+ cli: Cli.Cli,
+ cliOptions: Cli.create.Options,
+ output: Cli.serve.Options,
+): Promise<boolean> {
+ const manifest =
+ (argv.includes("--llms") || argv.includes("--llms-full")) &&
+ !argv.some((arg) =>
+ ["--help", "-h", "--version", "--schema"].includes(arg),
+ );
+ if (
+ !manifest &&
+ !argv.some((arg) => ["mcp", "skills", "skill"].includes(arg))
+ )
+ return false;
+ const words = parseArgs({
+ args: argv,
+ options: outputOptions,
+ strict: false,
+ allowPositionals: true,
+ }).positionals;
+ // Incur also accepts its binary name before a built-in command.
+ if (words[0] === cliName) {
+ argv = argv.toSpliced(argv.indexOf(cliName), 1);
+ words.shift();
+ }
+ const group = words[0] === "skill" ? "skills" : words[0];
+ if (!manifest && group !== "mcp" && group !== "skills") return false;
+ const { tokens, positionals, values } = parseArgs({
+ args: argv,
+ options,
+ allowPositionals: true,
+ tokens: true,
+ strict: group === "mcp" || group === "skills",
+ });
+ const plain = !Object.keys(formatOptions).some((key) =>
+ Object.hasOwn(values, key),
+ );
+ const full = values["full-output"] === true;
+ const { skills, mcp } = integrationGroups(
+ cli,
+ cliOptions,
+ manifest ? undefined : { output, plain, full },
+ );
+ if (manifest) {
+ // Put the mode first so a missing format/filter operand cannot consume it
+ // and fall through to a command handler.
+ const flag = argv.includes("--llms-full") ? "--llms-full" : "--llms";
+ await cli.serve(
+ [
+ flag,
+ ...argv.filter(
+ (arg) => !["--llms", "--llms-full", "--update"].includes(arg),
+ ),
+ ],
+ output,
+ );
+ return true;
+ }
+ if (group !== "mcp" && group !== "skills") return false;
+ const section = group === "mcp" ? mcp : skills;
+ const [, verb, ...extra] = positionals;
+ if (extra.length)
+ throw new Error(`Unexpected positional argument for ${group} ${verb}.`);
+ if (!verb && !values.version) {
+ const invalid = tokens.find(
+ (token) =>
+ token.kind === "option" && !Object.hasOwn(outputOptions, token.name),
+ );
+ if (invalid?.kind === "option")
+ throw new Error(`Unknown option for ${group}: ${invalid.rawName}`);
+ const children = Array.from(Cli.toCommands.get(section)!).flatMap(
+ ([name, entry]) =>
+ "description" in entry
+ ? [{ name, description: entry.description }]
+ : [],
+ );
+ output.stdout?.(
+ Help.formatRoot(`${cliName} ${group}`, {
+ aliases: section === skills ? ["skill"] : [],
+ description: descriptions[group],
+ commands: children,
+ }) + "\n",
+ );
+ return true;
+ }
+ if (verb && !Cli.toCommands.get(section)!.has(verb)) {
+ await cli.serve([group, verb, "--help"], output);
+ return true;
+ }
+ // The public flag names a scope directly. Incur reserves --no-* for
+ // negation; pass its schema's field name after Node tokenizes the CLI flag.
+ const args = argv.slice();
+ const groupToken = tokens.find((token) => token.kind === "positional")!;
+ for (const token of tokens) {
+ if (token.kind !== "option") continue;
+ if (token.name === "depth" && !token.value?.trim())
+ throw new Error("--depth requires a nonnegative integer.");
+ if (token.name === "no-global") args[token.index] = "--noGlobal";
+ }
+ args.splice(groupToken.index, 1);
+ await section.serve(args, output);
+ return true;
+}
diff --git a/sdk/typescript/src/cli-mcp.ts b/sdk/typescript/src/cli-mcp.ts
new file mode 100644
index 000000000..76f69aa02
--- /dev/null
+++ b/sdk/typescript/src/cli-mcp.ts
@@ -0,0 +1,137 @@
+import type { AgentType, McpServerConfig } from "add-mcp";
+import { SyncMcp } from "incur";
+import { lstat, realpath, stat } from "node:fs/promises";
+import { dirname, join } from "node:path";
+import { isWithin } from "./trusted-executable.js";
+
+// These CLI aliases are accepted by add-mcp in addition to its exported agent IDs.
+const agentAliases: Readonly<Record<string, AgentType>> = {
+ "cline-vscode": "cline",
+ codeium: "windsurf",
+ cascade: "windsurf",
+ droid: "factory-droid",
+ factory: "factory-droid",
+ gemini: "gemini-cli",
+ "github-copilot": "vscode",
+ grok: "grok-build",
+ "hermes-agent": "hermes",
+ kilo: "kilo-code",
+ kilocode: "kilo-code",
+ kimi: "kimi-code",
+ kiro: "kiro-cli",
+ mastra: "mastracode",
+ "pi-agent": "pi",
+};
+
+function mcpServerConfig(launch: string): McpServerConfig {
+ const value = launch.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))
+ return { command: value, args: [] };
+ const [command, ...args] = value.split(" ");
+ return args.length
+ ? { command: command!, args }
+ : { command: "npx", args: ["-y", value] };
+}
+
+async function checkProjectConfig(root: string, file: string) {
+ if (!isWithin(root, file))
+ throw new Error(`Project configuration must stay inside ${root}: ${file}`);
+ for (let path = file; path !== root; path = dirname(path)) {
+ let entry = await lstat(path).catch((error: NodeJS.ErrnoException) => {
+ if (error.code !== "ENOENT") throw error;
+ });
+ if (entry?.isSymbolicLink()) {
+ const target = await realpath(path);
+ if (!isWithin(root, target))
+ throw new Error(
+ `Project configuration resolves outside ${root}: ${path}`,
+ );
+ if (path === file) entry = await stat(target);
+ }
+ if (path === file && entry && (!entry.isFile() || entry.nlink !== 1))
+ throw new Error(
+ `Project configuration must be a regular file with one link: ${path}`,
+ );
+ }
+}
+
+export async function registerMcp(
+ cliName: string,
+ command: string,
+ requested: string[],
+ local: boolean,
+): Promise<SyncMcp.register.Result> {
+ // Import from the SDK installation. Never resolve or launch a package manager
+ // or installer from the project being configured.
+ const {
+ agents,
+ getAgentTypes,
+ detectGlobalAgents,
+ detectProjectAgents,
+ upsertServer,
+ } = await import("add-mcp");
+ const cwd = await realpath(process.cwd());
+ const all = getAgentTypes();
+ const targets = new Set<AgentType>();
+ if (requested.length) {
+ for (const target of requested) {
+ if (target === "amp") continue;
+ const key = target.toLowerCase();
+ const type =
+ all.find((type) => type === key) ??
+ (Object.hasOwn(agentAliases, key) ? agentAliases[key] : undefined);
+ if (!type)
+ throw new Error(
+ `Unknown MCP agent: ${target}. Available agents: ${[...all, "amp"].join(", ")}.`,
+ );
+ 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 config = mcpServerConfig(command);
+ for (const type of targets) {
+ const agent = agents[type];
+ if (!agent.supportedTransports.includes(config.type ?? "stdio"))
+ throw new Error(
+ `${agent.displayName} does not support this MCP transport.`,
+ );
+ if (local) {
+ if (!agent.localConfigPath)
+ throw new Error(
+ `${agent.displayName} does not support project registration.`,
+ );
+ const path =
+ agent.resolveConfigPath?.(agent, { local, cwd }) ??
+ join(cwd, agent.localConfigPath);
+ await checkProjectConfig(cwd, path);
+ }
+ }
+ const installed = [];
+ for (const type of targets) {
+ const result = upsertServer(type, cliName, config, { local, cwd });
+ if (!result.success)
+ 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);
+ }
+ return { command, agents: installed };
+}
diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.ts
index bd05fd1b1..ada871799 100644
--- a/sdk/typescript/src/cli.ts
+++ b/sdk/typescript/src/cli.ts
@@ -65,6 +65,11 @@ import {
stripVTControlCharacters,
} from "node:util";
import { Cli, Formatter, z } from "incur";
+import {
+ completeCli,
+ completionShell,
+ serveIntegration,
+} from "./cli-integrations.js";
import type { ZodType } from "zod";
import stringWidth from "string-width";
import Ajv2020, { type ValidateFunction } from "ajv/dist/2020.js";
@@ -2399,6 +2404,26 @@ export async function main(
dependencies: CliDependencies = DEFAULT_DEPENDENCIES,
onInterruptedSignIn?: () => void,
): Promise<number> {
+ // Build the command tree with no executable arguments for shell callbacks.
+ // Completion words, including literal action flags, belong to the shell.
+ const completion = completionShell.safeParse(process.env["COMPLETE"]);
+ const shellArgv = argv;
+ if (completion.success) argv = [];
+ if (
+ argv.includes("--mcp") &&
+ argv.some((arg) =>
+ [
+ "--help",
+ "-h",
+ "--schema",
+ "--version",
+ "--llms",
+ "--llms-full",
+ ].includes(arg),
+ )
+ ) {
+ argv = argv.filter((arg) => arg !== "--mcp");
+ }
const remediationOperation =
argv[0] === "patch"
? "patch"
@@ -7589,6 +7614,14 @@ export async function main(
},
});
+ if (completion.success) {
+ await writeCliOutput(
+ output,
+ completeCli(cli, cliOptions, completion.data, shellArgv),
+ );
+ return 0;
+ }
+
const commands = Cli.toCommands.get(cli)!;
const valueOptions = cliValueOptions(commands);
const commandIndex = argv.findIndex((value, index) => {
@@ -7889,15 +7922,23 @@ export async function main(
describeCommandInputs(commands);
}
try {
- await cli.serve(frameworkArgv, {
+ const serveOptions: Cli.serve.Options = {
stdout: frameworkCapture.stream.write,
exit: (code) => {
frameworkExit = code;
},
- });
+ };
+ if (
+ !(await serveIntegration(frameworkArgv, cli, cliOptions, serveOptions))
+ ) {
+ await cli.serve(frameworkArgv, serveOptions);
+ }
if (pendingUpdate !== undefined) {
notice = await Promise.race([pendingUpdate, undefined]);
}
+ } catch (error) {
+ errorOutput.write(`codex-security: ${diagnosticLines(error)}\n`);
+ return 2;
} finally {
updateController.abort();
}
diff --git a/sdk/typescript/tests-ts/cli-integrations.test.ts b/sdk/typescript/tests-ts/cli-integrations.test.ts
new file mode 100644
index 000000000..f57ea9034
--- /dev/null
+++ b/sdk/typescript/tests-ts/cli-integrations.test.ts
@@ -0,0 +1,368 @@
+import { describe, expect, test } from "bun:test";
+import {
+ link,
+ mkdir,
+ readFile,
+ readdir,
+ symlink,
+ unlink,
+ writeFile,
+} from "node:fs/promises";
+import { join } from "node:path";
+import { runCommand } from "./support/shell.js";
+import { scopedTemporaryDirectory } from "./support/temporary-directories.js";
+
+async function isolatedCli(root: string, environment: NodeJS.ProcessEnv = {}) {
+ const home = join(root, "home");
+ const project = join(root, "project");
+ await Promise.all([mkdir(home), mkdir(project)]);
+ const env = {
+ ...process.env,
+ HOME: home,
+ USERPROFILE: home,
+ XDG_CACHE_HOME: join(root, "cache"),
+ XDG_CONFIG_HOME: join(root, "config"),
+ XDG_DATA_HOME: join(root, "data"),
+ CODEX_HOME: join(root, "codex"),
+ CI: "1",
+ ...environment,
+ };
+ return {
+ home,
+ project,
+ run: (...args: string[]) =>
+ runCommand(
+ process.execPath,
+ [join(import.meta.dir, "../src/cli.ts"), ...args],
+ { env, cwd: project, timeout: 30_000 },
+ ),
+ };
+}
+
+describe("integration command dispatch", () => {
+ test.each([
+ { args: ["skills", "add", "--schema", "--json"], mode: "schema" },
+ {
+ args: ["mcp", "add", "--agent", "amp", "--schema", "--json"],
+ mode: "schema",
+ },
+ { args: ["skill", "add", "--version"], mode: "version" },
+ { args: ["mcp", "--version"], mode: "version" },
+ {
+ args: [
+ "--json",
+ "codex-security",
+ "mcp",
+ "add",
+ "--agent=amp",
+ "--schema",
+ ],
+ mode: "schema",
+ },
+ { args: ["mcp", "add", "--command", "--no-global"], mode: "error" },
+ { args: ["skills", "add", "surplus"], mode: "error" },
+ {
+ args: ["mcp", "add", "--agent=amp", "--filter-output", "--llms"],
+ mode: "error",
+ },
+ { args: ["skills", "--deph"], mode: "error" },
+ { args: ["mcp", "add", "--agent", "amp", "--version"], mode: "version" },
+ { args: ["skills", "add", "--no-glboal"], mode: "error" },
+ { args: ["skills", "add", "--depth", "NaN"], mode: "error" },
+ { args: ["skills", "list", "--depth=NaN"], mode: "error" },
+ { args: ["mcp", "add", "--agent", "amp", "--no-global"], mode: "error" },
+ {
+ args: [
+ "mcp",
+ "add",
+ "--agent=cursor",
+ "--agent=claude-desktop",
+ "--no-global",
+ ],
+ mode: "error",
+ },
+ { args: ["--mcp", "--help"], mode: "help" },
+ ])(
+ "leaves both installation scopes untouched for $args",
+ async ({ args, mode }) => {
+ await using temp = await scopedTemporaryDirectory("cli-inspection-");
+ const { home, project, run } = await isolatedCli(temp.path);
+ const result = await run(...args);
+ expect(result.status).toBe(mode === "error" ? 2 : 0);
+ if (mode === "schema")
+ expect(JSON.parse(result.stdout).options.properties.noGlobal.type).toBe(
+ "boolean",
+ );
+ if (mode === "version")
+ expect(result.stdout.trim()).toMatch(/^\d+\.\d+\.\d+/);
+ if (mode === "help")
+ expect(result.stdout).toContain("Usage: codex-security");
+ if (mode === "error") expect(result.stderr.length).toBeGreaterThan(0);
+ expect(await readdir(home)).toEqual([]);
+ expect(await readdir(project)).toEqual([]);
+ },
+ 30_000,
+ );
+
+ test.each([
+ { group: "mcp", term: "read-only info tool" },
+ { group: "skills", term: "Codex Security plugin" },
+ ])(
+ "$group help identifies the integration being managed",
+ async ({ group, term }) => {
+ await using temp = await scopedTemporaryDirectory(
+ "cli-integration-help-",
+ );
+ const { run } = await isolatedCli(temp.path);
+ const result = await run(group, "--help");
+ expect(result.status).toBe(0);
+ expect(result.stdout.replace(/\s+/gu, " ")).toContain(term);
+ },
+ 30_000,
+ );
+
+ test("shell hooks complete integration flags without executing commands", async () => {
+ await using temp = await scopedTemporaryDirectory(
+ "cli-integration-completions-",
+ );
+ const { home, project, run } = await isolatedCli(temp.path, {
+ COMPLETE: "bash",
+ });
+ for (const [args, flag] of [
+ [["cs", "skill", "ls", "--de"], "--depth"],
+ [["codex-security", "mcp", "add", "--ag"], "--agent"],
+ [["cs", "skills", "list", "--format", "ya"], "yaml"],
+ ] as const) {
+ const result = await run("--", ...args);
+ expect(result.status).toBe(0);
+ expect(result.stdout).toContain(flag);
+ }
+ expect(await readdir(home)).toEqual([]);
+ expect(await readdir(project)).toEqual([]);
+ }, 30_000);
+
+ test("zsh completes at the supplied cursor after an equals-form option", async () => {
+ await using temp = await scopedTemporaryDirectory("cli-zsh-completions-");
+ const { run } = await isolatedCli(temp.path, {
+ COMPLETE: "zsh",
+ _COMPLETE_INDEX: "4",
+ });
+ const result = await run(
+ "--",
+ "cs",
+ "skills",
+ "list",
+ "--format=json",
+ "--de",
+ "--json",
+ );
+ expect(result.status).toBe(0);
+ expect(result.stdout).toStartWith("--depth:");
+ }, 30_000);
+
+ test.each([
+ {
+ shell: "zsh",
+ words: ["cs", "info", "--co", "--mcp", "--help", "--update", "--schema"],
+ index: 2,
+ candidate: "--config:",
+ },
+ {
+ shell: "bash",
+ words: [
+ "codex-security",
+ "scan",
+ "--mode",
+ "d",
+ "--mcp",
+ "--format=invalid",
+ ],
+ index: 3,
+ candidate: "deep",
+ },
+ {
+ shell: "bash",
+ words: ["cs", "scan", "--mode"],
+ index: 3,
+ candidate: "standard\vdeep",
+ },
+ {
+ shell: "zsh",
+ words: ["cs", "info", "--config", "--update"],
+ index: 2,
+ candidate: "--config:",
+ },
+ {
+ shell: "fish",
+ words: ["cs", "scans", "sh"],
+ candidate: "show\t",
+ },
+ {
+ shell: "nushell",
+ words: ["cs", "sk"],
+ candidate: '"value":"skills"',
+ },
+ ])(
+ "the $shell hook completes ordinary CLI words without running actions",
+ async ({ shell, words, index, candidate }) => {
+ await using temp = await scopedTemporaryDirectory("cli-shell-word-");
+ const { home, project, run } = await isolatedCli(temp.path, {
+ COMPLETE: shell,
+ _COMPLETE_INDEX: index?.toString(),
+ PATH: join(temp.path, "no-package-runners"),
+ });
+ const result = await run("--", ...words);
+ expect(result.status).toBe(0);
+ expect(result.stdout).toContain(candidate);
+ expect(result.stderr).toBe("");
+ expect(await readdir(home)).toEqual([]);
+ expect(await readdir(project)).toEqual([]);
+ },
+ 30_000,
+ );
+
+ test("empty completion callbacks emit the shell registration script", async () => {
+ await using temp = await scopedTemporaryDirectory("cli-shell-script-");
+ const { run } = await isolatedCli(temp.path, { COMPLETE: "zsh" });
+ const result = await run();
+ expect(result.status).toBe(0);
+ expect(result.stdout).toContain("#compdef codex-security");
+ expect(result.stdout).toContain("#compdef cs");
+ }, 30_000);
+
+ test("the command manifest includes integration leaves without installing them", async () => {
+ await using temp = await scopedTemporaryDirectory(
+ "cli-integration-discovery-",
+ );
+ const { home, project, run } = await isolatedCli(temp.path);
+ const manifest = await run("--llms", "--json");
+ expect(manifest.status).toBe(0);
+ const commands = JSON.parse(manifest.stdout).commands.map(
+ (entry: { name: string }) => entry.name,
+ );
+ for (const command of [
+ "completions",
+ "mcp add",
+ "mcp doctor",
+ "skills add",
+ "skills list",
+ ])
+ expect(commands).toContain(command);
+ expect(await readdir(home)).toEqual([]);
+ expect(await readdir(project)).toEqual([]);
+ }, 30_000);
+
+ test("registers selected clients from the installed SDK with no package runners on PATH", async () => {
+ await using temp = await scopedTemporaryDirectory("cli-project-clients-");
+ const { home, project, run } = await isolatedCli(temp.path, {
+ PATH: join(temp.path, "no-executables"),
+ npm_config_user_agent: "pnpm/11",
+ npm_execpath: join(temp.path, "unavailable-pnpm.cjs"),
+ });
+ await mkdir(join(project, ".cursor"));
+ const decoy = join(project, "node_modules", "add-mcp");
+ await mkdir(decoy, { recursive: true });
+ await writeFile(
+ join(decoy, "package.json"),
+ JSON.stringify({ name: "add-mcp", main: "missing.js" }),
+ );
+ const local = await run("mcp", "add", "--no-global", "--json");
+ expect(local.status).toBe(0);
+ expect(JSON.parse(local.stdout).agents).toEqual(["Cursor"]);
+ const projectConfig = JSON.parse(
+ await readFile(join(project, ".cursor", "mcp.json"), "utf8"),
+ );
+ expect(projectConfig.mcpServers["codex-security"]).toMatchObject({
+ command: "npx",
+ args: ["--yes", "@openai/codex-security", "--mcp"],
+ });
+ expect(await readdir(home)).toEqual([]);
+ const global = await run(
+ "mcp",
+ "add",
+ "--agent=cursor",
+ "--command",
+ "my-tool --mcp",
+ "--json",
+ );
+ expect(global.status).toBe(0);
+ expect(JSON.parse(global.stdout).agents).toEqual(["Cursor"]);
+ const userConfig = JSON.parse(
+ await readFile(join(home, ".cursor", "mcp.json"), "utf8"),
+ );
+ expect(userConfig.mcpServers["codex-security"]).toMatchObject({
+ command: "my-tool",
+ args: ["--mcp"],
+ });
+ }, 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);
+ const dir = join(project, ".cursor");
+ const external = join(home, "mcp.json");
+ const register = () =>
+ run("mcp", "add", "--agent=cursor", "--no-global", "--json");
+ await writeFile(external, "{}");
+ await symlink(home, dir, process.platform === "win32" ? "junction" : "dir");
+ expect((await register()).status).toBe(2);
+ await unlink(dir);
+ await mkdir(dir);
+ await link(external, join(dir, "mcp.json"));
+ expect((await register()).status).toBe(2);
+ expect(await readFile(external, "utf8")).toBe("{}");
+ }, 30_000);
+
+ test("explicit JSON returns a parseable MCP installer result", async () => {
+ await using temp = await scopedTemporaryDirectory("cli-integrations-");
+ const { home, run } = await isolatedCli(temp.path);
+ const mcp = await run(
+ "mcp",
+ "add",
+ "--agent=amp",
+ "--agent",
+ "amp",
+ "--command",
+ "my-tool --mcp",
+ "--json",
+ );
+ expect(mcp.status).toBe(0);
+ expect(JSON.parse(mcp.stdout)).toMatchObject({
+ agents: ["Amp"],
+ command: "my-tool --mcp",
+ });
+ const configuration = JSON.parse(
+ await readFile(join(home, ".config", "amp", "settings.json"), "utf8"),
+ );
+ expect(configuration["amp.mcpServers"]["codex-security"]).toEqual({
+ command: "my-tool",
+ args: ["--mcp"],
+ });
+ }, 30_000);
+
+ 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 skills = await run(
+ "skill",
+ "add",
+ "--no-global",
+ "--depth=0",
+ "--json",
+ );
+ expect(skills.status).toBe(0);
+ const installed = JSON.parse(skills.stdout).skills;
+ expect(installed).toHaveLength(1);
+ expect(installed[0]).toStartWith(project);
+ 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 },
+ ]);
+ const human = await run("skills", "list", "--depth", "0");
+ expect(human.status).toBe(0);
+ expect(human.stdout).toContain("1 skill (1 installed)");
+ const defaultList = await run("skills", "list");
+ expect(defaultList.stdout).toContain("Skill grouping depth: 1");
+ }, 30_000);
+});