# https://github.com/alisaitteke/npm-mcp Project Manual

Generated at: 2026-05-30 18:56:58 UTC

## Table of Contents

- [Home](#home)
- [Installation](#installation)
- [Configuration](#configuration)
- [MCP Tools Overview](#mcp-tools-overview)
- [Package Search and Discovery](#package-search)
- [Security Auditing](#security-auditing)
- [Compatibility and Version Management](#compatibility-checking)
- [System Architecture](#architecture)
- [Development Guide](#development-guide)
- [Tool Reference](#tool-reference)

<a id='home'></a>

## Home

### Related Pages

Related topics: [Installation](#installation), [MCP Tools Overview](#mcp-tools-overview)

<details>
<summary>Related Source Files</summary>

The following source files were used to generate this page:

- [README.md](https://github.com/alisaitteke/npm-mcp/blob/main/README.md)
- [package.json](https://github.com/alisaitteke/npm-mcp/blob/main/package.json)
- [server.json](https://github.com/alisaitteke/npm-mcp/blob/main/server.json)
- [DEVELOPMENT.md](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md)
- [CONTRIBUTING.md](https://github.com/alisaitteke/npm-mcp/blob/main/CONTRIBUTING.md)
- [src/index.ts](https://github.com/alisaitteke/npm-mcp/blob/main/src/index.ts)
- [src/registry-client.ts](https://github.com/alisaitteke/npm-mcp/blob/main/src/registry-client.ts)
- [src/types.ts](https://github.com/alisaitteke/npm-mcp/blob/main/src/types.ts)
- [AI_USAGE.md](https://github.com/alisaitteke/npm-mcp/blob/main/AI_USAGE.md)
- [PROMPTS.md](https://github.com/alisaitteke/npm-mcp/blob/main/PROMPTS.md)
</details>

# 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](https://github.com/alisaitteke/npm-mcp/blob/main/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.

```mermaid
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

| Component | File | Purpose |
|-----------|------|---------|
| Server Entry | `src/index.ts` | MCP protocol handling, tool registration, request routing |
| Registry Client | `src/registry-client.ts` | HTTP client with caching, rate limiting, retry logic |
| Type Definitions | `src/types.ts` | Shared TypeScript interfaces and types |
| Tool Handlers | `src/tools/*.ts` | Individual MCP tool implementations |

**Source:** [DEVELOPMENT.md - Architecture](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md#L40-L44)

### 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](https://github.com/alisaitteke/npm-mcp/blob/main/src/registry-client.ts)

## Available Tools

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

### Tool Reference

| Tool | Input Parameters | Purpose |
|------|-----------------|---------|
| `search_packages` | `query`, `limit?` | Search npm registry with ranked results |
| `get_package_details` | `packageName`, `version?` | Retrieve comprehensive package metadata |
| `audit_security` | `packageName`, `version?` | Check for known vulnerabilities |
| `check_compatibility` | `packageName`, `version?`, `existingDependencies` | Verify peer dependency compatibility |
| `analyze_quality` | `packageName` | Score based on GitHub metrics and community |
| `compare_versions` | `packageName`, `fromVersion`, `toVersion` | Analyze breaking changes between versions |
| `analyze_npx_command` | `command`, `args?`, `timeout?` | Validate NPX commands before execution |
| `analyze_capabilities` | `packageName` | Analyze module systems and TypeScript support |

**Source:** [DEVELOPMENT.md - Tool reference](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md#L47-L70)

### Search Packages

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

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

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

**Source:** [DEVELOPMENT.md - search_packages](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md#L47-L49)

### Security Audit

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

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

**Source:** [AI_USAGE.md - audit_security](https://github.com/alisaitteke/npm-mcp/blob/main/AI_USAGE.md)

### Version Compatibility

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

```typescript
// 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](https://github.com/alisaitteke/npm-mcp/blob/main/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](https://github.com/alisaitteke/npm-mcp/blob/main/PRODUCTIVITY.md)

## MCP Prompts

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

### Available Prompts

| Prompt | Description |
|--------|-------------|
| `/check_before_install` | Full security and compatibility check before installing |
| `/find_package` | Search, compare, and recommend packages for a use case |
| `/audit_project` | Scan all dependencies in a package.json |
| `/analyze_bundle` | Analyze bundle size and tree-shaking support |

**Source:** [PROMPTS.md](https://github.com/alisaitteke/npm-mcp/blob/main/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:**
```
✅ express@4.18.2 is safe to install

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

Install: npm install express@4.18.2
```

**Source:** [PROMPTS.md - /check_before_install](https://github.com/alisaitteke/npm-mcp/blob/main/PROMPTS.md#L7-L25)

## Installation and Setup

### Prerequisites

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

**Source:** [DEVELOPMENT.md - Setup](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md#L4-L10)

### Quick Start

```bash
# 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](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md#L4-L10)

### Available Scripts

| Command | Description |
|---------|-------------|
| `npm run build` | Compile TypeScript to `dist/` directory |
| `npm test` | Run test suite with Vitest |
| `npm run test:coverage` | Generate coverage report |
| `npm run typecheck` | Run TypeScript type checking |
| `npm run dev` | Watch mode for development |

**Source:** [DEVELOPMENT.md - Scripts](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md#L13-L20)

## AI Integration Patterns

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

```mermaid
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:

| Trigger | Tool(s) Called | Purpose |
|---------|---------------|---------|
| "install X", "add X" | `audit_security` + `check_compatibility` | Validate before installation |
| "which package", "best library" | `search_packages` | Find and compare options |
| "npx create-..." | `analyze_npx_command` | Validate before execution |
| Mentions package name | `get_package_details` | Show info proactively |
| "update X", "upgrade X" | `compare_versions` + `audit_security` | Show changes and security |
| Pastes package.json | `audit_security` (all deps) | Security report |

**Source:** [AI_USAGE.md](https://github.com/alisaitteke/npm-mcp/blob/main/AI_USAGE.md)

### Configuration for AI Platforms

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

```markdown
# 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](https://github.com/alisaitteke/npm-mcp/blob/main/AI_USAGE.md)

## 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](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md#L22-L39)

## Adding New Tools

To extend npm-mcp with additional tools:

1. **Create the tool file** in `src/tools/<name>.ts`:

```typescript
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
}
```

2. **Register the tool** in `src/index.ts`:
   - Add to `ListToolsRequestSchema`
   - Add handler to `CallToolRequestSchema`

3. **Add tests** in `test/<name>.test.ts`

**Source:** [DEVELOPMENT.md - Adding a new tool](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md#L79-L83)

## Troubleshooting

### Server Won't Start

```bash
# 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](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md#L71-L76)

### 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](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md#L77-L79)

### Test Failures

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

**Source:** [DEVELOPMENT.md - Test fails](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md#L80-L85)

## 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](https://github.com/alisaitteke/npm-mcp/blob/main/CONTRIBUTING.md#L18-L24)

### 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](https://github.com/alisaitteke/npm-mcp/blob/main/CONTRIBUTING.md#L26-L34)

### 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](https://github.com/alisaitteke/npm-mcp/blob/main/CONTRIBUTING.md#L58-L73)

## See Also

- [Package Details Tool](./package-details.md) — Detailed documentation on retrieving package metadata
- [Security Audit Tool](./security-audit.md) — Vulnerability scanning implementation
- [Version Compatibility](./version-compatibility.md) — Peer dependency checking details
- [AI Usage Guide](./ai-usage.md) — Best practices for AI assistant integration
- [Automatic Workflows](./automatic.md) — Workflow automation examples
- [Capabilities Analysis](./capabilities.md) — Module system and TypeScript support analysis

---

<a id='installation'></a>

## Installation

### Related Pages

Related topics: [Home](#home), [Configuration](#configuration)

<details>
<summary>Related Source Files</summary>

The following source files were used to generate this page:

- [package.json](https://github.com/alisaitteke/npm-mcp/blob/main/package.json)
- [DEVELOPMENT.md](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md)
- [CONTRIBUTING.md](https://github.com/alisaitteke/npm-mcp/blob/main/CONTRIBUTING.md)
- [src/registry-client.ts](https://github.com/alisaitteke/npm-mcp/blob/main/src/registry-client.ts)
- [src/index.ts](https://github.com/alisaitteke/npm-mcp/blob/main/src/index.ts)
</details>

# 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](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md)

## Prerequisites

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

| Requirement | Version | Notes |
|-------------|---------|-------|
| Node.js | 18+ | Native fetch API required |
| npm | Latest stable | For package installation |
| Git | Any recent version | For cloning repository |

You can verify your Node.js version with:

```bash
node --version
```

Source: [DEVELOPMENT.md](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md)

## Installation Methods

### Method 1: NPX (Recommended for Quick Testing)

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

```bash
npx npm-registry-mcp
```

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

Source: [DEVELOPMENT.md](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md)

### Method 2: Clone from GitHub

For development or customization purposes, clone the repository:

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

Source: [CONTRIBUTING.md](https://github.com/alisaitteke/npm-mcp/blob/main/CONTRIBUTING.md)

## Installation Workflow

```mermaid
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](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md)

## Available npm Scripts

The project includes several npm scripts for common tasks:

| Command | Description |
|---------|-------------|
| `npm run build` | Compiles TypeScript to JavaScript in `dist/` directory |
| `npm test` | Runs the Vitest test suite |
| `npm run test:coverage` | Generates code coverage report |
| `npm run typecheck` | Runs TypeScript type checking without emitting files |
| `npm run dev` | Watches for changes and rebuilds automatically |

Source: [DEVELOPMENT.md](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md)

## Configuring MCP Clients

### Cursor Configuration

Add npm-mcp to your Cursor MCP settings:

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

### Claude Desktop Configuration

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

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

Source: [AI_USAGE.md](https://github.com/alisaitteke/npm-mcp/blob/main/AI_USAGE.md)

## Architecture Overview

The npm-mcp server uses a layered architecture:

```mermaid
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](https://github.com/alisaitteke/npm-mcp/blob/main/src/index.ts)

## Registry Client Configuration

The internal registry client handles API communication with npm services:

| Setting | Value | Description |
|---------|-------|-------------|
| Concurrency Limit | 10 | Maximum simultaneous requests |
| Cache TTL | 5 minutes | Time before cached data expires |
| Rate Limit Strategy | Exponential backoff | Retries on HTTP 429 responses |

Source: [src/registry-client.ts](https://github.com/alisaitteke/npm-mcp/blob/main/src/registry-client.ts)

## Troubleshooting Installation

### Server Won't Start

If the server fails to start:

1. **Verify Node.js version** - Ensure you have Node.js 18 or higher:
   ```bash
   node --version
   ```

2. **Rebuild the project** - Clear and rebuild:
   ```bash
   npm run build
   ```

3. **Check binary permissions** - For npx execution:
   ```bash
   chmod +x bin/npm-registry-mcp.js
   ```

Source: [DEVELOPMENT.md](https://github.com/alisaitteke/npm-mcp/blob/main/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](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md)

### Tests Fail

If the test suite fails, try a clean installation:

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

Source: [DEVELOPMENT.md](https://github.com/alisaitteke/npm-mcp/blob/main/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](https://github.com/alisaitteke/npm-mcp/blob/main/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](https://github.com/alisaitteke/npm-mcp/blob/main/CONTRIBUTING.md)

## See Also

- [Development Guide](./DEVELOPMENT.md) - Detailed development setup and architecture
- [Contributing Guide](./CONTRIBUTING.md) - How to contribute to the project
- [AI Usage Guide](./AI_USAGE.md) - Using npm-mcp with AI assistants
- [Capabilities Documentation](./CAPABILITIES.md) - Package capability analysis

---

<a id='configuration'></a>

## Configuration

### Related Pages

Related topics: [Installation](#installation), [Tool Reference](#tool-reference)

<details>
<summary>Related Source Files</summary>

The following source files were used to generate this page:

- [DEVELOPMENT.md](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md)
- [CONTRIBUTING.md](https://github.com/alisaitteke/npm-mcp/blob/main/CONTRIBUTING.md)
- [src/index.ts](https://github.com/alisaitteke/npm-mcp/blob/main/src/index.ts)
- [src/registry-client.ts](https://github.com/alisaitteke/npm-mcp/blob/main/src/registry-client.ts)
- [src/types.ts](https://github.com/alisaitteke/npm-mcp/blob/main/src/types.ts)
- [src/tools/package-details.ts](https://github.com/alisaitteke/npm-mcp/blob/main/src/tools/package-details.ts)
- [src/tools/version-compatibility.ts](https://github.com/alisaitteke/npm-mcp/blob/main/src/tools/version-compatibility.ts)
- [server.json](https://github.com/alisaitteke/npm-mcp/blob/main/server.json)
</details>

# 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](https://github.com/alisaitteke/npm-mcp/blob/main/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.

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

Source: [DEVELOPMENT.md](https://github.com/alisaitteke/npm-mcp/blob/main/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

```typescript
// 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](https://github.com/alisaitteke/npm-mcp/blob/main/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

```mermaid
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

| Parameter | Default Value | Description |
|-----------|---------------|-------------|
| `concurrencyLimit` | 10 | Maximum concurrent HTTP requests |
| `cacheTTL` | 5 minutes | Time-to-live for cached responses |
| `maxRetries` | 3 | Maximum retry attempts on failure |
| `backoffBase` | 1000ms | Base delay for exponential backoff |
| `backoffMax` | 10000ms | Maximum backoff delay |

Source: [DEVELOPMENT.md](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md)

### Caching Strategy

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

```typescript
// 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

```mermaid
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:

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

Source: [DEVELOPMENT.md](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md)

## Tool-Specific Configuration

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

### Search Packages Tool

| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `query` | string | Yes | - | Search query string |
| `limit` | number | No | 10 | Max results (1-50) |

```typescript
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](https://github.com/alisaitteke/npm-mcp/blob/main/src/tools/package-details.ts)

### Package Details Tool

| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `packageName` | string | Yes | - | npm package name |
| `version` | string | No | latest | Specific version to retrieve |

```typescript
export const PackageDetailsSchema = z.object({
  packageName: z.string().min(1),
  version: z.string().optional(),
});
```

Source: [src/tools/package-details.ts](https://github.com/alisaitteke/npm-mcp/blob/main/src/tools/package-details.ts)

### Security Audit Tool

| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `packageName` | string | Yes | - | Package to audit |
| `version` | string | No | latest | Specific version |

### Version Compatibility Tool

| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `packageName` | string | Yes | - | Package to check |
| `version` | string | No | latest | Target version |
| `existingDependencies` | Record<string, string> | Yes | - | Current project dependencies |

```typescript
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](https://github.com/alisaitteke/npm-mcp/blob/main/src/tools/version-compatibility.ts)

### Compare Versions Tool

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `packageName` | string | Yes | Package name |
| `fromVersion` | string | Yes | Starting version |
| `toVersion` | string | Yes | Target version |

### NPX Command Analysis Tool

| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `command` | string | Yes | - | Command to analyze (e.g., `create-react-app`) |
| `args` | string[] | No | [] | Command arguments |
| `timeout` | number | No | 30000 | Timeout in milliseconds |

## Type Definitions

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

```typescript
// 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](https://github.com/alisaitteke/npm-mcp/blob/main/src/types.ts)

## Environment Configuration

### Node.js Requirements

| Setting | Value | Description |
|---------|-------|-------------|
| `node` | >= 18.0.0 | Native fetch support required |
| `platform` | any | Cross-platform compatible |

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

### Package Scripts

| Script | Command | Purpose |
|--------|---------|---------|
| `build` | `tsc` | Compile TypeScript to `dist/` |
| `test` | `vitest` | Run test suite |
| `test:coverage` | `vitest --coverage` | Generate coverage report |
| `typecheck` | `tsc --noEmit` | TypeScript type checking |
| `dev` | `tsc --watch` | Watch mode for development |

Source: [DEVELOPMENT.md](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md)

## Adding Custom Tools

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

### Step 1: Create Tool Schema

```typescript
// 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

```typescript
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](https://github.com/alisaitteke/npm-mcp/blob/main/CONTRIBUTING.md)

## Error Handling Configuration

All tools return consistent JSON responses with error handling:

```typescript
// 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](https://github.com/alisaitteke/npm-mcp/blob/main/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:

```typescript
// Clear internal cache
client.clearCache();
```

### Tests Failing

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

Source: [DEVELOPMENT.md](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md)

## Configuration Data Flow

```mermaid
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

- [Development Guide](DEVELOPMENT.md) - Setup and development workflow
- [Contributing Guide](CONTRIBUTING.md) - How to add new tools
- [AI Usage Guide](AI_USAGE.md) - How AI assistants should use the tools
- [Prompts Reference](PROMPTS.md) - Available slash commands
- [Automatic Workflows](AUTOMATIC.md) - Autonomous AI workflows
- [Capabilities Analysis](CAPABILITIES.md) - Package capability detection
- [Productivity Tools](PRODUCTIVITY.md) - Package comparison tools

---

<a id='mcp-tools-overview'></a>

## MCP Tools Overview

### Related Pages

Related topics: [Package Search and Discovery](#package-search), [Security Auditing](#security-auditing), [Compatibility and Version Management](#compatibility-checking)

<details>
<summary>Related Source Files</summary>

The following source files were used to generate this page:

- [src/index.ts](https://github.com/alisaitteke/npm-mcp/blob/main/src/index.ts)
- [src/types.ts](https://github.com/alisaitteke/npm-mcp/blob/main/src/types.ts)
- [src/tools/package-details.ts](https://github.com/alisaitteke/npm-mcp/blob/main/src/tools/package-details.ts)
- [src/tools/npx-command.ts](https://github.com/alisaitteke/npm-mcp/blob/main/src/tools/npx-command.ts)
- [AI_USAGE.md](https://github.com/alisaitteke/npm-mcp/blob/main/AI_USAGE.md)
- [AUTOMATIC.md](https://github.com/alisaitteke/npm-mcp/blob/main/AUTOMATIC.md)
- [PRODUCTIVITY.md](https://github.com/alisaitteke/npm-mcp/blob/main/PRODUCTIVITY.md)
- [CAPABILITIES.md](https://github.com/alisaitteke/npm-mcp/blob/main/CAPABILITIES.md)
- [PROMPTS.md](https://github.com/alisaitteke/npm-mcp/blob/main/PROMPTS.md)
- [DEVELOPMENT.md](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md)
</details>

# 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](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md)

## 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.

```mermaid
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

| Component | File | Purpose |
|-----------|------|---------|
| Registry Client | `src/registry-client.ts` | HTTP client with caching, rate limiting, and retry logic |
| Type Definitions | `src/types.ts` | Shared TypeScript interfaces for API responses |
| MCP Entry Point | `src/index.ts` | Server 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](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md)

## 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.

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `query` | string | Yes | Search query string |
| `limit` | number | No | Maximum results to return (default: 10, max: 50) |

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

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

Source: [DEVELOPMENT.md:52-55](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md)

### get_package_details

Retrieves comprehensive metadata for a specific package.

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `packageName` | string | Yes | Name of the npm package |
| `version` | string | No | Specific 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](https://github.com/alisaitteke/npm-mcp/blob/main/src/tools/package-details.ts)

### audit_security

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

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `packageName` | string | Yes | Name of the npm package |
| `version` | string | No | Specific 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](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md)
Source: [AI_USAGE.md:1-15](https://github.com/alisaitteke/npm-mcp/blob/main/AI_USAGE.md)

### check_compatibility

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

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `packageName` | string | Yes | Name of the npm package |
| `version` | string | No | Specific version to check |
| `existingDependencies` | Record<string, string> | Yes | Current project dependencies |

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

```mermaid
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](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md)

### analyze_quality

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

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `packageName` | string | Yes | Name 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](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md)
Source: [DEVELOPMENT.md:101-103](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md)

### compare_versions

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

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `packageName` | string | Yes | Name of the npm package |
| `fromVersion` | string | Yes | Starting version |
| `toVersion` | string | Yes | Target 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](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md)

### analyze_npx_command

Validates and analyzes npx commands without executing them.

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `command` | string | Yes | Command string (e.g., `create-react-app` or `typescript@5.0.0`) |
| `args` | string[] | No | Arguments to pass to the command |
| `timeout` | number | No | Timeout 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](https://github.com/alisaitteke/npm-mcp/blob/main/src/tools/npx-command.ts)
Source: [DEVELOPMENT.md:74-79](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md)

## 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](https://github.com/alisaitteke/npm-mcp/blob/main/PRODUCTIVITY.md)

### 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](https://github.com/alisaitteke/npm-mcp/blob/main/PRODUCTIVITY.md)

### 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](https://github.com/alisaitteke/npm-mcp/blob/main/PRODUCTIVITY.md)

### analyze_capabilities

Provides comprehensive analysis of package capabilities.

**Analyzes**:

| Capability | Description |
|------------|-------------|
| Module System | ESM, CommonJS, UMD, or dual package support |
| TypeScript | Built-in types, type definitions location |
| Platform Support | Node.js, Browser, Deno, Bun, React, React Native |
| Export Formats | Main entry points and subpath exports |

Source: [CAPABILITIES.md:1-60](https://github.com/alisaitteke/npm-mcp/blob/main/CAPABILITIES.md)

## 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](https://github.com/alisaitteke/npm-mcp/blob/main/AUTOMATIC.md)

### Recommended Workflow: Check Before Install

For any package installation recommendation, the recommended workflow is:

```mermaid
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](https://github.com/alisaitteke/npm-mcp/blob/main/AI_USAGE.md)

### MCP Prompts (Slash Commands)

The server includes smart prompts for common workflows:

| Prompt | Purpose |
|--------|---------|
| `/check_before_install` | Full security and compatibility check before installing |
| `/find_package` | Find 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](https://github.com/alisaitteke/npm-mcp/blob/main/PROMPTS.md)

## Input Validation

All MCP tools use [Zod](https://zod.dev) 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](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md)

## Response Format

All tools return JSON-formatted strings with consistent structures:

### Success Response

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

### Error Response

```json
{
  "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](https://github.com/alisaitteke/npm-mcp/blob/main/src/tools/package-details.ts)

## Configuration and Environment

### Server Requirements

| Requirement | Value |
|-------------|-------|
| Node.js | >= 18.0.0 |
| Dependencies | MCP SDK, Zod, semver, Octokit, lru-cache |

Source: [package.json:1-30](https://github.com/alisaitteke/npm-mcp/blob/main/package.json)

### Rate Limits and Quotas

| API | Limit | Notes |
|-----|-------|-------|
| npm Registry | 10 concurrent requests | Shared pool across all tools |
| GitHub API | 60 req/hour (unauthenticated) | Used for `analyze_quality` |

Source: [DEVELOPMENT.md:93-97](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md)
Source: [DEVELOPMENT.md:101-103](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md)

## Common Failure Modes

| Issue | Cause | Solution |
|-------|-------|----------|
| Server won't start | Node version too old | Ensure Node 18+: `node --version` |
| Server won't start | Build outdated | Run `npm run build` |
| Server won't start | Bin not executable | `chmod +x bin/npm-registry-mcp.js` |
| Quality analysis fails | GitHub rate limit | Wait or use authenticated requests |
| Cache issues | Stale data | Internal cache has 5 min TTL |

Source: [DEVELOPMENT.md:105-115](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md)

## 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`

```typescript
// 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](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md)

## See Also

- [Development Guide](DEVELOPMENT.md) - Setup, architecture, and troubleshooting
- [Contributing Guidelines](CONTRIBUTING.md) - Code standards and PR process
- [AI Usage Patterns](AI_USAGE.md) - How AI assistants use these tools
- [Automatic Workflows](AUTOMATIC.md) - Autonomous AI agent integrations
- [Productivity Tools](PRODUCTIVITY.md) - Developer productivity features
- [Capabilities Analysis](CAPABILITIES.md) - Package capability detection

---

<a id='package-search'></a>

## Package Search and Discovery

### Related Pages

Related topics: [MCP Tools Overview](#mcp-tools-overview), [Security Auditing](#security-auditing)

<details>
<summary>Related Source Files</summary>

The following source files were used to generate this page:

- [src/tools/search-packages.ts](https://github.com/alisaitteke/npm-mcp/blob/main/src/tools/search-packages.ts)
- [src/registry-client.ts](https://github.com/alisaitteke/npm-mcp/blob/main/src/registry-client.ts)
- [src/types.ts](https://github.com/alisaitteke/npm-mcp/blob/main/src/types.ts)
- [src/tools/package-details.ts](https://github.com/alisaitteke/npm-mcp/blob/main/src/tools/package-details.ts)
- [src/tools/version-compatibility.ts](https://github.com/alisaitteke/npm-mcp/blob/main/src/tools/version-compatibility.ts)
- [PROMPTS.md](https://github.com/alisaitteke/npm-mcp/blob/main/PROMPTS.md)
- [PRODUCTIVITY.md](https://github.com/alisaitteke/npm-mcp/blob/main/PRODUCTIVITY.md)
</details>

# Package Search and Discovery

The Package Search and Discovery module provides AI assistants with comprehensive npm registry search capabilities. This module enables natural language queries to discover, compare, and analyze npm packages directly through the MCP (Model Context Protocol) interface, eliminating the need for manual web searches or documentation review.

## Overview

The search and discovery system consists of three primary tools that work together to provide a complete package discovery workflow:

| Tool | Purpose | Primary Use Case |
|------|---------|------------------|
| `search_packages` | Full-text search with scoring | Finding packages by keyword or use case |
| `find_similar_packages` | Alternative package discovery | Finding alternatives to deprecated or suboptimal packages |
| `compare_packages` | Side-by-side comparison | Choosing between competing packages |

Source: [PRODUCTIVITY.md](https://github.com/alisaitteke/npm-mcp/blob/main/PRODUCTIVITY.md)

### Search Flow Architecture

```mermaid
graph TD
    A[User Query] --> B[search_packages]
    B --> C[NPM Registry API]
    C --> D[Score Calculation]
    D --> E[Ranked Results]
    E --> F[Package Details]
    F --> G[compare_packages]
    E --> H[find_similar_packages]
    
    I[Registry Client] --> C
    J[LRU Cache] --> I
    K[Rate Limiter] --> I
```

## search_packages Tool

The `search_packages` tool provides full-text search functionality against the npm registry, returning ranked results with quality, popularity, and maintenance scores.

### Input Parameters

| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `query` | string | Yes | - | Search query string |
| `limit` | number | No | 10 | Maximum results to return (max: 50) |

Source: [src/tools/search-packages.ts](https://github.com/alisaitteke/npm-mcp/blob/main/src/tools/search-packages.ts)

### Response Schema

```typescript
interface SearchResponse {
  success: boolean;
  query: string;
  packages: SearchResult[];
  total: number;
  returned: number;
  message: string;
}

interface SearchResult {
  name: string;
  version: string;
  description: string;
  author: string;
  keywords: string[];
  links: {
    npm: string;
    homepage: string;
    repository: string;
  };
  score: {
    final: number;       // 0-100 scale
    quality: number;     // 0-100 scale
    popularity: number;  // 0-100 scale
    maintenance: number; // 0-100 scale
  };
  publishedAt: string;
}
```

Source: [src/types.ts](https://github.com/alisaitteke/npm-mcp/blob/main/src/types.ts)

### Score Calculation

The npm registry provides composite scores for each package. The `search_packages` tool normalizes these scores to a 0-100 scale:

```typescript
score: {
  final: Math.round(obj.score.final * 100),
  quality: Math.round(obj.score.detail.quality * 100),
  popularity: Math.round(obj.score.detail.popularity * 100),
  maintenance: Math.round(obj.score.detail.maintenance * 100),
}
```

Source: [src/tools/search-packages.ts:52-55](https://github.com/alisaitteke/npm-mcp/blob/main/src/tools/search-packages.ts)

### Example Usage

**AI Agent Detection Triggers:**

The search tool is automatically invoked when users mention:
- Search keywords: "search", "find", "discover", "look for", "best", "top"
- Package names in context: "express", "react", "lodash"
- Commands: "npm install", "yarn add", "pnpm add"
- Code patterns: `import` or `require` statements

Source: [AUTOMATIC.md](https://github.com/alisaitteke/npm-mcp/blob/main/AUTOMATIC.md)

**Example Request:**
```json
{
  "query": "react state management",
  "limit": 5
}
```

**Example Response:**
```json
{
  "success": true,
  "query": "react state management",
  "packages": [
    {
      "name": "zustand",
      "version": "4.4.7",
      "description": "A small, fast and scalable bearbones state-management solution",
      "author": "pmndrs",
      "keywords": ["react", "state-management", "hooks", "redux"],
      "links": {
        "npm": "https://www.npmjs.com/package/zustand",
        "homepage": "https://github.com/pmndrs/zustand",
        "repository": "https://github.com/pmndrs/zustand"
      },
      "score": {
        "final": 85,
        "quality": 92,
        "popularity": 78,
        "maintenance": 95
      },
      "publishedAt": "2023-01-15"
    }
  ],
  "total": 156,
  "returned": 5,
  "message": "Found 156 packages. Showing top 5."
}
```

## find_similar_packages Tool

The `find_similar_packages` tool discovers packages similar to a given package, useful for finding alternatives when a package is deprecated, unmaintained, or unsuitable.

### Use Cases

| Scenario | AI Behavior |
|----------|-------------|
| Deprecated package referenced | Auto-suggest modern alternatives |
| Performance concerns | Find lightweight alternatives |
| License incompatibility | Find packages with compatible licenses |
| Missing features | Find feature-rich alternatives |

Source: [PRODUCTIVITY.md](https://github.com/alisaitteke/npm-mcp/blob/main/PRODUCTIVITY.md)

### Example Workflow

```
User: "Is there something better than request?"

AI automatically:
1. find_similar_packages("request")
2. Finds: axios, node-fetch, got, undici
3. audit_security for each
4. Responds with recommendations
```

Source: [PRODUCTIVITY.md](https://github.com/alisaitteke/npm-mcp/blob/main/PRODUCTIVITY.md)

### Example Output

```json
{
  "original": {
    "name": "express",
    "keywords": ["framework", "web", "http", "server"]
  },
  "similar": [
    {
      "name": "fastify",
      "description": "Fast and low overhead web framework",
      "score": 95,
      "downloads": 2500000,
      "similarity": "Alternative"
    },
    {
      "name": "koa",
      "description": "Expressive middleware for node.js",
      "score": 88,
      "downloads": 1200000,
      "similarity": "Alternative"
    }
  ]
}
```

## compare_packages Tool

The `compare_packages` tool performs detailed side-by-side analysis of multiple packages, examining module systems, TypeScript support, popularity metrics, and bundle characteristics.

### Comparison Dimensions

| Dimension | Metrics Analyzed |
|-----------|------------------|
| **Module System** | ESM, CommonJS, UMD, Dual Package support |
| **TypeScript** | Built-in types, @types needed, TS source |
| **Popularity** | Weekly downloads, relative ranking |
| **Maintenance** | Last update, release frequency, active issues |
| **Bundle Size** | gzip size, tree-shake potential |
| **Platform Support** | Node.js, Browser, Deno, Bun |

Source: [PRODUCTIVITY.md](https://github.com/alisaitteke/npm-mcp/blob/main/PRODUCTIVITY.md)

### Example Comparison

```json
{
  "comparison": {
    "moduleSystem": {
      "axios": { "summary": "Dual (ESM + CJS)" },
      "node-fetch": { "summary": "ESM only" },
      "undici": { "summary": "Dual (ESM + CJS)" }
    },
    "typescript": {
      "axios": { "hasTypes": true },
      "node-fetch": { "hasTypes": true },
      "undici": { "hasTypes": true }
    },
    "popularity": {
      "axios": { "weeklyDownloads": "45M", "relative": "Very popular" },
      "node-fetch": { "weeklyDownloads": "32M", "relative": "Very popular" },
      "undici": { "weeklyDownloads": "8M", "relative": "Popular" }
    }
  },
  "recommendation": {
    "winner": "undici",
    "summary": "undici scores highest with Modern ESM support, Recently updated, Small size"
  }
}
```

## Integration with Discovery Tools

The search and discovery tools integrate with other npm-mcp tools to provide comprehensive package analysis:

```mermaid
graph LR
    A[search_packages] --> B[package_details]
    A --> C[audit_security]
    A --> D[analyze_capabilities]
    B --> E[compare_packages]
    C --> F[check_compatibility]
    
    G[/find_package] --> A
    G --> C
    G --> D
```

### Combined Analysis Workflow

1. **Search**: `search_packages("react http client")`
2. **Security**: `audit_security` on top results
3. **Capabilities**: `analyze_capabilities` for each package
4. **Compatibility**: `check_compatibility` with existing dependencies
5. **Compare**: `compare_packages` for final decision

Source: [CAPABILITIES.md](https://github.com/alisaitteke/npm-mcp/blob/main/CAPABILITIES.md)

### `/find_package` Prompt

The `/find_package` prompt provides a shortcut for the complete discovery workflow:

**Usage:**
```
/find_package state management
/find_package date library
/find_package testing framework
```

**Workflow:**
1. Searches npm registry
2. Gets top 3 results
3. Checks security + quality for each
4. Recommends best option

Source: [PROMPTS.md](https://github.com/alisaitteke/npm-mcp/blob/main/PROMPTS.md)

## Registry Client Architecture

All search operations route through the centralized `registry-client.ts`, which provides:

| Feature | Implementation |
|---------|----------------|
| **Caching** | LRU cache with 5-minute TTL |
| **Rate Limiting** | Max 10 concurrent requests |
| **Retry Logic** | Exponential backoff on 429 responses |
| **Error Handling** | Graceful degradation with error messages |

Source: [DEVELOPMENT.md](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md)

```mermaid
sequenceDiagram
    participant AI as AI Assistant
    participant MCP as MCP Server
    participant Client as Registry Client
    participant NPM as NPM Registry API
    participant Cache as LRU Cache
    
    AI->>MCP: search_packages({query})
    MCP->>Client: search(query)
    Client->>Cache: Check cache
    Cache-->>Client: Cache hit/miss
    alt Cache Miss
        Client->>NPM: GET /-/v1/search
        NPM-->>Client: Search results
        Client->>Cache: Store result
    end
    Client-->>MCP: Processed results
    MCP-->>AI: Ranked packages
```

## Common Search Patterns

### Pattern 1: Package Installation Check

```
User: "npm install typescript"
AI automatically:
1. search_packages("typescript")
2. analyze_capabilities("typescript")
3. check_compatibility("typescript")
4. Provide install recommendation
```

Source: [AUTOMATIC.md](https://github.com/alisaitteke/npm-mcp/blob/main/AUTOMATIC.md)

### Pattern 2: Alternative Discovery

```
User: "Search for React state management libraries"
AI automatically:
1. search_packages("react state management")
2. compare_packages([top 3 results])
3. analyze_bundle_size(each)
4. Response with comparison
```

Source: [AUTOMATIC.md](https://github.com/alisaitteke/npm-mcp/blob/main/AUTOMATIC.md)

### Pattern 3: Pre-Installation Audit

```
User: "use react-query"
AI automatically:
1. search_packages("react-query")
2. audit_security("react-query")
3. check_compatibility("react-query")
4. Show clear recommendation
```

Source: [AUTOMATIC.md](https://github.com/alisaitteke/npm-mcp/blob/main/AUTOMATIC.md)

## Error Handling

The search tools implement comprehensive error handling:

```typescript
try {
  // Search logic
} catch (error) {
  const errorMessage =
    error instanceof Error ? error.message : 'Unknown error occurred';

  return JSON.stringify({
    success: false,
    error: errorMessage,
    query: validated.query,
  });
}
```

Source: [src/tools/search-packages.ts:63-73](https://github.com/alisaitteke/npm-mcp/blob/main/src/tools/search-packages.ts)

### Error Response Format

| Field | Type | Description |
|-------|------|-------------|
| `success` | boolean | Always `false` on error |
| `error` | string | Human-readable error message |
| `query` | string | The original search query |
| `packageName` | string | Package name if applicable |

Source: [src/tools/package-details.ts](https://github.com/alisaitteke/npm-mcp/blob/main/src/tools/package-details.ts)

## Best Practices

### For AI Assistants

1. **Always use search before recommending** - Don't guess package names; verify with search
2. **Check security first** - Run `audit_security` on any package before recommending
3. **Provide alternatives** - When suggesting a package, mention similar options
4. **Use scores** - Leverage quality/popularity/maintenance scores for recommendations
5. **Include safe commands** - Always provide exact install commands with versions

Source: [AI_USAGE.md](https://github.com/alisaitteke/npm-mcp/blob/main/AI_USAGE.md)

### Red Flags to Watch For

| Indicator | Issue | Action |
|-----------|-------|--------|
| `popularity: < 50` | Low adoption | Verify reliability |
| `maintenance: < 60` | Poor maintenance | Check for forks |
| No TypeScript types | Missing types | Suggest @types package |
| CommonJS only | Old module system | Find modern alternative |
| High dependency count | Bloat risk | Evaluate bundle impact |

## See Also

- [Security Audit and Vulnerability Scanning](./Security-Audit.md) - Package vulnerability analysis
- [Package Quality Analysis](./Quality-Analysis.md) - Scoring and maintenance metrics
- [Version Compatibility Checking](./Version-Compatibility.md) - Dependency conflict detection
- [Capability Analysis](./Capabilities-Analysis.md) - Module system and platform support
- [Development Guide](./Development.md) - Contributing new tools

---

<a id='security-auditing'></a>

## Security Auditing

### Related Pages

Related topics: [MCP Tools Overview](#mcp-tools-overview), [Compatibility and Version Management](#compatibility-checking)

<details>
<summary>Related Source Files</summary>

The following source files were used to generate this page:

- [src/tools/security-audit.ts](https://github.com/alisaitteke/npm-mcp/blob/main/src/tools/security-audit.ts)
- [src/tools/package-details.ts](https://github.com/alisaitteke/npm-mcp/blob/main/src/tools/package-details.ts)
- [AI_USAGE.md](https://github.com/alisaitteke/npm-mcp/blob/main/AI_USAGE.md)
- [AUTOMATIC.md](https://github.com/alisaitteke/npm-mcp/blob/main/AUTOMATIC.md)
- [PROMPTS.md](https://github.com/alisaitteke/npm-mcp/blob/main/PROMPTS.md)
- [DEVELOPMENT.md](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md)
</details>

# 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](https://github.com/alisaitteke/npm-mcp/blob/main/AI_USAGE.md)  
Source: [PROMPTS.md](https://github.com/alisaitteke/npm-mcp/blob/main/PROMPTS.md)

## Architecture

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

```mermaid
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

| Component | Integration Type | Purpose |
|-----------|-----------------|---------|
| `RegistryClient` | HTTP Client | API communication with npm registry |
| `check_compatibility` | Parallel Tool | Combined security + compatibility reports |
| `analyze_quality` | Parallel Tool | Quality metrics alongside security |
| `/audit_project` Prompt | Workflow | Batch auditing of entire projects |
| `/check_before_install` Prompt | Workflow | Pre-installation security validation |

Source: [DEVELOPMENT.md](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md)  
Source: [PROMPTS.md](https://github.com/alisaitteke/npm-mcp/blob/main/PROMPTS.md)

## Tool Reference

### `audit_security`

The primary tool for checking package vulnerabilities.

#### Input Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `packageName` | string | Yes | Name of the npm package to audit |
| `version` | string | No | Specific version to check (defaults to latest) |

#### Response Structure

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

#### Example Response with Vulnerabilities

```json
{
  "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 lodash@4.17.21"
}
```

Source: [AI_USAGE.md](https://github.com/alisaitteke/npm-mcp/blob/main/AI_USAGE.md)  
Source: [src/tools/package-details.ts](https://github.com/alisaitteke/npm-mcp/blob/main/src/tools/package-details.ts)

## Workflow Integration

### Pre-Installation Validation

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

```mermaid
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:

```mermaid
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](https://github.com/alisaitteke/npm-mcp/blob/main/AUTOMATIC.md)  
Source: [AI_USAGE.md](https://github.com/alisaitteke/npm-mcp/blob/main/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:**
```
✅ express@4.18.2 is safe to install

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

Install: npm install express@4.18.2
```

### `/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):
- react@18.2.0
- axios@1.6.0
...

⚠️ Vulnerable packages (2):

1. lodash@4.17.20 (HIGH)
   - Issue: Prototype pollution
   - Fix: npm install lodash@4.17.21
   
2. express@4.17.1 (MODERATE)
   - Issue: Open redirect
   - Fix: npm install express@4.18.2

Total: 25 packages, 2 need updates
```

Source: [PROMPTS.md](https://github.com/alisaitteke/npm-mcp/blob/main/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](https://github.com/alisaitteke/npm-mcp/blob/main/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

| Severity | Icon | Action Required |
|----------|------|-----------------|
| Critical | 🔴 | Immediate upgrade required |
| High | 🟠 | Upgrade strongly recommended |
| Moderate | 🟡 | Upgrade when possible |
| Low | 🟢 | Consider upgrading |

Source: [AI_USAGE.md](https://github.com/alisaitteke/npm-mcp/blob/main/AI_USAGE.md)

## Automatic Security Triggers

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

| User Action | Automatic Tool Call | Purpose |
|-------------|---------------------|---------|
| "install X", "add X" | `audit_security` + `check_compatibility` | Check before recommending install |
| Mentions package name | `get_package_details` | Show info proactively |
| "update X", "upgrade X" | `compare_versions` + `audit_security` | Show changes and security |
| Pastes package.json | `audit_security` (all deps) | Security report for all dependencies |
| AI writing package.json | `audit_security` (auto) | Verify each dependency |

Source: [AUTOMATIC.md](https://github.com/alisaitteke/npm-mcp/blob/main/AUTOMATIC.md)  
Source: [AI_USAGE.md](https://github.com/alisaitteke/npm-mcp/blob/main/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:

```
✅ express@4.18.2 is safe to install

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

Install:
npm install express@4.18.2
```

When vulnerabilities are found:

```
⚠️ SECURITY WARNING: lodash@4.17.20 has 2 vulnerabilities

Severity: High
Issue: Prototype pollution
Safe version: lodash@4.17.21

Recommended:
npm install lodash@4.17.21
```

Source: [AI_USAGE.md](https://github.com/alisaitteke/npm-mcp/blob/main/AI_USAGE.md)

## Caching and Rate Limiting

The security auditing feature benefits from the underlying `RegistryClient` infrastructure:

| Feature | Value | Description |
|---------|-------|-------------|
| Cache TTL | 5 minutes | Package metadata and security data |
| Concurrent Requests | Max 10 | Prevents API throttling |
| 429 Handling | Exponential backoff | Automatic retry on rate limits |
| Cache Clear | `client.clearCache()` | Internal method for fresh data |

Source: [DEVELOPMENT.md](https://github.com/alisaitteke/npm-mcp/blob/main/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

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

Source: [DEVELOPMENT.md](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md)

## See Also

- [Package Details](package-details) - Detailed package metadata retrieval
- [Version Compatibility](version-compatibility) - Dependency conflict detection
- [Quality Analysis](quality-analysis) - Package maintenance and popularity metrics
- [NPX Command Analysis](npx-command-analysis) - Safe command execution
- [Automatic Security](automatic-security) - MCP resource-based security automation
- [MCP Prompts](mcp-prompts) - Slash commands for common workflows
- [Development Guide](development) - Contributing and adding new tools

---

<a id='compatibility-checking'></a>

## Compatibility and Version Management

### Related Pages

Related topics: [MCP Tools Overview](#mcp-tools-overview), [Security Auditing](#security-auditing)

<details>
<summary>Related Source Files</summary>

The following source files were used to generate this page:

- [src/tools/version-compatibility.ts](https://github.com/alisaitteke/npm-mcp/blob/main/src/tools/version-compatibility.ts)
- [src/tools/package-details.ts](https://github.com/alisaitteke/npm-mcp/blob/main/src/tools/package-details.ts)
- [src/registry-client.ts](https://github.com/alisaitteke/npm-mcp/blob/main/src/registry-client.ts)
- [src/types.ts](https://github.com/alisaitteke/npm-mcp/blob/main/src/types.ts)
- [DEVELOPMENT.md](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md)
</details>

# 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.

```mermaid
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:**

| Feature | Implementation |
|---------|----------------|
| **Concurrency Limit** | Maximum 10 concurrent requests |
| **Cache Duration** | 5-minute LRU cache |
| **Rate Limiting** | Exponential backoff on HTTP 429 responses |
| **Error Handling** | Automatic retry with backoff |

Source: [DEVELOPMENT.md](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md)

### Type Definitions

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

| Type | Purpose |
|------|---------|
| `Packument` | Complete package metadata from npm registry |
| `AbbreviatedPackument` | Reduced metadata for specific endpoints |
| `DownloadStats` | Weekly download statistics |
| `RegistryError` | Error responses from registry API |

Source: [src/types.ts](https://github.com/alisaitteke/npm-mcp/blob/main/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

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `packageName` | string | Yes | Name of the npm package |
| `fromVersion` | string | Yes | Starting version (semver) |
| `toVersion` | string | Yes | Target version (semver) |

### Output Structure

The tool returns a JSON response containing:

```typescript
{
  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](https://github.com/alisaitteke/npm-mcp/blob/main/src/tools/version-compatibility.ts)

### How It Works

```mermaid
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 Type | Semver Diff | Implication |
|-------------|-------------|-------------|
| **Major** | `major` | Breaking changes, likely API changes |
| **Minor** | `minor` | New features, backward compatible |
| **Patch** | `patch` | Bug fixes only |
| **Prerelease** | `prerelease` | Alpha/beta releases |
| **Build** | `build` | Build metadata only |

### Recommendation Logic

The tool provides contextual recommendations based on the change type:

```typescript
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](https://github.com/alisaitteke/npm-mcp/blob/main/src/tools/version-compatibility.ts)

## 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

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `packageName` | string | Yes | Name of the npm package |
| `version` | string | No | Specific version to check (defaults to latest) |
| `installedPackages` | object | No | Map of currently installed packages and versions |

### Output Structure

```typescript
{
  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](https://github.com/alisaitteke/npm-mcp/blob/main/src/tools/version-compatibility.ts)

### Compatibility Analysis Flow

```mermaid
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:

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

Source: [src/tools/version-compatibility.ts](https://github.com/alisaitteke/npm-mcp/blob/main/src/tools/version-compatibility.ts)

### Suggested Actions

When incompatibilities are detected, the tool generates actionable recommendations:

| Issue Type | Suggested 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 Point | Source | Description |
|------------|--------|-------------|
| `versions.latest` | `dist-tags.latest` | Current stable release |
| `versions.total` | `Object.keys(versions).length` | Count of all versions |
| `versions.recent` | Filtered by publish time | Latest 10 versions |
| `versions.deprecated` | Versions with `deprecated` field | Deprecated version list |
| `timestamps.created` | `time.created` | Packument creation time |
| `timestamps.modified` | `time.modified` | Last modification time |
| `timestamps.versionPublished` | `time[version]` | Specific version publish date |

Source: [src/tools/package-details.ts](https://github.com/alisaitteke/npm-mcp/blob/main/src/tools/package-details.ts)

### Deprecated Version Tracking

The system identifies deprecated versions:

```typescript
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:

```mermaid
graph LR
    A[Current: lodash@4.17.20] --> 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 lodash@4.17.21]
    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:

```typescript
{
  success: false,
  error: "Version X.X.X not found"
}
```

| Error Scenario | Response |
|----------------|----------|
| 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 semver | Handled by Zod validation schema |

Source: [src/tools/version-compatibility.ts](https://github.com/alisaitteke/npm-mcp/blob/main/src/tools/version-compatibility.ts)

## Architecture Summary

The version management subsystem follows a layered architecture:

```mermaid
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
```

| Layer | Component | Responsibility |
|-------|------------|----------------|
| **Tools** | version-compatibility.ts | Version comparison and compatibility checking |
| **Tools** | package-details.ts | Package metadata retrieval |
| **Client** | registry-client.ts | HTTP requests, caching, rate limiting |
| **Validation** | Zod schemas | Input validation and type safety |
| **API** | npm Registry | Source of truth for package data |

## See Also

- [Package Search and Discovery](search-packages.md) - Finding packages to compare
- [Security Audit](security-audit.md) - Vulnerability scanning for packages
- [Quality Analysis](quality-analysis.md) - Package scoring and maintenance assessment
- [AI Usage Guide](AI_USAGE.md) - Integration patterns for AI assistants
- [Prompt Reference](PROMPTS.md) - Slash commands for common workflows

---

<a id='architecture'></a>

## System Architecture

### Related Pages

Related topics: [Development Guide](#development-guide), [Tool Reference](#tool-reference)

<details>
<summary>Related Source Files</summary>

The following source files were used to generate this page:

- [src/index.ts](https://github.com/alisaitteke/npm-mcp/blob/main/src/index.ts)
- [src/registry-client.ts](https://github.com/alisaitteke/npm-mcp/blob/main/src/registry-client.ts)
- [src/types.ts](https://github.com/alisaitteke/npm-mcp/blob/main/src/types.ts)
- [DEVELOPMENT.md](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md)
- [CONTRIBUTING.md](https://github.com/alisaitteke/npm-mcp/blob/main/CONTRIBUTING.md)
- [src/tools/package-details.ts](https://github.com/alisaitteke/npm-mcp/blob/main/src/tools/package-details.ts)
- [src/tools/version-compatibility.ts](https://github.com/alisaitteke/npm-mcp/blob/main/src/tools/version-compatibility.ts)
</details>

# 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](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md)

## High-Level Architecture

```mermaid
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

| Principle | Implementation |
|-----------|----------------|
| Separation of Concerns | Tool handlers are isolated modules; registry client handles all API communication |
| Input Validation | Zod schemas validate all tool inputs before processing |
| Resilience | Exponential backoff on rate limits; LRU caching to reduce API calls |
| Type Safety | TypeScript with strict mode throughout the codebase |
| Testability | Each tool is independently testable with mocked dependencies |

Source: [DEVELOPMENT.md](https://github.com/alisaitteke/npm-mcp/blob/main/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](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md)

### Core Components

| Component | File | Responsibility |
|-----------|------|----------------|
| MCP Server | `src/index.ts` | Initialize MCP transport, register tools, route requests |
| Registry Client | `src/registry-client.ts` | HTTP calls to npm/GitHub, caching, rate limiting, retries |
| Type Definitions | `src/types.ts` | Shared interfaces for package metadata, API responses |
| Search Tool | `src/tools/search-packages.ts` | Search npm registry by query |
| Package Details | `src/tools/package-details.ts` | Retrieve detailed package information |
| Security Audit | `src/tools/security-audit.ts` | Check for vulnerabilities via npm audit API |
| Version Compatibility | `src/tools/version-compatibility.ts` | Check peer dependency compatibility |
| Quality Analysis | `src/tools/quality-analysis.ts` | Analyze maintenance, popularity, GitHub metrics |
| NPX Command | `src/tools/npx-command.ts` | Validate 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.

```mermaid
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](https://github.com/alisaitteke/npm-mcp/blob/main/src/index.ts)

## Registry Client Architecture

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

```mermaid
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

| Option | Default | Description |
|--------|---------|-------------|
| `concurrencyLimit` | 10 | Maximum concurrent API requests |
| `cacheTTL` | 300000 (5 min) | Cache time-to-live in milliseconds |
| `npmRegistryBase` | `registry.npmjs.org` | Base URL for npm registry API |
| `githubApiBase` | `api.github.com` | Base URL for GitHub API |
| `maxRetries` | 3 | Maximum retry attempts on failure |
| `backoffBase` | 1000 | Base delay for exponential backoff (ms) |

Source: [src/registry-client.ts](https://github.com/alisaitteke/npm-mcp/blob/main/src/registry-client.ts)

### Caching Strategy

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

```typescript
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:

```mermaid
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](https://github.com/alisaitteke/npm-mcp/blob/main/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

```typescript
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

| Tool | Input Schema | Primary API Used |
|------|--------------|------------------|
| `search_packages` | `query: string`, `limit?: number` | npm search API |
| `get_package_details` | `packageName: string`, `version?: string` | npm packument endpoint |
| `audit_security` | `packageName: string`, `version?: string` | npm audit API |
| `check_compatibility` | `packageName`, `version?`, `existingDependencies` | npm packument |
| `analyze_quality` | `packageName: string` | npm stats + GitHub API |
| `compare_versions` | `packageName`, `fromVersion`, `toVersion` | npm packument |
| `analyze_npx_command` | `command: string`, `args?`, `timeout?` | npm view + validation |

### Tool Invocation Flow

```mermaid
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

```mermaid
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

```mermaid
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](https://github.com/alisaitteke/npm-mcp/blob/main/src/tools/version-compatibility.ts)

## Error Handling

The system employs consistent error handling across all components:

### Error Response Format

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

### Error Sources

| Source | Handling |
|--------|----------|
| Invalid input (Zod) | Throws `ZodError` with validation details |
| Package not found | Returns `{ success: false, error: "Package not found" }` |
| Rate limited (429) | Exponential backoff retry (up to 3 attempts) |
| Network failure | Returns `{ success: false, error: "Network error" }` |
| GitHub API limit | Partial results with warning; some packages may fail |

Source: [src/tools/package-details.ts](https://github.com/alisaitteke/npm-mcp/blob/main/src/tools/package-details.ts)

## Type System

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

```typescript
// 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](https://github.com/alisaitteke/npm-mcp/blob/main/src/types.ts)

## External Dependencies

### Runtime Dependencies

| Package | Purpose |
|---------|---------|
| `@modelcontextprotocol/sdk` | MCP protocol implementation |
| `zod` | Schema validation and type inference |
| `semver` | Semantic version parsing and comparison |
| `@octokit/rest` | GitHub API client for quality analysis |
| `node-fetch` | HTTP client (with fallback for Node 18+) |

### Development Dependencies

| Package | Purpose |
|---------|---------|
| `typescript` | Type checking and compilation |
| `vitest` | Unit testing framework |
| `tsx` | TypeScript execution for CLI |

Source: [DEVELOPMENT.md](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md)

## Adding New Tools

To extend the MCP server with a new tool:

```mermaid
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
3. **Add tests in `test/<name>.test.ts`**
4. **Update documentation** as needed

Source: [CONTRIBUTING.md](https://github.com/alisaitteke/npm-mcp/blob/main/CONTRIBUTING.md)

## Deployment Architecture

### Entry Points

| Method | Entry Point | Use Case |
|--------|-------------|----------|
| npx | `bin/npm-registry-mcp.js` | Quick testing |
| Direct | `node dist/index.js` | Custom integrations |
| npm link | Linked globally | Development |

### Environment Requirements

| Requirement | Minimum | Notes |
|-------------|---------|-------|
| Node.js | 18+ | Uses native fetch API |
| npm | Any | For installation only |

Source: [DEVELOPMENT.md](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md)

## See Also

- [Development Setup](DEVELOPMENT.md) — Local development workflow and commands
- [Contributing Guide](CONTRIBUTING.md) — Adding new tools and code standards
- [API Usage Guide](AI_USAGE.md) — How AI assistants should use the MCP tools
- [Command Reference](PROMPTS.md) — Available prompts and slash commands

---

<a id='development-guide'></a>

## Development Guide

### Related Pages

Related topics: [System Architecture](#architecture), [Tool Reference](#tool-reference)

<details>
<summary>Related Source Files</summary>

The following source files were used to generate this page:

- [DEVELOPMENT.md](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md)
- [CONTRIBUTING.md](https://github.com/alisaitteke/npm-mcp/blob/main/CONTRIBUTING.md)
- [src/index.ts](https://github.com/alisaitteke/npm-mcp/blob/main/src/index.ts)
- [src/registry-client.ts](https://github.com/alisaitteke/npm-mcp/blob/main/src/registry-client.ts)
- [src/types.ts](https://github.com/alisaitteke/npm-mcp/blob/main/src/types.ts)
- [src/tools/package-details.ts](https://github.com/alisaitteke/npm-mcp/blob/main/src/tools/package-details.ts)
- [src/tools/version-compatibility.ts](https://github.com/alisaitteke/npm-mcp/blob/main/src/tools/version-compatibility.ts)
</details>

# 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](https://github.com/alisaitteke/npm-mcp/blob/main/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](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md)

## 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

```mermaid
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

| Component | Technology | Description |
|-----------|------------|-------------|
| Runtime | Node.js 18+ | Uses native `fetch` API |
| Language | TypeScript | Strict mode enabled |
| MCP SDK | MCP Protocol | Server implementation |
| Validation | Zod | Input schema validation |
| HTTP Client | Native fetch | With retry logic |
| Testing | Vitest | Unit and integration tests |
| Build | tsup | ESM/CJS dual output |

Source: [DEVELOPMENT.md:27-32](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md)

## 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:

```bash
node --version
```

### Initial Setup

Follow these steps to set up the local development environment:

```bash
# 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](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md)

## Available Scripts

The project provides several npm scripts for development workflows:

| Command | Description |
|---------|-------------|
| `npm run build` | Compiles TypeScript to JavaScript in the `dist/` directory |
| `npm test` | Runs the test suite using Vitest |
| `npm run test:coverage` | Runs tests and generates coverage report |
| `npm run typecheck` | Runs TypeScript type checking without emitting files |
| `npm run dev` | Runs the build in watch mode for development |

Source: [DEVELOPMENT.md:17-23](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md)

## 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](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md)

## Registry Client Architecture

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

### Key Features

| Feature | Implementation | Details |
|---------|----------------|---------|
| Concurrency Limit | 10 requests | Prevents overwhelming npm API |
| Cache | LRU, 5 minute TTL | Reduces redundant requests |
| Retry Logic | Exponential backoff | Handles 429 rate limit responses |
| Error Handling | Graceful degradation | Returns structured error responses |

Source: [DEVELOPMENT.md:33-36](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md)

### Cache Behavior

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

```mermaid
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:

```typescript
client.clearCache()
```

Source: [DEVELOPMENT.md:54-56](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md)

### 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:

```mermaid
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

```mermaid
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:

```typescript
// 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](https://github.com/alisaitteke/npm-mcp/blob/main/CONTRIBUTING.md)

## Available Tools Reference

### Tool Input and Output Specifications

| Tool | Input Parameters | Returns |
|------|------------------|---------|
| `search_packages` | `query`, `size?` | Array of matching packages with metadata |
| `package_details` | `packageName`, `version?` | Full package metadata, dependencies, downloads |
| `security_audit` | `packageName`, `version?` | Vulnerability report with severity levels |
| `check_compatibility` | `packageName`, `fromVersion?`, `toVersion?`, `projectDependencies?` | Breaking changes, dependency diff, semver summary |
| `quality_analysis` | `packageName`, `version?` | Quality score, maintenance status, ecosystem metrics |
| `analyze_npx_command` | `command`, `args?`, `timeout?` | Package validation, warnings, suggested safe command |

Source: [DEVELOPMENT.md:38-48](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md)

### 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:

| Prefix | Purpose | Example |
|--------|---------|---------|
| `feature/` | New features | `feature/capabilities-analysis` |
| `fix/` | Bug fixes | `fix/cache-invalidation` |
| `docs/` | Documentation updates | `docs/api-reference` |
| `test/` | Test additions or fixes | `test/security-audit` |
| `refactor/` | Code refactoring | `refactor/version-comparison` |

Source: [CONTRIBUTING.md:22-27](https://github.com/alisaitteke/npm-mcp/blob/main/CONTRIBUTING.md)

### Commit Message Format

Follow conventional commits specification:

```
<type>: <description>

[optional body]
```

**Types:**

| Type | Description |
|------|-------------|
| `feat` | New feature |
| `fix` | Bug fix |
| `docs` | Documentation changes |
| `test` | Test additions or fixes |
| `refactor` | Code 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](https://github.com/alisaitteke/npm-mcp/blob/main/CONTRIBUTING.md)

### Pull Request Process

Follow this workflow for contributing changes:

```mermaid
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:**

1. **Create a Feature Branch**
   ```bash
   git checkout -b feature/my-new-feature
   ```

2. **Make Your Changes**
   - Write code following the tool implementation pattern
   - Add tests for all new functionality
   - Update documentation as needed

3. **Run Tests**
   ```bash
   npm test
   npm run test:coverage
   npm run typecheck
   ```

4. **Commit and Push**
   ```bash
   git add .
   git commit -m "feat: add my new feature"
   git push origin feature/my-new-feature
   ```

5. **Open Pull Request**
   - Provide a clear description of changes
   - Link related issues
   - Ensure CI passes

Source: [CONTRIBUTING.md:62-80](https://github.com/alisaitteke/npm-mcp/blob/main/CONTRIBUTING.md)

## Code Style Guidelines

### TypeScript Standards

| Rule | Description |
|------|-------------|
| Strict mode | TypeScript strict mode must be enabled |
| JSDoc comments | Add JSDoc for all public APIs |
| Function size | Keep functions small and focused |
| Naming | Use descriptive variable names |
| Patterns | Follow existing code patterns |

Source: [CONTRIBUTING.md:44-51](https://github.com/alisaitteke/npm-mcp/blob/main/CONTRIBUTING.md)

### Testing Standards

| Requirement | Description |
|-------------|-------------|
| Coverage | Write tests for all new features |
| Cases | Test both success and error cases |
| Naming | Use descriptive test names |

**Example test structure:**

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

Source: [CONTRIBUTING.md:53-61](https://github.com/alisaitteke/npm-mcp/blob/main/CONTRIBUTING.md)

## 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:

```typescript
// 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](https://github.com/alisaitteke/npm-mcp/blob/main/CONTRIBUTING.md)

### 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`:

```typescript
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

```bash
npm run build
npm test
npm run typecheck
```

## Troubleshooting

### Server Won't Start

If the server fails to start, verify:

1. **Node version**: Ensure Node.js 18+ is installed
   ```bash
   node --version
   ```

2. **Rebuild the project**:
   ```bash
   npm run build
   ```

3. **Check binary permissions** (for Unix systems):
   ```bash
   chmod +x bin/npm-registry-mcp.js
   ```

Source: [DEVELOPMENT.md:58-64](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md)

### 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](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md)

### Tests Fail

If tests are failing unexpectedly, try a clean reinstall:

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

Source: [DEVELOPMENT.md:69-73](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md)

## Caching and Rate Limits Summary

| Resource | Limit | TTL |
|----------|-------|-----|
| Package metadata | 10 concurrent | 5 minutes |
| Download stats | 10 concurrent | 5 minutes |
| GitHub API | 60/hour (unauthenticated) | N/A |
| Retry on 429 | Exponential backoff | Variable |

To clear the cache internally:

```typescript
client.clearCache()
```

Source: [DEVELOPMENT.md:54-56](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md)

## See Also

- [Contributing Guide](./CONTRIBUTING.md) - Detailed contribution guidelines and workflow
- [Capabilities Analysis](./CAPABILITIES.md) - Package capability analysis tool documentation
- [AI Usage Guide](./AI_USAGE.md) - Guidelines for AI assistants using this MCP
- [Automatic Workflows](./AUTOMATIC.md) - Automated workflow patterns
- [Prompts Reference](./PROMPTS.md) - Available slash commands and prompts
- [Productivity Tips](./PRODUCTIVITY.md) - Combined workflow patterns

---

<a id='tool-reference'></a>

## Tool Reference

### Related Pages

Related topics: [MCP Tools Overview](#mcp-tools-overview), [System Architecture](#architecture)

<details>
<summary>Related Source Files</summary>

The following source files were used to generate this page:

- [src/tools/search-packages.ts](https://github.com/alisaitteke/npm-mcp/blob/main/src/tools/search-packages.ts)
- [src/tools/package-details.ts](https://github.com/alisaitteke/npm-mcp/blob/main/src/tools/package-details.ts)
- [src/tools/security-audit.ts](https://github.com/alisaitteke/npm-mcp/blob/main/src/tools/security-audit.ts)
- [src/tools/version-compatibility.ts](https://github.com/alisaitteke/npm-mcp/blob/main/src/tools/version-compatibility.ts)
- [src/tools/quality-analysis.ts](https://github.com/alisaitteke/npm-mcp/blob/main/src/tools/quality-analysis.ts)
- [src/tools/npx-command.ts](https://github.com/alisaitteke/npm-mcp/blob/main/src/tools/npx-command.ts)
</details>

# 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.

```mermaid
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](https://github.com/alisaitteke/npm-mcp/blob/main/src/index.ts)

## Tool Summary

| Tool | Purpose | Primary Input |
|------|---------|---------------|
| `search_packages` | Discover packages by keyword | `query`, `limit` |
| `get_package_details` | Retrieve comprehensive package metadata | `packageName`, `version?` |
| `audit_security` | Check for known vulnerabilities | `packageName`, `version?` |
| `check_compatibility` | Verify peer dependency compatibility | `packageName`, `version?`, `existingDependencies` |
| `analyze_quality` | Assess package health and maintenance | `packageName` |
| `compare_versions` | Analyze changes between versions | `packageName`, `fromVersion`, `toVersion` |
| `analyze_npx_command` | Validate npx command execution | `command`, `args?`, `timeout?` |

Source: [DEVELOPMENT.md](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md)

---

## search_packages

Searches the npm registry for packages matching a query string. Returns ranked results with relevance scores and download statistics.

### Input Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `query` | string | Yes | Search query string (keywords, package name, or description) |
| `limit` | number | No | Maximum results to return (default: 10, max: 50) |

### Output Structure

```typescript
{
  success: boolean;
  packages: Array<{
    name: string;
    version: string;
    description: string;
    score: number;
    downloads: number;
  }>;
  total: number;
}
```

### Usage Example

```json
{
  "query": "state management react",
  "limit": 5
}
```

### Response Example

```json
{
  "success": true,
  "packages": [
    {
      "name": "zustand",
      "version": "4.4.7",
      "description": "Bear-premises state management",
      "score": 0.95,
      "downloads": 2500000
    },
    {
      "name": "redux",
      "version": "5.0.1",
      "description": "Predictable state container",
      "score": 0.92,
      "downloads": 8000000
    }
  ],
  "total": 2
}
```

### Implementation Details

The search tool queries the npm registry's search endpoint and ranks results by a composite score incorporating package popularity, quality, and relevance. Results are sorted by score in descending order.

Source: [src/tools/search-packages.ts](https://github.com/alisaitteke/npm-mcp/blob/main/src/tools/search-packages.ts)

---

## get_package_details

Retrieves comprehensive metadata for a specific npm package, including version information, dependencies, repository details, and download statistics.

### Input Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `packageName` | string | Yes | Name of the npm package |
| `version` | string | No | Specific version to retrieve (defaults to latest) |

### Output Structure

```typescript
{
  success: boolean;
  package: {
    name: string;
    version: string;
    description: string;
    isLatest: boolean;
    deprecated: string | null;
  };
  metadata: {
    license: string;
    author: object;
    maintainers: Array<object>;
    keywords: string[];
    homepage: string;
    repository: object;
    bugs: object;
  };
  versions: {
    latest: string;
    tags: Record<string, string>;
    total: number;
    recent: Array<{ version: string; date: string }>;
    deprecatedVersions: Array<{ version: string; message: string }>;
  };
  dependencies: {
    dependencies: Record<string, string>;
    devDependencies: Record<string, string>;
    peerDependencies: Record<string, string>;
    optionalDependencies: Record<string, string>;
  };
  dist: {
    tarball: string;
    shasum: string;
    integrity: string;
    fileCount: number;
    unpackedSize: string;
  };
  timestamps: {
    created: string;
    modified: string;
    versionPublished: string;
  };
  stats: {
    weeklyDownloads: string;
    period: string;
  };
}
```

Source: [src/tools/package-details.ts](https://github.com/alisaitteke/npm-mcp/blob/main/src/tools/package-details.ts)

### Key Response Fields

| Field | Description |
|-------|-------------|
| `package.isLatest` | Boolean indicating if queried version matches dist-tags.latest |
| `package.deprecated` | Deprecation message if package/version is deprecated, null otherwise |
| `versions.recent` | Last 5 released versions with publication dates |
| `versions.deprecatedVersions` | All deprecated versions with deprecation messages |
| `stats.weeklyDownloads` | Downloads in the last 7 days (from CDN download counts API) |

### Usage Example

```json
{
  "packageName": "express",
  "version": "4.18.2"
}
```

### Response Example

```json
{
  "success": true,
  "package": {
    "name": "express",
    "version": "4.18.2",
    "description": "Fast, unopinionated, minimalist web framework",
    "isLatest": true,
    "deprecated": null
  },
  "metadata": {
    "license": "MIT",
    "author": { "name": "TJ Holowaychuk", "email": "tj@vision-media.ca" },
    "maintainers": [...],
    "keywords": ["express", "framework", "web", "http", "server"]
  },
  "versions": {
    "latest": "4.18.2",
    "tags": { "latest": "4.18.2", "beta": "5.0.0-beta.1" },
    "total": 186,
    "recent": [...],
    "deprecatedVersions": []
  },
  "dependencies": {
    "dependencies": { "accepts": "~1.3.8", "array-flatten": "1.1.1" },
    "devDependencies": {},
    "peerDependencies": {},
    "optionalDependencies": {}
  },
  "dist": {
    "tarball": "https://registry.npmjs.org/express/-/express-4.18.2.tgz",
    "shasum": "e2f1c9c1c31e4c02a1a4d4f2...",
    "integrity": "sha512-5/Ps6PjKaNq...",
    "fileCount": 35,
    "unpackedSize": "256.45 KB"
  },
  "stats": {
    "weeklyDownloads": "28,450,000",
    "period": "2024-01-01 to 2024-01-07"
  }
}
```

---

## audit_security

Checks a package for known security vulnerabilities using the npm Registry Security Advisory API.

### Input Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `packageName` | string | Yes | Name of the npm package to audit |
| `version` | string | No | Specific version to audit (defaults to latest) |

### Output Structure

```typescript
{
  success: boolean;
  package: string;
  version: string;
  vulnerable: boolean;
  advisories?: Array<{
    id: string;
    severity: 'critical' | 'high' | 'moderate' | 'low';
    vulnerability: string;
    url: string;
    patchedIn?: string;
  }>;
  recommendation?: string;
}
```

### Security Severity Levels

| Level | Description |
|-------|-------------|
| `critical` | Remote code execution, data breach potential |
| `high` | Significant vulnerability with high impact |
| `moderate` | Moderate impact, may require specific conditions |
| `low` | Minimal impact, low exploitability |

### Usage Example

```json
{
  "packageName": "lodash",
  "version": "4.17.20"
}
```

### Safe Response Example

```json
{
  "success": true,
  "package": "express",
  "version": "4.18.2",
  "vulnerable": false,
  "message": "No known security vulnerabilities"
}
```

### Vulnerable Response Example

```json
{
  "success": true,
  "package": "lodash",
  "version": "4.17.20",
  "vulnerable": true,
  "advisories": [
    {
      "id": "GHSA-4xc9-xhrj-v574",
      "severity": "high",
      "vulnerability": "Prototype Pollution",
      "url": "https://www.npmjs.com/advisories/1673",
      "patchedIn": "4.17.21"
    }
  ],
  "recommendation": "Upgrade to lodash@4.17.21 or later"
}
```

Source: [src/tools/security-audit.ts](https://github.com/alisaitteke/npm-mcp/blob/main/src/tools/security-audit.ts)

---

## check_compatibility

Analyzes a package's peer dependencies against the user's existing dependencies to detect potential conflicts before installation.

### Input Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `packageName` | string | Yes | Package to check compatibility for |
| `version` | string | No | Specific version (defaults to latest) |
| `existingDependencies` | Record<string, string> | Yes | Current project dependencies |

### Output Structure

```typescript
{
  success: boolean;
  package: string;
  version: string;
  compatible: boolean;
  analysis: {
    peerDependencies: {
      total: number;
      compatible: number;
      conflicts: number;
      missing: number;
    };
    details: {
      compatible: Array<{ package: string; required: string; installed: string }>;
      conflicts: Array<{ package: string; required: string; installed: string }>;
      missing: Array<{ package: string; required: string }>;
    };
  };
  recommendation: string;
  suggestedActions?: string[];
}
```

### Usage Example

```json
{
  "packageName": "react-router-dom",
  "version": "6.20.0",
  "existingDependencies": {
    "react": "18.2.0",
    "react-dom": "18.2.0"
  }
}
```

### Compatible Response Example

```json
{
  "success": true,
  "package": "react-router-dom",
  "version": "6.20.0",
  "compatible": true,
  "analysis": {
    "peerDependencies": {
      "total": 1,
      "compatible": 1,
      "conflicts": 0,
      "missing": 0
    },
    "details": {
      "compatible": [
        { "package": "react", "required": "^18.0.0", "installed": "18.2.0" }
      ],
      "conflicts": [],
      "missing": []
    }
  },
  "recommendation": "Package is compatible with existing dependencies. Safe to install."
}
```

### Conflict Response Example

```json
{
  "success": true,
  "package": "styled-components",
  "version": "6.1.0",
  "compatible": false,
  "analysis": {
    "peerDependencies": {
      "total": 1,
      "compatible": 0,
      "conflicts": 1,
      "missing": 0
    },
    "details": {
      "compatible": [],
      "conflicts": [
        { "package": "react", "required": "^18.0.0", "installed": "16.14.0" }
      ],
      "missing": []
    }
  },
  "recommendation": "Compatibility issues detected. 1 peer dependency conflict(s) detected.",
  "suggestedActions": [
    "Update conflicting dependencies to compatible versions"
  ]
}
```

### Semver Matching Logic

The tool uses semver range matching to determine compatibility:

- `^1.0.0` matches `1.x.x` (compatible in minor/patch)
- `~1.0.0` matches `1.0.x` (compatible in patch only)
- `>=1.0.0` matches any version >= specified
- Exact versions must match exactly

Source: [src/tools/version-compatibility.ts](https://github.com/alisaitteke/npm-mcp/blob/main/src/tools/version-compatibility.ts)

---

## analyze_quality

Assesses a package's quality score based on popularity metrics, maintenance status, and community indicators.

### Input Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `packageName` | string | Yes | Package to analyze |

### Output Structure

```typescript
{
  success: boolean;
  package: string;
  quality: {
    score: number;           // 0-100 composite score
    popularity: {
      weeklyDownloads: number;
      trend: 'increasing' | 'stable' | 'decreasing';
    };
    maintenance: {
      lastCommit: string;
      releases: number;
      openIssues: number;
      closedIssues: number;
    };
    community: {
      stars?: number;
      forks?: number;
      contributors?: number;
      subscribers?: number;
    };
  };
  recommendation: string;
}
```

### Quality Score Breakdown

| Score Range | Rating | Interpretation |
|-------------|--------|-----------------|
| 90-100 | Excellent | Highly maintained, popular, well-documented |
| 75-89 | Good | Active maintenance, reasonable popularity |
| 50-74 | Fair | Some maintenance, moderate usage |
| 25-49 | Poor | Limited maintenance, low popularity |
| 0-24 | Critical | Abandoned or deprecated |

### GitHub Metrics

Quality analysis incorporates GitHub data when available:

- **Stars**: Community adoption indicator
- **Forks**: Developer engagement
- **Contributors**: Maintenance diversity
- **Subscribers**: Interest level

### Rate Limiting Note

This tool uses the GitHub API, which has rate limits for unauthenticated requests (60 requests/hour). Some packages may fail analysis if rate limits are exceeded.

Source: [src/tools/quality-analysis.ts](https://github.com/alisaitteke/npm-mcp/blob/main/src/tools/quality-analysis.ts)

---

## compare_versions

Analyzes breaking changes and dependency differences between two versions of a package.

### Input Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `packageName` | string | Yes | Package to compare |
| `fromVersion` | string | Yes | Starting version |
| `toVersion` | string | Yes | Target version |

### Output Structure

```typescript
{
  success: boolean;
  package: string;
  comparison: {
    fromVersion: string;
    toVersion: string;
    breakingChanges: Array<{
      type: 'removed' | 'changed' | 'deprecated';
      detail: string;
    }>;
    dependencyDiff: {
      added: Record<string, string>;
      removed: string[];
      changed: Record<string, { from: string; to: string }>;
    };
    semverSummary: {
      major: number;
      minor: number;
      patch: number;
    };
  };
  recommendation: string;
}
```

### Semver Change Classification

| Change Type | Semver | Implication |
|-------------|--------|-------------|
| Major | X.0.0 | Breaking changes, API changes |
| Minor | 0.X.0 | New features, backward compatible |
| Patch | 0.0.X | Bug fixes, backward compatible |

### Usage Example

```json
{
  "packageName": "axios",
  "fromVersion": "1.5.0",
  "toVersion": "1.6.0"
}
```

### Response Example

```json
{
  "success": true,
  "package": "axios",
  "comparison": {
    "fromVersion": "1.5.0",
    "toVersion": "1.6.0",
    "breakingChanges": [],
    "dependencyDiff": {
      "added": { "form-data": "^3.0.0" },
      "removed": [],
      "changed": {
        "follow-redirects": { "from": "^2.0.0", "to": "^3.0.0" }
      }
    },
    "semverSummary": {
      "major": 0,
      "minor": 1,
      "patch": 0
    }
  },
  "recommendation": "Minor version update. Should be backward compatible."
}
```

---

## analyze_npx_command

Validates and analyzes an npx command before execution, providing safety warnings and a verified safe command string.

### Input Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `command` | string | Yes | Command to analyze (e.g., `create-react-app` or `typescript@5.0.0`) |
| `args` | string[] | No | Arguments to pass to the command |
| `timeout` | number | No | Execution timeout in seconds (default: 300) |

### Output Structure

```typescript
{
  success: boolean;
  analysis: {
    package: string;
    version: string;
    command: string;
    isLatest: boolean;
  };
  validation: {
    packageExists: boolean;
    versionExists: boolean;
    hasExecutable: boolean;
    sizeKB: number;
    dependencyCount: number;
    publishedDaysAgo: number;
  };
  metadata: {
    description: string;
    license: string;
    author: string;
    repository?: string;
    homepage?: string;
  };
  warnings: string[];
  recommendations: string[];
  safeCommand: string;
  note: string;
}
```

### Warning Conditions

The tool generates warnings for:

| Condition | Warning Level | Description |
|-----------|---------------|-------------|
| Large package (>50MB) | Medium | May take significant time to download |
| Many dependencies (>100) | Medium | Potential security surface |
| Old version (>1 year) | Medium | May have unpatched vulnerabilities |
| Deprecated package | High | Package is deprecated |
| No executable found | High | Command may not be available |

### Usage Example

```json
{
  "command": "create-react-app",
  "args": ["my-app", "--template", "typescript"],
  "timeout": 600
}
```

### Response Example

```json
{
  "success": true,
  "analysis": {
    "package": "create-react-app",
    "version": "5.0.1",
    "command": "npx create-react-app@5.0.1",
    "isLatest": true
  },
  "validation": {
    "packageExists": true,
    "versionExists": true,
    "hasExecutable": true,
    "sizeKB": 234,
    "dependencyCount": 2,
    "publishedDaysAgo": 45
  },
  "metadata": {
    "description": "Create React apps with no build configuration",
    "license": "MIT",
    "author": "Facebook",
    "repository": "https://github.com/facebook/create-react-app"
  },
  "warnings": ["✅ No significant warnings"],
  "recommendations": [
    "Use --template typescript for TypeScript projects",
    "Node.js 18+ recommended"
  ],
  "safeCommand": "npx create-react-app@5.0.1 my-app --template typescript",
  "note": "Command analyzed but not executed. Execute manually after review."
}
```

### Command Format Support

The tool accepts multiple command formats:

| Format | Example | Behavior |
|--------|---------|----------|
| Package only | `create-react-app` | Uses latest version |
| Package with version | `typescript@5.0.0` | Uses specified version |
| Scoped package | `@angular/cli` | Works with scoped packages |
| With arguments | `create-next-app --ts` | Preserves arguments in safeCommand |

Source: [src/tools/npx-command.ts](https://github.com/alisaitteke/npm-mcp/blob/main/src/tools/npx-command.ts)

---

## Data Flow Architecture

```mermaid
sequenceDiagram
    participant AI as AI Assistant
    participant MCP as MCP Server
    participant Cache as LRU Cache
    participant NPM as NPM Registry
    participant GH as GitHub API

    AI->>MCP: call_tool(search_packages, {query})
    MCP->>Cache: check cache key
    Cache-->>MCP: cache miss
    MCP->>NPM: GET /-/v1/search
    NPM-->>MCP: search results
    MCP->>Cache: store result (5 min TTL)
    MCP-->>AI: ranked packages

    AI->>MCP: call_tool(audit_security, {package})
    MCP->>Cache: check cache
    MCP->>NPM: GET /-/v1/security/advisories
    NPM-->>MCP: advisory data
    MCP->>Cache: store
    MCP-->>AI: vulnerability report

    AI->>MCP: call_tool(analyze_quality, {package})
    MCP->>Cache: check cache
    MCP->>NPM: GET package metadata
    NPM-->>MCP: metadata
    MCP->>GH: GET repo metrics
    GH-->>MCP: stars, forks, issues
    MCP-->>AI: quality score
```

## Error Handling

All tools return consistent error responses when failures occur:

```typescript
{
  success: false,
  error: string;  // Human-readable error message
  packageName?: string;  // If applicable
  version?: string;  // If applicable
}
```

### Common Error Scenarios

| Error | Cause | Resolution |
|-------|-------|------------|
| `E404` | Package not found | Verify package name spelling |
| `ETIMEDOUT` | Registry timeout | Retry with exponential backoff |
| `E429` | Rate limited | Wait and retry (handled internally) |
| `ENOTFOUND` | Network issue | Check internet connection |

### Internal Retry Logic

The registry client implements automatic retry with exponential backoff:

1. First retry: 1 second delay
2. Second retry: 2 seconds delay
3. Third retry: 4 seconds delay
4. After 3 failures: return error

---

## Caching Strategy

| Resource | TTL | Invalidation |
|----------|-----|--------------|
| Package metadata | 5 minutes | Manual cache clear |
| Search results | 5 minutes | Manual cache clear |
| Download stats | 5 minutes | Manual cache clear |
| GitHub metrics | 5 minutes | Manual cache clear |

### Cache Configuration

```typescript
{
  maxAge: 5 * 60 * 1000,  // 5 minutes in milliseconds
  concurrencyLimit: 10,   // Maximum concurrent requests
  maxRetries: 3           // Retry attempts on failure
}
```

Source: [src/registry-client.ts](https://github.com/alisaitteke/npm-mcp/blob/main/src/registry-client.ts)

---

## Adding New Tools

To add a new tool to the MCP server:

### 1. Create Tool Module

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

export const MyNewToolSchema = z.object({
  param1: z.string(),
  param2: z.number().optional(),
});

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

### 2. Register in Server

In `src/index.ts`, add the tool to both request schemas:

```typescript
// ListToolsRequestSchema - declare the tool
{
  name: 'my_new_tool',
  description: 'Description of what the tool does',
  inputSchema: {
    type: 'object',
    properties: {
      param1: { type: 'string', description: '...' },
    },
    required: ['param1']
  }
}

// CallToolRequestSchema - handle the tool
if (tool.name === 'my_new_tool') {
  return await myNewTool(args, registryClient);
}
```

### 3. Add Tests

```typescript
// test/my-new-tool.test.ts
import { describe, it, expect } from 'vitest';

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

Source: [DEVELOPMENT.md](https://github.com/alisaitteke/npm-mcp/blob/main/DEVELOPMENT.md#adding-a-new-tool)

---

## See Also

- [Quick Start Guide](./Quick-Start.md) - Getting started with npm-registry-mcp
- [Configuration](./Configuration.md) - Server configuration options
- [AI Usage Guide](./AI-Usage.md) - Integrating with AI assistants
- [Troubleshooting](./Troubleshooting.md) - Common issues and solutions
- [Contributing Guide](../CONTRIBUTING.md) - Adding new tools

---

<!-- evidence_pipeline_checked: true -->

---

## Pitfall Log

Project: alisaitteke/npm-mcp

Summary: 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
- Evidence strength: source_linked
- Finding: README/documentation is current enough for a first validation pass.
- User impact: May increase setup, validation, or first-run risk for the user.
- Suggested 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
- Evidence strength: source_linked
- 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.
- Suggested 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
- Evidence strength: source_linked
- Finding: no_demo
- User impact: May increase setup, validation, or first-run risk for the user.
- Suggested 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
- Evidence strength: source_linked
- Finding: no_demo
- User impact: May increase setup, validation, or first-run risk for the user.
- Suggested 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
- Evidence strength: source_linked
- Finding: issue_or_pr_quality=unknown。
- User impact: May increase setup, validation, or first-run risk for the user.
- Suggested 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
- Evidence strength: source_linked
- Finding: release_recency=unknown。
- User impact: May increase setup, validation, or first-run risk for the user.
- Suggested 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

<!-- canonical_name: alisaitteke/npm-mcp; human_manual_source: deepwiki_human_wiki -->
