Doramagic Project Pack · Human Manual

npm-mcp

npm-mcp is an open-source MCP server that bridges AI assistants with the npm registry ecosystem. It enables AI-powered tools to perform sophisticated package analysis without leaving the A...

Home

Related topics: Installation, MCP Tools Overview

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Core Components

Continue reading this section for the full explanation and source context.

Section Registry Client Features

Continue reading this section for the full explanation and source context.

Section Tool Reference

Continue reading this section for the full explanation and source context.

Related topics: Installation, MCP Tools Overview

Home

Welcome to the npm-mcp (npm Registry MCP Server) documentation. This is a Model Context Protocol (MCP) server that provides AI assistants with comprehensive access to the npm registry for package discovery, security auditing, compatibility checking, and more.

Overview

npm-mcp is an open-source MCP server that bridges AI assistants with the npm registry ecosystem. It enables AI-powered tools to perform sophisticated package analysis without leaving the AI environment.

Key capabilities include:

  • Package search and discovery with relevance ranking
  • Security vulnerability auditing via npm advisory data
  • Version compatibility checking against existing dependencies
  • Quality analysis based on GitHub metrics and community indicators
  • Bundle size analysis for performance optimization
  • NPX command validation and safety checks

Source: README.md

Architecture

npm-mcp follows a modular architecture with clear separation of concerns. The system consists of three primary layers: the MCP protocol interface, tool handlers, and the registry client.

graph TD
    subgraph "MCP Protocol Layer"
        A[MCP Client] -->|JSON-RPC| B[Server Entry<br/>src/index.ts]
    end
    
    subgraph "Tool Handlers"
        B --> C[search_packages]
        B --> D[get_package_details]
        B --> E[audit_security]
        B --> F[check_compatibility]
        B --> G[analyze_quality]
        B --> H[compare_versions]
        B --> I[analyze_npx_command]
    end
    
    subgraph "Data Layer"
        C --> J[Registry Client]
        D --> J
        E --> J
        F --> J
        G --> J
        H --> J
        I --> J
        
        J -->|npmjs.org API| K[NPM Registry]
        J -->|GitHub API| L[GitHub API]
        J -->|bundlephobia.com| M[Bundlephobia API]
        J -->|download stats| N[CDN Downloads API]
    end
    
    subgraph "Infrastructure"
        J -->|5min TTL| O[LRU Cache]
        J -->|rate limit| P[Circuit Breaker]
        J -->|retry logic| Q[Exponential Backoff]
    end

Core Components

