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 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 | /** * MCP Config Repair Module * * Automatically repairs broken or incomplete MCP configurations. * Provides autonomous recovery for common failure scenarios. * * @packageDocumentation */ import { existsSync } from "node:fs"; import { resolve } from "node:path"; import type { AIClientConfig } from "./types.js"; import { type ValidationResult, validateClientConfig } from "./validate.js"; import { getSnapbackMCPConfig, resolveNodePath, writeClientConfig } from "./write.js"; // ============================================================================= // TYPES // ============================================================================= export interface RepairResult { /** Whether repair was successful */ success: boolean; /** Issues that were fixed */ fixed: string[]; /** Issues that remain unfixed */ remaining: string[]; /** Error message if repair failed */ error?: string; } export interface RepairOptions { /** API key for Pro features */ apiKey?: string; /** Workspace ID for tier resolution */ workspaceId?: string; /** Workspace root path (auto-detected if not provided) */ workspaceRoot?: string; /** Whether to force complete reconfiguration */ force?: boolean; } // ============================================================================= // REPAIR FUNCTIONS // ============================================================================= /** * Automatically repair a client's MCP configuration * * @param client - The client to repair * @param options - Repair options * @returns Repair result with fixes applied * * @example * ```ts * const client = getClient('qoder'); * const result = await repairClientConfig(client, { * workspaceRoot: process.cwd() * }); * * if (result.success) { * console.log('Fixed:', result.fixed); * } else { * console.error('Remaining issues:', result.remaining); * } * ``` */ export function repairClientConfig(client: AIClientConfig, options: RepairOptions = {}): RepairResult { const fixed: string[] = []; const remaining: string[] = []; // Validate current config const validation = validateClientConfig(client); // If force, just reconfigure completely if (options.force) { return performFullReconfiguration(client, options); } // If no issues, no repair needed if (validation.valid && validation.issues.length === 0) { return { success: true, fixed: [], remaining: [] }; } // Try to fix each issue for (const issue of validation.issues) { const fixResult = attemptFix(client, issue, validation, options); if (fixResult.success) { fixed.push(issue.message); } else { remaining.push(issue.message); } } // If critical issues remain, do full reconfiguration const hasCriticalErrors = remaining.some((msg) => validation.issues.find((i) => i.message === msg && i.severity === "error"), ); if (hasCriticalErrors) { return performFullReconfiguration(client, options); } return { success: remaining.length === 0, fixed, remaining, }; } /** * Auto-inject workspace path into MCP config * * This is the most common repair needed - automatically detecting * and injecting the correct workspace path when missing. * * @param client - The client to update * @param workspaceRoot - Workspace path (auto-detected if not provided) * @returns Result of the injection */ export function injectWorkspacePath(client: AIClientConfig, workspaceRoot?: string): RepairResult { const fixed: string[] = []; const remaining: string[] = []; // Detect workspace if not provided const detectedWorkspace = workspaceRoot || detectWorkspaceRoot(process.cwd()); if (!detectedWorkspace) { return { success: false, fixed, remaining: ["Could not auto-detect workspace root"], error: "No workspace markers found (.git, package.json, .snapback)", }; } // Validate detected workspace if (!existsSync(detectedWorkspace)) { return { success: false, fixed, remaining: [`Workspace path does not exist: ${detectedWorkspace}`], error: "Invalid workspace path", }; } // Get current config const validation = validateClientConfig(client); if (!validation.config) { return { success: false, fixed, remaining: ["No existing SnapBack config found"], error: "Must run initial configuration first", }; } // Check if using stdio transport if (!validation.config.command) { // Using HTTP transport, no workspace injection needed return { success: true, fixed: ["Config uses HTTP transport - no workspace path needed"], remaining: [], }; } // Check if workspace already set const hasWorkspace = validation.config.args?.includes("--workspace"); if (hasWorkspace) { fixed.push("Workspace path already configured"); return { success: true, fixed, remaining }; } // Inject workspace by full reconfiguration const result = performFullReconfiguration(client, { workspaceRoot: detectedWorkspace, }); if (result.success) { fixed.push(`Injected workspace path: ${detectedWorkspace}`); } return { success: result.success, fixed, remaining }; } // ============================================================================= // HELPER FUNCTIONS // ============================================================================= /** * Attempt to fix a specific issue */ function attemptFix( client: AIClientConfig, issue: ValidationResult["issues"][0], _validation: ValidationResult, options: RepairOptions, ): { success: boolean } { switch (issue.code) { case "CONFIG_NOT_FOUND": case "CONFIG_PARSE_ERROR": case "SNAPBACK_NOT_CONFIGURED": case "MISSING_COMMAND_OR_URL": case "MISSING_ARGS": case "MISSING_MCP_ARG": case "MISSING_STDIO_ARG": case "DEPRECATED_SHIM_COMMAND": case "INVALID_URL": // These require full reconfiguration return performFullReconfiguration(client, options); case "COMMAND_NOT_EXECUTABLE": { // Auto-fix by resolving correct node path // This is the most common issue in IDE environments return performFullReconfiguration(client, options); } case "CLI_PATH_NOT_FOUND": { // Try to find CLI path automatically const cliPath = findCliPath(); if (cliPath) { return performFullReconfiguration(client, options); } return { success: false }; } case "MISSING_WORKSPACE_ARG": { // Try to inject workspace const workspace = options.workspaceRoot || detectWorkspaceRoot(process.cwd()); if (workspace) { return performFullReconfiguration(client, { ...options, workspaceRoot: workspace }); } return { success: false }; } case "WORKSPACE_NOT_FOUND": { // Try to detect correct workspace const detected = detectWorkspaceRoot(process.cwd()); if (detected) { return performFullReconfiguration(client, { ...options, workspaceRoot: detected }); } return { success: false }; } case "WORKSPACE_NO_MARKERS": // Warn but don't fail - workspace might be valid return { success: true }; case "NO_AUTH": // Info only, not an error return { success: true }; default: return { success: false }; } } /** * Perform full reconfiguration * Auto-fixes node path issues by using resolveNodePath() */ function performFullReconfiguration(client: AIClientConfig, options: RepairOptions): RepairResult { try { // Detect workspace if not provided const workspaceRoot = options.workspaceRoot || detectWorkspaceRoot(process.cwd()); const cliPath = findCliPath(); // Determine config mode based on available paths // biome-ignore lint/suspicious/noImplicitAnyLet: type inferred from getSnapbackMCPConfig return type let mcpConfig; if (cliPath && workspaceRoot) { // Local dev mode with proper node path resolution mcpConfig = getSnapbackMCPConfig({ apiKey: options.apiKey, workspaceId: options.workspaceId, workspaceRoot, useLocalDev: true, localCliPath: cliPath, client: client.format, // Pass client format for transport selection }); // Log the node path being used for debugging const nodePath = resolveNodePath(); console.error(`[MCP Repair] Using node path: ${nodePath}`); } else { // Fallback mode - pass client format so stdio-only clients (like Claude Desktop) use npx mcpConfig = getSnapbackMCPConfig({ apiKey: options.apiKey, workspaceId: options.workspaceId, useLocalDev: false, client: client.format, // Pass client format for transport selection }); console.error("[MCP Repair] Using default mode (CLI not found locally)"); } // Write config const writeResult = writeClientConfig(client, mcpConfig); if (writeResult.success) { return { success: true, fixed: ["Full reconfiguration completed (node path resolved)"], remaining: [], }; } return { success: false, fixed: [], remaining: ["Write failed"], error: writeResult.error, }; } catch (error) { return { success: false, fixed: [], remaining: ["Reconfiguration failed"], error: error instanceof Error ? error.message : "Unknown error", }; } } /** * Detect workspace root by traversing upward from current directory */ function detectWorkspaceRoot(startPath: string): string | null { let currentPath = resolve(startPath); const maxIterations = 50; let iterations = 0; while (iterations < maxIterations) { iterations++; // Check for workspace markers const hasGit = existsSync(resolve(currentPath, ".git")); const hasPackageJson = existsSync(resolve(currentPath, "package.json")); const hasSnapback = existsSync(resolve(currentPath, ".snapback")); if (hasGit || hasPackageJson || hasSnapback) { return currentPath; } // Move up one directory const parent = resolve(currentPath, ".."); if (parent === currentPath) { // Reached filesystem root break; } currentPath = parent; } return null; } /** * Find CLI path for local dev mode * Tries common locations relative to current directory */ function findCliPath(): string | undefined { const cwd = process.cwd(); // Try common paths const candidates = [ resolve(cwd, "apps/cli/dist/index.js"), // Monorepo resolve(cwd, "dist/index.js"), // Direct CLI repo resolve(cwd, "../cli/dist/index.js"), // Sibling directory resolve(cwd, "../../apps/cli/dist/index.js"), // Nested monorepo ]; for (const path of candidates) { if (existsSync(path)) { return path; } } return undefined; } |