# Directory Structure ``` ├── .github │ ├── ISSUE_TEMPLATE │ │ ├── bug_report.md │ │ └── feature_request.md │ └── workflows │ └── publish.yml ├── .gitignore ├── .nvmrc ├── CHANGELOG.md ├── CODE_OF_CONDUCT.md ├── Dockerfile ├── images │ ├── cline-config.png │ └── cursor-config.png ├── LICENSE ├── package-lock.json ├── package.json ├── Pitfalls.md ├── public │ ├── no-Severity-response.json │ └── Severity-response.json ├── README.md ├── smithery.yaml ├── src │ ├── handlers │ │ └── security.ts │ ├── index.ts │ ├── test │ │ └── test.ts │ └── types │ ├── index.ts │ └── npm-registry-fetch.d.ts └── tsconfig.json ``` # Files -------------------------------------------------------------------------------- /.nvmrc: -------------------------------------------------------------------------------- ``` 22 ``` -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- ``` node_modules/ *.log .env* build/ dist/ .vscode ``` -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- ```markdown # Security Audit Tool [](https://smithery.ai/server/@qianniuspace/mcp-security-audit) [](https://www.npmjs.com/package/mcp-security-audit) [](https://opensource.org/licenses/MIT) <a href="https://glama.ai/mcp/servers/jjnmdxzmeu"> <img width="380" height="200" src="https://glama.ai/mcp/servers/jjnmdxzmeu/badge" /> </a> A powerful MCP (Model Context Protocol) Server that audits npm package dependencies for security vulnerabilities. Built with remote npm registry integration for real-time security checks. ## Features - 🔍 Real-time security vulnerability scanning - 🚀 Remote npm registry integration - 📊 Detailed vulnerability reports with severity levels - 🛡️ Support for multiple severity levels (critical, high, moderate, low) - 📦 Compatible with npm/pnpm/yarn package managers - 🔄 Automatic fix recommendations - 📋 CVSS scoring and CVE references ### Installing via Smithery To install Security Audit Tool for Claude Desktop automatically via [Smithery](https://smithery.ai/server/@qianniuspace/mcp-security-audit): ```bash npx -y @smithery/cli install @qianniuspace/mcp-security-audit --client claude ``` ### MCP Integration #### Option 1: Using NPX (Recommended) 1. Add MCP configuration to Cline /Cursor: ```json { "mcpServers": { "mcp-security-audit": { "command": "npx", "args": ["-y", "mcp-security-audit"] } } } ``` #### Option 2: Download Source Code and Configure Manually 1. Clone the repository: ```bash git clone https://github.com/qianniuspace/mcp-security-audit.git cd mcp-security-audit ``` 2. Install dependencies and build: ```bash npm install npm run build ``` 3. Add MCP configuration to Cline /Cursor : ```json { "mcpServers": { "mcp-security-audit": { "command": "npx", "args": ["-y", "/path/to/mcp-security-audit/build/index.js"] } } } ``` ## Configuration Screenshots ### Cursor Configuration  ### Cline Configuration  ## API Response Format The tool provides detailed vulnerability information including severity levels, fix recommendations, CVSS scores, and CVE references. ### Response Examples #### 1. When Vulnerabilities Found (Severity-response.json) ```json { "content": [{ "vulnerability": { "packageName": "lodash", "version": "4.17.15", "severity": "high", "description": "Prototype Pollution in lodash", "cve": "CVE-2020-8203", "githubAdvisoryId": "GHSA-p6mc-m468-83gw", "recommendation": "Upgrade to version 4.17.19 or later", "fixAvailable": true, "fixedVersion": "4.17.19", "cvss": { "score": 7.4, "vector": "CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:H/A:N" }, "cwe": ["CWE-1321"], "url": "https://github.com/advisories/GHSA-p6mc-m468-83gw" }, "metadata": { "timestamp": "2024-04-23T10:00:00.000Z", "packageManager": "npm" } }] } ``` #### 2. When No Vulnerabilities Found (no-Severity-response.json) ```json { "content": [{ "vulnerability": null, "metadata": { "timestamp": "2024-04-23T10:00:00.000Z", "packageManager": "npm", "message": "No known vulnerabilities found" } }] } ``` ## Development For development reference, check the example response files in the `public` directory: - [Severity-response.json](public/Severity-response.json) : Example response when vulnerabilities are found (transformed from npm audit API response) - [no-Severity-response.json](public/no-Severity-response.json) : Example response when no vulnerabilities are found (transformed from npm audit API response) Note: The example responses shown above are transformed from the raw npm audit API responses to provide a more structured format. The original npm audit API responses contain additional metadata and may have a different structure. ## Contributing Contributions are welcome! Please read our [Contributing Guide](CODE_OF_CONDUCT.md) for details on our code of conduct and the process for submitting pull requests. ## License This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details. ## Author ESX ([email protected]) ## Links - [GitHub Repository](https://github.com/qianniuspace/mcp-security-audit) - [Issue Tracker](https://github.com/qianniuspace/mcp-security-audit/issues) - [Changelog](CHANGELOG.md) ``` ``` -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- ```markdown # Contributor Covenant Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behaviour that contributes to creating a positive environment include: - Using welcoming and inclusive language - Being respectful of differing viewpoints and experiences - Gracefully accepting constructive criticism - Focusing on what is best for the community - Showing empathy towards other community members Examples of unacceptable behaviours by participants include: - The use of sexualized language or imagery and unwelcome sexual attention or advances - Trolling, insulting/derogatory comments, and personal or political attacks - Public or private harassment - Publishing others' private information, such as a physical or electronic address, without explicit permission - Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behaviour and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behaviour. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviours that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behaviour may be reported by contacting the project team at [email protected]. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html [homepage]: https://www.contributor-covenant.org For answers to common questions about this code of conduct, see https://www.contributor-covenant.org/faq ``` -------------------------------------------------------------------------------- /public/no-Severity-response.json: -------------------------------------------------------------------------------- ```json { "actions": [], "advisories": {}, "muted": [], "metadata": { "vulnerabilities": { "info": 0, "low": 0, "moderate": 0, "high": 0, "critical": 0 }, "dependencies": 1, "devDependencies": 0, "optionalDependencies": 0, "totalDependencies": 1 } } ``` -------------------------------------------------------------------------------- /src/types/npm-registry-fetch.d.ts: -------------------------------------------------------------------------------- ```typescript declare module 'npm-registry-fetch' { interface FetchOptions { method?: string; body?: any; gzip?: boolean; [key: string]: any; } interface NpmFetch { json(url: string, options?: FetchOptions): Promise<any>; } const npmFetch: NpmFetch; export default npmFetch; } ``` -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- ```json { "compilerOptions": { "target": "ES2022", "module": "Node16", "moduleResolution": "Node16", "outDir": "./build", "rootDir": "./src", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true }, "include": ["src/**/*"], "exclude": ["node_modules"] } ``` -------------------------------------------------------------------------------- /smithery.yaml: -------------------------------------------------------------------------------- ```yaml # Smithery configuration file: https://smithery.ai/docs/config#smitheryyaml startCommand: type: stdio configSchema: # JSON Schema defining the configuration options for the MCP. type: object required: [] properties: {} commandFunction: # A function that produces the CLI command to start the MCP on stdio. |- (config) => ({ command: 'node', args: ['build/index.js'], env: {} }) ``` -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- ```markdown # Changelog All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. ### [1.0.4](https://github.com/qianniuspace/mcp-security-audit/compare/v1.0.3...v1.0.4) (2025-02-21) ### [1.0.3](https://github.com/qianniuspace/mcp-security-audit/compare/v1.0.1...v1.0.3) (2025-02-21) ### 1.0.2 (2025-02-20) ### 1.0.1 (2025-02-20) ``` -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- ```markdown --- name: Feature request about: Suggest an idea for this project title: "[FEATURE]" labels: enhancement assignees: StevenStavrakis --- **Is your feature request related to a problem? Please describe.** A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] **Describe the solution you'd like** A clear and concise description of what you want to happen. **Describe alternatives you've considered** A clear and concise description of any alternative solutions or features you've considered. **Additional context** Add any other context or screenshots about the feature request here. ``` -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- ```dockerfile # Generated by https://smithery.ai. See: https://smithery.ai/docs/config#dockerfile # Use the official Node.js 18 image as the base image FROM node:18-alpine AS builder # Set the working directory inside the container WORKDIR /app # Copy package.json and package-lock.json to the working directory COPY package.json package-lock.json ./ # Install dependencies (ignoring scripts to prevent premature build) RUN npm install --ignore-scripts # Copy the rest of the application code to the container COPY . . # Build the TypeScript files RUN npm run build # Final stage: Use a smaller Node.js image to run the application FROM node:18-alpine # Set the working directory inside the container WORKDIR /app # Copy built files from the builder stage COPY --from=builder /app/build /app/build COPY --from=builder /app/package.json /app/package.json COPY --from=builder /app/package-lock.json /app/package-lock.json # Install production dependencies only RUN npm install --omit=dev --ignore-scripts # Command to run the application ENTRYPOINT ["node", "build/index.js"] ``` -------------------------------------------------------------------------------- /src/types/index.ts: -------------------------------------------------------------------------------- ```typescript /** * Type definitions for the security audit system */ /** * Represents a single security vulnerability */ 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 } ``` -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- ```markdown --- name: Bug report about: Report an issue with the mcp-security-audit tool title: "[BUG]" labels: bug assignees: qianniuspace --- **Describe the bug** A clear and concise description of what the bug is. **To Reproduce** Steps to reproduce the behavior: 1. Command or configuration used 2. Package.json content or dependencies being audited 3. Environment details (Node.js version, npm version) 4. Error message or unexpected output **Expected behavior** A clear and concise description of what you expected to happen. **Actual behavior** What actually happened, including any error messages, logs, or unexpected output. **Screenshots** If applicable, add screenshots to help explain your problem. **Environment information:** - OS: [e.g. macOS, Windows, Linux] - Node.js version: [e.g. 18.15.0] - npm version: [e.g. 9.5.0] - mcp-security-audit version: [e.g. 1.0.4] - Integration method: [e.g. npx, local installation, Smithery] - Client used: [e.g. Claude Desktop, Cursor, Cline] **Additional context** Add any other context about the problem here, such as: - Were you auditing a specific package? - Did the issue occur with specific dependency versions? - Any recent changes to your environment? ``` -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- ```json { "name": "mcp-security-audit", "version": "1.0.4", "description": "Audit your package.json dependencies", "author": { "name": "esx", "email": "[email protected]", "url": "https://cloudesx.com/" }, "license": "MIT", "keywords": [ "mcp", "modelcontextprotocol", "package", "audit", "dependencies", "package.json" ], "bugs": { "url": "https://github.com/qianniuspace/mcp-security-audit/issues" }, "homepage": "https://github.com/qianniuspace/mcp-security-audit#readme", "repository": { "type": "git", "url": "git+https://github.com/qianniuspace/mcp-security-audit.git" }, "type": "module", "bin": { "mcp-security-audit": "./build/index.js" }, "files": [ "build" ], "main": "index.js", "scripts": { "build": "tsc && node -e \"require('fs').chmodSync('build/index.js', '755')\"", "prepare": "npm run build", "watch": "tsc --watch", "inspector": "npx @modelcontextprotocol/inspector build/index.js", "bump": "npx -y standard-version --skip.tag && git add . ; git commit -m 'chore: bump version' ; git push" }, "dependencies": { "@modelcontextprotocol/sdk": "^1.5.0", "chalk": "^5.4.1", "npm-audit-report": "^6.0.0", "npm-registry-fetch": "^18.0.2", "zod": "^3.24.2" }, "devDependencies": { "@types/node": "^22.13.4", "typescript": "^5.7.3" } } ``` -------------------------------------------------------------------------------- /.github/workflows/publish.yml: -------------------------------------------------------------------------------- ```yaml name: Publish Package to npmjs on: workflow_dispatch: release: types: [published] push: branches: - main # cancel previous runs if a new one is triggered concurrency: group: ${{ github.workflow }}-${{ github.ref }} jobs: build: runs-on: ubuntu-latest permissions: contents: write id-token: write steps: - uses: actions/checkout@v4 # Setup .npmrc file to publish to npm - uses: actions/setup-node@v4 with: node-version: "22.x" registry-url: "https://registry.npmjs.org" - run: npm install - name: Get version from package.json id: version run: echo "version=$(node -p "require('./package.json').version")" >> $GITHUB_OUTPUT - name: Create Git tag if: ${{ !contains(github.event.head_commit.message, 'chore(release)') && github.event_name != 'workflow_dispatch' }} run: | git config --local user.email "[email protected]" git config --local user.name "GitHub Action" git tag -a "v${{ steps.version.outputs.version }}" -m "Release v${{ steps.version.outputs.version }}" git push origin "v${{ steps.version.outputs.version }}" - name: Create GitHub Release if: ${{ !contains(github.event.head_commit.message, 'chore(release)') && github.event_name != 'workflow_dispatch' }} uses: softprops/action-gh-release@v1 with: tag_name: v${{ steps.version.outputs.version }} name: Release v${{ steps.version.outputs.version }} generate_release_notes: true - run: npm publish --provenance --access public # only if the commit message contains chore(release), or if manually triggered with workflow_dispatch if: ${{ contains(github.event.head_commit.message, 'chore(release)') || github.event_name == 'workflow_dispatch' }} env: NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} ``` -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- ```typescript #!/usr/bin/env node /** * Main server file for the Security Audit MCP Server * Handles tool registration and request processing for security audits */ import { Server } from '@modelcontextprotocol/sdk/server/index.js' import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js' import { CallToolRequestSchema, ErrorCode, ListToolsRequestSchema, McpError, } from '@modelcontextprotocol/sdk/types.js' import { SecurityAuditHandler } from './handlers/security.js' import { NpmDependencies } from './types/index.js' /** * Server class that handles security audit requests * Implements the Model Context Protocol for tool integration */ class SecurityAuditServer { private server: Server private securityHandler: SecurityAuditHandler constructor() { // Initialize MCP server with basic configuration this.server = new Server( { name: 'mcp-security-audit-server', version: '0.1.0', }, { capabilities: { tools: {}, }, } ) // Create security audit handler instance this.securityHandler = new SecurityAuditHandler() this.setupToolHandlers() // Setup error handling this.server.onerror = (error) => console.error('[MCP Error]', error) // Handle graceful shutdown process.on('SIGINT', async () => { await this.server.close() process.exit(0) }) } /** * Setup handlers for tool-related requests * Registers available tools and their handlers */ 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}`); } }) } /** * Start the server using stdio transport */ async run() { const transport = new StdioServerTransport() await this.server.connect(transport) console.error('Security Audit MCP server running on stdio') } } // Create and start server instance const server = new SecurityAuditServer() server.run().catch(console.error) ``` -------------------------------------------------------------------------------- /src/test/test.ts: -------------------------------------------------------------------------------- ```typescript import npmFetch from 'npm-registry-fetch'; import { SecurityAuditHandler } from '../handlers/security.js'; import * as path from 'path'; import * as fs from 'fs'; async function testNpmRegistry() { try { // 测试 1: Registry 连接和完整响应 // console.log('Test 1: Testing npm registry connection and full response...'); // const pingResponse = await npmFetch.json('/-/ping'); // console.log('Registry connection:', pingResponse ? 'OK' : 'Failed'); // console.log('Full ping response:', JSON.stringify(pingResponse, null, 2)); // 测试 2: 单个依赖审计(已知漏洞版本)- 完整响应 console.log('\nTest 2: Testing single dependency audit with full response...'); const handler = new SecurityAuditHandler(); const singleDep = { // 'lodash': '4.17.1', // 多个已知漏洞 // '@modelcontextprotocol/sdk': '1.5.0', "next": "14.2.17" }; console.log('\nSending audit requests for single dependencies:'); for (const [name, version] of Object.entries(singleDep)) { console.log(`\nAuditing ${name}@${version}`); const auditData = { name: "single-dependency-audit", version: "1.0.0", requires: { [name]: version }, dependencies: { [name]: { version: version.replace('^', '') } } }; console.log('Request data:', JSON.stringify(auditData, null, 2)); try { const response = await npmFetch.json('/-/npm/v1/security/audits', { method: 'POST', body: auditData, gzip: true }); console.log('Full API Response:', JSON.stringify(response, null, 2)); } catch (error) { console.error(`Error auditing ${name}:`, error); } } // const singleAuditResult = await handler.auditDependencies({ // dependencies: singleDep, // level: 'low' // }); // console.log('\nProcessed Single Dependency Results:'); // console.log(JSON.stringify(singleAuditResult, null, 2)); // // 测试 3: 多个依赖审计 - 完整响应 // console.log('\nTest 3: Testing multiple dependencies audit with full response...'); // const multipleDeps = { // 'lodash': '4.17.1', // 'express': '4.0.0', // 'moment': '2.0.0' // }; // console.log('\nSending audit requests for multiple dependencies:'); // for (const [name, version] of Object.entries(multipleDeps)) { // console.log(`\nAuditing ${name}@${version}`); // const auditData = { // name: "multiple-dependencies-audit", // version: "1.0.0", // requires: { [name]: version }, // dependencies: { // [name]: { version: version.replace('^', '') } // } // }; // console.log('Request data:', JSON.stringify(auditData, null, 2)); // try { // const response = await npmFetch.json('/-/npm/v1/security/audits', { // method: 'POST', // body: auditData, // gzip: true // }); // console.log('Full API Response:', JSON.stringify(response, null, 2)); // } catch (error) { // console.error(`Error auditing ${name}:`, error); // } // } // const multipleAuditResult = await handler.auditDependencies({ // dependencies: multipleDeps, // level: 'low' // }); // console.log('\nProcessed Multiple Dependencies Results:'); // console.log(JSON.stringify(multipleAuditResult, null, 2)); // 测试 lodash 4.17.1 的漏洞 // console.log('\nTesting [email protected] vulnerabilities...'); // const handler = new SecurityAuditHandler(); // const dependencies = { // "@ai-sdk/deepseek": "^0.1.0" // 已知有漏洞的版本 // }; // try { // const result = await handler.auditDependencies({ dependencies }); // console.log('\nAudit Summary:'); // console.log(JSON.stringify(result, null, 2)); // } catch (error) { // console.error('Error during audit:', error); // } } catch (error) { console.error('Test failed:', error instanceof Error ? error.message : 'Unknown error'); console.error('Full error:', error); process.exit(1); } } // 运行测试 console.log('Starting tests...\n'); testNpmRegistry().catch(error => { console.error('Test execution failed:', error); console.error('Full error details:', error); process.exit(1); }); ``` -------------------------------------------------------------------------------- /src/handlers/security.ts: -------------------------------------------------------------------------------- ```typescript /** * Security audit handler for npm dependencies * Provides functionality to check for vulnerabilities in npm packages */ import { Vulnerability, NpmDependencies } from '../types/index.js'; import { McpError, ErrorCode } from '@modelcontextprotocol/sdk/types.js'; import npmFetch from 'npm-registry-fetch'; export class SecurityAuditHandler { /** * Audits a single dependency for security vulnerabilities * @param name - The name of the package to audit * @param version - The version of the package to audit * @returns Promise containing the audit results */ 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'}` ); } } /** * Main method to audit multiple dependencies * @param dependencies - Object containing package names and versions to audit * @returns Promise containing consolidated audit 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'}` ); } } /** * Process raw vulnerability data into standardized format * @param auditData - Raw audit data from npm registry * @returns Array of processed vulnerabilities */ 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 })); } /** * Generate summary statistics for vulnerabilities * @param vulnerabilities - Array of processed vulnerabilities * @returns Summary object with counts by severity */ private generateSummary(vulnerabilities: Vulnerability[]) { return { total: vulnerabilities.length, critical: vulnerabilities.filter(v => v.severity === 'critical').length, high: vulnerabilities.filter(v => v.severity === 'high').length, moderate: vulnerabilities.filter(v => v.severity === 'moderate').length, low: vulnerabilities.filter(v => v.severity === 'low').length }; } } ``` -------------------------------------------------------------------------------- /public/Severity-response.json: -------------------------------------------------------------------------------- ```json { "actions": [ { "isMajor": false, "action": "install", "resolves": [ { "id": 1085674, "path": "lodash", "dev": false, "optional": false, "bundled": false }, { "id": 1094499, "path": "lodash", "dev": false, "optional": false, "bundled": false }, { "id": 1094500, "path": "lodash", "dev": false, "optional": false, "bundled": false }, { "id": 1096305, "path": "lodash", "dev": false, "optional": false, "bundled": false }, { "id": 1096996, "path": "lodash", "dev": false, "optional": false, "bundled": false }, { "id": 1097130, "path": "lodash", "dev": false, "optional": false, "bundled": false }, { "id": 1097140, "path": "lodash", "dev": false, "optional": false, "bundled": false } ], "module": "lodash", "target": "4.17.21" } ], "advisories": { "1085674": { "findings": [ { "version": "4.17.1", "paths": [ "lodash" ] } ], "found_by": null, "deleted": null, "references": "- https://nvd.nist.gov/vuln/detail/CVE-2019-1010266\n- https://github.com/lodash/lodash/issues/3359\n- https://snyk.io/vuln/SNYK-JS-LODASH-73639\n- https://github.com/lodash/lodash/commit/5c08f18d365b64063bfbfa686cbb97cdd6267347\n- https://github.com/lodash/lodash/wiki/Changelog\n- https://security.netapp.com/advisory/ntap-20190919-0004/\n- https://github.com/advisories/GHSA-x5rq-j2xg-h7qm", "created": "2019-07-19T16:13:07.000Z", "id": 1085674, "npm_advisory_id": null, "overview": "lodash prior to 4.7.11 is affected by: CWE-400: Uncontrolled Resource Consumption. The impact is: Denial of service. The component is: Date handler. The attack vector is: Attacker provides very long strings, which the library attempts to match using a regular expression. The fixed version is: 4.7.11.", "reported_by": null, "title": "Regular Expression Denial of Service (ReDoS) in lodash", "metadata": null, "cves": [ "CVE-2019-1010266" ], "access": "public", "severity": "moderate", "module_name": "lodash", "vulnerable_versions": "<4.17.11", "github_advisory_id": "GHSA-x5rq-j2xg-h7qm", "recommendation": "Upgrade to version 4.17.11 or later", "patched_versions": ">=4.17.11", "updated": "2023-01-09T05:01:38.000Z", "cvss": { "score": 0, "vectorString": null }, "cwe": [ "CWE-400" ], "url": "https://github.com/advisories/GHSA-x5rq-j2xg-h7qm" }, "1094499": { "findings": [ { "version": "4.17.1", "paths": [ "lodash" ] } ], "found_by": null, "deleted": null, "references": "- https://nvd.nist.gov/vuln/detail/CVE-2018-16487\n- https://hackerone.com/reports/380873\n- https://github.com/advisories/GHSA-4xc9-xhrj-v574\n- https://www.npmjs.com/advisories/782\n- https://security.netapp.com/advisory/ntap-20190919-0004/\n- https://github.com/lodash/lodash/commit/90e6199a161b6445b01454517b40ef65ebecd2ad", "created": "2019-02-07T18:16:48.000Z", "id": 1094499, "npm_advisory_id": null, "overview": "Versions of `lodash` before 4.17.11 are vulnerable to prototype pollution. \n\nThe vulnerable functions are 'defaultsDeep', 'merge', and 'mergeWith' which allow a malicious user to modify the prototype of `Object` via `{constructor: {prototype: {...}}}` causing the addition or modification of an existing property that will exist on all objects.\n\n\n\n\n## Recommendation\n\nUpdate to version 4.17.11 or later.", "reported_by": null, "title": "Prototype Pollution in lodash", "metadata": null, "cves": [ "CVE-2018-16487" ], "access": "public", "severity": "high", "module_name": "lodash", "vulnerable_versions": "<4.17.11", "github_advisory_id": "GHSA-4xc9-xhrj-v574", "recommendation": "Upgrade to version 4.17.11 or later", "patched_versions": ">=4.17.11", "updated": "2023-11-01T23:00:56.000Z", "cvss": { "score": 0, "vectorString": null }, "cwe": [ "CWE-400" ], "url": "https://github.com/advisories/GHSA-4xc9-xhrj-v574" }, "1094500": { "findings": [ { "version": "4.17.1", "paths": [ "lodash" ] } ], "found_by": null, "deleted": null, "references": "- https://nvd.nist.gov/vuln/detail/CVE-2020-28500\n- https://github.com/lodash/lodash/pull/5065\n- https://github.com/lodash/lodash/pull/5065/commits/02906b8191d3c100c193fe6f7b27d1c40f200bb7\n- https://github.com/lodash/lodash/blob/npm/trimEnd.js%23L8\n- https://security.netapp.com/advisory/ntap-20210312-0006/\n- https://snyk.io/vuln/SNYK-JS-LODASH-1018905\n- https://snyk.io/vuln/SNYK-JAVA-ORGFUJIONWEBJARS-1074896\n- https://snyk.io/vuln/SNYK-JAVA-ORGWEBJARS-1074894\n- https://snyk.io/vuln/SNYK-JAVA-ORGWEBJARSBOWER-1074892\n- https://snyk.io/vuln/SNYK-JAVA-ORGWEBJARSBOWERGITHUBLODASH-1074895\n- https://snyk.io/vuln/SNYK-JAVA-ORGWEBJARSNPM-1074893\n- https://www.oracle.com//security-alerts/cpujul2021.html\n- https://www.oracle.com/security-alerts/cpuoct2021.html\n- https://www.oracle.com/security-alerts/cpujan2022.html\n- https://www.oracle.com/security-alerts/cpujul2022.html\n- https://cert-portal.siemens.com/productcert/pdf/ssa-637483.pdf\n- https://github.com/lodash/lodash/commit/c4847ebe7d14540bb28a8b932a9ce1b9ecbfee1a\n- https://github.com/advisories/GHSA-29mw-wpgm-hmr9", "created": "2022-01-06T20:30:46.000Z", "id": 1094500, "npm_advisory_id": null, "overview": "All versions of package lodash prior to 4.17.21 are vulnerable to Regular Expression Denial of Service (ReDoS) via the `toNumber`, `trim` and `trimEnd` functions. \n\nSteps to reproduce (provided by reporter Liyuan Chen):\n```js\nvar lo = require('lodash');\n\nfunction build_blank(n) {\n var ret = \"1\"\n for (var i = 0; i < n; i++) {\n ret += \" \"\n }\n return ret + \"1\";\n}\nvar s = build_blank(50000) var time0 = Date.now();\nlo.trim(s) \nvar time_cost0 = Date.now() - time0;\nconsole.log(\"time_cost0: \" + time_cost0);\nvar time1 = Date.now();\nlo.toNumber(s) var time_cost1 = Date.now() - time1;\nconsole.log(\"time_cost1: \" + time_cost1);\nvar time2 = Date.now();\nlo.trimEnd(s);\nvar time_cost2 = Date.now() - time2;\nconsole.log(\"time_cost2: \" + time_cost2);\n```", "reported_by": null, "title": "Regular Expression Denial of Service (ReDoS) in lodash", "metadata": null, "cves": [ "CVE-2020-28500" ], "access": "public", "severity": "moderate", "module_name": "lodash", "vulnerable_versions": "<4.17.21", "github_advisory_id": "GHSA-29mw-wpgm-hmr9", "recommendation": "Upgrade to version 4.17.21 or later", "patched_versions": ">=4.17.21", "updated": "2023-11-01T23:21:12.000Z", "cvss": { "score": 5.3, "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:L" }, "cwe": [ "CWE-400", "CWE-1333" ], "url": "https://github.com/advisories/GHSA-29mw-wpgm-hmr9" }, "1096305": { "findings": [ { "version": "4.17.1", "paths": [ "lodash" ] } ], "found_by": null, "deleted": null, "references": "- https://github.com/lodash/lodash/issues/4744\n- https://github.com/lodash/lodash/commit/c84fe82760fb2d3e03a63379b297a1cc1a2fce12\n- https://nvd.nist.gov/vuln/detail/CVE-2020-8203\n- https://hackerone.com/reports/712065\n- https://github.com/lodash/lodash/issues/4874\n- https://github.com/github/advisory-database/pull/2884\n- https://hackerone.com/reports/864701\n- https://github.com/lodash/lodash/wiki/Changelog#v41719\n- https://web.archive.org/web/20210914001339/https://github.com/lodash/lodash/issues/4744\n- https://security.netapp.com/advisory/ntap-20200724-0006/\n- https://github.com/advisories/GHSA-p6mc-m468-83gw", "created": "2020-07-15T19:15:48.000Z", "id": 1096305, "npm_advisory_id": null, "overview": "Versions of lodash prior to 4.17.19 are vulnerable to Prototype Pollution. The functions `pick`, `set`, `setWith`, `update`, `updateWith`, and `zipObjectDeep` allow a malicious user to modify the prototype of Object if the property identifiers are user-supplied. Being affected by this issue requires manipulating objects based on user-provided property values or arrays.\n\nThis vulnerability causes the addition or modification of an existing property that will exist on all objects and may lead to Denial of Service or Code Execution under specific circumstances.", "reported_by": null, "title": "Prototype Pollution in lodash", "metadata": null, "cves": [ "CVE-2020-8203" ], "access": "public", "severity": "high", "module_name": "lodash", "vulnerable_versions": ">=3.7.0 <4.17.19", "github_advisory_id": "GHSA-p6mc-m468-83gw", "recommendation": "Upgrade to version 4.17.19 or later", "patched_versions": ">=4.17.19", "updated": "2024-01-26T15:32:50.000Z", "cvss": { "score": 7.4, "vectorString": "CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:N/I:H/A:H" }, "cwe": [ "CWE-770", "CWE-1321" ], "url": "https://github.com/advisories/GHSA-p6mc-m468-83gw" }, "1096996": { "findings": [ { "version": "4.17.1", "paths": [ "lodash" ] } ], "found_by": null, "deleted": null, "references": "- https://nvd.nist.gov/vuln/detail/CVE-2021-23337\n- https://github.com/lodash/lodash/commit/3469357cff396a26c363f8c1b5a91dde28ba4b1c\n- https://snyk.io/vuln/SNYK-JS-LODASH-1040724\n- https://github.com/lodash/lodash/blob/ddfd9b11a0126db2302cb70ec9973b66baec0975/lodash.js#L14851\n- https://github.com/lodash/lodash/blob/ddfd9b11a0126db2302cb70ec9973b66baec0975/lodash.js%23L14851\n- https://snyk.io/vuln/SNYK-JAVA-ORGFUJIONWEBJARS-1074932\n- https://snyk.io/vuln/SNYK-JAVA-ORGWEBJARS-1074930\n- https://snyk.io/vuln/SNYK-JAVA-ORGWEBJARSBOWER-1074928\n- https://snyk.io/vuln/SNYK-JAVA-ORGWEBJARSBOWERGITHUBLODASH-1074931\n- https://snyk.io/vuln/SNYK-JAVA-ORGWEBJARSNPM-1074929\n- https://www.oracle.com//security-alerts/cpujul2021.html\n- https://www.oracle.com/security-alerts/cpuoct2021.html\n- https://www.oracle.com/security-alerts/cpujan2022.html\n- https://www.oracle.com/security-alerts/cpujul2022.html\n- https://cert-portal.siemens.com/productcert/pdf/ssa-637483.pdf\n- https://security.netapp.com/advisory/ntap-20210312-0006\n- https://github.com/advisories/GHSA-35jh-r3h4-6jhm", "created": "2021-05-06T16:05:51.000Z", "id": 1096996, "npm_advisory_id": null, "overview": "`lodash` versions prior to 4.17.21 are vulnerable to Command Injection via the template function.", "reported_by": null, "title": "Command Injection in lodash", "metadata": null, "cves": [ "CVE-2021-23337" ], "access": "public", "severity": "high", "module_name": "lodash", "vulnerable_versions": "<4.17.21", "github_advisory_id": "GHSA-35jh-r3h4-6jhm", "recommendation": "Upgrade to version 4.17.21 or later", "patched_versions": ">=4.17.21", "updated": "2024-04-17T18:39:19.000Z", "cvss": { "score": 7.2, "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:H/A:H" }, "cwe": [ "CWE-77", "CWE-94" ], "url": "https://github.com/advisories/GHSA-35jh-r3h4-6jhm" }, "1097130": { "findings": [ { "version": "4.17.1", "paths": [ "lodash" ] } ], "found_by": null, "deleted": null, "references": "- https://nvd.nist.gov/vuln/detail/CVE-2018-3721\n- https://hackerone.com/reports/310443\n- https://github.com/advisories/GHSA-fvqr-27wr-82fm\n- https://www.npmjs.com/advisories/577\n- https://github.com/lodash/lodash/commit/d8e069cc3410082e44eb18fcf8e7f3d08ebe1d4a\n- https://security.netapp.com/advisory/ntap-20190919-0004", "created": "2018-07-26T15:14:52.000Z", "id": 1097130, "npm_advisory_id": null, "overview": "Versions of `lodash` before 4.17.5 are vulnerable to prototype pollution. \n\nThe vulnerable functions are 'defaultsDeep', 'merge', and 'mergeWith' which allow a malicious user to modify the prototype of `Object` via `__proto__` causing the addition or modification of an existing property that will exist on all objects.\n\n\n\n\n## Recommendation\n\nUpdate to version 4.17.5 or later.", "reported_by": null, "title": "Prototype Pollution in lodash", "metadata": null, "cves": [ "CVE-2018-3721" ], "access": "public", "severity": "moderate", "module_name": "lodash", "vulnerable_versions": "<4.17.5", "github_advisory_id": "GHSA-fvqr-27wr-82fm", "recommendation": "Upgrade to version 4.17.5 or later", "patched_versions": ">=4.17.5", "updated": "2024-04-22T19:49:54.000Z", "cvss": { "score": 6.5, "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:N/I:H/A:N" }, "cwe": [ "CWE-471", "CWE-1321" ], "url": "https://github.com/advisories/GHSA-fvqr-27wr-82fm" }, "1097140": { "findings": [ { "version": "4.17.1", "paths": [ "lodash" ] } ], "found_by": null, "deleted": null, "references": "- https://github.com/lodash/lodash/pull/4336\n- https://nvd.nist.gov/vuln/detail/CVE-2019-10744\n- https://snyk.io/vuln/SNYK-JS-LODASH-450202\n- https://www.npmjs.com/advisories/1065\n- https://access.redhat.com/errata/RHSA-2019:3024\n- https://security.netapp.com/advisory/ntap-20191004-0005/\n- https://support.f5.com/csp/article/K47105354?utm_source=f5support&utm_medium=RSS\n- https://www.oracle.com/security-alerts/cpujan2021.html\n- https://www.oracle.com/security-alerts/cpuoct2020.html\n- https://support.f5.com/csp/article/K47105354?utm_source=f5support&%3Butm_medium=RSS\n- https://github.com/advisories/GHSA-jf85-cpcp-j695", "created": "2019-07-10T19:45:23.000Z", "id": 1097140, "npm_advisory_id": null, "overview": "Versions of `lodash` before 4.17.12 are vulnerable to Prototype Pollution. The function `defaultsDeep` allows a malicious user to modify the prototype of `Object` via `{constructor: {prototype: {...}}}` causing the addition or modification of an existing property that will exist on all objects.\n\n## Recommendation\n\nUpdate to version 4.17.12 or later.", "reported_by": null, "title": "Prototype Pollution in lodash", "metadata": null, "cves": [ "CVE-2019-10744" ], "access": "public", "severity": "critical", "module_name": "lodash", "vulnerable_versions": "<4.17.12", "github_advisory_id": "GHSA-jf85-cpcp-j695", "recommendation": "Upgrade to version 4.17.12 or later", "patched_versions": ">=4.17.12", "updated": "2024-04-22T19:49:44.000Z", "cvss": { "score": 9.1, "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:H/A:H" }, "cwe": [ "CWE-20", "CWE-1321" ], "url": "https://github.com/advisories/GHSA-jf85-cpcp-j695" } }, "muted": [], "metadata": { "vulnerabilities": { "info": 0, "low": 0, "moderate": 3, "high": 3, "critical": 1 }, "dependencies": 1, "devDependencies": 0, "optionalDependencies": 0, "totalDependencies": 1 } } ```