ComponentFilePurpose
Server Entrysrc/index.tsMCP protocol handling, tool registration, request routing
Registry Clientsrc/registry-client.tsHTTP client with caching, rate limiting, retry logic
Type Definitionssrc/types.tsShared TypeScript interfaces and types
Tool Handlerssrc/tools/*.tsIndividual MCP tool implementations

Source: DEVELOPMENT.md - Architecture

Registry Client Features

The registry client provides robust infrastructure for API communication:

  • Concurrency Limit: Maximum 10 concurrent requests
  • LRU Cache: 5-minute TTL for package metadata and download stats
  • Rate Limiting: Exponential backoff on HTTP 429 responses
  • Error Handling: Graceful degradation with descriptive error messages

Source: src/registry-client.ts

Available Tools

npm-mcp provides eight distinct tools for package analysis and management.

Tool Reference

ToolInput ParametersPurpose
search_packagesquery, limit?Search npm registry with ranked results
get_package_detailspackageName, version?Retrieve comprehensive package metadata
audit_securitypackageName, version?Check for known vulnerabilities
check_compatibilitypackageName, version?, existingDependenciesVerify peer dependency compatibility
analyze_qualitypackageNameScore based on GitHub metrics and community
compare_versionspackageName, fromVersion, toVersionAnalyze breaking changes between versions
analyze_npx_commandcommand, args?, timeout?Validate NPX commands before execution
analyze_capabilitiespackageNameAnalyze module systems and TypeScript support

Source: DEVELOPMENT.md - Tool reference

Search Packages

The search_packages tool enables full-text search across the npm registry with relevance scoring.

// Example input
{
  "query": "react state management",
  "limit": 10
}

Returns: Ranked list of packages with scores, descriptions, and download counts.

Source: DEVELOPMENT.md - search_packages

Security Audit

The audit_security tool queries npm's advisory database to identify vulnerabilities.

// Example output
{
  "success": true,
  "package": "axios",
  "version": "1.6.0",
  "vulnerabilities": [],
  "recommendation": "No known vulnerabilities"
}

Source: AI_USAGE.md - audit_security

Version Compatibility

The check_compatibility tool validates peer dependencies against your project's existing dependencies.

// Example input
{
  "packageName": "react-dom",
  "version": "18.2.0",
  "existingDependencies": {
    "react": "^18.0.0"
  }
}

Returns: Compatibility status, conflicting dependencies, and suggested resolutions.

Source: src/tools/version-compatibility.ts

Quality Analysis

The analyze_quality tool evaluates packages based on:

  • Popularity metrics (weekly downloads)
  • Maintenance status (last update, repository health)
  • Community engagement (GitHub stars, issues, contributors)
  • Bundle size impact

Source: PRODUCTIVITY.md

MCP Prompts

npm-mcp includes smart prompts that serve as shortcuts for common AI workflows.

Available Prompts

PromptDescription
/check_before_installFull security and compatibility check before installing
/find_packageSearch, compare, and recommend packages for a use case
/audit_projectScan all dependencies in a package.json
/analyze_bundleAnalyze bundle size and tree-shaking support

Source: PROMPTS.md

Check Before Install

The most frequently used prompt. It combines security auditing, compatibility checking, and maintenance analysis into a single command:

/check_before_install express

Output:

[email protected] is safe to install

Security: No known vulnerabilities
Compatibility: ✅ No peer dependency conflicts
Maintenance: Active (last update: 2 days ago)

Install: npm install [email protected]

Source: PROMPTS.md - /check_before_install

Installation and Setup

Prerequisites

  • Node.js 18.0 or higher (uses native fetch)
  • npm, yarn, or pnpm package manager

Source: DEVELOPMENT.md - Setup

Quick Start

# Clone the repository
git clone https://github.com/alisaitteke/npm-mcp.git
cd npm-mcp

# Install dependencies
npm install

# Build the project
npm run build

Source: DEVELOPMENT.md - Setup

Available Scripts

CommandDescription
npm run buildCompile TypeScript to dist/ directory
npm testRun test suite with Vitest
npm run test:coverageGenerate coverage report
npm run typecheckRun TypeScript type checking
npm run devWatch mode for development

Source: DEVELOPMENT.md - Scripts

AI Integration Patterns

npm-mcp is designed to enhance AI assistants with npm package intelligence. The tools work together to provide comprehensive package analysis.

graph LR
    A[User Request] --> B{Intent Detection}
    
    B -->|Search/Find| C[search_packages]
    B -->|Install/Add| D[audit_security]
    B -->|Check Compatibility| E[check_compatibility]
    B -->|Compare Options| F[compare_packages]
    B -->|NPX Command| G[analyze_npx_command]
    
    C --> H[Package Details]
    D --> I[Quality Analysis]
    E --> J[Version Compare]
    
    H --> K[Response with<br/>Recommendations]
    I --> K
    J --> K
    F --> K
    G --> K

Automatic Workflows

AI assistants can use npm-mcp tools automatically based on user intent:

TriggerTool(s) CalledPurpose
"install X", "add X"audit_security + check_compatibilityValidate before installation
"which package", "best library"search_packagesFind and compare options
"npx create-..."analyze_npx_commandValidate before execution
Mentions package nameget_package_detailsShow info proactively
"update X", "upgrade X"compare_versions + audit_securityShow changes and security
Pastes package.jsonaudit_security (all deps)Security report

Source: AI_USAGE.md

Configuration for AI Platforms

For Cursor Desktop, add to ~/.cursor/.cursorrules:

# Global NPM Safety Rules

For ANY project with package.json:
- Before suggesting npm install: use npm-registry-mcp audit_security
- On package.json edit: scan new dependencies
- On npx mention: use npm-registry-mcp analyze_npx_command
- Auto-suggest updates for vulnerable packages

Source: AI_USAGE.md - Cursor Rules

Project Structure

npm-mcp/
├── src/
│   ├── index.ts                 # MCP server entry point
│   ├── registry-client.ts       # NPM API client with cache/retry
│   ├── types.ts                 # TypeScript type definitions
│   └── tools/
│       ├── search-packages.ts   # Package search tool
│       ├── package-details.ts   # Package metadata retrieval
│       ├── security-audit.ts    # Vulnerability scanning
│       ├── version-compatibility.ts  # Peer dependency checking
│       ├── quality-analysis.ts # GitHub metrics and quality scoring
│       └── npx-command.ts       # NPX command validation
├── test/                        # Vitest test suite
├── bin/
│   └── npm-registry-mcp.js      # CLI entry point for npx
├── server.json                  # MCP registry metadata
├── package.json                 # Project dependencies
└── tsconfig.json               # TypeScript configuration

Source: DEVELOPMENT.md - Project structure

Adding New Tools

To extend npm-mcp with additional tools:

  1. Create the tool file in src/tools/<name>.ts:
import { z } from 'zod';
import { RegistryClient } from '../registry-client.js';

export const MyToolSchema = z.object({
  param: z.string(),
});

export async function myTool(
  params: z.infer<typeof MyToolSchema>,
  client: RegistryClient
): Promise<string> {
  // Implementation
}
  1. Register the tool in src/index.ts:
  • Add to ListToolsRequestSchema
  • Add handler to CallToolRequestSchema
  1. Add tests in test/<name>.test.ts

Source: DEVELOPMENT.md - Adding a new tool

Troubleshooting

Server Won't Start

# Verify Node.js version
node --version

# Rebuild the project
npm run build

# Make bin executable
chmod +x bin/npm-registry-mcp.js

Source: DEVELOPMENT.md - Troubleshooting

GitHub Rate Limits

Quality analysis tools use the GitHub API. Unauthenticated requests are limited to 60 requests per hour. Some package quality checks may fail for heavily analyzed packages.

Source: DEVELOPMENT.md - GitHub rate limits

Test Failures

# Clean reinstall
rm -rf node_modules package-lock.json
npm install
npm run build
npm test

Source: DEVELOPMENT.md - Test fails

Contributing

We welcome contributions! Please follow these guidelines:

Branch Naming

  • feature/ — New features
  • fix/ — Bug fixes
  • docs/ — Documentation updates
  • test/ — Test additions
  • refactor/ — Code refactoring

Source: CONTRIBUTING.md - Branch Naming

Commit Messages

Follow conventional commits format:

feat: add new search filter
fix: resolve caching issue
docs: update README examples
test: add coverage for quality analysis
refactor: simplify version comparison logic

Source: CONTRIBUTING.md - Commit Messages

Pull Request Process

  1. Create a feature branch: git checkout -b feature/my-feature
  2. Make your changes and add tests
  3. Run validation: npm test, npm run test:coverage, npm run typecheck
  4. Commit and push
  5. Open a pull request with clear description and linked issues

Source: CONTRIBUTING.md - Pull Request Process

See Also

Source: https://github.com/alisaitteke/npm-mcp / Human Manual

Installation

Related topics: Home, Configuration

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Method 1: NPX (Recommended for Quick Testing)

Continue reading this section for the full explanation and source context.

Section Method 2: Clone from GitHub

Continue reading this section for the full explanation and source context.

Section Cursor Configuration

Continue reading this section for the full explanation and source context.

Related topics: Home, Configuration

Installation

This page provides comprehensive instructions for setting up and configuring the npm-mcp (NPM Registry MCP Server) in your development environment.

Overview

The npm-mcp is a Model Context Protocol (MCP) server that provides AI assistants with direct access to npm registry data. It enables automated security audits, package compatibility checks, quality analysis, and version comparisons without leaving your development workflow.

Source: DEVELOPMENT.md

Prerequisites

Before installing npm-mcp, ensure your system meets the following requirements:

RequirementVersionNotes
Node.js18+Native fetch API required
npmLatest stableFor package installation
GitAny recent versionFor cloning repository

You can verify your Node.js version with:

node --version

Source: DEVELOPMENT.md

Installation Methods

The simplest way to run npm-mcp without installation is using npx:

npx npm-registry-mcp

This method automatically downloads and executes the latest version from the npm registry.

Source: DEVELOPMENT.md

Method 2: Clone from GitHub

For development or customization purposes, clone the repository:

git clone https://github.com/alisaitteke/npm-mcp.git
cd npm-mcp
npm install
npm run build

Source: CONTRIBUTING.md

Installation Workflow

graph TD
    A[Start Installation] --> B{Check Prerequisites}
    B -->|Node.js < 18| E[Update Node.js]
    B -->|Node.js >= 18| C[Clone Repository]
    E --> C
    C --> D[Install Dependencies]
    D --> F[Build Project]
    F --> G{Run Tests?}
    G -->|Yes| H[Execute Test Suite]
    G -->|No| I[Installation Complete]
    H --> I
    I --> J[Configure MCP Client]
    J --> K[Start Using npm-mcp]

Project Structure

After cloning, the project structure is organized as follows:

npm-mcp/
├── src/
│   ├── index.ts              # MCP server entry point
│   ├── registry-client.ts    # NPM API client implementation
│   ├── types.ts               # Shared TypeScript type definitions
│   └── tools/
│       ├── search-packages.ts
│       ├── package-details.ts
│       ├── security-audit.ts
│       ├── version-compatibility.ts
│       ├── quality-analysis.ts
│       └── npx-command.ts
├── test/                      # Vitest test files
├── bin/
│   └── npm-registry-mcp.js    # CLI entry point for npx
├── server.json               # MCP registry metadata
└── package.json              # Project dependencies and scripts

Source: DEVELOPMENT.md

Available npm Scripts

The project includes several npm scripts for common tasks:

CommandDescription
npm run buildCompiles TypeScript to JavaScript in dist/ directory
npm testRuns the Vitest test suite
npm run test:coverageGenerates code coverage report
npm run typecheckRuns TypeScript type checking without emitting files
npm run devWatches for changes and rebuilds automatically

Source: DEVELOPMENT.md

Configuring MCP Clients

Cursor Configuration

Add npm-mcp to your Cursor MCP settings:

{
  "mcpServers": {
    "npm-registry-mcp": {
      "command": "npx",
      "args": ["npm-registry-mcp"]
    }
  }
}

Claude Desktop Configuration

For Claude Desktop users, add to your claude_desktop_config.json:

{
  "mcpServers": {
    "npm-registry-mcp": {
      "command": "npx",
      "args": ["npm-registry-mcp"]
    }
  }
}

Source: AI_USAGE.md

Architecture Overview

The npm-mcp server uses a layered architecture:

graph TD
    A[MCP Client<br/>Cursor/Claude] --> B[Index.ts<br/>Request Router]
    B --> C[Tool Handlers]
    C --> D[search_packages]
    C --> E[get_package_details]
    C --> F[audit_security]
    C --> G[check_compatibility]
    C --> H[analyze_quality]
    C --> I[compare_versions]
    C --> J[analyze_npx_command]
    D --> K[Registry Client]
    E --> K
    F --> K
    G --> K
    H --> K
    I --> K
    J --> K
    K --> L[External APIs]
    L --> M[npm Registry API]
    L --> N[Bundlephobia API]
    L --> O[GitHub API]

Source: src/index.ts

Registry Client Configuration

The internal registry client handles API communication with npm services:

SettingValueDescription
Concurrency Limit10Maximum simultaneous requests
Cache TTL5 minutesTime before cached data expires
Rate Limit StrategyExponential backoffRetries on HTTP 429 responses

Source: src/registry-client.ts

Troubleshooting Installation

Server Won't Start

If the server fails to start:

``bash node --version ``

  1. Verify Node.js version - Ensure you have Node.js 18 or higher:

``bash npm run build ``

  1. Rebuild the project - Clear and rebuild:

``bash chmod +x bin/npm-registry-mcp.js ``

  1. Check binary permissions - For npx execution:

Source: DEVELOPMENT.md

GitHub Rate Limits

The analyze_quality tool uses the GitHub API. Unauthenticated requests are limited to 60 requests per hour. Some quality analysis operations may fail for packages with large GitHub datasets.

Source: DEVELOPMENT.md

Tests Fail

If the test suite fails, try a clean installation:

rm -rf node_modules package-lock.json
npm install
npm run build
npm test

Source: DEVELOPMENT.md

Verification

After installation, verify that npm-mcp is working correctly by checking if the server responds to tool requests. The available tools include:

  • search_packages - Search npm registry for packages
  • get_package_details - Retrieve detailed package information
  • audit_security - Check for security vulnerabilities
  • check_compatibility - Verify peer dependency compatibility
  • analyze_quality - Assess package quality metrics
  • compare_versions - Compare package versions
  • analyze_npx_command - Validate npx command execution

Source: DEVELOPMENT.md

Next Steps

After successful installation, consider:

  1. Configure AI Integration - Set up npm-mcp in your preferred AI assistant (Cursor, Claude Desktop)
  2. Review Available Tools - Familiarize yourself with the MCP tools available
  3. Try Example Workflows - Test security checks before installing packages
  4. Contribute - See CONTRIBUTING.md for development guidelines

Source: CONTRIBUTING.md

See Also

Source: https://github.com/alisaitteke/npm-mcp / Human Manual

Configuration

Related topics: Installation, Tool Reference

Section Related Pages

Continue reading this section for the full explanation and source context.

Section server.json

Continue reading this section for the full explanation and source context.

Section Tool Registration

Continue reading this section for the full explanation and source context.

Section Architecture

Continue reading this section for the full explanation and source context.

Related topics: Installation, Tool Reference

Configuration

This page documents the configuration architecture for npm-mcp, covering MCP server configuration, registry client settings, tool-specific parameters, and environment-based customization.

Overview

npm-mcp is a Model Context Protocol (MCP) server that provides AI assistants with tools to interact with the npm registry. The project uses a layered configuration approach:

  1. MCP Protocol Configuration - Server metadata and tool definitions in server.json
  2. Registry Client Configuration - HTTP client settings, caching, and rate limiting
  3. Tool Configuration - Individual tool input schemas and parameters
  4. Build Configuration - TypeScript and package build settings

Source: DEVELOPMENT.md

MCP Server Configuration

server.json

The server.json file defines MCP registry metadata that enables AI platforms to discover and connect to the npm-mcp server.

{
  "name": "npm-registry-mcp",
  "version": "1.0.0",
  "description": "MCP server for npm registry operations"
}

Source: DEVELOPMENT.md

Tool Registration

Tools are registered in src/index.ts using the MCP SDK's ListToolsRequestSchema and CallToolRequestSchema handlers. Each tool must be:

  1. Listed in the tools array with its Zod schema
  2. Connected to a handler function in the call handler
// List available tools
case 'list_tools':
  return {
    tools: [
      { name: 'search_packages', description: 'Search npm registry', inputSchema: SearchPackagesSchema },
      { name: 'get_package_details', description: 'Get package details', inputSchema: PackageDetailsSchema },
      { name: 'audit_security', description: 'Security audit', inputSchema: SecurityAuditSchema },
      { name: 'check_compatibility', description: 'Check peer dependencies', inputSchema: CompatibilitySchema },
      { name: 'analyze_quality', description: 'Quality analysis', inputSchema: QualityAnalysisSchema },
      { name: 'compare_versions', description: 'Compare versions', inputSchema: CompareVersionsSchema },
      { name: 'analyze_npx_command', description: 'Analyze npx commands', inputSchema: NpxCommandSchema },
    ],
  };

Source: src/index.ts

Registry Client Configuration

The RegistryClient class in src/registry-client.ts handles all HTTP communication with the npm registry and GitHub API.

Architecture

graph TD
    A[Tool Request] --> B[RegistryClient]
    B --> C{Cache Check}
    C -->|Hit| D[Return Cached Data]
    C -->|Miss| E[HTTP Request]
    E --> F{Rate Limit?}
    F -->|429| G[Exponential Backoff]
    G --> E
    F -->|Success| H[Update Cache]
    H --> I[Return Data]

Configuration Parameters

ParameterDefault ValueDescription
concurrencyLimit10Maximum concurrent HTTP requests
cacheTTL5 minutesTime-to-live for cached responses
maxRetries3Maximum retry attempts on failure
backoffBase1000msBase delay for exponential backoff
backoffMax10000msMaximum backoff delay

Source: DEVELOPMENT.md

Caching Strategy

The registry client implements an LRU (Least Recently Used) cache with a 5-minute TTL:

// Cache configuration from registry-client.ts
const cacheConfig = {
  ttl: 5 * 60 * 1000, // 5 minutes
  maxSize: 1000 // maximum cached entries
};

Cached data includes:

  • Package metadata from npm registry
  • Download statistics
  • GitHub repository information

Rate Limiting

sequenceDiagram
    participant Client
    participant RegistryClient
    participant NPM_Registry
    
    Client->>RegistryClient: Request
    RegistryClient->>NPM_Registry: HTTP Request
    NPM_Registry-->>RegistryClient: 429 Rate Limited
    RegistryClient->>RegistryClient: Wait (exponential backoff)
    RegistryClient->>NPM_Registry: Retry Request
    NPM_Registry-->>RegistryClient: 200 OK
    RegistryClient-->>Client: Response

The client implements exponential backoff when receiving HTTP 429 responses:

const backoffConfig = {
  base: 1000,      // 1 second
  max: 10000,      // 10 seconds max
  factor: 2        // double delay each retry
};

Source: DEVELOPMENT.md

Tool-Specific Configuration

Each MCP tool has its own input schema defined using Zod.

Search Packages Tool

ParameterTypeRequiredDefaultDescription
querystringYes-Search query string
limitnumberNo10Max results (1-50)
export const SearchPackagesSchema = z.object({
  query: z.string().min(1),
  limit: z.number().int().min(1).max(50).default(10),
});

Source: src/tools/package-details.ts

Package Details Tool

ParameterTypeRequiredDefaultDescription
packageNamestringYes-npm package name
versionstringNolatestSpecific version to retrieve
export const PackageDetailsSchema = z.object({
  packageName: z.string().min(1),
  version: z.string().optional(),
});

Source: src/tools/package-details.ts

Security Audit Tool

ParameterTypeRequiredDefaultDescription
packageNamestringYes-Package to audit
versionstringNolatestSpecific version

Version Compatibility Tool

ParameterTypeRequiredDefaultDescription
packageNamestringYes-Package to check
versionstringNolatestTarget version
existingDependenciesRecord<string, string>Yes-Current project dependencies
export const CompatibilitySchema = z.object({
  packageName: z.string().min(1),
  version: z.string().optional(),
  existingDependencies: z.record(z.string()),
});

Source: src/tools/version-compatibility.ts

Compare Versions Tool

ParameterTypeRequiredDescription
packageNamestringYesPackage name
fromVersionstringYesStarting version
toVersionstringYesTarget version

NPX Command Analysis Tool

ParameterTypeRequiredDefaultDescription
commandstringYes-Command to analyze (e.g., create-react-app)
argsstring[]No[]Command arguments
timeoutnumberNo30000Timeout in milliseconds

Type Definitions

The src/types.ts file contains shared TypeScript interfaces used across the project:

// Example structure from types.ts
interface PackageMetadata {
  name: string;
  version: string;
  description?: string;
  license?: string;
  dependencies?: Record<string, string>;
  devDependencies?: Record<string, string>;
  peerDependencies?: Record<string, string>;
}

interface DownloadStats {
  downloads: number;
  start: string;
  end: string;
}

Source: src/types.ts

Environment Configuration

Node.js Requirements

SettingValueDescription
node>= 18.0.0Native fetch support required
platformanyCross-platform compatible

The project uses Node.js 18+ native fetch API, eliminating external HTTP library dependencies.

Package Scripts

ScriptCommandPurpose
buildtscCompile TypeScript to dist/
testvitestRun test suite
test:coveragevitest --coverageGenerate coverage report
typechecktsc --noEmitTypeScript type checking
devtsc --watchWatch mode for development

Source: DEVELOPMENT.md

Adding Custom Tools

To add a new tool, follow the pattern established in the codebase:

Step 1: Create Tool Schema

// src/tools/my-tool.ts
import { z } from 'zod';

export const MyToolSchema = z.object({
  param: z.string(),
  optionalParam: z.number().optional(),
});

Step 2: Implement Handler

export async function myTool(
  params: z.infer<typeof MyToolSchema>,
  client: RegistryClient
): Promise<string> {
  const validated = MyToolSchema.parse(params);
  // Implementation
  return JSON.stringify({ success: true });
}

Step 3: Register in Server

Update src/index.ts to include the new tool in both list_tools and call_tool handlers.

Source: CONTRIBUTING.md

Error Handling Configuration

All tools return consistent JSON responses with error handling:

// Success response
{
  success: true,
  package: "package-name",
  // ... tool-specific data
}

// Error response
{
  success: false,
  error: "Error message",
  packageName?: "package-name"
}

Source: src/tools/package-details.ts

Troubleshooting Configuration Issues

Server Won't Start

  1. Verify Node.js version: node --version (requires 18+)
  2. Rebuild the project: npm run build
  3. Check binary permissions: chmod +x bin/npm-registry-mcp.js

GitHub Rate Limits

Quality analysis tools use the GitHub API with unauthenticated limits of 60 requests/hour. Some packages may fail to return GitHub metrics under high usage.

Cache Issues

To reset cache during debugging:

// Clear internal cache
client.clearCache();

Tests Failing

rm -rf node_modules package-lock.json
npm install
npm run build
npm test

Source: DEVELOPMENT.md

Configuration Data Flow

graph LR
    A[AI Assistant] -->|MCP Protocol| B[src/index.ts]
    B --> C[Tool Handler]
    C --> D[RegistryClient]
    D -->|Cache Hit| E[Return Cached]
    D -->|Cache Miss| F[npmjs.org API]
    D -->|429 Response| G[Exponential Backoff]
    G --> F
    F -->|Response| H[Update Cache]
    H --> E
    E --> C
    C -->|JSON String| B
    B -->|MCP Response| A

See Also

Source: https://github.com/alisaitteke/npm-mcp / Human Manual

MCP Tools Overview

Related topics: Package Search and Discovery, Security Auditing, Compatibility and Version Management

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Core Infrastructure Components

Continue reading this section for the full explanation and source context.

Section searchpackages

Continue reading this section for the full explanation and source context.

Section getpackagedetails

Continue reading this section for the full explanation and source context.

Related topics: Package Search and Discovery, Security Auditing, Compatibility and Version Management

MCP Tools Overview

This page provides a comprehensive overview of the Model Context Protocol (MCP) tools implemented by the npm-mcp server. These tools enable AI assistants like Claude or Cursor to interact with the npm registry, performing package searches, security audits, quality analysis, and compatibility checks directly within conversational contexts.

Purpose and Scope

The npm-mcp server exposes a suite of MCP tools that wrap the npm registry API and GitHub API, providing structured, validated responses for package management tasks. The tools are designed to:

  • Automate package research: Eliminate manual npmjs.com browsing by enabling AI assistants to fetch package data directly
  • Enhance security: Run security audits before recommending package installations
  • Improve developer productivity: Generate quick-start code examples and compare packages automatically
  • Provide contextual awareness: Check compatibility with existing dependencies before suggesting new packages

Source: DEVELOPMENT.md:47-51

Tool Architecture

The MCP server follows a modular architecture where each tool is implemented as a separate module. All tools share common infrastructure for registry communication, caching, and input validation.

graph TD
    subgraph "MCP Server"
        A["MCP SDK"] --> B["Tool Router<br/>(index.ts)"]
        B --> C["Zod Validation"]
        B --> D["Tool Handlers"]
    end
    
    subgraph "Tool Modules"
        D --> E["search_packages"]
        D --> F["get_package_details"]
        D --> G["audit_security"]
        D --> H["check_compatibility"]
        D --> I["analyze_quality"]
        D --> J["compare_versions"]
        D --> K["analyze_npx_command"]
    end
    
    subgraph "Infrastructure"
        L["Registry Client<br/>(registry-client.ts)"]
        M["LRU Cache<br/>(5 min TTL)"]
        N["Concurrency Limiter<br/>(max 10)"]
        O["Retry with<br/>Exponential Backoff"]
    end
    
    subgraph "External APIs"
        P["npm Registry API"]
        Q["Bundlephobia API"]
        R["GitHub API<br/>(Octokit)"]
    end
    
    E --> L
    F --> L
    G --> L
    G --> R
    I --> L
    I --> R
    
    L --> M
    L --> N
    L --> O
    L --> P

Core Infrastructure Components

ComponentFilePurpose
Registry Clientsrc/registry-client.tsHTTP client with caching, rate limiting, and retry logic
Type Definitionssrc/types.tsShared TypeScript interfaces for API responses
MCP Entry Pointsrc/index.tsServer initialization, tool registration, and request routing

The registry client implements several resilience patterns:

  • LRU Cache: Package metadata, download stats, and GitHub data are cached for 5 minutes to reduce API calls
  • Concurrency Limiter: Maximum of 10 concurrent requests prevents overwhelming the registry API
  • Exponential Backoff: Automatically retries failed requests with increasing delays when encountering HTTP 429 (rate limit) responses

Source: DEVELOPMENT.md:37-39

Core Tools Reference

This section documents the primary MCP tools available in the npm-mcp server.

search_packages

Searches the npm registry for packages matching a query string.

ParameterTypeRequiredDescription
querystringYesSearch query string
limitnumberNoMaximum results to return (default: 10, max: 50)

Returns: A ranked list of packages with relevance scores, sorted by match quality.

Example Response:

{
  "packages": [
    {
      "name": "express",
      "version": "4.18.2",
      "description": "Fast, unopinionated, minimalist web framework",
      "score": 0.95
    }
  ]
}

Source: DEVELOPMENT.md:52-55

get_package_details

Retrieves comprehensive metadata for a specific package.

ParameterTypeRequiredDescription
packageNamestringYesName of the npm package
versionstringNoSpecific version to query (defaults to latest)

Returns: Package details including versions, dependencies, repository info, download statistics, and distribution metadata.

The response structure includes:

  • Package metadata: Name, version, description, deprecation status
  • Versions: List of all versions, tags, deprecated versions
  • Dependencies: Regular, dev, peer, and optional dependencies
  • Distribution: Tarball URL, integrity hash, unpacked size
  • Statistics: Weekly download counts and period
  • Timestamps: Creation, modification, and publication dates

Source: src/tools/package-details.ts:1-150

audit_security

Performs a security audit on a package to identify known vulnerabilities.

ParameterTypeRequiredDescription
packageNamestringYesName of the npm package
versionstringNoSpecific version to audit

Returns: CVE information, severity levels, and suggested safe versions.

This tool is critical for the "check before install" workflow. AI assistants should automatically call this before recommending any package installation.

Source: DEVELOPMENT.md:56-59 Source: AI_USAGE.md:1-15

check_compatibility

Checks whether a package version is compatible with existing project dependencies.

ParameterTypeRequiredDescription
packageNamestringYesName of the npm package
versionstringNoSpecific version to check
existingDependenciesRecord<string, string>YesCurrent project dependencies

Returns: Peer dependency conflict analysis, compatibility status, and resolution hints.

graph LR
    A["Input: package + deps"] --> B["Check Peer Dependencies"]
    B --> C{Conflicts?}
    C -->|Yes| D["Return Conflicts + Hints"]
    C -->|No| E["Return: Compatible"]

Source: DEVELOPMENT.md:60-63

analyze_quality

Analyzes package quality using maintenance, popularity, and community metrics.

ParameterTypeRequiredDescription
packageNamestringYesName of the npm package

Returns: Quality scores (0-100), popularity metrics, maintenance status, and GitHub repository data.

The analysis includes:

  • Quality score: Overall package health rating
  • Popularity score: Weekly downloads, star count
  • Maintenance score: Release frequency, issue responsiveness
  • GitHub metrics: Stars, forks, open issues, last commit date

Note: GitHub API has an unauthenticated rate limit of 60 requests per hour, which may cause some packages to fail analysis.

Source: DEVELOPMENT.md:64-67 Source: DEVELOPMENT.md:101-103

compare_versions

Compares two versions of the same package to identify breaking changes.

ParameterTypeRequiredDescription
packageNamestringYesName of the npm package
fromVersionstringYesStarting version
toVersionstringYesTarget version

Returns: Breaking changes list, dependency diff, and semver change summary.

This tool uses the semver library for accurate version comparison and detects:

  • Major version changes (potential breaking changes)
  • Dependency additions/removals
  • Version bumps in dependencies

Source: DEVELOPMENT.md:68-73

analyze_npx_command

Validates and analyzes npx commands without executing them.

ParameterTypeRequiredDescription
commandstringYesCommand string (e.g., create-react-app or [email protected])
argsstring[]NoArguments to pass to the command
timeoutnumberNoTimeout in milliseconds

Returns: Package validation results, warnings, metadata, and a suggested safe command.

The analysis includes:

  • Package existence and version validation
  • Executable binary verification
  • Package size and dependency count
  • Publication age (days since release)
  • Recommended safe command string

Important: This tool analyzes commands but does not execute them. It provides warnings about potential issues before the user runs the command manually.

Source: src/tools/npx-command.ts:1-80 Source: DEVELOPMENT.md:74-79

Productivity Tools

Additional tools designed to enhance developer productivity when working with npm packages.

generate_quick_start

Generates ready-to-use code examples for any package.

Returns:

  • Install commands for npm, yarn, pnpm, and bun
  • Basic usage examples with imports/requires
  • Framework-specific examples (React, Vue, Express, etc.)
  • TypeScript tips and type definitions
  • Warnings about peer dependencies and engine requirements

Source: PRODUCTIVITY.md:14-38

analyze_bundle_size

Analyzes the bundle impact of adding a package to a project.

Returns:

  • Unpacked size (on disk)
  • Minified size (production)
  • Gzipped size (actual network transfer)
  • Tree-shaking support detection
  • Dependencies count
  • Impact rating (Excellent/Good/Medium/Large)

This tool uses the Bundlephobia API for accurate size data.

Source: PRODUCTIVITY.md:65-88

find_similar_packages

Finds alternative packages with similar functionality.

Returns: Ranked list of similar packages with:

  • Similarity scores
  • Weekly download counts
  • Package descriptions
  • Recommendation context

Source: PRODUCTIVITY.md:47-63

analyze_capabilities

Provides comprehensive analysis of package capabilities.

Analyzes:

CapabilityDescription
Module SystemESM, CommonJS, UMD, or dual package support
TypeScriptBuilt-in types, type definitions location
Platform SupportNode.js, Browser, Deno, Bun, React, React Native
Export FormatsMain entry points and subpath exports

Source: CAPABILITIES.md:1-60

AI Workflows and Automation

The MCP tools are designed to work together automatically when AI assistants detect package-related queries.

Automatic Trigger Patterns

The AI automatically invokes MCP tools when it detects:

  • Search queries: "search", "find", "discover", "look for", "best", "top"
  • Compare requests: "compare", "vs", "or", "better", "alternative"
  • Package mentions: express, react, lodash, or other package names
  • Install commands: npm install, yarn add, pnpm add
  • Code imports: import/require statements with new packages
  • File changes: package.json modifications

Source: AUTOMATIC.md:1-50

For any package installation recommendation, the recommended workflow is:

graph TD
    A["User mentions package"] --> B["Call audit_security"]
    B --> C{Vulnerabilities?}
    C -->|Yes| D["Suggest safe version"]
    C -->|No| E["Call get_package_details"]
    E --> F["Call check_compatibility"]
    F --> G{Compatible?}
    G -->|Yes| H["Show install command"]
    G -->|No| I["Show conflict + hints"]
    D --> H

This workflow ensures:

  1. Security first: Always audit before recommending
  2. Full context: Get package details and compatibility
  3. Clear output: Use ✅/⚠️ indicators for visibility
  4. Actionable results: Always provide safe install commands

Source: AI_USAGE.md:50-70

MCP Prompts (Slash Commands)

The server includes smart prompts for common workflows:

PromptPurpose
/check_before_installFull security and compatibility check before installing
/find_packageFind and compare packages for a specific use case

These prompts provide shortcut commands that invoke multiple tools in sequence for comprehensive analysis.

Source: PROMPTS.md:1-50

Input Validation

All MCP tools use Zod for input validation. This provides:

  • Type safety: Ensures parameters match expected types
  • Parse errors: Returns clear error messages for invalid inputs
  • Default values: Applies sensible defaults for optional parameters
  • Schema enforcement: Rejects requests that don't match the tool's schema

The Zod schemas are defined in each tool module and are used during the MCP request handling in src/index.ts.

Source: DEVELOPMENT.md:40

Response Format

All tools return JSON-formatted strings with consistent structures:

Success Response

{
  "success": true,
  "data": { ... }
}

Error Response

{
  "success": false,
  "error": "Error message",
  "packageName": "...",
  "version": "..."
}

This consistent format allows AI assistants to easily parse responses and handle errors appropriately.

Source: src/tools/package-details.ts:140-155

Configuration and Environment

Server Requirements

RequirementValue
Node.js>= 18.0.0
DependenciesMCP SDK, Zod, semver, Octokit, lru-cache

Source: package.json:1-30

Rate Limits and Quotas

APILimitNotes
npm Registry10 concurrent requestsShared pool across all tools
GitHub API60 req/hour (unauthenticated)Used for analyze_quality

Source: DEVELOPMENT.md:93-97 Source: DEVELOPMENT.md:101-103

Common Failure Modes

IssueCauseSolution
Server won't startNode version too oldEnsure Node 18+: node --version
Server won't startBuild outdatedRun npm run build
Server won't startBin not executablechmod +x bin/npm-registry-mcp.js
Quality analysis failsGitHub rate limitWait or use authenticated requests
Cache issuesStale dataInternal cache has 5 min TTL

Source: DEVELOPMENT.md:105-115

Extending the Tool Suite

To add a new MCP tool:

  1. Create the tool module: Add src/tools/<name>.ts with Zod schema and handler function
  2. Register the tool: Add to ListToolsRequestSchema in src/index.ts
  3. Add request handling: Add case for the tool in CallToolRequestSchema handler
  4. Write tests: Add tests in test/<name>.test.ts
// src/tools/example.ts
import { z } from 'zod';

const ExampleSchema = z.object({
  param: z.string(),
});

export async function handleExample(args: unknown) {
  const validated = ExampleSchema.parse(args);
  // Implementation
  return JSON.stringify({ success: true, data: {} });
}

Source: DEVELOPMENT.md:117-123

See Also

Source: https://github.com/alisaitteke/npm-mcp / Human Manual

Security Auditing

Related topics: MCP Tools Overview, Compatibility and Version Management

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Integration Points

Continue reading this section for the full explanation and source context.

Section auditsecurity

Continue reading this section for the full explanation and source context.

Section Pre-Installation Validation

Continue reading this section for the full explanation and source context.

Related topics: MCP Tools Overview, Compatibility and Version Management

Security Auditing

The Security Auditing feature in npm-mcp provides automated vulnerability detection and security analysis for npm packages. It integrates with the npm Registry API and security advisories to help AI assistants identify potentially dangerous dependencies before installation, ensuring safe and secure package management workflows.

Overview

Security Auditing serves as a proactive shield against vulnerable packages by:

  • Querying npm security advisories for known vulnerabilities
  • Analyzing package versions against vulnerability databases
  • Providing actionable remediation recommendations
  • Supporting batch auditing for entire project dependencies
  • Integrating seamlessly with other npm-mcp tools like compatibility checking and quality analysis

Source: AI_USAGE.md Source: PROMPTS.md

Architecture

The security auditing system operates within the broader npm-mcp architecture, utilizing the centralized RegistryClient for API communication and caching.

graph TD
    A[AI Assistant] -->|Requests| B[Security Audit Tool]
    B --> C[RegistryClient]
    C -->|Cached Response| D[npm Security API]
    C -->|Vulnerability Data| E[Audit Result]
    B --> F[Remediation Suggestions]
    
    G[Compatibility Check] -->|Combined Check| B
    H[Quality Analysis] -->|Combined Check| B

Integration Points

ComponentIntegration TypePurpose
RegistryClientHTTP ClientAPI communication with npm registry
check_compatibilityParallel ToolCombined security + compatibility reports
analyze_qualityParallel ToolQuality metrics alongside security
/audit_project PromptWorkflowBatch auditing of entire projects
/check_before_install PromptWorkflowPre-installation security validation

Source: DEVELOPMENT.md Source: PROMPTS.md

Tool Reference

`audit_security`

The primary tool for checking package vulnerabilities.

#### Input Parameters

ParameterTypeRequiredDescription
packageNamestringYesName of the npm package to audit
versionstringNoSpecific version to check (defaults to latest)

#### Response Structure

{
  "success": true,
  "packageName": "lodash",
  "version": "4.17.21",
  "vulnerabilities": [],
  "severity": "none",
  "recommendation": "safe to install"
}

#### Example Response with Vulnerabilities

{
  "success": true,
  "packageName": "lodash",
  "version": "4.17.20",
  "vulnerabilities": [
    {
      "id": "SNYK-JS-LODASH-590103",
      "title": "Prototype Pollution",
      "severity": "high",
      "url": "https://www.npmjs.com/advisories/1673"
    }
  ],
  "severity": "high",
  "recommendation": "upgrade to 4.17.21",
  "fixCommand": "npm install [email protected]"
}

Source: AI_USAGE.md Source: src/tools/package-details.ts

Workflow Integration

Pre-Installation Validation

The recommended workflow for any package installation follows a security-first approach:

graph LR
    A[User mentions package] --> B{Is it safe?}
    B -->|audit_security| C[Query npm advisories]
    C --> D{Any vulnerabilities?}
    D -->|No| E[✅ Safe to install]
    D -->|Yes| F[Check for safe version]
    F --> G{Update available?}
    G -->|Yes| H[✅ Suggest safe version]
    G -->|No| I[⚠️ Warn user]
    E --> J[Proceed with install]
    H --> J

Combined Security and Compatibility Check

For comprehensive package validation, security auditing combines with compatibility checking:

graph TD
    A[Package mentioned] --> B[audit_security]
    A --> C[check_compatibility]
    B --> D[Security Report]
    C --> E[Compatibility Report]
    D --> F{Security OK?}
    E --> G{Compatible?}
    F -->|Yes| G
    F -->|No| H[Show safe version]
    G -->|Yes| I[✅ Recommend install]
    G -->|No| J[⚠️ Show conflicts]

Source: AUTOMATIC.md Source: AI_USAGE.md

MCP Prompts for Security

`/check_before_install`

Full security and compatibility check before installing a package.

Usage:

/check_before_install express

What it does:

  1. Runs audit_security for vulnerabilities
  2. Gets package_details to verify maintenance status
  3. Checks check_compatibility with existing dependencies
  4. Shows clear ✅/⚠️ recommendation with install command

Response format:

[email protected] is safe to install

Security: No known vulnerabilities
Compatibility: ✅ No peer dependency conflicts
Maintenance: Active (last update: 2 days ago)

Install: npm install [email protected]

`/audit_project`

Security audit for all dependencies in your project.

Usage:

/audit_project

What it does:

  1. Reads project package.json dependencies
  2. Runs security audit on each package in parallel
  3. Summarizes vulnerable packages by severity
  4. Provides update commands for all issues

Response format:

📊 Security Audit Results

✅ Safe packages (23):
- [email protected]
- [email protected]
...

⚠️ Vulnerable packages (2):

1. [email protected] (HIGH)
   - Issue: Prototype pollution
   - Fix: npm install [email protected]
   
2. [email protected] (MODERATE)
   - Issue: Open redirect
   - Fix: npm install [email protected]

Total: 25 packages, 2 need updates

Source: PROMPTS.md

Response Templates

Safe Package Template

✅ {packageName}@{version} is safe to install

Security: No vulnerabilities
Compatibility: ✅ Compatible with your dependencies
Quality: {score}/100 ({downloads} weekly downloads)

Install:
npm install {packageName}@{version}

Source: AI_USAGE.md

Security Warning Template

⚠️ SECURITY WARNING: {packageName}@{version} has {count} vulnerabilities

Severity: {severity}
Issue: {vulnerability_title}
Safe version: {safe_version}

Recommended:
npm install {packageName}@{safe_version}

Vulnerability Severity Levels

SeverityIconAction Required
Critical🔴Immediate upgrade required
High🟠Upgrade strongly recommended
Moderate🟡Upgrade when possible
Low🟢Consider upgrading

Source: AI_USAGE.md

Automatic Security Triggers

The MCP server automatically triggers security checks in the following scenarios:

User ActionAutomatic Tool CallPurpose
"install X", "add X"audit_security + check_compatibilityCheck before recommending install
Mentions package nameget_package_detailsShow info proactively
"update X", "upgrade X"compare_versions + audit_securityShow changes and security
Pastes package.jsonaudit_security (all deps)Security report for all dependencies
AI writing package.jsonaudit_security (auto)Verify each dependency

Source: AUTOMATIC.md Source: AI_USAGE.md

Best Practices

For AI Assistants

  1. Always check security first - Never recommend install without audit
  2. Be proactive - Don't wait for user to ask "is it safe?"
  3. Batch operations - Check multiple packages in parallel for efficiency
  4. Clear warnings - Use ⚠️ 🔒 ✅ emojis for visibility
  5. Actionable output - Always provide safe install command
  6. Suggest alternatives - If package has issues, recommend safer options

Response Guidelines

When presenting audit results:

[email protected] is safe to install

Security: No vulnerabilities
Compatibility: ✅ Compatible with your dependencies
Quality: 95/100 (11M weekly downloads)

Install:
npm install [email protected]

When vulnerabilities are found:

⚠️ SECURITY WARNING: [email protected] has 2 vulnerabilities

Severity: High
Issue: Prototype pollution
Safe version: [email protected]

Recommended:
npm install [email protected]

Source: AI_USAGE.md

Caching and Rate Limiting

The security auditing feature benefits from the underlying RegistryClient infrastructure:

FeatureValueDescription
Cache TTL5 minutesPackage metadata and security data
Concurrent RequestsMax 10Prevents API throttling
429 HandlingExponential backoffAutomatic retry on rate limits
Cache Clearclient.clearCache()Internal method for fresh data

Source: DEVELOPMENT.md

Common Failure Modes

GitHub Rate Limits

Quality analysis uses the GitHub API, which has an unauthenticated limit of 60 requests/hour. Some package analyses may fail under heavy usage.

Workaround: Implement GitHub authentication tokens for production environments.

Server Won't Start

  • Ensure Node 18+ is installed: node --version
  • Rebuild the project: npm run build
  • Check bin executable permissions: chmod +x bin/npm-registry-mcp.js

Tests Failing

rm -rf node_modules package-lock.json
npm install
npm run build
npm test

Source: DEVELOPMENT.md

See Also

Source: https://github.com/alisaitteke/npm-mcp / Human Manual

Compatibility and Version Management

Related topics: MCP Tools Overview, Security Auditing

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Registry Client Layer

Continue reading this section for the full explanation and source context.

Section Type Definitions

Continue reading this section for the full explanation and source context.

Section Purpose and Scope

Continue reading this section for the full explanation and source context.

Related topics: MCP Tools Overview, Security Auditing

Compatibility and Version Management

The Compatibility and Version Management subsystem in npm-mcp provides tools for analyzing npm package versions, comparing changes between releases, and verifying peer dependency compatibility. This system enables AI assistants to make informed recommendations about package updates and installations by examining version relationships, dependency modifications, and peer dependency conflicts.

Overview

When working with npm packages, understanding version compatibility is critical for maintaining stable applications. The npm-mcp server exposes two primary tools that address these concerns:

  1. compare_versions - Analyzes differences between two versions of the same package
  2. check_compatibility - Validates whether a package's peer dependencies align with existing project dependencies

These tools integrate with the registry client layer, which handles caching, rate limiting, and error recovery to ensure reliable API interactions.

graph TD
    A[User Request] --> B{Which Tool?}
    B -->|Compare Versions| C[compare_versions]
    B -->|Check Install| D[check_compatibility]
    
    C --> E[Registry Client]
    D --> E
    
    E --> F[Fetch Packument]
    F --> G[Parse Version Data]
    
    G --> H[Compare Dependencies]
    G --> I[Analyze Peer Deps]
    
    H --> J[Generate Report]
    I --> J
    
    J --> K[JSON Response]

Core Components

Registry Client Layer

The registry client (src/registry-client.ts) serves as the foundation for all version-related operations. It provides the getPackage() method that retrieves full packument data from the npm registry.

Key capabilities:

FeatureImplementation
Concurrency LimitMaximum 10 concurrent requests
Cache Duration5-minute LRU cache
Rate LimitingExponential backoff on HTTP 429 responses
Error HandlingAutomatic retry with backoff

Source: DEVELOPMENT.md

Type Definitions

The type system (src/types.ts) defines the data structures used throughout version management operations:

TypePurpose
PackumentComplete package metadata from npm registry
AbbreviatedPackumentReduced metadata for specific endpoints
DownloadStatsWeekly download statistics
RegistryErrorError responses from registry API

Source: src/types.ts

Tool: compare_versions

The compare_versions tool analyzes the differences between two versions of the same npm package. This is essential for understanding the impact of potential updates before applying them.

Purpose and Scope

When you need to upgrade or downgrade a package, understanding what changed between versions helps assess risk. The tool identifies:

  • Dependency additions and removals
  • Dependency version changes
  • Peer dependency modifications
  • Breaking change detection

Input Parameters

ParameterTypeRequiredDescription
packageNamestringYesName of the npm package
fromVersionstringYesStarting version (semver)
toVersionstringYesTarget version (semver)

Output Structure

The tool returns a JSON response containing:

{
  success: boolean;
  package: string;
  versionChange: {
    from: string;
    to: string;
    changeType: "major" | "minor" | "patch" | "prerelease" | "build";
    isUpgrade: boolean;
    isBreaking: boolean;
    publishedDates: { from: string; to: string };
  };
  dependencyChanges: {
    added: number;
    removed: number;
    changed: number;
    details: {
      added: Record<string, string>;
      removed: Record<string, string>;
      changed: Record<string, { from: string; to: string }>;
    };
  };
  peerDependencyChanges: {
    total: number;
    details: PeerChange[];
  };
  recommendation: string;
}

Source: src/tools/version-compatibility.ts

How It Works

sequenceDiagram
    participant User
    participant Tool as compare_versions
    participant Client as Registry Client
    participant NPM as npm registry
    
    User->>Tool: compare_versions({pkg, from, to})
    Tool->>Client: getPackage(pkg)
    Client->>NPM: GET /package/{pkg}
    NPM-->>Client: Packument JSON
    Client-->>Tool: Packument
    Tool->>Tool: Parse fromVer and toVer
    Tool->>Tool: Calculate semver.diff()
    Tool->>Tool: Compare dependencies object
    Tool->>Tool: Compare peerDependencies object
    Tool->>Tool: Generate recommendation
    Tool-->>User: JSON Report

Version Change Classification

The tool uses semantic versioning rules to classify changes:

Change TypeSemver DiffImplication
MajormajorBreaking changes, likely API changes
MinorminorNew features, backward compatible
PatchpatchBug fixes only
PrereleaseprereleaseAlpha/beta releases
BuildbuildBuild metadata only

Recommendation Logic

The tool provides contextual recommendations based on the change type:

recommendation:
  diff === 'major'
    ? 'Major version change detected. Review changelog and test thoroughly.'
    : diff === 'minor'
    ? 'Minor version change. New features added, should be backward compatible.'
    : diff === 'patch'
    ? 'Patch version change. Bug fixes only, safe to upgrade.'
    : 'Version comparison complete.'

Source: src/tools/version-compatibility.ts:95-103

Tool: check_compatibility

The check_compatibility tool validates whether a package's peer dependencies are satisfied by the existing project dependencies. This prevents "missing peer dependency" warnings during installation and potential runtime errors.

Purpose and Scope

Peer dependencies declare a package's expectations about its environment. The compatibility checker:

  • Identifies conflicting peer dependencies
  • Detects missing peer dependencies
  • Validates version compatibility

Input Parameters

ParameterTypeRequiredDescription
packageNamestringYesName of the npm package
versionstringNoSpecific version to check (defaults to latest)
installedPackagesobjectNoMap of currently installed packages and versions

Output Structure

{
  success: boolean;
  package: string;
  version: string;
  compatible: boolean;
  analysis: {
    peerDependencies: {
      total: number;
      compatible: number;
      conflicts: number;
      missing: number;
    };
    details: {
      compatible: CompatiblePeer[];
      conflicts: ConflictPeer[];
      missing: MissingPeer[];
    };
  };
  recommendation: string;
  suggestedActions: string[];
}

Source: src/tools/version-compatibility.ts

Compatibility Analysis Flow

graph TD
    A[Start Compatibility Check] --> B[Fetch Package Packument]
    B --> C[Get Target Version]
    C --> D[Extract Peer Dependencies]
    
    D --> E{Installed Packages Provided?}
    E -->|No| F[Mark all as missing]
    E -->|Yes| G[Compare Each Peer Dep]
    
    G --> H{Version Satisfies Range?}
    H -->|Yes| I[Mark Compatible]
    H -->|No| J{Any Installed Version?}
    J -->|Yes| K[Mark Conflict]
    J -->|No| L[Mark Missing]
    
    I --> M[Generate Report]
    K --> M
    L --> M
    
    M --> N{conflicts === 0<br/>missing === 0?}
    N -->|Yes| O[compatible: true]
    N -->|No| P[compatible: false]

Conflict Resolution Strategy

The tool determines compatibility by checking if installed package versions satisfy the semver ranges specified in peer dependencies:

// For each peer dependency
const installedVersion = installedPackages[peerDep.package];
const isCompatible = installedVersion && 
  semver.satisfies(installedVersion, peerDep.required);

Source: src/tools/version-compatibility.ts

Suggested Actions

When incompatibilities are detected, the tool generates actionable recommendations:

Issue TypeSuggested Action
Conflicts"Update conflicting dependencies to compatible versions"
Missing"Install missing peer dependencies: {list}"

Integration with Package Details

The version information displayed by get_package_details complements the compatibility tools by providing context about available versions and their status.

Version Metadata

The package details tool (src/tools/package-details.ts) retrieves comprehensive version information:

Data PointSourceDescription
versions.latestdist-tags.latestCurrent stable release
versions.totalObject.keys(versions).lengthCount of all versions
versions.recentFiltered by publish timeLatest 10 versions
versions.deprecatedVersions with deprecated fieldDeprecated version list
timestamps.createdtime.createdPackument creation time
timestamps.modifiedtime.modifiedLast modification time
timestamps.versionPublishedtime[version]Specific version publish date

Source: src/tools/package-details.ts

Deprecated Version Tracking

The system identifies deprecated versions:

deprecatedVersions: Object.entries(packument.versions)
  .filter(([, v]) => v.deprecated !== undefined)
  .map(([v, data]) => ({
    version: v,
    message: data.deprecated === true 
      ? 'Deprecated' 
      : String(data.deprecated)
  }))

This enables users to avoid versions that have known issues or have been officially deprecated by package maintainers.

Common Usage Patterns

Pattern 1: Pre-Update Assessment

Before upgrading a dependency, run both tools to understand the full impact:

graph LR
    A[Current: [email protected]] --> B[compare_versions]
    B --> C{Major change?}
    C -->|Yes| D[Review changelog<br/>Test thoroughly]
    C -->|No| E[check_compatibility]
    E --> F{Compatible?}
    F -->|Yes| G[npm install [email protected]]
    F -->|No| H[Install missing peer deps]

Pattern 2: Dependency Upgrade Workflow

For automated dependency management:

  1. Use compare_versions to identify the nature of changes
  2. Use check_compatibility to verify peer dependency alignment
  3. Generate an installation command with safe version

Pattern 3: Security Update Evaluation

When a security patch is available:

Input: compare_versions({ "package": "axios", "from": "1.5.0", "to": "1.6.0" })

Expected Output:
- Shows if it's a patch/minor/major change
- Lists any dependency modifications
- Provides recommendation based on change type

Error Handling

Both tools handle errors gracefully by returning structured JSON error responses:

{
  success: false,
  error: "Version X.X.X not found"
}
Error ScenarioResponse
Package not found{ success: false, error: "Package not found" }
Version not found{ success: false, error: "Version X.X.X not found" }
Registry error{ success: false, error: "<error message>" }
Invalid semverHandled by Zod validation schema

Source: src/tools/version-compatibility.ts

Architecture Summary

The version management subsystem follows a layered architecture:

graph BT
    A[compare_versions] --> B[Registry Client]
    A1[check_compatibility] --> B
    C[get_package_details] --> B
    
    B --> D[npm Registry API]
    B --> E[LRU Cache]
    
    F[Zod Validation] -.-> A
    F -.-> A1
    F -.-> C
LayerComponentResponsibility
Toolsversion-compatibility.tsVersion comparison and compatibility checking
Toolspackage-details.tsPackage metadata retrieval
Clientregistry-client.tsHTTP requests, caching, rate limiting
ValidationZod schemasInput validation and type safety
APInpm RegistrySource of truth for package data

See Also

Source: https://github.com/alisaitteke/npm-mcp / Human Manual

System Architecture

Related topics: Development Guide, Tool Reference

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Architecture Principles

Continue reading this section for the full explanation and source context.

Section Project Structure

Continue reading this section for the full explanation and source context.

Section Core Components

Continue reading this section for the full explanation and source context.

Related topics: Development Guide, Tool Reference

System Architecture

This document describes the system architecture of npm-mcp, a Model Context Protocol (MCP) server that provides AI assistants with programmatic access to npm registry data, security audits, and package compatibility analysis.

Overview

npm-mcp acts as a bridge between AI assistants and the npm ecosystem. It implements the MCP specification to expose a collection of tools that allow AI agents to search packages, audit security vulnerabilities, check version compatibility, and analyze package quality—without requiring the AI to make direct HTTP calls to external APIs.

Core responsibilities:

  • Expose npm registry operations as MCP tools for AI consumption
  • Handle caching, rate limiting, and retry logic for npm API calls
  • Validate all inputs using Zod schemas before processing
  • Provide consistent JSON responses for AI parsing
  • Integrate with GitHub API for extended package analysis

Source: DEVELOPMENT.md

High-Level Architecture

graph TD
    subgraph "Client Layer"
        AI[AI Assistant<br/>Cursor/Claude Desktop]
    end

    subgraph "MCP Protocol Layer"
        MCP[MCP SDK<br/>JSON-RPC Transport]
    end

    subgraph "Application Layer"
        Server[MCP Server<br/>src/index.ts]
        Tools[Tool Handlers<br/>src/tools/*.ts]
        Schemas[Zod Validation<br/>Input Schemas]
    end

    subgraph "Service Layer"
        RegistryClient[Registry Client<br/>src/registry-client.ts]
        Cache[LRU Cache<br/>5 min TTL]
        RateLimiter[Rate Limiter<br/>Max 10 concurrent]
    end

    subgraph "External APIs"
        NPM[NPM Registry API<br/>registry.npmjs.org]
        GitHub[GitHub API<br/>api.github.com]
    end

    AI --> MCP
    MCP --> Server
    Server --> Tools
    Server --> Schemas
    Tools --> RegistryClient
    RegistryClient --> Cache
    RegistryClient --> RateLimiter
    RegistryClient --> NPM
    RegistryClient --> GitHub

Architecture Principles

PrincipleImplementation
Separation of ConcernsTool handlers are isolated modules; registry client handles all API communication
Input ValidationZod schemas validate all tool inputs before processing
ResilienceExponential backoff on rate limits; LRU caching to reduce API calls
Type SafetyTypeScript with strict mode throughout the codebase
TestabilityEach tool is independently testable with mocked dependencies

Source: DEVELOPMENT.md

Component Architecture

Project Structure

npm-mcp/
├── src/
│   ├── index.ts              # MCP server entry point
│   ├── registry-client.ts    # NPM API client with cache/retry/limit
│   ├── types.ts              # Shared TypeScript types
│   └── tools/
│       ├── search-packages.ts
│       ├── package-details.ts
│       ├── security-audit.ts
│       ├── version-compatibility.ts
│       ├── quality-analysis.ts
│       └── npx-command.ts
├── test/                     # Vitest test suite
├── bin/npm-registry-mcp.js   # CLI entry point for npx
├── server.json               # MCP registry metadata
└── package.json

Source: DEVELOPMENT.md

Core Components

ComponentFileResponsibility
MCP Serversrc/index.tsInitialize MCP transport, register tools, route requests
Registry Clientsrc/registry-client.tsHTTP calls to npm/GitHub, caching, rate limiting, retries
Type Definitionssrc/types.tsShared interfaces for package metadata, API responses
Search Toolsrc/tools/search-packages.tsSearch npm registry by query
Package Detailssrc/tools/package-details.tsRetrieve detailed package information
Security Auditsrc/tools/security-audit.tsCheck for vulnerabilities via npm audit API
Version Compatibilitysrc/tools/version-compatibility.tsCheck peer dependency compatibility
Quality Analysissrc/tools/quality-analysis.tsAnalyze maintenance, popularity, GitHub metrics
NPX Commandsrc/tools/npx-command.tsValidate and suggest safe npx commands

MCP Server Implementation

The MCP server is the central orchestration component. It uses the @modelcontextprotocol/sdk package to handle the MCP protocol.

sequenceDiagram
    participant AI as AI Assistant
    participant MCP as MCP Server (index.ts)
    participant Handler as Tool Handler
    participant Client as Registry Client

    AI->>MCP: ListToolsRequest
    MCP-->>AI: Tool manifest (6 tools)

    AI->>MCP: CallToolRequest (search_packages)
    MCP->>Handler: Invoke tool handler
    Handler->>Client: Fetch data
    Client->>Client: Check cache
    alt Cache hit
        Client-->>Handler: Cached data
    else Cache miss
        Client->>NPM: GET /-/v1/search
        NPM-->>Client: Search results
        Client-->>Handler: Fresh data
    end
    Handler-->>MCP: JSON response
    MCP-->>AI: Tool result

Request Routing

The server handles two primary request types:

  1. ListToolsRequest: Returns manifest of available tools with their input schemas
  2. CallToolRequest: Routes tool calls to the appropriate handler based on tool name

Source: src/index.ts

Registry Client Architecture

The RegistryClient class encapsulates all external API communication with built-in resilience features.

graph LR
    subgraph "RegistryClient"
        direction TB
        Cache[LRU Cache<br/>5 min TTL]
        RateLimit[Rate Limiter<br/>Max 10 concurrent]
        Retry[Exponential Backoff<br/>On 429 errors]
    end

    subgraph "Endpoints"
        NPM_Search[/-/v1/search]
        NPM_Package[/package/{name}]
        NPM_Downloads[/downloads/range]
        NPM_Audit[/-/npm/v1/security/audits]
        GH_API[api.github.com]
    end

Configuration Options

OptionDefaultDescription
concurrencyLimit10Maximum concurrent API requests
cacheTTL300000 (5 min)Cache time-to-live in milliseconds
npmRegistryBaseregistry.npmjs.orgBase URL for npm registry API
githubApiBaseapi.github.comBase URL for GitHub API
maxRetries3Maximum retry attempts on failure
backoffBase1000Base delay for exponential backoff (ms)

Source: src/registry-client.ts

Caching Strategy

The registry client implements an LRU (Least Recently Used) cache with configurable TTL:

interface CacheEntry<T> {
  data: T;
  timestamp: number;
  ttl: number;
}

// Cache check on every request
async get<T>(key: string): Promise<T | null>
async set<T>(key: string, data: T, ttl?: number): Promise<void>
clearCache(): void  // Manual cache invalidation

Cached endpoints:

  • Package metadata (details, versions)
  • Download statistics
  • GitHub repository information

Non-cached operations:

  • Security audit (always fresh data)
  • Search queries (volatile results)

Rate Limiting

The client enforces concurrency limits to prevent overwhelming external APIs:

graph TD
    A[Incoming Request] --> B{Available slots?}
    B -->|Yes| C[Execute Request]
    B -->|No| D[Queue/Wait]
    C --> E[Release Slot]
    D --> B
    E --> F[Response]

When a 429 Too Many Requests response is received, the client automatically retries with exponential backoff:

Retry 1: wait 1 second
Retry 2: wait 2 seconds  
Retry 3: wait 4 seconds

Source: DEVELOPMENT.md

Tool Architecture

Each MCP tool follows a consistent pattern:

  1. Define Input Schema using Zod
  2. Validate Input by parsing against schema
  3. Execute Logic using RegistryClient
  4. Return JSON String response

Tool Handler Pattern

import { z } from 'zod';
import { RegistryClient } from '../registry-client.js';

// 1. Define schema
export const MyToolSchema = z.object({
  param: z.string(),
});

// 2. Handler function
export async function myTool(
  params: z.infer<typeof MyToolSchema>,
  client: RegistryClient
): Promise<string> {
  const validated = MyToolSchema.parse(params);  // Throws on invalid
  // 3. Execute logic
  const result = await client.fetchData(validated.param);
  // 4. Return JSON string
  return JSON.stringify(result, null, 2);
}

Available Tools

ToolInput SchemaPrimary API Used
search_packagesquery: string, limit?: numbernpm search API
get_package_detailspackageName: string, version?: stringnpm packument endpoint
audit_securitypackageName: string, version?: stringnpm audit API
check_compatibilitypackageName, version?, existingDependenciesnpm packument
analyze_qualitypackageName: stringnpm stats + GitHub API
compare_versionspackageName, fromVersion, toVersionnpm packument
analyze_npx_commandcommand: string, args?, timeout?npm view + validation

Tool Invocation Flow

sequenceDiagram
    participant MCP as MCP Server
    participant Tool as Tool Handler
    participant Client as Registry Client
    participant NPM as NPM Registry

    MCP->>Tool: CallTool(name, arguments)
    
    Note over Tool: Zod validation
    
    alt Invalid Input
        Tool-->>MCP: ZodError (thrown)
    else Valid Input
        Tool->>Client: Fetch packument
        Client->>NPM: GET /package/{name}
        NPM-->>Client: Packument JSON
        Client-->>Tool: Packument data
        
        Tool->>Tool: Process data
        Tool-->>MCP: JSON string response
    end

Data Flow Examples

Security Audit Flow

graph TD
    A[audit_security tool] --> B[Fetch package metadata]
    B --> C[Get current version if not specified]
    C --> D[POST to npm audit API]
    D --> E{Arror?}
    E -->|429 Rate Limit| F[Wait + Retry]
    E -->|Other Error| G[Return error JSON]
    E -->|Success| H[Parse audit response]
    H --> I{Has vulnerabilities?}
    I -->|Yes| J[Format CVE details]
    I -->|No| K[Return clean status]
    J --> L[Suggest safe version]
    K --> M[Return success JSON]
    L --> M

Version Compatibility Check Flow

graph TD
    A[check_compatibility tool] --> B[Fetch package metadata]
    B --> C[Extract peerDependencies]
    C --> D[Compare with existingDependencies]
    D --> E{Conflicts?}
    E -->|Yes| F[Generate conflict report]
    E -->|No| G{Check missing?}
    G -->|Yes| H[Generate missing deps report]
    G -->|No| I[Return compatible status]
    F --> J[Build suggested actions]
    H --> J
    I --> K[Return JSON result]
    J --> K

Source: src/tools/version-compatibility.ts

Error Handling

The system employs consistent error handling across all components:

Error Response Format

interface ErrorResponse {
  success: false;
  error: string;        // Human-readable error message
  packageName?: string; // Context when applicable
  version?: string;     // Context when applicable
}

Error Sources

SourceHandling
Invalid input (Zod)Throws ZodError with validation details
Package not foundReturns { success: false, error: "Package not found" }
Rate limited (429)Exponential backoff retry (up to 3 attempts)
Network failureReturns { success: false, error: "Network error" }
GitHub API limitPartial results with warning; some packages may fail

Source: src/tools/package-details.ts

Type System

The types.ts file defines shared interfaces used across the application:

// Example type structure
interface PackageMetadata {
  name: string;
  version: string;
  description?: string;
  dependencies?: Record<string, string>;
  devDependencies?: Record<string, string>;
  peerDependencies?: Record<string, string>;
  repository?: RepositoryInfo;
  license?: string;
  author?: Person;
  maintainers?: Person[];
}

interface SecurityAudit {
  vulnerabilities: Vulnerability[];
  metadata: AuditMetadata;
}

interface VersionCompatibility {
  compatible: boolean;
  peerDependencies: {
    compatible: PeerDep[];
    conflicts: Conflict[];
    missing: MissingDep[];
  };
}

Source: src/types.ts

External Dependencies

Runtime Dependencies

PackagePurpose
@modelcontextprotocol/sdkMCP protocol implementation
zodSchema validation and type inference
semverSemantic version parsing and comparison
@octokit/restGitHub API client for quality analysis
node-fetchHTTP client (with fallback for Node 18+)

Development Dependencies

PackagePurpose
typescriptType checking and compilation
vitestUnit testing framework
tsxTypeScript execution for CLI

Source: DEVELOPMENT.md

Adding New Tools

To extend the MCP server with a new tool:

graph LR
    A[Create tool file] --> B[Define Zod schema]
    B --> C[Implement handler]
    C --> D[Register in index.ts]
    D --> E[Add tests]
    E --> F[Document]

Steps

  1. Create src/tools/<name>.ts with Zod schema and handler
  2. Register in src/index.ts:
  • Add to ListToolsRequestSchema handler's tool list
  • Add case to CallToolRequestSchema handler switch
  1. Add tests in test/<name>.test.ts
  2. Update documentation as needed

Source: CONTRIBUTING.md

Deployment Architecture

Entry Points

MethodEntry PointUse Case
npxbin/npm-registry-mcp.jsQuick testing
Directnode dist/index.jsCustom integrations
npm linkLinked globallyDevelopment

Environment Requirements

RequirementMinimumNotes
Node.js18+Uses native fetch API
npmAnyFor installation only

Source: DEVELOPMENT.md

See Also

Source: https://github.com/alisaitteke/npm-mcp / Human Manual

Development Guide

Related topics: System Architecture, Tool Reference

Section Related Pages

Continue reading this section for the full explanation and source context.

Section System Architecture Diagram

Continue reading this section for the full explanation and source context.

Section Architecture Specifications

Continue reading this section for the full explanation and source context.

Section Prerequisites

Continue reading this section for the full explanation and source context.

Related topics: System Architecture, Tool Reference

Development Guide

This guide covers setup, architecture, and tool development for contributing to @alisaitteke/npm-mcp. It is intended for developers who want to understand the codebase, extend functionality, or contribute improvements.

Purpose and Scope

The Development Guide provides technical documentation for setting up a local development environment, understanding the system architecture, implementing new tools, and following the project's contribution workflow. This guide is based on the actual implementation details found in the source code and documentation files. Source: DEVELOPMENT.md

Project Overview

npm-mcp is a Model Context Protocol (MCP) server that provides AI assistants with tools for interacting with the npm registry. It offers capabilities including package search, security auditing, version compatibility checking, quality analysis, and capability analysis. Source: DEVELOPMENT.md:1-5

Architecture Overview

The project follows a modular architecture with clear separation of concerns between the MCP server layer, the registry client layer, and individual tool implementations.

System Architecture Diagram

graph TD
    subgraph "Client Layer"
        AI[AI Assistant / Cursor]
    end

    subgraph "MCP Server Layer"
        Server[index.ts]
        Handlers[Tool Handlers]
    end

    subgraph "Registry Client Layer"
        Client[registry-client.ts]
        Cache[LRU Cache<br/>5 min TTL]
        RateLimiter[Rate Limiter<br/>Max 10 concurrent]
        Retry[Exponential Backoff]
    end

    subgraph "External Services"
        NPM[NPM Registry API]
        GitHub[GitHub API]
        Bundlephobia[Bundlephobia API]
    end

    AI --> Server
    Server --> Handlers
    Handlers --> Client
    Client --> Cache
    Client --> RateLimiter
    Client --> Retry
    Client --> NPM
    Client --> GitHub
    Handlers --> Bundlephobia

    style Cache fill:#e1f5fe
    style RateLimiter fill:#fff3e0
    style Retry fill:#f3e5f5

Architecture Specifications

ComponentTechnologyDescription
RuntimeNode.js 18+Uses native fetch API
LanguageTypeScriptStrict mode enabled
MCP SDKMCP ProtocolServer implementation
ValidationZodInput schema validation
HTTP ClientNative fetchWith retry logic
TestingVitestUnit and integration tests
BuildtsupESM/CJS dual output

Source: DEVELOPMENT.md:27-32

Development Setup

Prerequisites

Before setting up the development environment, ensure you have the following installed:

  • Node.js 18+: The project uses the native fetch API available in Node.js 18 and later
  • npm 8+: For package management and running scripts

Verify your Node.js version:

node --version

Initial Setup

Follow these steps to set up the local development environment:

# 1. Clone the repository
git clone https://github.com/alisaitteke/npm-mcp.git
cd npm-mcp

# 2. Install dependencies
npm install

# 3. Build the project
npm run build

Source: DEVELOPMENT.md:7-15

Available Scripts

The project provides several npm scripts for development workflows:

CommandDescription
npm run buildCompiles TypeScript to JavaScript in the dist/ directory
npm testRuns the test suite using Vitest
npm run test:coverageRuns tests and generates coverage report
npm run typecheckRuns TypeScript type checking without emitting files
npm run devRuns the build in watch mode for development

Source: DEVELOPMENT.md:17-23

Project Structure

The codebase is organized into a clear directory structure:

npm-mcp/
├── src/
│   ├── index.ts                 # MCP server entry point
│   ├── registry-client.ts       # NPM API client with cache and retry
│   ├── types.ts                 # Shared TypeScript type definitions
│   └── tools/
│       ├── search-packages.ts       # Package search functionality
│       ├── package-details.ts       # Detailed package information
│       ├── security-audit.ts        # Security vulnerability auditing
│       ├── version-compatibility.ts # Peer dependency checking
│       ├── quality-analysis.ts      # Package quality metrics
│       └── npx-command.ts           # NPX command validation
├── test/                        # Vitest test files
├── bin/
│   └── npm-registry-mcp.js      # npx entry point
├── server.json                  # MCP registry metadata
├── package.json
├── tsconfig.json
├── vitest.config.ts
└── tsup.config.ts

Source: DEVELOPMENT.md:35-50

Registry Client Architecture

The registry-client.ts module provides a centralized HTTP client for interacting with npm registry APIs.

Key Features

FeatureImplementationDetails
Concurrency Limit10 requestsPrevents overwhelming npm API
CacheLRU, 5 minute TTLReduces redundant requests
Retry LogicExponential backoffHandles 429 rate limit responses
Error HandlingGraceful degradationReturns structured error responses

Source: DEVELOPMENT.md:33-36

Cache Behavior

The registry client implements an internal LRU cache with automatic expiration:

sequenceDiagram
    participant Tool as Tool Handler
    participant Client as Registry Client
    participant Cache as LRU Cache
    participant API as NPM Registry

    Tool->>Client: Request package data
    Client->>Cache: Check cache
    alt Cache Hit
        Cache-->>Client: Return cached data
        Client-->>Tool: Response
    else Cache Miss
        Client->>API: Fetch from registry
        API-->>Client: Raw data
        Client->>Cache: Store with TTL
        Client-->>Tool: Response
    end

To clear the cache programmatically:

client.clearCache()

Source: DEVELOPMENT.md:54-56

Rate Limiting

The client enforces a maximum of 10 concurrent requests to the npm registry. When a 429 response is received, exponential backoff is applied before retrying:

graph LR
    A[Request] --> B{Hit rate limit?}
    B -->|No| C[Proceed]
    B -->|Yes| D[Wait exponential backoff]
    D --> E[Retry request]
    E --> B

Tool Implementation Pattern

Each tool follows a consistent implementation pattern with input validation and error handling.

Tool Structure

graph TD
    A[Tool Request] --> B[Zod Validation]
    B --> C{Valid?}
    C -->|No| D[Return validation error]
    C -->|Yes| E[Execute Logic]
    E --> F[Registry API]
    F --> G[Process Response]
    G --> H[Return JSON Result]

Tool Pattern Example

Each tool module follows this structure:

// 1. Import dependencies
import { z } from 'zod';
import { RegistryClient } from '../registry-client.js';

// 2. Define Zod schema for input validation
export const ToolSchema = z.object({
  param1: z.string(),
  param2: z.string().optional(),
});

// 3. Implement tool handler
export async function toolHandler(
  params: z.infer<typeof ToolSchema>,
  client: RegistryClient
): Promise<string> {
  try {
    // Validate input
    const validated = ToolSchema.parse(params);
    
    // Execute logic
    const result = { /* ... */ };
    
    // Return JSON string
    return JSON.stringify(result, null, 2);
  } catch (error) {
    return JSON.stringify({
      success: false,
      error: error instanceof Error ? error.message : 'Unknown error'
    });
  }
}

