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 382 383 384 385 | /** * MCP Config Validation Module * * Validates MCP configurations and detects common issues. * Provides detailed diagnostics for troubleshooting. * * @packageDocumentation */ import { execSync } from "node:child_process"; import { existsSync, readFileSync } from "node:fs"; import { resolve } from "node:path"; import type { AIClientConfig, MCPServerConfig } from "./types.js"; // ============================================================================= // TYPES // ============================================================================= export interface ValidationIssue { /** Severity of the issue */ severity: "error" | "warning" | "info"; /** Issue code for programmatic handling */ code: string; /** Human-readable message */ message: string; /** Suggested fix */ fix?: string; } export interface ValidationResult { /** Whether the config is valid */ valid: boolean; /** List of issues found */ issues: ValidationIssue[]; /** The parsed snapback config (if found) */ config?: MCPServerConfig; } export interface WorkspaceValidation { /** Whether workspace path exists */ exists: boolean; /** Whether workspace has markers (.git, package.json, .snapback) */ hasMarkers: boolean; /** Workspace path being validated */ path?: string; } // ============================================================================= // VALIDATION FUNCTIONS // ============================================================================= /** * Validate an AI client's MCP configuration * * @param client - The client to validate * @returns Validation result with issues * * @example * ```ts * const client = getClient('qoder'); * const result = validateClientConfig(client); * * if (!result.valid) { * for (const issue of result.issues) { * console.error(`${issue.severity}: ${issue.message}`); * if (issue.fix) console.log(`Fix: ${issue.fix}`); * } * } * ``` */ export function validateClientConfig(client: AIClientConfig): ValidationResult { const issues: ValidationIssue[] = []; // Check if config file exists if (!existsSync(client.configPath)) { issues.push({ severity: "error", code: "CONFIG_NOT_FOUND", message: `Config file not found: ${client.configPath}`, fix: `Run: snap tools configure --${client.name}`, }); return { valid: false, issues }; } // Try to read and parse config let configContent: string; let parsedConfig: unknown; try { configContent = readFileSync(client.configPath, "utf-8"); } catch (error) { issues.push({ severity: "error", code: "CONFIG_READ_ERROR", message: `Cannot read config file: ${error instanceof Error ? error.message : "Unknown error"}`, fix: "Check file permissions", }); return { valid: false, issues }; } try { parsedConfig = JSON.parse(configContent); } catch (error) { issues.push({ severity: "error", code: "CONFIG_PARSE_ERROR", message: `Invalid JSON in config file: ${error instanceof Error ? error.message : "Unknown error"}`, fix: `Edit ${client.configPath} to fix JSON syntax, or run: snap tools configure --${client.name} --force`, }); return { valid: false, issues }; } // Check if SnapBack is configured if (!client.hasSnapback) { issues.push({ severity: "warning", code: "SNAPBACK_NOT_CONFIGURED", message: "SnapBack MCP server not found in config", fix: `Run: snap tools configure --${client.name}`, }); return { valid: false, issues }; } // Extract snapback config based on format const snapbackConfig = extractSnapbackConfig(parsedConfig, client.format); if (!snapbackConfig) { issues.push({ severity: "error", code: "SNAPBACK_CONFIG_INVALID", message: "SnapBack config found but cannot be parsed", }); return { valid: false, issues }; } // Validate snapback config structure validateSnapbackConfig(snapbackConfig, issues); // Validate workspace path if present if (snapbackConfig.command && snapbackConfig.args) { const workspaceIdx = snapbackConfig.args.indexOf("--workspace"); if (workspaceIdx !== -1 && workspaceIdx + 1 < snapbackConfig.args.length) { const workspacePath = snapbackConfig.args[workspaceIdx + 1]; const wsValidation = validateWorkspacePath(workspacePath); if (!wsValidation.exists) { issues.push({ severity: "error", code: "WORKSPACE_NOT_FOUND", message: `Workspace path does not exist: ${workspacePath}`, fix: "Update workspace path or run: snap tools configure --force", }); } else if (!wsValidation.hasMarkers) { issues.push({ severity: "warning", code: "WORKSPACE_NO_MARKERS", message: `Workspace path has no markers (.git, package.json, .snapback): ${workspacePath}`, fix: "Run: snap init", }); } } } return { valid: issues.filter((i) => i.severity === "error").length === 0, issues, config: snapbackConfig, }; } /** * Validate workspace path */ export function validateWorkspacePath(workspacePath: string): WorkspaceValidation { const absPath = resolve(workspacePath); if (!existsSync(absPath)) { return { exists: false, hasMarkers: false, path: absPath }; } // Check for workspace markers const hasGit = existsSync(resolve(absPath, ".git")); const hasPackageJson = existsSync(resolve(absPath, "package.json")); const hasSnapback = existsSync(resolve(absPath, ".snapback")); return { exists: true, hasMarkers: hasGit || hasPackageJson || hasSnapback, path: absPath, }; } // ============================================================================= // HELPER FUNCTIONS // ============================================================================= /** * Extract SnapBack config from parsed config file */ function extractSnapbackConfig(parsed: unknown, format: AIClientConfig["format"]): MCPServerConfig | null { if (!parsed || typeof parsed !== "object") { return null; } const config = parsed as Record<string, unknown>; switch (format) { case "claude": case "cursor": case "windsurf": case "vscode": case "cline": case "roo-code": case "qoder": case "gemini": case "zed": // Standard mcpServers format if ("mcpServers" in config && typeof config.mcpServers === "object" && config.mcpServers !== null) { const servers = config.mcpServers as Record<string, unknown>; if ("snapback" in servers) { return servers.snapback as MCPServerConfig; } } return null; case "continue": // Continue uses experimental.modelContextProtocolServers array if ("experimental" in config && typeof config.experimental === "object" && config.experimental !== null) { const experimental = config.experimental as Record<string, unknown>; if ( "modelContextProtocolServers" in experimental && Array.isArray(experimental.modelContextProtocolServers) ) { const server = experimental.modelContextProtocolServers.find( (s: unknown) => typeof s === "object" && s !== null && (s as Record<string, unknown>).name === "snapback", ); return server ? (server as MCPServerConfig) : null; } } return null; default: return null; } } /** * Validate SnapBack config structure */ function validateSnapbackConfig(config: MCPServerConfig, issues: ValidationIssue[]): void { // Must have either command or url if (!config.command && !config.url) { issues.push({ severity: "error", code: "MISSING_COMMAND_OR_URL", message: "Config must have either 'command' (stdio) or 'url' (HTTP)", fix: "Run: snap tools configure --force", }); return; } // If using stdio transport (command), validate structure if (config.command) { // CRITICAL: Validate that command is executable if (!isCommandExecutable(config.command)) { issues.push({ severity: "error", code: "COMMAND_NOT_EXECUTABLE", message: `Command not found or not executable: ${config.command}`, fix: "Run: snap tools repair (will auto-fix node path)", }); } if (!config.args || !Array.isArray(config.args)) { issues.push({ severity: "error", code: "MISSING_ARGS", message: "Command-based config must have 'args' array", fix: "Run: snap tools configure --force", }); } else { // Check for required args if (!config.args.includes("mcp")) { issues.push({ severity: "error", code: "MISSING_MCP_ARG", message: "Args must include 'mcp' command", fix: "Run: snap tools configure --force", }); } if (!config.args.includes("--stdio")) { issues.push({ severity: "error", code: "MISSING_STDIO_ARG", message: "Args must include '--stdio' flag", fix: "Run: snap mcp repair --client <name>", }); } // Check for deprecated 'shim' command (removed in favor of --stdio) if (config.args.includes("shim")) { issues.push({ severity: "error", code: "DEPRECATED_SHIM_COMMAND", message: "Args contain deprecated 'shim' command - use '--stdio' instead", fix: "Run: snap mcp repair --client <name>", }); } // Warn if missing workspace if (!config.args.includes("--workspace")) { issues.push({ severity: "warning", code: "MISSING_WORKSPACE_ARG", message: "Args should include '--workspace' path for reliability", fix: "Run: snap tools configure --force", }); } // Validate CLI path exists (first arg after command) if (config.args.length > 0) { const cliPath = config.args[0]; if (cliPath?.endsWith(".js") && !existsSync(cliPath)) { issues.push({ severity: "error", code: "CLI_PATH_NOT_FOUND", message: `CLI script not found: ${cliPath}`, fix: "Rebuild CLI: pnpm --filter @snapback/cli build", }); } } } } // If using HTTP transport (url), validate if (config.url) { try { new URL(config.url); } catch { issues.push({ severity: "error", code: "INVALID_URL", message: `Invalid server URL: ${config.url}`, fix: "Run: snap tools configure --force", }); } } // Check for API key or workspace ID in env if (config.env) { if (!config.env.SNAPBACK_API_KEY && !config.env.SNAPBACK_WORKSPACE_ID) { issues.push({ severity: "info", code: "NO_AUTH", message: "No API key or workspace ID found (free tier will be used)", }); } } } /** * Check if a command is executable (exists in PATH or is absolute path) * * @param command - Command to check * @returns True if command is likely executable */ function isCommandExecutable(command: string): boolean { // If it's an absolute path, check if file exists if (command.startsWith("/") || command.match(/^[A-Z]:\\/i)) { return existsSync(command); } // For relative commands, try to find them try { const isWindows = process.platform === "win32"; const cmd = isWindows ? `where ${command}` : `which ${command}`; execSync(cmd, { encoding: "utf-8", timeout: 5000 }); return true; } catch { return false; } } |