All files / src/cli/install codex.ts

100% Statements 146/146
100% Branches 125/125
100% Functions 25/25
100% Lines 132/132

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361          6x 6x 6x 6x 6x   6x 6x 6x           6x 6x 6x   6x     6x                                               6x         133x         133x                 14x             6x 44x       6x 42x 42x 39x 39x 38x       30x 30x 27x 27x     1x         6x 18x 17x 17x 13x     21x       4x       26x 26x 4x   22x   21x 21x 21x       30x         30x 48x 26x       38x 19x     5x               8x 2x   6x 6x 2x   4x               6x 50x 22x 21x                                 20x   20x 19x 19x 18x   1x         20x 20x 3x                             10x 3x       7x 5x   5x                   6x 42x 42x   42x 42x   4x     38x   38x 38x   1x 1x   37x 1x                     36x 2x                   34x 34x 34x 8x 8x       30x 30x   30x 9x 9x           21x 3x 3x 3x 3x     18x 1x   18x   18x                   6x                 6x 17x 17x   220x 220x 220x   215x 1x 214x   17x       6x 5x 5x 1x 1x   4x       4x 4x 3x 3x   6x     4x    
/**
 * Codex installer: drives the Codex CLI (`codex mcp list|get|add|remove`) so
 * Codex itself edits config.toml and keeps every unrelated setting.
 */
 
import { existsSync, readFileSync } from 'node:fs';
import { homedir } from 'node:os';
import { join } from 'node:path';
import { sync as spawnSync } from 'cross-spawn';
import { parse as parseToml } from 'smol-toml';
import { BackupResult, InstallResult } from './types';
import { isRemoteServerConfig, McpServerConfig } from '../init/types';
import { createBackup, restoreBackup } from './backup';
import { MCP_SERVER_NAME, PLUGIN_NAME } from '../plugin/listing';
 
/**
 * Name of the entry this installer manages; other GitLab entries are only reported.
 * It is the plugin's server name, so Codex runs one of the two, never both.
 */
export const CODEX_SERVER_NAME = MCP_SERVER_NAME;
const CODEX_COMMAND = 'codex';
const PACKAGE_PATTERN = /@structured-world\/gitlab-mcp(?:@[^\s/]*)?$/;
const CHECKOUT_PATTERN =
  /gitlab-mcp[\\/](?:packages[\\/]gitlab-mcp[\\/])?dist[\\/]src[\\/]main\.js$/;
// The executable a global npm install puts on PATH (`.cmd`/`.ps1` shims on Windows).
// Only the command is matched: `npx gitlab-mcp` runs an unrelated unscoped package.
const GLOBAL_BIN_PATTERN = /(?:^|[\\/])gitlab-mcp(?:\.cmd|\.ps1|\.exe)?$/i;
 
/** Transport of a configured server as `codex mcp list --json` reports it. */
export type CodexTransport =
  | { type: 'stdio'; command: string; args?: string[] | null; env?: Record<string, string> | null }
  | { type: 'streamable_http'; url: string };
 
export interface CodexServer {
  name: string;
  transport: CodexTransport;
  /** False when a higher-precedence configuration disables the server. */
  enabled?: boolean;
  disabled_reason?: string | null;
}
 
interface RunResult {
  status: number | null;
  stdout: string;
  stderr: string;
  error?: Error;
}
 
// `codex mcp list` contacts configured remote servers; one that never answers
// must not hang the install. The browser sign-in takes as long as the user needs.
const CODEX_TIMEOUT_MS = 60_000;
 
function runCodex(args: string[], interactive = false): RunResult {
  // cross-spawn runs npm's codex.cmd shim on Windows without a shell, so
  // arguments with spaces or cmd.exe metacharacters pass through intact.
  const result = spawnSync(CODEX_COMMAND, args, {
    stdio: interactive ? 'inherit' : 'pipe',
    encoding: 'utf8',
    ...(interactive ? {} : { timeout: CODEX_TIMEOUT_MS }),
  });
  return {
    status: result.status,
    stdout: typeof result.stdout === 'string' ? result.stdout : '',
    stderr: typeof result.stderr === 'string' ? result.stderr : '',
    error: result.error,
  };
}
 
