All files / src/cli/install detector.ts

96.55% Statements 84/87
78.43% Branches 40/51
100% Functions 14/14
96.34% Lines 79/82

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          4x 4x 4x           4x 4x     17x         4x 40x 40x 40x           4x 14x 14x       13x   1x                 4x       24x             5x 4x       1x       1x 1x           1x             4x 20x 20x 20x 1x     19x 19x     18x 18x 14x       4x 4x 1x     3x   1x                 7x 7x             7x 4x     4x     1x     7x           4x 37x 30x 30x 30x   30x           30x 30x     30x   4x 2x   4x     5x       5x   5x 5x 1x     5x         21x 21x 21x 11x     21x       30x 30x 30x 13x       30x           4x 24x           4x 8x           4x 8x    
/**
 * MCP client detection module
 * Detects which MCP clients are installed on the system
 */
 
import { existsSync, readFileSync } from 'fs';
import { spawnSync } from 'child_process';
import {
  InstallableClient,
  ClientDetectionResult,
  CLIENT_METADATA,
  INSTALLABLE_CLIENTS,
} from './types';
import { expandPath } from '../utils/path-utils.js';
import { codexConfigPath, hasGlobalEntry } from './codex';
 
// Re-export expandPath for backwards compatibility with existing imports
export { expandPath } from '../utils/path-utils.js';
 
/**
 * Get config path for a client on current platform
 */
export function getConfigPath(client: InstallableClient): string | undefined {
  const metadata = CLIENT_METADATA[client];
  const platform = process.platform as 'darwin' | 'win32' | 'linux';
  return metadata.configPaths[platform];
}
 
/**
 * Check if a CLI command exists
 */
export function commandExists(command: string): boolean {
  try {
    const result = spawnSync(process.platform === 'win32' ? 'where' : 'which', [command], {
      stdio: 'pipe',
      encoding: 'utf8',
    });
    return result.status === 0;
  } catch {
    return false;
  }
}
 
/**
 * Validate bundle ID format to prevent command injection
 * Bundle IDs must be reverse-domain format with at least 2 segments: com.example
 * Exported for testing
 */
export function isValidBundleId(bundleId: string): boolean {
  // Require at least one dot (2 segments) and valid characters
  // Valid: com.example, com.example.app, org.test-app.Main
  // Invalid: a, com, com., .com, com..example, -com.example
  return /^[a-zA-Z0-9][a-zA-Z0-9-]*(\.[a-zA-Z0-9][a-zA-Z0-9-]*)+$/.test(bundleId);
}
 
/**
 * Check if macOS app bundle exists
 */
function appBundleExists(bundleId: string): boolean {
  if (process.platform !== 'darwin') {
    return false;
  }
 
  // Validate bundleId format to prevent command injection
  Iif (!isValidBundleId(bundleId)) {
    return false;
  }
 
  try {
    const result = spawnSync('mdfind', [`kMDItemCFBundleIdentifier == "${bundleId}"`], {
      stdio: 'pipe',
      encoding: 'utf8',
    });
    return result.status === 0 && result.stdout.trim().length > 0;
  } catch {
    return false;
  }
}
 
/**
 * Check if gitlab-mcp is already configured in a JSON config file
 */
export function isAlreadyConfigured(configPath: string): boolean {
  try {
    const expanded = expandPath(configPath);
    if (!existsSync(expanded)) {
      return false;
    }
 
    const content = readFileSync(expanded, 'utf8');
    const config = JSON.parse(content) as Record<string, unknown>;
 
    // Check for mcpServers.gitlab or mcpServers["gitlab-mcp"]
    const mcpServers = config.mcpServers as Record<string, unknown> | undefined;
    if (mcpServers) {
      return 'gitlab' in mcpServers || 'gitlab-mcp' in mcpServers;
    }
 
    // Check for servers.gitlab (different config format)
    const servers = config.servers as Record<string, unknown> | undefined;
    if (servers) {
      return 'gitlab' in servers || 'gitlab-mcp' in servers;
    }
 
    return false;
  } catch {
    return false;
  }
}
 
/**
 * Codex is found through its CLI; whether the gitlab entry the installer
 * manages exists is read from the global config.toml.
 */
function detectCodex(): ClientDetectionResult {
  const configPath = codexConfigPath();
  const result: ClientDetectionResult = {
    client: 'codex',
    detected: commandExists('codex'),
    method: 'cli-command',
    configPath,
    configExists: existsSync(configPath),
  };
  if (result.detected) {
    try {
      // Only the entry the installer would replace, read from config.toml:
      // `codex mcp list` contacts remote servers and can stall detection.
      result.alreadyConfigured = hasGlobalEntry(configPath);
    } catch {
      // An unreadable config.toml is reported by the installer itself.
      result.alreadyConfigured = false;
    }
  }
  return result;
}
 
/**
 * Detect a single MCP client
 */
export function detectClient(client: InstallableClient): ClientDetectionResult {
  if (client === 'codex') return detectCodex();
  const metadata = CLIENT_METADATA[client];
  const configPath = getConfigPath(client);
  const expandedPath = configPath ? expandPath(configPath) : undefined;
 
  const result: ClientDetectionResult = {
    client,
    detected: false,
    method: metadata.detectionMethod,
  };
 
  Eif (configPath) {
    result.configPath = expandedPath;
  }
 
  switch (metadata.detectionMethod) {
    case 'cli-command':
      if (metadata.cliCommand && commandExists(metadata.cliCommand)) {
        result.detected = true;
      }
      break;
 
    case 'app-bundle':
      Iif (metadata.appBundleId && appBundleExists(metadata.appBundleId)) {
        result.detected = true;
      }
      // Also check config file as fallback
      Eif (!result.detected && expandedPath) {
        // Check if config directory exists (even without config file)
        const configDir = expandedPath.replace(/\/[^/]+$/, '');
        if (existsSync(configDir)) {
          result.detected = true;
        }
      }
      break;
 
    case 'config-file':
      // For config-file detection, check if parent directory exists
      // (client may be installed but not configured yet)
      Eif (expandedPath) {
        const configDir = expandedPath.replace(/\/[^/]+$/, '');
        if (existsSync(configDir)) {
          result.detected = true;
        }
      }
      break;
  }
 
  // Check if config file exists and if already configured
  Eif (expandedPath) {
    result.configExists = existsSync(expandedPath);
    if (result.configExists) {
      result.alreadyConfigured = isAlreadyConfigured(expandedPath);
    }
  }
 
  return result;
}
 
/**
 * Detect all installed MCP clients
 */
export function detectAllClients(): ClientDetectionResult[] {
  return INSTALLABLE_CLIENTS.map((client) => detectClient(client));
}
 
/**
 * Get list of detected clients (installed on the system)
 */
export function getDetectedClients(): ClientDetectionResult[] {
  return detectAllClients().filter((result) => result.detected);
}
 
/**
 * Get list of clients that are already configured with gitlab-mcp
 */
export function getConfiguredClients(): ClientDetectionResult[] {
  return detectAllClients().filter((result) => result.alreadyConfigured);
}