Source: CONTRIBUTING.md:85-95

Available Tools Reference

Tool Input and Output Specifications

ToolInput ParametersReturns
search_packagesquery, size?Array of matching packages with metadata
package_detailspackageName, version?Full package metadata, dependencies, downloads
security_auditpackageName, version?Vulnerability report with severity levels
check_compatibilitypackageName, fromVersion?, toVersion?, projectDependencies?Breaking changes, dependency diff, semver summary
quality_analysispackageName, version?Quality score, maintenance status, ecosystem metrics
analyze_npx_commandcommand, args?, timeout?Package validation, warnings, suggested safe command

Source: DEVELOPMENT.md:38-48

Tool Integration in Server

Tools are registered in src/index.ts using the MCP SDK's ListToolsRequestSchema and handled via CallToolRequestSchema. When adding a new tool:

  1. Add the tool file to src/tools/
  2. Register the tool schema in ListToolsRequestSchema
  3. Add the handler case in CallToolRequestSchema

Development Workflow

Branch Naming Conventions

Use descriptive branch names with appropriate prefixes:

PrefixPurposeExample
feature/New featuresfeature/capabilities-analysis
fix/Bug fixesfix/cache-invalidation
docs/Documentation updatesdocs/api-reference
test/Test additions or fixestest/security-audit
refactor/Code refactoringrefactor/version-comparison