function failure(result: RunResult): string {
  return (
    result.error?.message ??
    (result.stderr.trim() || result.stdout.trim() || `codex exited with ${result.status}`)
  );
}
 
/** Path of the Codex configuration file, honouring CODEX_HOME. */
export function codexConfigPath(): string {
  return join(process.env.CODEX_HOME ?? join(homedir(), '.codex'), 'config.toml');
}
 
/** Every server Codex runs, including those installed plugins provide. */
export function listCodexServers(): CodexServer[] {
  const result = runCodex(['mcp', 'list', '--json']);
  if (result.status !== 0) throw new Error(`codex mcp list failed: ${failure(result)}`);
  const parsed = JSON.parse(result.stdout) as unknown;
  if (!Array.isArray(parsed)) throw new Error('codex mcp list returned an unexpected format');
  return parsed as CodexServer[];
}
 
function getCodexServer(name: string): CodexServer | undefined {
  const result = runCodex(['mcp', 'get', name, '--json']);
  if (result.status !== 0) return undefined;
  try {
    return JSON.parse(result.stdout) as CodexServer;
  } catch {
    // Unreadable output proves nothing about what was saved.
    return undefined;
  }
}
 
/** True when the entry runs GitLab MCP, by name, package, checkout or endpoint. */
export function isGitlabMcpServer(server: CodexServer, target?: McpServerConfig): boolean {
  if (server.name === CODEX_SERVER_NAME || server.name.startsWith('gitlab-mcp')) return true;
  const transport = server.transport;
  if (transport.type === 'stdio') {
    return (
      GLOBAL_BIN_PATTERN.test(transport.command) ||
      [transport.command, ...(transport.args ?? [])].some(
        (part) => PACKAGE_PATTERN.test(part) || CHECKOUT_PATTERN.test(part),
      )
    );
  }
  return target !== undefined && isRemoteServerConfig(target) && transport.url === target.url;
}
 
function matches(server: CodexServer, config: McpServerConfig): boolean {
  const transport = server.transport;
  if (isRemoteServerConfig(config)) {
    return transport.type === 'streamable_http' && transport.url === config.url;
  }
  if (transport.type !== 'stdio') return false;
  // Codex writes no env table when none was given, and lists the saved values verbatim.
  const saved = transport.env ?? {};
  const wanted = Object.entries(config.env);
  return (
    transport.command === config.command &&
    JSON.stringify(transport.args ?? []) === JSON.stringify(config.args) &&
    Object.keys(saved).length === wanted.length &&
    wanted.every(([key, value]) => saved[key] === value)
  );
}
 
function addArgs(config: McpServerConfig): string[] {
  if (isRemoteServerConfig(config)) return ['mcp', 'add', CODEX_SERVER_NAME, '--url', config.url];
  const env = Object.entries(config.env).flatMap(([key, value]) => ['--env', `${key}=${value}`]);
  return ['mcp', 'add', CODEX_SERVER_NAME, ...env, '--', config.command, ...config.args];
}
 
function duplicateNotes(servers: CodexServer[], config: McpServerConfig): string[] {
  return servers
    .filter((s) => s.name !== CODEX_SERVER_NAME && isGitlabMcpServer(s, config))
    .map(
      (s) =>
        `"${s.name}" also runs GitLab MCP, so Codex lists its tools twice; ` +
        `remove the one you do not use (codex mcp remove ${s.name}, or disable the plugin).`,
    );
}
 
/** Removes the managed entry; returns the reason when it was left in place. */
function removeExisting(configPath: string, backup: BackupResult | undefined): string | undefined {
  // Removing the old entry is undoable only through the backup.
  if (backup && !backup.created) {
    return `Could not back up ${configPath}: ${backup.error ?? 'unknown error'}`;
  }
  const removed = runCodex(['mcp', 'remove', CODEX_SERVER_NAME]);
  if (removed.status !== 0) {
    return `Failed to remove the existing ${CODEX_SERVER_NAME} entry: ${failure(removed)}`;
  }
  return undefined;
}
 
