{"record":{"id":"5ac1073d34135483","repo":"ruvnet/ruflo","slug":"aidefence-package-not-available-install-with-npm","errorCode":null,"errorMessage":"AIDefence package not available. Install with: npm install @claude-flow/aidefence","messagePattern":"AIDefence package not available\\. Install with: npm install @claude-flow/aidefence","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"v3/@claude-flow/cli/src/mcp-tools/security-tools.ts","lineNumber":75,"sourceCode":"    const aidefence = await import(packageName);\n    const instance = aidefence.createAIDefence({ enableLearning: true });\n    if (!instance) {\n      throw new Error('createAIDefence returned null');\n    }\n    aidefenceInstance = instance;\n    return instance;\n  } catch (e) {\n    // Package not found or failed to load\n    const error = e as Error;\n    if (!error.message?.includes('Cannot find package') && !error.message?.includes('ERR_MODULE_NOT_FOUND')) {\n      // Different error - might be a real issue\n      throw new Error(`AIDefence failed to load: ${error.message}`);\n    }\n  }\n\n  // Don't attempt install more than once per session\n  if (installAttempted) {\n    throw new Error('AIDefence package not available. Install with: npm install @claude-flow/aidefence');\n  }\n  installAttempted = true;\n\n  // Second attempt - auto-install and retry\n  console.error(`[claude-flow] ${packageName} not found, attempting auto-install...`);\n  const installed = await autoInstallPackage(packageName);\n\n  if (!installed) {\n    throw new Error('AIDefence package not available. Install with: npm install @claude-flow/aidefence');\n  }\n\n  // #1807 — auto-install lands the package somewhere Node's standard\n  // resolver couldn't find on the FIRST attempt (npm-global installs are\n  // a common offender). Try Node's resolver again first (it may have\n  // picked up the new node_modules directory), then fall back to the\n  // file:// + cache-bust import dance, then surface a clearly actionable\n  // error if everything still fails.\n  // Plain re-import (covers project-local installs that landed where Node","sourceCodeStart":57,"sourceCodeEnd":93,"githubUrl":"https://github.com/ruvnet/ruflo/blob/fa13ee4ad60ac2090b1480656eb233521790d640/v3/@claude-flow/cli/src/mcp-tools/security-tools.ts#L57-L93","documentation":"The AIDefence loader auto-installs the optional @claude-flow/aidefence package at most once per process (module-level `installAttempted` flag). This variant is thrown when a load is attempted again in the same session after an earlier attempt already tried (and failed) to install — the short-circuit fires before any new install is attempted. The message tells you the durable fix is a manual install or a server restart.","triggerScenarios":"First call to a security tool triggered auto-install which failed silently from the caller's perspective; a second call to any AIDefence-backed tool in the same MCP session then throws this immediately. Also hit when the package was installed to a location Node still can't resolve: the flag is set, so no retry occurs.","commonSituations":"Long-running MCP server where the first scan failed and users retry the tool; installing into the wrong directory (global CLI run from a project-less cwd); offline first attempt then network restored — the session never retries automatically.","solutions":["Install the package where the server resolves modules: npm install --save @claude-flow/aidefence in the working directory the MCP server runs from.","Restart the MCP server after installing — the per-session flag and module cache both reset.","Or run via npx ruflo@latest mcp start from a directory whose node_modules contains the package.","Check installability once at startup (see validation) so the first real tool call never depends on auto-install."],"exampleFix":"# before (mid-session retry keeps failing)\n> security_scan ...  # error: AIDefence package not available\n> security_scan ...  # same error, installAttempted already true\n\n# after\nnpm install --save @claude-flow/aidefence\n# restart the MCP server, then retry the tool","handlingStrategy":"validation","validationCode":"import { createRequire } from 'node:module';\nconst require = createRequire(import.meta.url);\nfunction aidefenceResolvable(): boolean {\n  try { require.resolve('@claude-flow/aidefence'); return true; } catch { return false; }\n}\n// At MCP server startup:\nif (!aidefenceResolvable()) {\n  console.error('[setup] @claude-flow/aidefence missing — run: npm install --save @claude-flow/aidefence');\n  // install NOW, before any tool call, so the once-per-session auto-install budget isn't wasted\n}","typeGuard":null,"tryCatchPattern":"try {\n  return await securityScan(input);\n} catch (e) {\n  if (e instanceof Error && e.message.includes('AIDefence package not available')) {\n    disableToolCategory('aidefence'); // stop retrying this session; surface install instructions\n    return { error: 'Install @claude-flow/aidefence and restart the MCP server to enable security scanning.' };\n  }\n  throw e;\n}","preventionTips":["Install the package before the server starts (Dockerfile/CI) instead of relying on runtime auto-install.","Check resolvability once at startup and log a clear action item — the auto-install runs at most once per process.","Restart the MCP server after any manual install; the module-level flag and import cache are per-process."],"tags":["security","aidefence","missing-dependency","npm","session-state"],"backgroundTag":"missing-optional-dependency","analyzedSha":"fa13ee4ad60ac2090b1480656eb233521790d640","analyzedAt":"2026-08-18T21:34:22.708Z","contentChangedAt":"2026-08-18T21:34:22.708Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}