Source: CONTRIBUTING.md:22-27

Commit Message Format

Follow conventional commits specification:

<type>: <description>

[optional body]

Types:

TypeDescription
featNew feature
fixBug fix
docsDocumentation changes
testTest additions or fixes
refactorCode refactoring

Examples:

feat: add new search filter
fix: resolve caching issue
docs: update README examples
test: add coverage for quality analysis
refactor: simplify version comparison logic

Source: CONTRIBUTING.md:29-42

Pull Request Process

Follow this workflow for contributing changes:

graph LR
    A[Fork & Clone] --> B[Create Branch]
    B --> C[Write Code]
    C --> D[Add Tests]
    D --> E[Update Docs]
    E --> F[Run Tests]
    F --> G{All Pass?}
    G -->|No| H[Fix Issues]
    H --> F
    G -->|Yes| I[Commit & Push]
    I --> J[Open PR]
    J --> K[Review & Merge]

Steps:

``bash git checkout -b feature/my-new-feature ``

  1. Create a Feature Branch
  1. Make Your Changes
  • Write code following the tool implementation pattern
  • Add tests for all new functionality
  • Update documentation as needed

``bash npm test npm run test:coverage npm run typecheck ``

  1. Run Tests

``bash git add . git commit -m "feat: add my new feature" git push origin feature/my-new-feature ``

  1. Commit and Push
  1. Open Pull Request
  • Provide a clear description of changes
  • Link related issues
  • Ensure CI passes