/**
 * True when the user's own config.toml defines the managed entry. `mcp list`
 * also reports servers from plugins and project configuration, which
 * `mcp remove` cannot edit, and `mcp remove` exits 0 for a missing name.
 */
export function hasGlobalEntry(configPath: string): boolean {
  if (!existsSync(configPath)) return false;
  const servers = parseToml(readFileSync(configPath, 'utf8')).mcp_servers;
  return (
    typeof servers === 'object' && servers !== null && Object.hasOwn(servers, CODEX_SERVER_NAME)
  );
}
 
interface InstalledPlugin {
  pluginId: string;
  name: string;
  enabled: boolean;
}
 
/**
 * Installed GitLab MCP plugins as Codex resolves them across its configuration layers
 * (user, project, system). `mcp list` omits a disabled plugin's server, and a global
 * entry of the same name hides an enabled one, so only the plugin list shows them all.
 */
function installedPlugins(): InstalledPlugin[] {
  const result = runCodex(['plugin', 'list', '--json']);
  // A Codex without the plugin command has no plugins for the entry to hide.
  if (result.status !== 0) return [];
  try {
    const { installed } = JSON.parse(result.stdout) as { installed?: InstalledPlugin[] };
    return (installed ?? []).filter((plugin) => plugin.name === PLUGIN_NAME);
  } catch {
    return [];
  }
}
 
function shadowNotes(plugins: InstalledPlugin[]): string[] {
  const entry = CODEX_SERVER_NAME;
  return plugins.map(({ pluginId: id, enabled }) =>
    enabled
      ? `The ${id} plugin is installed and its "${entry}" server stays unused while this ` +
        `entry exists; keep one (codex plugin remove ${id}, or codex mcp remove ${entry}).`
      : // Removing the entry alone would leave no GitLab server at all.
        `The ${id} plugin is installed but disabled; while this entry exists its "${entry}" ` +
        `server stays unused even when enabled. To use the plugin, enable it, then run ` +
        `codex mcp remove ${entry}; or remove it with codex plugin remove ${id}.`,
  );
}
 
/**
 * Undoes a failed add and says how: the backup is restored, or, when there was
 * no entry before, the one Codex saved is removed.
 */
function rollBack(hadEntry: boolean, backupPath: string | undefined, configPath: string): string {
  if (backupPath !== undefined) {
    return restoreBackup(backupPath, configPath)
      ? '; the previous Codex configuration was restored'
      : `; restoring the previous Codex configuration failed, restore it by hand from ${backupPath}`;
  }
  if (hadEntry || !hasGlobalEntry(configPath)) return '';
  runCodex(['mcp', 'remove', CODEX_SERVER_NAME]);
  // A leftover entry would make the next install refuse without --force.
  return hasGlobalEntry(configPath)
    ? `; the partly saved ${CODEX_SERVER_NAME} entry is still in config.toml, remove it with: codex mcp remove ${CODEX_SERVER_NAME}`
    : `; the partly saved ${CODEX_SERVER_NAME} entry was removed`;
}
 
/**
 * Registers GitLab MCP in Codex. An existing entry of its name is replaced only
 * with `force`; GitLab MCP registered under other names, including by an
 * installed plugin, is reported and left alone.
 */
