audit_nodejs_dependencies
Audit Node.js dependencies from package.json for security vulnerabilities. Provides detailed reports and remediation advice.
Instructions
Audit specific dependencies for vulnerabilities
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| dependencies | Yes | Dependencies object from package.json |
Implementation Reference
- src/handlers/security.ts:64-113 (handler)Main handler function that audits multiple npm dependencies. Iterates over dependencies, calls auditSingleDependency for each, processes vulnerabilities, and returns consolidated results.
async auditNodejsDependencies(args: { dependencies: NpmDependencies }) { try { // Validate dependencies object if (!args || typeof args.dependencies !== 'object') { throw new McpError( ErrorCode.InvalidParams, 'Invalid dependencies object' ); } // Handle potentially nested dependencies object const actualDeps = args.dependencies.dependencies || args.dependencies; const auditResults = []; for (const [name, version] of Object.entries(actualDeps)) { if (typeof version !== 'string') continue try { const result = await this.auditSingleDependency(name, version); auditResults.push(result); } catch (error) { console.error(`[ERROR] Failed to audit ${name}@${version}:`, error); // Continue processing other dependencies } } // Merge and process all vulnerability results const mergedVulnerabilities = auditResults.flatMap(result => this.processVulnerabilities(result) ); // Return consolidated results return { content: [ { type: 'text', text: JSON.stringify(mergedVulnerabilities, null, 2), }, ] }; } catch (error) { console.error('[ERROR] Audit failed:', error); if (error instanceof McpError) { throw error; } throw new McpError( ErrorCode.InternalError, `Audit failed: ${error instanceof Error ? error.message : 'Unknown error'}` ); } } - src/handlers/security.ts:18-57 (handler)Private helper that audits a single npm dependency by calling the npm registry security audit API. Validates input, cleans version strings, and sends POST request to /-/npm/v1/security/audits.
private async auditSingleDependency(name: string, version: string): Promise<any> { try { // Validate input parameters if (!name || !version) { throw new Error(`Invalid package name or version: ${name}@${version}`); } // Clean version string by removing prefix characters (^ or ~) const cleanVersion = version.trim().replace(/^[\^~]/, ''); // Prepare audit data structure const auditData = { name: "single-dependency-audit", version: "1.0.0", requires: { [name]: cleanVersion }, dependencies: { [name]: { version: cleanVersion } } }; // Send audit request to npm registry const result = await npmFetch.json('/-/npm/v1/security/audits', { method: 'POST', body: auditData, gzip: true }); if (!result) { throw new Error(`No response received for ${name}@${cleanVersion}`); } return result; } catch (error) { console.error(`[ERROR] Error auditing ${name}@${version}:`, error); throw new McpError( ErrorCode.InternalError, `Failed to audit ${name}@${version}: ${error instanceof Error ? error.message : 'Unknown error'}` ); } } - src/handlers/security.ts:120-138 (handler)Private helper that processes raw audit data from npm registry into standardized Vulnerability objects.
private processVulnerabilities(auditData: any): Vulnerability[] { if (!auditData.advisories || Object.keys(auditData.advisories).length === 0) { return []; } const advisories = auditData.advisories; return Object.values(advisories).map((advisory: any) => ({ name: advisory.module_name, version: advisory.vulnerable_versions, severity: advisory.severity, description: advisory.overview, recommendation: advisory.recommendation, fixAvailable: !!advisory.patched_versions, fixedVersion: advisory.patched_versions, githubAdvisoryId: advisory.github_advisory_id, updatedAt: advisory.updated, moreInfo: advisory.url })); } - src/index.ts:59-102 (registration)Tool registration in ListToolsRequestSchema handler (name, description, inputSchema) and routing in CallToolRequestSchema switch case that dispatches to securityHandler.auditNodejsDependencies.
private setupToolHandlers() { // Register available tools this.server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: [ { name: 'audit_nodejs_dependencies', description: 'Audit specific dependencies for vulnerabilities', inputSchema: { type: 'object', properties: { dependencies: { type: 'object', additionalProperties: { type: 'string', }, description: 'Dependencies object from package.json', } }, required: ['dependencies'], }, }, ], })) // Handle tool execution requests this.server.setRequestHandler(CallToolRequestSchema, async (request) => { // Validate request parameters if (!request.params.arguments) { throw new McpError( ErrorCode.InvalidParams, 'Missing arguments' ) } // Route request to appropriate handler switch (request.params.name) { case 'audit_nodejs_dependencies': return this.securityHandler.auditNodejsDependencies( request.params.arguments as { dependencies: NpmDependencies } ); default: throw new McpError(ErrorCode.MethodNotFound, `Unknown tool: ${request.params.name}`); } }) - src/types/index.ts:8-33 (schema)Type definitions: Vulnerability interface (name, version, severity, description, etc.) and NpmDependencies interface (package name -> version mapping).
export interface Vulnerability { name: string; // Package name version: string; // Affected version range severity: string; // Severity level (critical, high, moderate, low) description: string; // Detailed description of the vulnerability recommendation: string; // Recommended action to fix the vulnerability fixAvailable: boolean; // Whether a fix is available fixedVersion?: string; // Version that fixes the vulnerability // references: string[]; githubAdvisoryId?: string; // GitHub Security Advisory ID updatedAt?: string; // Last update timestamp cvss?: { // Common Vulnerability Scoring System score: number; vector: string; }; cwe?: string[]; // Common Weakness Enumeration identifiers url?: string; // URL for more information } /** * Represents a map of package names to their versions */ export interface NpmDependencies { [key: string]: string; // Package name -> version mapping }