Source: CONTRIBUTING.md:62-80

Code Style Guidelines

TypeScript Standards

RuleDescription
Strict modeTypeScript strict mode must be enabled
JSDoc commentsAdd JSDoc for all public APIs
Function sizeKeep functions small and focused
NamingUse descriptive variable names
PatternsFollow existing code patterns

Source: CONTRIBUTING.md:44-51

Testing Standards

RequirementDescription
CoverageWrite tests for all new features
CasesTest both success and error cases
NamingUse descriptive test names

Example test structure:

it('should handle invalid package names gracefully', async () => {
  // Test implementation
});

Source: CONTRIBUTING.md:53-61

Adding a New Tool

To add a new tool to the MCP server, follow these steps:

Step 1: Create Tool File

Create a new file in src/tools/ with the tool name:

// src/tools/my-tool.ts
import { z } from 'zod';
import { RegistryClient } from '../registry-client.js';

export const MyToolSchema = z.object({
  param: z.string(),
});

export async function myTool(
  params: z.infer<typeof MyToolSchema>,
  client: RegistryClient
): Promise<string> {
  try {
    const validated = MyToolSchema.parse(params);
    // Tool implementation
    return JSON.stringify({ success: true, data: validated });
  } catch (error) {
    return JSON.stringify({
      success: false,
      error: error instanceof Error ? error.message : 'Unknown error'
    });
  }
}

