Skip to main content
Glama
qianniuspace

MCP Security Audit Server

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

TableJSON Schema
NameRequiredDescriptionDefault
dependenciesYesDependencies object from package.json

Implementation Reference

  • 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'}`
            );
        }
    }
  • 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'}`
            );
        }
    }
  • 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}`);
            }
        })
  • 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
    }
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations provided, so description carries full burden. It fails to mention whether the operation is read-only, requires network access, or what happens with the dependencies data.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is one sentence, no unnecessary words. It is concise but slightly under-informative for its brevity.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

No output schema and minimal description leave the return value and behavior undocumented. The nested object type is not elaborated.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema coverage is 100% with a clear description for the parameter. The tool description adds no additional semantic value beyond the schema.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states it audits dependencies for vulnerabilities, using a verb-object structure. However, without sibling tools, differentiation is not necessary.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

No guidance on when to use the tool, prerequisites, or alternatives. The description assumes the agent knows the context.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/qianniuspace/mcp-security-audit'

If you have feedback or need assistance with the MCP directory API, please join our Discord server