diff --git a/v3/@claude-flow/cli/src/mcp-tools/auto-install.ts b/v3/@claude-flow/cli/src/mcp-tools/auto-install.ts new file mode 100644 index 0000000000..40e96516e0 --- /dev/null +++ b/v3/@claude-flow/cli/src/mcp-tools/auto-install.ts @@ -0,0 +1,145 @@ +/** + * Auto-install utility for optional MCP tool dependencies + * + * When an MCP tool requires an optional package that isn't installed, + * this utility attempts to install it automatically on first use. + */ + +import { execSync } from 'child_process'; + +// Track which packages we've attempted to install this session +const installAttempts = new Set(); + +export interface AutoInstallOptions { + /** + * Timeout in milliseconds for npm install (default: 60000) + */ + timeout?: number; + + /** + * Whether to save to package.json (default: false) + */ + save?: boolean; + + /** + * Silent install (no console output) + */ + silent?: boolean; +} + +/** + * Auto-install a package if not available + * + * @param packageName - npm package name to install + * @param options - Installation options + * @returns true if installed successfully or already attempted + */ +export async function autoInstallPackage( + packageName: string, + options: AutoInstallOptions = {} +): Promise { + const { timeout = 60000, save = false, silent = false } = options; + + // Only attempt once per session + if (installAttempts.has(packageName)) { + return false; + } + installAttempts.add(packageName); + + try { + if (!silent) { + console.error(`[claude-flow] Auto-installing ${packageName}...`); + } + + const saveFlag = save ? '--save' : '--no-save'; + execSync(`npm install ${packageName} ${saveFlag}`, { + stdio: silent ? 'pipe' : ['pipe', 'pipe', 'pipe'], + timeout, + }); + + if (!silent) { + console.error(`[claude-flow] Successfully installed ${packageName}`); + } + return true; + } catch (error) { + if (!silent) { + console.error(`[claude-flow] Failed to auto-install ${packageName}: ${error}`); + } + return false; + } +} + +/** + * Try to import a package, auto-install if not found, and retry + * + * @param packageName - npm package name + * @param options - Installation options + * @returns The imported module or null if failed + */ +export async function tryImportOrInstall( + packageName: string, + options: AutoInstallOptions = {} +): Promise { + try { + // First try to import + return await import(packageName) as T; + } catch { + // Package not found, try to install + const installed = await autoInstallPackage(packageName, options); + if (installed) { + try { + // Retry import after installation + return await import(packageName) as T; + } catch { + console.error(`[claude-flow] ${packageName} installed but failed to load. Restart MCP server.`); + return null; + } + } + return null; + } +} + +/** + * Check if a package is available without installing + */ +export async function isPackageAvailable(packageName: string): Promise { + try { + await import(packageName); + return true; + } catch { + return false; + } +} + +/** + * Reset install attempts (useful for testing) + */ +export function resetInstallAttempts(): void { + installAttempts.clear(); +} + +/** + * Optional package dependencies and their purposes + */ +export const OPTIONAL_PACKAGES = { + '@claude-flow/aidefence': { + description: 'AI manipulation defense (prompt injection, PII detection)', + tools: ['aidefence_scan', 'aidefence_analyze', 'aidefence_stats', 'aidefence_learn'], + }, + '@claude-flow/embeddings': { + description: 'Vector embeddings with ONNX support', + tools: ['embeddings_generate', 'embeddings_search', 'embeddings_batch'], + }, + 'onnxruntime-node': { + description: 'ONNX runtime for neural network inference', + tools: ['neural_*'], + }, +} as const; + +export default { + autoInstallPackage, + tryImportOrInstall, + isPackageAvailable, + resetInstallAttempts, + OPTIONAL_PACKAGES, +};