Source: CONTRIBUTING.md:85-102

Step 2: Register in Server

In src/index.ts:

  1. Import the new tool and schema
  2. Add the schema to ListToolsRequestSchema
  3. Add the handler case in CallToolRequestSchema

Step 3: Add Tests

Create a test file in test/my-tool.test.ts:

import { describe, it, expect } from 'vitest';
import { myTool } from '../src/tools/my-tool.js';

describe('myTool', () => {
  it('should handle valid input', async () => {
    // Test implementation
  });
});

Step 4: Run Verification

npm run build
npm test
npm run typecheck

Troubleshooting

Server Won't Start

If the server fails to start, verify:

``bash node --version ``

  1. Node version: Ensure Node.js 18+ is installed

``bash npm run build ``

  1. Rebuild the project:

``bash chmod +x bin/npm-registry-mcp.js ``

  1. Check binary permissions (for Unix systems):

Source: DEVELOPMENT.md:58-64

GitHub Rate Limits

The quality analysis tool uses the GitHub API. Unauthenticated requests are limited to 60 requests per hour. Some packages may fail analysis if this limit is reached.

Source: DEVELOPMENT.md:65-67

Tests Fail

If tests are failing unexpectedly, try a clean reinstall:

rm -rf node_modules package-lock.json
npm install
npm run build
npm test