export function installCodex(config: McpServerConfig, force: boolean): InstallResult {
  const client = 'codex' as const;
  const configPath = codexConfigPath();
  let servers: CodexServer[];
  try {
    servers = listCodexServers();
  } catch (error) {
    return { client, success: false, error: (error as Error).message };
  }
 
  const notes = duplicateNotes(servers, config);
  let existing: boolean;
  try {
    existing = hasGlobalEntry(configPath);
  } catch (error) {
    const reason = (error as Error).message;
    return { client, success: false, error: `Cannot read ${configPath}: ${reason}`, notes };
  }
  if (!existing && servers.some((s) => s.name === CODEX_SERVER_NAME)) {
    return {
      client,
      success: false,
      error:
        `Codex already runs a server named "${CODEX_SERVER_NAME}" from a plugin or project ` +
        'configuration; disable it there before installing.',
      configPath,
      notes,
    };
  }
 
  if (existing && !force) {
    return {
      client,
      success: false,
      error: 'gitlab-mcp is already configured. Use --force to overwrite.',
      wasAlreadyConfigured: true,
      configPath,
      notes: [...notes, ...shadowNotes(installedPlugins())],
    };
  }
 
  const backup = existsSync(configPath) ? createBackup({ configPath }) : undefined;
  const backupPath = backup?.created ? backup.backupPath : undefined;
  if (existing) {
    const error = removeExisting(configPath, backup);
    if (error) return { client, success: false, error, backupPath, configPath, notes };
  }
 
  // A remote server starts the browser sign-in right away; it needs the terminal.
  const added = runCodex(addArgs(config), isRemoteServerConfig(config));
  const applied = getCodexServer(CODEX_SERVER_NAME);
 
  if (!applied || !matches(applied, config)) {
    const error = `codex mcp add failed: ${failure(added)}${rollBack(existing, backupPath, configPath)}`;
    return { client, success: false, error, backupPath, configPath, notes };
  }
 
  // A project, system or managed config.toml can disable the server. A new entry is
  // correct and stays, with the reason reported; a replaced entry is restored, since
  // a managed allowlist can enable the old command while disabling the new one.
  if (applied.enabled === false) {
    const reason = applied.disabled_reason ?? 'no reason given';
    const restored = existing ? rollBack(existing, backupPath, configPath) : '';
    const error = `Codex saved the ${CODEX_SERVER_NAME} entry but keeps it disabled: ${reason}${restored}`;
    return { client, success: false, error, backupPath, configPath, notes };
  }
 
  if (added.status !== 0 && isRemoteServerConfig(config)) {
    notes.push(`Sign-in did not complete; run: codex mcp login ${CODEX_SERVER_NAME}`);
  }
  notes.push(...shadowNotes(installedPlugins()));
 
  return {
    client,
    success: true,
    backupPath,
    configPath,
    wasAlreadyConfigured: existing,
    notes,
  };
}
 
const TOML_SHORT_ESCAPES: Readonly<Record<string, string>> = {
  '\\': String.raw`\\`,
  '"': String.raw`\"`,
  '\n': String.raw`\n`,
  '\t': String.raw`\t`,
  '\r': String.raw`\r`,
};
 
/** TOML basic string (TOML 1.0, "Basic strings"). */
export function tomlString(value: string): string {
  let escaped = '';
  for (const char of value) {
    // Iterating a string yields non-empty characters, so position 0 always has a code point.
    const code = char.codePointAt(0) as number;
    const short = TOML_SHORT_ESCAPES[char];
    if (short !== undefined) escaped += short;
    // Other control characters have no short escape.
    else if (code < 0x20 || code === 0x7f) {
      escaped += String.raw`\u` + code.toString(16).padStart(4, '0');
    } else escaped += char;
  }
  return `"${escaped}"`;
}
 
/** The config.toml entry `installCodex` produces, for --show. */
export function codexConfigPreview(config: McpServerConfig): string {
  const lines = [`[mcp_servers.${CODEX_SERVER_NAME}]`];
  if (isRemoteServerConfig(config)) {
    lines.push(`url = ${tomlString(config.url)}`);
    return lines.join('\n');
  }
  lines.push(
    `command = ${tomlString(config.command)}`,
    `args = [${config.args.map(tomlString).join(', ')}]`,
  );
  const env = Object.entries(config.env);
  if (env.length > 0) {
    lines.push('', `[mcp_servers.${CODEX_SERVER_NAME}.env]`);
    for (const [key, value] of env) {
      // Bare keys are A-Za-z0-9_- (TOML 1.0, "Keys"); anything else is quoted.
      lines.push(`${/^[A-Za-z0-9_-]+$/.test(key) ? key : tomlString(key)} = ${tomlString(value)}`);
    }
  }
  return lines.join('\n');
}