Source: DEVELOPMENT.md:69-73

Caching and Rate Limits Summary

ResourceLimitTTL
Package metadata10 concurrent5 minutes
Download stats10 concurrent5 minutes
GitHub API60/hour (unauthenticated)N/A
Retry on 429Exponential backoffVariable

To clear the cache internally:

client.clearCache()

Source: DEVELOPMENT.md:54-56

See Also

Source: https://github.com/alisaitteke/npm-mcp / Human Manual

Tool Reference

Related topics: MCP Tools Overview, System Architecture

Section Related Pages

Continue reading this section for the full explanation and source context.

Related topics: MCP Tools Overview, System Architecture

Tool Reference

This page documents all MCP (Model Context Protocol) tools provided by the npm-registry-mcp server. Each tool exposes npm registry functionality to AI assistants, enabling automated package discovery, security analysis, compatibility checking, and quality assessment.

Overview

The npm-registry-mcp server implements seven distinct MCP tools that wrap npm Registry API calls with intelligent caching, rate limiting, and validation. These tools are designed for AI-assisted development workflows where automated package analysis replaces manual research.

graph TD
    A[AI Assistant] -->|Call Tool| B[MCP Server]
    B --> C{Which Tool?}
    C -->|Search| D[search_packages]
    C -->|Details| E[get_package_details]
    C -->|Security| F[audit_security]
    C -->|Compatibility| G[check_compatibility]
    C -->|Quality| H[analyze_quality]
    C -->|Version Compare| I[compare_versions]
    C -->|NPX Command| J[analyze_npx_command]
    
    D --> K[NPM Registry API]
    E --> K
    F --> K
    G --> K
    H --> K
    I --> K
    J --> K
    
    K -->|Response| L[AI Assistant]
    L -->|Decision| M[Safe Install / Warning / Alternative]

Source: src/index.ts

Tool Summary

ToolPurposePrimary Input
search_packagesDiscover packages by keywordquery, limit
get_package_detailsRetrieve comprehensive package metadatapackageName, version?
audit_securityCheck for known vulnerabilitiespackageName, version?
check_compatibilityVerify peer dependency compatibilitypackageName, version?, existingDependencies
analyze_qualityAssess package health and maintenancepackageName
compare_versionsAnalyze changes between versionspackageName, fromVersion, toVersion
analyze_npx_commandValidate npx command executioncommand, args?, timeout?

Source: DEVELOPMENT.md

Source: https://github.com/alisaitteke/npm-mcp / Human Manual

Doramagic Pitfall Log

Source-linked risks stay visible on the manual page so the preview does not read like a recommendation.

medium Capability evidence risk requires verification

May increase setup, validation, or first-run risk for the user.

medium Maintenance risk requires verification

May increase setup, validation, or first-run risk for the user.

medium Security or permission risk requires verification

May increase setup, validation, or first-run risk for the user.

medium Security or permission risk requires verification

May increase setup, validation, or first-run risk for the user.

Doramagic Pitfall Log

Found 6 structured pitfall item(s), including 0 high/blocking item(s). Top priority: Capability evidence risk - Capability evidence risk requires verification.

1. Capability evidence risk: Capability evidence risk requires verification

  • Severity: medium
  • Finding: README/documentation is current enough for a first validation pass.
  • User impact: May increase setup, validation, or first-run risk for the user.
  • Recommended check: Reproduce the official install and quickstart path in an isolated environment.
  • Evidence: capability.assumptions | mcp_registry:io.github.alisaitteke/npm-mcp:0.0.3 | https://registry.modelcontextprotocol.io/v0.1/servers/io.github.alisaitteke%2Fnpm-mcp/versions/0.0.3

2. Maintenance risk: Maintenance risk requires verification

  • Severity: medium
  • Finding: Project evidence flags a maintenance risk. Review the linked source before relying on this workflow.
  • User impact: May increase setup, validation, or first-run risk for the user.
  • Recommended check: Reproduce the official install and quickstart path in an isolated environment.
  • Evidence: evidence.maintainer_signals | mcp_registry:io.github.alisaitteke/npm-mcp:0.0.3 | https://registry.modelcontextprotocol.io/v0.1/servers/io.github.alisaitteke%2Fnpm-mcp/versions/0.0.3

3. Security or permission risk: Security or permission risk requires verification

  • Severity: medium
  • Finding: no_demo
  • User impact: May increase setup, validation, or first-run risk for the user.
  • Recommended check: Reproduce the official install and quickstart path in an isolated environment.
  • Evidence: downstream_validation.risk_items | mcp_registry:io.github.alisaitteke/npm-mcp:0.0.3 | https://registry.modelcontextprotocol.io/v0.1/servers/io.github.alisaitteke%2Fnpm-mcp/versions/0.0.3

4. Security or permission risk: Security or permission risk requires verification

  • Severity: medium
  • Finding: no_demo
  • User impact: May increase setup, validation, or first-run risk for the user.
  • Recommended check: Reproduce the official install and quickstart path in an isolated environment.
  • Evidence: risks.scoring_risks | mcp_registry:io.github.alisaitteke/npm-mcp:0.0.3 | https://registry.modelcontextprotocol.io/v0.1/servers/io.github.alisaitteke%2Fnpm-mcp/versions/0.0.3

5. Maintenance risk: Maintenance risk requires verification

  • Severity: low
  • Finding: issue_or_pr_quality=unknown。
  • User impact: May increase setup, validation, or first-run risk for the user.
  • Recommended check: Reproduce the official install and quickstart path in an isolated environment.
  • Evidence: evidence.maintainer_signals | mcp_registry:io.github.alisaitteke/npm-mcp:0.0.3 | https://registry.modelcontextprotocol.io/v0.1/servers/io.github.alisaitteke%2Fnpm-mcp/versions/0.0.3

6. Maintenance risk: Maintenance risk requires verification

  • Severity: low
  • Finding: release_recency=unknown。
  • User impact: May increase setup, validation, or first-run risk for the user.
  • Recommended check: Reproduce the official install and quickstart path in an isolated environment.
  • Evidence: evidence.maintainer_signals | mcp_registry:io.github.alisaitteke/npm-mcp:0.0.3 | https://registry.modelcontextprotocol.io/v0.1/servers/io.github.alisaitteke%2Fnpm-mcp/versions/0.0.3

Source: Doramagic discovery, validation, and Project Pack records

Community Discussion Evidence

These external discussion links are review inputs, not standalone proof that the project is production-ready.

Sources 1

Count of project-level external discussion links exposed on this manual page.

Use Review before install

Open the linked issues or discussions before treating the pack as ready for your environment.

Community Discussion Evidence

Doramagic exposes project-level community discussion separately from official documentation. Review these links before using npm-mcp with real data or production workflows.

Source: Project Pack community evidence and pitfall evidence