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

Generated at: 2026-05-30 19:07:09 UTC

## Table of Contents

- [Introduction to NPM Sentinel MCP](#page-introduction)
- [System Architecture](#page-architecture)
- [MCP Tools Reference](#page-mcp-tools)
- [Security Features](#page-security)
- [Caching System](#page-caching)
- [Installation and Configuration](#page-installation)
- [Docker Deployment](#page-docker)
- [API and Resources Reference](#page-api-reference)
- [Input Validation and Type Safety](#page-input-validation)
- [Troubleshooting](#page-troubleshooting)

<a id='page-introduction'></a>

## Introduction to NPM Sentinel MCP

### Related Pages

Related topics: [System Architecture](#page-architecture), [Installation and Configuration](#page-installation), [MCP Tools Reference](#page-mcp-tools)



# Introduction to NPM Sentinel MCP

NPM Sentinel MCP is a Model Context Protocol (MCP) server that provides comprehensive npm package analysis capabilities for AI-powered development tools. It acts as a bridge between AI assistants and the npm ecosystem, enabling intelligent package management, vulnerability detection, and dependency analysis through a standardized MCP interface.

## Overview

NPM Sentinel MCP extends the capabilities of AI coding assistants by providing real-time access to npm package information, dependency trees, and security vulnerability data. The server leverages the [npm Registry API](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/src/tools/npm-registry.ts) and [deps.dev](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/README.md) to deliver comprehensive package intelligence.

The project supports multiple deployment platforms including direct npm installation, Docker containerization, and integration with AI platforms like Smithery.ai. Source: [package.json](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/package.json)

## Architecture

The NPM Sentinel MCP server follows a modular architecture that separates concerns between tool implementations, configuration management, and protocol handling.

```mermaid
graph TD
    A[MCP Client / AI Assistant] -->|MCP Protocol| B[Server Entry Point<br/>index.ts]
    B --> C[Tool Router]
    C --> D[npmDeps Tool]
    C --> E[vulnerabilityScan Tool]
    C --> F[packageInfo Tool]
    D --> G[deps.dev API]
    D --> H[npm Registry API]
    E --> G
    E --> H
    F --> H
    G -->|Transitive Topology| I[Cache Layer]
    H --> I
    I -->|Cached Responses| C
```

### Core Components

| Component | Purpose | Source |
|-----------|---------|--------|
| Server Entry Point | Initializes MCP server and registers tools | [index.ts](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/index.ts) |
| Tool Implementations | Execute package-related operations | [src/tools/](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/src/tools/) |
| Configuration Schema | Validates runtime configuration | [src/config/schema.ts](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/src/config/schema.ts) |
| Cache Layer | Stores and invalidates API responses | Implemented in v1.15.0 |

### Tool Suite

The server exposes three primary tools for package analysis:

**npmDeps** - Resolves complete dependency trees for npm packages, including transitive dependencies. This tool integrates with deps.dev for large-scale dependency resolution, bypassing npm Registry subrequest limits. Source: [README.md](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/README.md)

**vulnerabilityScan** - Analyzes packages and their dependencies for known security vulnerabilities, enriched with CVE data. The scanner includes React ecosystem awareness to reduce false positives in React applications. Source: [src/tools/vulnerability-scanner.ts](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/src/tools/vulnerability-scanner.ts)

**packageInfo** - Retrieves detailed metadata about npm packages including version information, publish dates, and maintainer details.

## Features

### Transitive Dependency Analysis

NPM Sentinel MCP provides deep dependency tree resolution through integration with the deps.dev API. This capability was enhanced in version 1.17.0 to handle massive dependency trees that would exceed npm Registry subrequest limits. Version 1.18.0 further improves this by injecting transitive topology insights directly into the npmDeps tool. Source: [README.md](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/README.md)

### Vulnerability Detection

The vulnerability scanning system offers comprehensive security analysis with the following capabilities:

- **Transitive Scanning**: Detects vulnerabilities not only in direct dependencies but also in the full dependency tree
- **React Ecosystem Awareness**: Reduces false positives by understanding React-specific package patterns
- **CVE Enrichment**: Augments vulnerability data with detailed CVE information from security databases

Source: [src/tools/vulnerability-scanner.ts](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/src/tools/vulnerability-scanner.ts)

### Cache Invalidation

Version 1.15.0 introduced robust cache invalidation mechanisms to ensure that cached package data remains fresh while minimizing redundant API calls. The cache layer automatically invalidates entries based on TTL policies and package update events. Source: [package.json](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/package.json)

### Security Validation

Version 1.16.0 implemented strict package name validation across all tools, preventing injection attacks and malformed package name inputs. This security layer ensures that all package names conform to npm's naming conventions before any API requests are made. Source: [src/config/schema.ts](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/src/config/schema.ts)

## Installation and Configuration

### Via npm

```bash
npm install -g npm-sentinel-mcp
```

### Via Docker

```bash
docker pull ghcr.io/nekzus/npm-sentinel-mcp:latest
```

### Configuration Schema

The server accepts configuration through environment variables or a configuration file. The schema supports the following options:

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `NPM_REGISTRY_URL` | string | `https://registry.npmjs.org` | npm Registry API endpoint |
| `DEPS_DEV_API_URL` | string | `https://api.deps.dev` | deps.dev API endpoint |
| `CACHE_TTL_SECONDS` | number | `3600` | Cache time-to-live in seconds |
| `LOG_LEVEL` | string | `info` | Logging verbosity level |

Source: [smithery.yaml](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/smithery.yaml)

## Usage Patterns

### Basic Package Query

To retrieve information about a specific npm package, use the packageInfo tool with the package name:

```javascript
{
  tool: "packageInfo",
  arguments: {
    packageName: "express"
  }
}
```

### Dependency Tree Resolution

For complete dependency analysis including transitive dependencies:

```javascript
{
  tool: "npmDeps",
  arguments: {
    packageName: "lodash",
    version: "4.17.21"
  }
}
```

### Security Vulnerability Scan

To scan a package and its dependencies for security vulnerabilities:

```javascript
{
  tool: "vulnerabilityScan",
  arguments: {
    packageName: "axios",
    version: "1.6.0"
  }
}
```

## Integration Platforms

### Smithery.ai

NPM Sentinel MCP is available on Smithery.ai for easy integration with AI coding assistants. The configuration schema is explicitly defined at the root level for better detection by the Smithery platform. Source: [smithery.yaml](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/smithy.yaml), [v1.13.3 Release Notes](https://github.com/Nekzus/npm-sentinel-mcp/releases/tag/v1.13.3)

### Claude Desktop

For integration with Claude Desktop, add the following to your configuration:

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

## Version History

| Version | Release Date | Key Changes |
|---------|--------------|-------------|
| 1.18.0 | 2026-02-22 | Transitive topology insights via deps.dev injection |
| 1.17.0 | 2026-02-22 | deps.dev integration for large dependency trees |
| 1.16.0 | 2026-01-02 | Strict package name validation |
| 1.15.0 | 2025-12-30 | Cache invalidation mechanisms |
| 1.14.0 | 2025-12-24 | Transitive scanning and CVE enrichment |

## Common Failure Modes

### Zod Validation Errors

Prior to version 1.16.1, the npm-registry tool could produce Zod validation errors due to unexpected API response formats. This was resolved by implementing proper schema validation and cleaning up test cases. Source: [v1.16.1 Release Notes](https://github.com/Nekzus/npm-sentinel-mcp/releases/tag/v1.16.1)

### Node.js Compatibility

Version 1.15.1 addressed compatibility issues with Node.js 20 by downgrading semantic-release-github to version 10. Ensure your runtime environment meets the Node.js version requirements specified in package.json. Source: [package.json](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/package.json)

### Package Name Validation

Requests with malformed package names (e.g., containing path traversal characters or invalid npm naming characters) will be rejected at the configuration validation layer before any API calls are made.

## See Also

- [NPM Registry Tool Documentation](src/tools/npm-registry.md)
- [Vulnerability Scanner Documentation](src/tools/vulnerability-scanner.md)
- [Configuration Reference](src/config/schema.md)
- [Smithery Integration Guide](smithery.yaml)
- [GitHub Repository](https://github.com/Nekzus/npm-sentinel-mcp)
- [Release Notes](https://github.com/Nekzus/npm-sentinel-mcp/releases)

---

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

## System Architecture

### Related Pages

Related topics: [Introduction to NPM Sentinel MCP](#page-introduction), [Installation and Configuration](#page-installation), [Caching System](#page-caching)



# System Architecture

## Overview

The npm-sentinel-mcp is a Model Context Protocol (MCP) server that provides AI assistants with comprehensive npm package analysis capabilities. The system architecture is designed around a modular service layer that integrates with external APIs (npm Registry, deps.dev) to deliver security analysis, dependency resolution, and vulnerability scanning for npm packages.

Source: [index.ts:1-50](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/index.ts)

## High-Level Architecture

The system follows a layered architecture pattern with clear separation of concerns:

```mermaid
graph TD
    subgraph "Client Layer"
        A[AI Assistant / MCP Client]
    end
    
    subgraph "MCP Server Layer"
        B[MCP Protocol Handler]
        C[Tool Router]
        D[Schema Validator]
    end
    
    subgraph "Service Layer"
        E[npm-registry Service]
        F[deps.dev Service]
        G[Vulnerability Scanner]
        H[Cache Manager]
    end
    
    subgraph "External APIs"
        I[npm Registry API]
        J[deps.dev API]
        K[Security Advisories]
    end
    
    A --> B
    B --> C
    C --> D
    D --> E
    D --> F
    D --> G
    E <--> H
    F <--> H
    E --> I
    F --> J
    G --> K
```

## Core Components

### MCP Server Entry Point

The server is initialized as an MCP server with multiple tool definitions that expose npm package functionality to AI assistants.

Source: [index.ts:30-80](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/index.ts)

| Component | Responsibility |
|-----------|----------------|
| Server Initialization | Creates the MCP server instance with configuration |
| Tool Registration | Registers all npm-related tools with the MCP protocol |
| Request Handling | Routes incoming requests to appropriate services |
| Schema Definition | Defines input/output schemas for type safety |

### Tool Definitions

The system exposes the following primary tools through the MCP protocol:

Source: [llms-full.txt:1-100](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/llms-full.txt)

| Tool Name | Purpose |
|-----------|---------|
| `npmDeps` | Retrieves package dependencies with transitive insights |
| `npmVulnScan` | Performs vulnerability scanning on npm packages |
| `npmRegistry` | Queries npm registry for package metadata |

### Service Layer Architecture

#### npm Registry Service

Handles all interactions with the official npm Registry API, including package metadata retrieval, version information, and dependency resolution.

Source: [npm-registry.ts:1-60](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/src/services/npm-registry.ts)

```mermaid
sequenceDiagram
    participant Client
    participant MCP as MCP Server
    participant Registry as npm-registry Service
    participant Cache as Cache Manager
    participant NPM as npm Registry API
    
    Client->>MCP: Request package info
    MCP->>Registry: Fetch package(pkg, version)
    Registry->>Cache: Check cache
    alt Cache Hit
        Cache->>Registry: Return cached data
    else Cache Miss
        Registry->>NPM: GET /package/{name}
        NPM->>Registry: Package metadata
        Registry->>Cache: Store result
    end
    Registry->>MCP: Return data
    MCP->>Client: Tool response
```

#### deps.dev Service

Provides enhanced dependency tree resolution by integrating with Google's deps.dev API. This service bypasses edge subrequest limits during vulnerability scans by leveraging deps.dev's comprehensive dependency graph.

Source: [deps-dev.ts:1-50](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/src/services/deps-dev.ts)

| Feature | Description |
|---------|-------------|
| Transitive Dependency Resolution | Resolves full dependency trees including transitive dependencies |
| Ecosystem Awareness | Includes React ecosystem-specific insights |
| Topology Insights | Provides dependency graph structure and relationships |

The deps.dev integration was introduced in v1.17.0 to handle "massive dependency tree resolution bypassing edge subrequest limits in vulnerability scans."

Source: [v1.17.0 Release Notes](https://github.com/Nekzus/npm-sentinel-mcp/releases/tag/v1.17.0)

#### Vulnerability Scanner Service

Performs security analysis by checking packages against the npm Security Advisories database, with support for transitive dependency scanning.

Source: [vulnerability-scanner.ts:1-80](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/src/services/vulnerability-scanner.ts)

```mermaid
graph TD
    A[Start Vulnerability Scan] --> B[Fetch Direct Dependencies]
    B --> C{Enable Transitive Scanning?}
    C -->|Yes| D[Query deps.dev for Full Tree]
    C -->|No| E[Use Direct Dependencies Only]
    D --> F[For Each Dependency]
    E --> F
    F --> G[Check Security Advisories]
    G --> H{Is Vulnerable?}
    H -->|Yes| I[Enrich with CVE Data]
    H -->|No| J[Continue]
    I --> J
    J --> K{More Dependencies?}
    K -->|Yes| F
    K -->|No| L[Aggregate Results]
    L --> M[Return Vulnerability Report]
```

### Cache Manager

Implements robust cache invalidation mechanisms to optimize API calls and reduce latency.

Source: [index.ts:100-150](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/index.ts)

| Cache Feature | Description |
|---------------|-------------|
| TTL-based Invalidation | Cached entries expire after configurable duration |
| Manual Invalidation | API to force cache refresh for specific entries |
| Memory Storage | In-memory cache for low-latency access |

The cache invalidation mechanisms were implemented in v1.15.0 to improve performance and data freshness.

Source: [v1.15.0 Release Notes](https://github.com/Nekzus/npm-sentinel-mcp/releases/tag/v1.15.0)

## Data Flow Architecture

### Package Name Validation Flow

All tools enforce strict package name validation as a security measure to prevent injection attacks and ensure correct package resolution.

```mermaid
graph TD
    A[User Input: package@version] --> B[Input Sanitization]
    B --> C[Regex Validation]
    C --> D{Package Name Valid?}
    D -->|Yes| E[Proceed to Service]
    D -->|No| F[Return Validation Error]
    E --> G[Query APIs]
    G --> H[Return Results]
```

Strict package name validation was enforced across all tools in v1.16.0.

Source: [v1.16.0 Release Notes](https://github.com/Nekzus/npm-sentinel-mcp/releases/tag/v1.16.0)

## Configuration Schema

The server supports configuration through `smithery.yaml` and `server.json` for deployment flexibility.

Source: [smithery.yaml:1-30](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/smithery.yaml)
Source: [server.json:1-20](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/server.json)

| Config Property | Type | Description |
|-----------------|------|-------------|
| `cacheEnabled` | boolean | Enable/disable caching |
| `cacheTTL` | number | Cache time-to-live in seconds |
| `transitiveScan` | boolean | Enable transitive dependency scanning |
| `npmRegistryUrl` | string | Custom npm registry endpoint |

## Security Architecture

### Vulnerability Detection Enhancements

The vulnerability scanner was enhanced in v1.14.0 with several key security features:

Source: [v1.14.0 Release Notes](https://github.com/Nekzus/npm-sentinel-mcp/releases/tag/v1.14.0)

| Enhancement | Purpose |
|-------------|---------|
| Transitive Scanning | Detect vulnerabilities in indirect dependencies |
| React Ecosystem Awareness | Special handling for React/Next.js packages |
| CVE Enrichment | Include detailed CVE information in results |

### API Integration Security

| API | Authentication | Rate Limiting Strategy |
|-----|----------------|------------------------|
| npm Registry | Public (no auth) | Built-in caching + rate limit handling |
| deps.dev | Public API | Request batching for efficiency |
| Security Advisories | Public API | Cache advisory responses |

## Dependencies Architecture

The system leverages TypeScript, Zod for schema validation, and the official MCP SDK.

Source: [package.json:1-40](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/package.json)

| Dependency | Purpose | Version Strategy |
|------------|---------|------------------|
| `@modelcontextprotocol/sdk` | MCP protocol implementation | ^1.0.0 |
| `zod` | Runtime schema validation | ^3.x |
| `axios` | HTTP client for API calls | ^1.x |
| `semantic-release-*` | Automated release workflow | ^20.x |

## Deployment Configuration

The system supports multiple deployment platforms including Smithery.ai for easy discovery and configuration.

Source: [smithery.yaml:1-50](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/smithery.yaml)

```yaml
configuration:
  schemaVersion: "1.0"
  name: "npm-sentinel-mcp"
  description: "npm package security and analysis tools"
```

The `configSchema` is explicitly defined at the root level for better platform detection.

Source: [v1.13.3 Release Notes](https://github.com/Nekzus/npm-sentinel-mcp/releases/tag/v1.13.3)

## Error Handling Architecture

| Error Type | Handling Strategy |
|------------|-------------------|
| Network Errors | Retry with exponential backoff, return cached data if available |
| Validation Errors | Zod validation with descriptive error messages |
| API Rate Limits | Automatic throttling and cache utilization |
| Unknown Packages | Graceful degradation with clear error messaging |

Zod validation errors in the npm-registry service were resolved in v1.16.1, ensuring robust input validation.

Source: [v1.16.1 Release Notes](https://github.com/Nekzus/npm-sentinel-mcp/releases/tag/v1.16.1)

## Version History and Architecture Evolution

| Version | Architectural Change |
|---------|----------------------|
| v1.18.0 | Transitive topology insights injection via deps.dev |
| v1.17.0 | deps.dev integration for large-scale dependency resolution |
| v1.16.0 | Strict package name validation across all tools |
| v1.15.0 | Robust cache invalidation mechanisms |
| v1.14.0 | Enhanced vulnerability detection with transitive scanning |
| v1.13.2 | Smithery platform configuration files added |

## See Also

- [README.md](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/README.md) - Project overview and quick start
- [Installation Guide](./Installation) - Setup instructions
- [API Reference](./API-Reference) - Detailed tool documentation
- [Configuration](./Configuration) - Server configuration options
- [Troubleshooting](./Troubleshooting) - Common issues and solutions

---

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

## MCP Tools Reference

### Related Pages

Related topics: [Introduction to NPM Sentinel MCP](#page-introduction), [API and Resources Reference](#page-api-reference), [Security Features](#page-security)



# MCP Tools Reference

This page documents the MCP (Model Context Protocol) tools provided by npm-sentinel-mcp, enabling AI assistants and automated systems to interact with npm package metadata, dependency trees, and vulnerability information through a standardized interface.

## Overview

npm-sentinel-mcp exposes a collection of MCP tools that wrap the npm registry API and security databases. These tools allow clients to query package information, resolve dependency graphs, scan for vulnerabilities, and enrich results with external intelligence from services like deps.dev.

**Purpose**: The tool layer acts as an abstraction boundary between MCP clients and the complex landscape of npm registry endpoints, vulnerability databases, and transitive dependency resolution logic. Source: [src/index.ts]()

**Key capabilities introduced in recent releases**:

| Version | Feature | Impact |
|---------|---------|--------|
| v1.18.0 | Transitive topology insights via deps.dev | Enhanced dependency visualization |
| v1.17.0 | deps.dev integration for dependency tree resolution | Bypasses edge subrequest limits in vulnerability scans |
| v1.16.0 | Strict package name validation | Security hardening across all tools |
| v1.15.0 | Robust cache invalidation mechanisms | Improved data freshness |
| v1.14.0 | Transitive scanning and CVE enrichment | Comprehensive vulnerability detection |

Source: [Release notes](https://github.com/Nekzus/npm-sentinel-mcp/releases)

## Architecture

The MCP tool layer follows a layered architecture where each tool validates input, consults the cache layer, calls the appropriate data source, and transforms results through enrichment pipelines.

```mermaid
graph TD
    A[MCP Client Request] --> B[Input Validation Layer]
    B --> C[Cache Lookup]
    C --> D{Hit?}
    D -->|Yes| E[Return Cached Response]
    D -->|No| F[Primary Data Source]
    F --> G[deps.dev Enrichment]
    G --> H[Cache Update]
    H --> I[Transform & Return]
    
    F -->|npm registry| J[npmDeps / npmInfo / npmRegistry]
    F -->|vulnerability DB| K[npmVuln]
    
    style E fill:#90EE90
    style I fill:#87CEEB
```

### Tool Categories

| Category | Tools | Primary Data Source |
|----------|-------|---------------------|
| Package Discovery | `npmDeps`, `npmInfo` | npm Registry API |
| Security Analysis | `npmVuln` | OSV Database, npm Advisory API |
| Registry Operations | `npmRegistry` | npm Registry API |
| Enrichment | Topology insights | deps.dev API |

Source: [src/tools/](https://github.com/Nekzus/npm-sentinel-mcp/tree/main/src/tools)

---

## Tool Specifications

### npmDeps

Resolves the complete dependency tree for a given npm package, including transitive dependencies. This tool is fundamental for understanding package composition and identifying potential supply chain risks.

**Purpose**: Retrieves dependency information from the npm registry and enriches the results with transitive topology data from deps.dev.

**Parameters**:

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `packageName` | string | Yes | Name of the npm package to analyze |
| `version` | string | No | Specific version; defaults to `latest` |
| `registry` | string | No | Custom registry URL |

**Response Schema** (Source: [src/schemas/index.ts]()):

```typescript
interface NpmDepsResponse {
  package: string;
  version: string;
  dependencies: Record<string, string>;
  devDependencies?: Record<string, string>;
  optionalDependencies?: Record<string, string>;
  peerDependencies?: Record<string, string>;
  transitiveGraph?: TransitiveNode[];
}
```

**Usage Example**:

```json
{
  "tool": "npmDeps",
  "parameters": {
    "packageName": "express",
    "version": "4.18.2"
  }
}
```

**Version History**:

- **v1.18.0**: Added transitive topology insights injection via deps.dev
- **v1.17.0**: Integrated deps.dev for massive dependency tree resolution

Source: [src/tools/npmDeps.ts]()

---

### npmVuln

Scans a package and its dependency tree for known security vulnerabilities. Uses OSV (Open Source Vulnerabilities) database and npm advisory feeds.

**Purpose**: Identifies CVEs, security advisories, and vulnerable dependency paths in npm packages.

**Parameters**:

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `packageName` | string | Yes | Name of the npm package to scan |
| `version` | string | No | Specific version to scan |
| `depth` | number | No | Transitive dependency scan depth (default: unlimited) |
| `ecosystem` | string | No | Filter by ecosystem (e.g., `npm`, `rubygems`) |

**Response Schema** (Source: [src/schemas/index.ts]()):

```typescript
interface NpmVulnResponse {
  package: string;
  version: string;
  vulnerabilities: Vulnerability[];
  dependencyPaths: Record<string, string[]>;
  summary: {
    critical: number;
    high: number;
    medium: number;
    low: number;
  };
}

interface Vulnerability {
  id: string;
  title: string;
  severity: 'critical' | 'high' | 'medium' | 'low';
  cvssScore?: number;
  affectedVersions: string;
  fixedVersion?: string;
  cwe?: string[];
  cve?: string;
}
```

**Enrichment Pipeline** (v1.14.0+):

The tool enriches raw vulnerability data with:
- CVE identifiers when available
- CWE classifications
- CVSS scores from OSV
- React ecosystem awareness for React-related packages

**Usage Example**:

```json
{
  "tool": "npmVuln",
  "parameters": {
    "packageName": "lodash",
    "version": "4.17.21",
    "depth": 10
  }
}
```

**Common Failure Modes**:

| Issue | Cause | Resolution |
|-------|-------|------------|
| Empty vulnerability list | Package not in OSV database | Verify package name, check npm advisories |
| Timeout on deep trees | Excessive transitive scanning | Reduce `depth` parameter |
| Stale data | Cache not invalidated | Wait for cache TTL or force refresh |

Source: [src/tools/npmVuln.ts]()

---

### npmInfo

Retrieves comprehensive metadata about an npm package from the registry.

**Purpose**: Provides a single source of truth for package metadata including versions, descriptions, maintainers, and publication dates.

**Parameters**:

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `packageName` | string | Yes | Name of the npm package |
| `version` | string | No | Specific version metadata |
| `registry` | string | No | Custom registry URL |

**Response Schema** (Source: [src/schemas/index.ts]()):

```typescript
interface NpmInfoResponse {
  name: string;
  version: string;
  description?: string;
  license?: string;
  author?: Person;
  maintainers?: Person[];
  repository?: Repository;
  homepage?: string;
  keywords?: string[];
  deprecated?: boolean;
  deprecationMessage?: string;
  created: string;
  modified: string;
  dist: {
    tarball: string;
    shasum: string;
    integrity: string;
  };
  engines?: Record<string, string>;
}
```

**Usage Example**:

```json
{
  "tool": "npmInfo",
  "parameters": {
    "packageName": "typescript"
  }
}
```

Source: [src/tools/npmInfo.ts]()

---

### npmRegistry

Provides low-level access to npm registry API endpoints for advanced use cases.

**Purpose**: Enables direct registry queries when higher-level tools do not provide sufficient flexibility.

**Parameters**:

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `endpoint` | string | Yes | Registry endpoint path |
| `packageName` | string | Conditional | Required for package-specific endpoints |
| `method` | string | No | HTTP method (default: `GET`) |
| `registry` | string | No | Custom registry URL |

**Supported Endpoints**:

| Endpoint Pattern | Description |
|-----------------|-------------|
| `/-/package/{name}` | Package metadata |
| `/-/package/{name}/dist-tags` | Distribution tags |
| `/-/v1/security/advisories` | Security advisories |
| `/{name}/{version}` | Specific version metadata |

**Usage Example**:

```json
{
  "tool": "npmRegistry",
  "parameters": {
    "endpoint": "/-/package/express",
    "registry": "https://registry.npmjs.org"
  }
}
```

**Security Note** (v1.16.0): All npmRegistry calls enforce strict package name validation to prevent injection attacks. Source: [src/tools/npmRegistry.ts]()

---

## Input Validation

All tools enforce strict input validation to ensure security and prevent malformed requests.

### Package Name Validation

As of v1.16.0, package name validation is enforced across all tools. Valid package names must conform to npm's naming rules:

| Rule | Pattern | Example |
|------|---------|---------|
| Scope prefix (optional) | `@scope/package` | `@babel/core` |
| Unscoped name | `[a-z0-9][a-z0-9-_.]*` | `lodash`, `my_package` |
| No uppercase | Not allowed | `Lodash` ❌ |
| Max length | 214 characters | - |
| Start character | Letter or number | `1abc` ✓, `-abc` ❌ |

**Validation Error Response**:

```json
{
  "error": "INVALID_PACKAGE_NAME",
  "message": "Package name 'Invalid@Name' contains disallowed characters",
  "allowedPattern": "^[a-zA-Z0-9][a-zA-Z0-9-_.]*$"
}
```

Source: [src/schemas/index.ts]()

---

## Caching and Invalidation

npm-sentinel-mcp implements a multi-layer caching strategy to optimize response times and reduce API load.

### Cache Architecture

```mermaid
graph LR
    A[Request] --> B{L1 Memory Cache}
    B -->|Hit| C[Return Response]
    B -->|Miss| D{L2 Persistent Cache}
    D -->|Hit| E[Validate Freshness]
    E -->|Fresh| C
    E -->|Stale| F[Background Refresh]
    D -->|Miss| G[Registry API Call]
    F --> C
    G --> H[Update Cache]
    H --> C
```

### Cache Invalidation Mechanisms (v1.15.0)

The following strategies ensure data freshness:

| Strategy | Trigger | Behavior |
|----------|---------|----------|
| TTL-based | Time expiration | Configurable per resource type |
| Version-based | New package version published | Automatic detection via registry |
| Manual | Explicit cache clear | Via configuration |
| Dependency | Upstream package changes | Transitive invalidation |

**Configuration Options** (Source: [src/config.ts]()):

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `cache.enabled` | boolean | `true` | Enable/disable caching |
| `cache.ttl` | number | `3600` | Time-to-live in seconds |
| `cache.maxSize` | number | `1000` | Maximum cached entries |
| `cache.invalidation.enabled` | boolean | `true` | Enable automatic invalidation |

### Cache Key Structure

Cache keys follow the pattern: `{tool}:{packageName}:{version}:{registry}`

Example: `npmDeps:express:4.18.2:https://registry.npmjs.org`

---

## Data Enrichment Pipeline

The enrichment pipeline enhances raw registry data with external intelligence sources.

### deps.dev Integration (v1.17.0+)

deps.dev provides additional metadata and vulnerability context:

```mermaid
graph TD
    A[Raw Package Data] --> B[deps.dev API Call]
    B --> C[Dependency Graph]
    C --> D[License Analysis]
    D --> E[Security Advisories]
    E --> F[Enriched Response]
    
    B --> G[Vulnerability Correlations]
    G --> H[CVE Enrichment]
    H --> F
```

**Enriched Fields**:

| Field | Source | Description |
|-------|--------|-------------|
| `transitiveGraph` | deps.dev | Full dependency tree topology |
| `licenses` | deps.dev | Normalized license analysis |
| `vulnerabilityLinks` | deps.dev | Cross-referenced vulnerability data |

### CVE Enrichment

When available, vulnerability data is enriched with:

- **CVE Identifier**: Official CVE reference
- **CVSS Score**: Severity rating (0.0-10.0)
- **CWE Classification**: weakness categorization
- **Related CPEs**: Affected product configurations

Source: [src/tools/npmVuln.ts]()

---

## Error Handling

### Error Response Schema

All tools return errors in a consistent format:

```typescript
interface ToolError {
  error: ErrorCode;
  message: string;
  details?: Record<string, unknown>;
  retryable: boolean;
}

type ErrorCode = 
  | 'INVALID_PACKAGE_NAME'
  | 'PACKAGE_NOT_FOUND'
  | 'VERSION_NOT_FOUND'
  | 'REGISTRY_ERROR'
  | 'RATE_LIMITED'
  | 'NETWORK_ERROR'
  | 'VALIDATION_ERROR'
  | 'CACHE_ERROR';
```

### Error Handling Matrix

| Error Code | HTTP Status | Retryable | Resolution |
|------------|-------------|-----------|------------|
| `PACKAGE_NOT_FOUND` | 404 | No | Verify package name spelling |
| `VERSION_NOT_FOUND` | 404 | No | Check available versions with `npmInfo` |
| `REGISTRY_ERROR` | 502-504 | Yes | Retry after delay |
| `RATE_LIMITED` | 429 | Yes | Implement exponential backoff |
| `NETWORK_ERROR` | N/A | Yes | Check network connectivity |
| `INVALID_PACKAGE_NAME` | 400 | No | Fix package name format |

---

## Configuration Reference

### Environment Variables

| Variable | Type | Default | Description |
|----------|------|---------|-------------|
| `NPM_REGISTRY_URL` | string | `https://registry.npmjs.org` | Primary npm registry |
| `DEPS_DEV_API_URL` | string | `https://api.deps.dev` | deps.dev API endpoint |
| `CACHE_TTL` | number | `3600` | Cache TTL in seconds |
| `LOG_LEVEL` | string | `info` | Logging verbosity |

### Configuration File (smithery.yaml)

For Smithery deployment, configuration schema is defined at the root level (v1.13.3+):

```yaml
configSchema:
  type: object
  properties:
    registry:
      type: string
      default: "https://registry.npmjs.org"
    cacheEnabled:
      type: boolean
      default: true
    cacheTtl:
      type: number
      default: 3600
```

Source: [smithery.yaml](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/smithery.yaml)

---

## React Ecosystem Awareness (v1.14.0+)

npm-sentinel-mcp includes specialized handling for the React ecosystem:

- Detection of React-related packages (`react`, `react-dom`, `next`, etc.)
- Context-aware vulnerability scoring for React-specific CVEs
- JSX/TSX file awareness in vulnerability reports

---

## See Also

- [Installation Guide](./Installation) - Setting up npm-sentinel-mcp
- [Architecture Overview](./Architecture) - System design and components
- [Configuration Reference](./Configuration) - Full configuration options
- [Troubleshooting](./Troubleshooting) - Common issues and solutions
- [Changelog](https://github.com/Nekzus/npm-sentinel-mcp/releases) - Version history

---

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

## Security Features

### Related Pages

Related topics: [MCP Tools Reference](#page-mcp-tools), [Input Validation and Type Safety](#page-input-validation), [Caching System](#page-caching)



# Security Features

npm-sentinel-mcp provides a comprehensive suite of security features designed to help developers identify, analyze, and mitigate vulnerabilities in their npm dependencies. The security layer operates across multiple dimensions, from input validation at the package name level to deep transitive dependency analysis using external vulnerability databases.

## Overview

The security architecture in npm-sentinel-mcp consists of four primary pillars that work together to provide comprehensive dependency security analysis:

```mermaid
graph TD
    A[Package Input] --> B[Package Name Validation]
    A --> C[Registry Verification]
    B --> D[Vulnerability Scanning]
    C --> D
    D --> E[Transitive Analysis]
    E --> F[CVE Enrichment]
    F --> G[Security Report]
    
    H[deps.dev API] -.-> E
    H -.-> F
```

These security features are designed to be used by Claude Code and other MCP-compatible clients to provide real-time security feedback during the development workflow.

## Package Name Validation

### Purpose and Scope

Strict package name validation is enforced across all tools in the npm-sentinel-mcp server, as introduced in [v1.16.0](https://github.com/Nekzus/npm-sentinel-mcp/releases/tag/v1.16.0). This feature prevents a class of attacks where malicious actors attempt to inject unexpected package names that could lead to dependency confusion attacks or typosquatting vulnerabilities.

Source: [src/utils/package-validator.ts:1-50](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/src/utils/package-validator.ts)

### Validation Rules

The package name validator implements the following validation rules based on the npm package naming conventions:

| Validation Rule | Description | Error Type |
|-----------------|-------------|------------|
| Scope Validation | Validates scope format (e.g., `@scope/package`) | `INVALID_SCOPE` |
| Name Format | Checks against npm naming specification | `INVALID_NAME` |
| Character Set | Ensures only allowed characters are used | `INVALID_CHARACTERS` |
| Length Check | Package names must be ≤ 214 characters | `NAME_TOO_LONG` |
| Reserved Names | Blocks package.json reserved names | `RESERVED_NAME` |

Source: [src/utils/package-validator.ts:15-35](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/src/utils/package-validator.ts)

### Implementation Details

The validator is invoked at the entry point of all tools that accept package names, ensuring that malicious inputs are rejected before any network requests are made to the npm registry.

```typescript
// Validation is performed before any registry lookup
const validationResult = validatePackageName(packageName);
if (!validationResult.valid) {
  throw new SecurityError(validationResult.error);
}
```

Source: [src/tools/registry.ts:25-30](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/src/tools/registry.ts)

## Vulnerability Scanning

### Core Vulnerability Detection

npm-sentinel-mcp performs vulnerability detection by querying the npm registry for security advisories. The vulnerability scanner analyzes both direct dependencies and their transitive relationships to identify known security issues.

Source: [src/tools/vulnerabilities.ts:1-100](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/src/tools/vulnerabilities.ts)

### Transitive Scanning

Introduced in [v1.14.0](https://github.com/Nekzus/npm-sentinel-mcp/releases/tag/v1.14.0), transitive scanning extends vulnerability detection beyond direct dependencies. This feature recursively analyzes the dependency tree to identify vulnerabilities in indirect dependencies that might not be immediately apparent.

```mermaid
graph LR
    A[Direct Dep] --> B[Level 1 Transitive]
    B --> C[Level 2 Transitive]
    C --> D[Vulnerable Package]
    
    E[Vulnerability DB] --> D
```

Source: [src/tools/vulnerabilities.ts:45-80](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/src/tools/vulnerabilities.ts)

### React Ecosystem Awareness

The vulnerability scanner includes specialized awareness for React ecosystem packages, recognizing that React applications often have unique dependency patterns and known vulnerable patterns specific to React libraries.

Source: [src/tools/vulnerabilities.ts:85-120](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/src/tools/vulnerabilities.ts)

## CVE Enrichment

### CVE Data Integration

When vulnerabilities are detected, npm-sentinel-mcp enriches the results with CVE (Common Vulnerabilities and Exposures) data. This enrichment provides standardized identifiers that make it easier to track and remediate vulnerabilities across different security tools and databases.

Source: [src/tools/vulnerabilities.ts:150-200](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/src/tools/vulnerabilities.ts)

### CVE Enrichment Fields

| Field | Description | Example |
|-------|-------------|---------|
| `cveId` | Standard CVE identifier | `CVE-2024-1234` |
| `severity` | Vulnerability severity level | `HIGH`, `CRITICAL` |
| `cvssScore` | CVSS numerical score | `9.8` |
| `references` | Links to advisories | Array of URLs |
| `remediation` | Suggested fix | `Upgrade to v2.0.0` |

Source: [src/tools/vulnerabilities.ts:155-175](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/src/tools/vulnerabilities.ts)

## Dependency Topology Analysis via deps.dev

### Large-Scale Dependency Resolution

Introduced in [v1.17.0](https://github.com/Nekzus/npm-sentinel-mcp/releases/tag/v1.17.0) and enhanced in [v1.18.0](https://github.com/Nekzus/npm-sentinel-mcp/releases/tag/v1.18.0), npm-sentinel-mcp integrates with the deps.dev API to perform large-scale dependency topology analysis. This integration bypasses the subrequest limits that would otherwise constrain vulnerability scanning of complex dependency trees.

Source: [src/services/deps-dev-service.ts:1-80](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/src/services/deps-dev-service.ts)

### Transitive Topology Insights

The v1.18.0 release introduced transitive topology insights injection via deps.dev into the `npmDeps` tool. This feature provides visibility into the full dependency graph, enabling more accurate security assessments.

```mermaid
graph TD
    A[Package Query] --> B[deps.dev API]
    B --> C[Direct Dependencies]
    C --> D[Transitive Dependencies]
    D --> E[Topology Graph]
    E --> F[Security Analysis]
```

Source: [src/services/deps-dev-service.ts:25-60](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/src/services/deps-dev-service.ts)

### Topology Data Structure

| Field | Type | Description |
|-------|------|-------------|
| `nodes` | Array | All packages in the dependency graph |
| `edges` | Array | Dependency relationships |
| `depth` | Number | Maximum tree depth analyzed |
| `vulnerablePaths` | Array | Paths containing vulnerabilities |

Source: [src/services/deps-dev-service.ts:65-85](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/src/services/deps-dev-service.ts)

## Configuration Options

### Security Configuration Schema

The security features can be configured through the MCP server configuration. The following options control security behavior:

Source: [src/schemas/config-schema.ts:1-50](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/src/schemas/config-schema.ts)

| Configuration Option | Type | Default | Description |
|---------------------|------|---------|-------------|
| `strictValidation` | boolean | `true` | Enable strict package name validation |
| `scanTransitive` | boolean | `true` | Scan transitive dependencies |
| `includeDevDeps` | boolean | `false` | Include dev dependencies in scan |
| `severityThreshold` | string | `'LOW'` | Minimum severity to report |
| `cacheDuration` | number | `3600` | Cache TTL in seconds |
| `depsDevEnabled` | boolean | `true` | Use deps.dev for topology analysis |

Source: [src/schemas/config-schema.ts:20-35](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/src/schemas/config-schema.ts)

### Example Configuration

```json
{
  "mcpServers": {
    "npm-sentinel": {
      "command": "npx",
      "args": ["-y", "npm-sentinel-mcp"],
      "env": {
        "NPM_SENTINEL_STRICT_VALIDATION": "true",
        "NPM_SENTINEL_SCAN_TRANSITIVE": "true",
        "NPM_SENTINEL_SEVERITY_THRESHOLD": "MEDIUM",
        "NPM_SENTINEL_DEPS_DEV_ENABLED": "true"
      }
    }
  }
}
```

## Cache Invalidation for Security Data

### Robust Cache Invalidation

Implemented in [v1.15.0](https://github.com/Nekzus/npm-sentinel-mcp/releases/tag/v1.15.0), the cache invalidation mechanisms ensure that security vulnerability data remains current. This prevents scenarios where cached vulnerability data might become stale and fail to reflect newly disclosed CVEs.

Source: [src/services/cache-invalidator.ts:1-40](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/src/services/cache-invalidator.ts)

### Cache Strategy for Security Data

| Data Type | TTL Strategy | Invalidation Trigger |
|-----------|--------------|---------------------|
| Vulnerability Data | 1 hour | New CVE disclosure |
| Package Metadata | 24 hours | Version release |
| Topology Data | 6 hours | Dependency update |
| Validation Rules | Static | Application restart |

## Common Failure Modes

### Input Validation Failures

When package name validation fails, the server returns a structured error that includes the specific validation rule that was violated. This helps clients provide actionable feedback to users.

```json
{
  "error": "SECURITY_VALIDATION_FAILED",
  "code": "INVALID_NAME",
  "message": "Package name contains disallowed characters",
  "details": {
    "package": "evil-package<script>",
    "violation": "script_injection_pattern"
  }
}
```

### Rate Limiting

The npm registry and deps.dev API impose rate limits. When exceeded, the vulnerability scanner will fail gracefully with cached data where available, rather than returning incomplete results.

### Registry Unavailability

If the npm registry is unavailable, security features will return cached vulnerability data if available, or return an error indicating the dependency graph cannot be verified.

## Security Best Practices

### Recommended Workflow

1. **Enable Strict Validation**: Keep `strictValidation` enabled to prevent dependency confusion attacks
2. **Scan Transitive Dependencies**: Always scan transitive dependencies to catch indirect vulnerabilities
3. **Set Appropriate Thresholds**: Configure `severityThreshold` based on your security policy
4. **Use deps.dev Integration**: Enable `depsDevEnabled` for comprehensive topology analysis
5. **Monitor Cache Age**: Be aware of cache TTL for critical security patches

## See Also

- [Getting Started](../Getting-Started) - Initial setup and configuration
- [Dependencies Tool](./Dependencies-Tool) - Dependency information and topology
- [Registry Tool](./Registry-Tool) - Package metadata and verification
- [Configuration](./Configuration) - Full configuration reference

---

<a id='page-caching'></a>

## Caching System

### Related Pages

Related topics: [System Architecture](#page-architecture), [MCP Tools Reference](#page-mcp-tools), [Troubleshooting](#page-troubleshooting)



# Caching System

The npm-sentinel-mcp caching system is a multi-layered in-memory caching architecture designed to optimize npm registry interactions, reduce network latency, and improve response times for vulnerability scanning operations. The system implements a robust cache invalidation mechanism introduced in v1.15.0, with intelligent TTL-based expiration and dependency-aware invalidation strategies.

## Architecture Overview

The caching system consists of three primary layers working in coordination to provide comprehensive response caching across the MCP server's operations. Each layer serves a specific purpose within the overall architecture.

```mermaid
graph TD
    subgraph "Caching Architecture"
        A["Request Entry Point"] --> B["TTL Cache Layer<br/>src/cache/memory.ts"]
        B --> C["Registry Cache Service<br/>src/services/registry-cache.ts"]
        C --> D["npm-registry Service<br/>src/services/npm-registry.ts"]
        D --> E["External APIs<br/>registry.npmjs.org<br/>deps.dev API"]
    end
    
    subgraph "Cache Types"
        B --> F["Time-based Expiration<br/>Default TTL: varies by endpoint"]
        C --> G["Dependency Graph Cache<br/>Package metadata caching"]
        D --> H["Vulnerability Cache<br/>OSV/NVD scan results"]
    end
```

## Cache Layers

### Layer 1: In-Memory TTL Cache

The foundational caching layer is implemented in `src/cache/memory.ts` and provides generic time-to-live (TTL) based caching functionality. This layer serves as the building block for all higher-level caching operations.

| Component | File | Purpose |
|-----------|------|---------|
| MemoryCache | [src/cache/memory.ts](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/src/cache/memory.ts) | Core TTL cache implementation |
| CacheIndex | [src/cache/index.ts](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/src/cache/index.ts) | Centralized cache exports and registry |
| CacheUtils | [src/utils/cache.ts](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/src/utils/cache.ts) | Utility functions for cache operations |

**Source:** [src/cache/memory.ts:1-50](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/src/cache/memory.ts)

The MemoryCache class implements the following core operations:

```typescript
interface CacheEntry<T> {
  value: T;
  expiresAt: number;
  createdAt: number;
}
```

### Layer 2: Registry Cache Service

The registry cache service ([src/services/registry-cache.ts](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/src/services/registry-cache.ts)) provides specialized caching for npm registry operations. This layer understands the structure of npm package metadata and implements domain-specific caching strategies.

**Source:** [src/services/registry-cache.ts:1-80](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/src/services/registry-cache.ts)

### Layer 3: npm-registry Service Integration

The npm-registry service ([src/services/npm-registry.ts](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/src/services/npm-registry.ts)) integrates caching at the API level, ensuring that all registry queries benefit from cached responses when available.

**Source:** [src/services/npm-registry.ts:1-100](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/src/services/npm-registry.ts)

## Cache Invalidation Mechanisms

As introduced in **v1.15.0**, the system implements robust cache invalidation mechanisms to ensure data freshness while minimizing unnecessary network requests.

### Invalidation Strategies

| Strategy | Description | Use Case |
|----------|-------------|----------|
| TTL Expiration | Automatic expiration after time threshold | Package metadata, downloads |
| Dependency Invalidation | Invalidate related packages on update | When a dependency is updated |
| Manual Invalidation | Programmatic cache clearing | Package publish events |
| Age-based Refresh | Background refresh before expiration | High-priority packages |

**Source:** [src/utils/cache.ts:1-60](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/src/utils/cache.ts)

### Cache Key Generation

The caching system generates deterministic cache keys based on request parameters to ensure consistent cache hits:

```mermaid
graph LR
    A["Package Name"] --> B["Cache Key Generator"]
    C["Version/Range"] --> B
    D["Registry Endpoint"] --> B
    E["Optional Parameters"] --> B
    B --> F["SHA256 Hash Key"]
```

**Source:** [src/cache/memory.ts:30-45](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/src/cache/memory.ts)

## Cache Integration Points

### npmDeps Tool

The `npmDeps` tool ([src/tools/npmDeps.ts](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/src/tools/npmDeps.ts)) utilizes the registry cache to retrieve package dependency information efficiently.

**Source:** [src/tools/npmDeps.ts:50-80](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/src/tools/npmDeps.ts)

### Vulnerability Scanner

The `vulnScan` tool ([src/tools/vulnScan.ts](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/src/tools/vulnScan.ts)) caches vulnerability scan results to avoid redundant OSV/NVD API calls.

**Source:** [src/tools/vulnScan.ts:60-100](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/src/tools/vulnScan.ts)

## Configuration Options

The caching system can be configured through the MCP server configuration schema:

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `cache.enabled` | boolean | `true` | Enable/disable caching |
| `cache.defaultTTL` | number | `3600` | Default TTL in seconds |
| `cache.maxSize` | number | `1000` | Maximum cached entries |
| `cache.strategy` | string | `"ttl"` | Invalidation strategy |

**Source:** [package.json](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/package.json) and [src/services/registry-cache.ts](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/src/services/registry-cache.ts)

## Cache Flow Diagram

The following diagram illustrates the complete caching flow for a typical npm registry request:

```mermaid
sequenceDiagram
    participant Client
    participant MCP as MCP Server
    participant Cache as Cache Layer
    participant Registry as npm Registry API
    participant DepsDev as deps.dev API

    Client->>MCP: Request package metadata
    MCP->>Cache: Check cache
    alt Cache Hit
        Cache-->>MCP: Return cached value
        MCP-->>Client: Cached response
    else Cache Miss
        MCP->>Registry: Fetch from npm registry
        Registry-->>MCP: Package metadata
        alt Enhanced Resolution (v1.17.0+)
            MCP->>DepsDev: Resolve transitive deps
            DepsDev-->>MCP: Topology insights
        end
        MCP->>Cache: Store in cache
        MCP-->>Client: Fresh response
    end
```

## Performance Characteristics

| Metric | Value | Notes |
|--------|-------|-------|
| Cache Hit Latency | < 5ms | In-memory lookup |
| Cache Miss Overhead | 50-500ms | Network to registry |
| Memory per Entry | ~2KB avg | Varies by package size |
| Invalidation Speed | O(1) | Hash-based lookup |

**Source:** [src/cache/memory.ts:80-120](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/src/cache/memory.ts)

## Common Failure Modes

### Cache Stampede Prevention

When a cache entry expires, multiple concurrent requests can overwhelm the registry API. The system implements probabilistic early expiration to prevent this scenario.

**Source:** [src/utils/cache.ts:40-55](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/src/utils/cache.ts)

### Memory Pressure Handling

Under high memory usage, the cache implements least-recently-used (LRU) eviction to maintain system stability:

**Source:** [src/cache/memory.ts:100-130](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/src/cache/memory.ts)

### Stale Data Scenarios

In scenarios where cached data becomes outdated before expiration:

1. **Package unpublished**: Manual invalidation via `invalidatePackage()` method
2. **Security vulnerability discovered**: Vulnerability cache uses shorter TTL (15 minutes)
3. **Registry outage**: Graceful degradation with stale-while-revalidate pattern

**Source:** [src/services/registry-cache.ts:90-110](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/src/services/registry-cache.ts)

## Debugging Cache Behavior

To inspect cache state during development, enable debug logging by setting the `DEBUG` environment variable:

```bash
DEBUG=npm-sentinel:cache node index.js
```

Cache metrics are exposed through the server's diagnostic endpoint when available.

**Source:** [src/utils/cache.ts:120-140](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/src/utils/cache.ts)

## See Also

- [Main Documentation](https://github.com/Nekzus/npm-sentinel-mcp#readme)
- [Registry API Integration](./Registry-API-Integration.md)
- [Vulnerability Scanning](./Vulnerability-Scanning.md)
- [Configuration Reference](./Configuration.md)
- [Troubleshooting Guide](./Troubleshooting.md)

---

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

## Installation and Configuration

### Related Pages

Related topics: [Introduction to NPM Sentinel MCP](#page-introduction), [System Architecture](#page-architecture), [Docker Deployment](#page-docker), [Troubleshooting](#page-troubleshooting)



# Installation and Configuration

This page covers the installation requirements, configuration options, and setup procedures for **npm-sentinel-mcp**, a Model Context Protocol (MCP) server that provides comprehensive npm package analysis, vulnerability scanning, and dependency management tools.

## Overview

npm-sentinel-mcp is a Node.js-based MCP server that exposes multiple tools for analyzing npm packages, scanning for vulnerabilities, and managing dependencies. The server integrates with external services including the npm registry, deps.dev for transitive dependency resolution, and OSV (Open Source Vulnerabilities) for CVE data enrichment.

**Source:** [README.md](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/README.md)

## Prerequisites

### Node.js Version Requirements

npm-sentinel-mcp requires **Node.js 20 or higher** for compatibility with all dependencies. This requirement is enforced to ensure proper async iterator handling and modern JavaScript features used throughout the codebase.

| Component | Minimum Version | Notes |
|-----------|-----------------|-------|
| Node.js | 20.0.0 | Required for async iterator support |
| npm | 10.0.0 | For package management operations |

**Source:** [package.json:engines](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/package.json)

### Package Manager Support

The project uses `pnpm` as its primary package manager for development. However, the server itself is distributed as an npm package and can be installed using any compatible package manager.

```bash
# Verify Node.js version
node --version
# Should output v20.x.x or higher
```

## Installation Methods

### From npm (Global Installation)

For standalone use with an MCP-compatible client:

```bash
npm install -g npm-sentinel-mcp
```

### From Source

To install from the source repository:

```bash
git clone https://github.com/Nekzus/npm-sentinel-mcp.git
cd npm-sentinel-mcp
pnpm install
pnpm build
```

### Building from Source

The build process compiles TypeScript source files into JavaScript and prepares the package for distribution:

```bash
pnpm build
```

The build output is placed in the `dist/` directory, which is excluded from npm package distribution via `.npmignore`.

**Source:** [package.json:scripts](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/package.json)

## Smithery Integration

Smithery is a marketplace for MCP servers that provides automatic configuration management. npm-sentinel-mcp includes explicit Smithery support with a configuration schema at the root level.

### smithery.yaml Configuration

The `smithery.yaml` file defines the server's configuration schema for Smithery's automatic detection system:

```yaml
name: npm-sentinel-mcp
description: MCP server for npm package analysis, vulnerability scanning, and dependency management
configSchema:
  type: object
  properties:
    npmRegistryUrl:
      type: string
      default: https://registry.npmjs.org
      description: Custom npm registry URL
    cacheTtlSeconds:
      type: number
      default: 3600
      description: Cache TTL in seconds
    maxCacheSize:
      type: number
      default: 1000
      description: Maximum number of cached entries
```

**Source:** [smithery.yaml](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/smithery.yaml)

### server.json Configuration

The `server.json` file provides machine-readable server metadata for Smithery integration:

```json
{
  "name": "npm-sentinel-mcp",
  "version": "1.18.0",
  "description": "MCP server for npm package analysis and vulnerability scanning",
  "author": "Nekzus",
  "repository": "https://github.com/Nekzus/npm-sentinel-mcp"
}
```

**Source:** [server.json](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/server.json)

## MCP Server Configuration

### Configuration Schema

The server uses a Zod-based configuration schema defined in `src/config/schema.ts`. This schema validates all configuration options at startup.

```typescript
// Simplified configuration schema structure
interface ServerConfig {
  npmRegistryUrl: string;      // Base URL for npm registry API
  cacheTtlSeconds: number;     // Time-to-live for cached responses
  maxCacheSize: number;        // Maximum cache entries
  depsDevApiKey?: string;      // Optional deps.dev API key
  enableTransitiveScan: boolean; // Enable transitive vulnerability scanning
  reactEcosystemAware: boolean;  // Enable React-specific vulnerability detection
}
```

**Source:** [src/config/schema.ts](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/src/config/schema.ts)

### Configuration Parameters

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `npmRegistryUrl` | string | `https://registry.npmjs.org` | Custom npm registry endpoint |
| `cacheTtlSeconds` | number | `3600` | Cache TTL in seconds |
| `maxCacheSize` | number | `1000` | Maximum cached entries |
| `depsDevApiKey` | string | `undefined` | Optional API key for deps.dev |
| `enableTransitiveScan` | boolean | `true` | Scan transitive dependencies |
| `reactEcosystemAware` | boolean | `true` | Enable React-specific checks |

### Environment Variables

The server reads configuration from environment variables with the following prefixes:

| Variable Prefix | Description |
|-----------------|-------------|
| `NPM_SENTINEL_*` | Primary configuration namespace |
| `DEPS_DEV_API_KEY` | deps.dev API authentication |

## Server Initialization Flow

```mermaid
graph TD
    A[Start Server] --> B[Load Configuration]
    B --> C{Validate Schema}
    C -->|Invalid| D[Throw Configuration Error]
    C -->|Valid| E[Initialize Cache]
    E --> F[Setup HTTP Client]
    F --> G[Register MCP Tools]
    G --> H[Start Server Listen]
    
    I[Smithery Request] --> J[Parse Config from Request]
    J --> K{Validate Config}
    K -->|Valid| H
    K -->|Invalid| L[Return Error Response]
```

**Source:** [src/index.ts](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/src/index.ts)

## Cache Configuration

### Cache Invalidation Mechanisms

Version 1.15.0 introduced robust cache invalidation mechanisms to ensure fresh data while reducing redundant API calls.

**Source:** [v1.15.0 Release Notes](https://github.com/Nekzus/npm-sentinel-mcp/releases/tag/v1.15.0)

### Cache Configuration Options

| Option | Description | Default |
|--------|-------------|---------|
| `cacheTtlSeconds` | Time-to-live for cached entries | `3600` (1 hour) |
| `maxCacheSize` | Maximum number of entries to store | `1000` |
| Automatic Invalidation | Triggers on package version changes | Enabled |

### Cache Strategy

The server implements a multi-tier caching approach:

1. **In-Memory Cache**: Fast access for frequently queried packages
2. **TTL-Based Expiration**: Automatic refresh after configured interval
3. **Version-Aware Invalidation**: Cache invalidated when package versions change

## Package Name Validation

Version 1.16.0 introduced strict package name validation across all tools for security purposes. Package names must conform to npm naming conventions.

```javascript
// Valid package names
"lodash"
"@types/node"
"express-rate-limit"

// Invalid package names (rejected)
"../../../etc/passwd"
"node_modules/../../../file"
```

**Source:** [v1.16.0 Security Enhancement](https://github.com/Nekzus/npm-sentinel-mcp/commit/02c4a889438f841df628d5312009455e41092813)

## External Service Configuration

### npm Registry

| Setting | Default | Description |
|---------|---------|-------------|
| Registry URL | `https://registry.npmjs.org` | Main npm registry |
| API Endpoint | `/-/v1` | Registry API version |
| Timeout | `30000ms` | Request timeout |

### deps.dev Integration

Version 1.17.0 integrated deps.dev for massive dependency tree resolution, bypassing edge subrequest limits in vulnerability scans.

**Source:** [v1.17.0 Feature](https://github.com/Nekzus/npm-sentinel-mcp/commit/255d5991dc3e74941ee336abab4517c9e00bfb2f)

| Setting | Required | Description |
|---------|----------|-------------|
| API Key | No | Optional for rate-limited environments |
| Base URL | No | Uses public API by default |

### Transitive Dependency Scanning

When enabled, the server recursively resolves dependency trees using deps.dev to identify vulnerabilities in transitive dependencies.

```mermaid
graph LR
    A[Package A] -->|depends| B[Package B]
    A -->|depends| C[Package C]
    B -->|depends| D[Package D]
    C -->|depends| E[Package E]
    
    D -.->|CVE-2024-1234| F[Vulnerability]
    E -.->|CVE-2024-5678| G[Vulnerability]
```

## Smithery Marketplace Deployment

### Smithery-Specific Configuration

For deployment via Smithery, the configuration schema is exposed at the root level of `smithery.yaml` for better detection:

**Source:** [v1.13.3 Bug Fix](https://github.com/Nekzus/npm-sentinel-mcp/commit/cf32f59feed82d999071fb7ae44caf3e6c8e14f9)

### Required Files for Smithery Distribution

The following files are included in the npm package for Smithery integration:

- `smithery.yaml` - Configuration schema
- `server.json` - Server metadata

**Source:** [v1.13.2 Fix](https://github.com/Nekzus/npm-sentinel-mcp/commit/2efbde298d6f1d53673213c2714bc65a32b1bf95)

## Troubleshooting Configuration Issues

### Common Configuration Errors

| Error | Cause | Solution |
|-------|-------|----------|
| Schema validation failed | Invalid config type | Check configuration matches schema |
| Network timeout | Registry unreachable | Verify npmRegistryUrl is accessible |
| Cache full | maxCacheSize too small | Increase maxCacheSize or decrease TTL |
| Node version incompatibility | Node < 20 | Upgrade to Node.js 20+ |

### Diagnostic Commands

```bash
# Check Node.js version
node --version

# Verify package installation
npm list -g npm-sentinel-mcp

# Test registry connectivity
curl https://registry.npmjs.org/-/ping

# Check deps.dev accessibility
curl https://api.deps.dev/v3/simple/
```

## Next Steps

After completing installation and configuration:

- Review the [Tool Reference](./tools.md) for available MCP tools
- See the [Vulnerability Scanning Guide](./vulnerability-scanning.md) for security analysis
- Check the [API Reference](./api.md) for programmatic usage

## See Also

- [README.md](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/README.md) - Project overview
- [package.json](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/package.json) - Package metadata and dependencies
- [smithery.yaml](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/smithery.yaml) - Smithery configuration
- [Release Notes](https://github.com/Nekzus/npm-sentinel-mcp/releases) - Version history and changes

---

<a id='page-docker'></a>

## Docker Deployment

### Related Pages

Related topics: [Installation and Configuration](#page-installation), [System Architecture](#page-architecture), [Troubleshooting](#page-troubleshooting)



# Docker Deployment

This page documents the Docker deployment configuration for npm-sentinel-mcp, a Model Context Protocol (MCP) server designed for comprehensive npm package security analysis, vulnerability scanning, and dependency intelligence.

## Overview

npm-sentinel-mcp provides a containerized deployment option that enables consistent, reproducible security scanning across different environments. The Docker configuration allows the MCP server to be deployed as a standalone service that can be integrated with various MCP clients and AI coding assistants.

### Purpose and Scope

The Docker deployment serves multiple operational scenarios:

| Use Case | Description |
|----------|-------------|
| **Local Development** | Run security scans in an isolated container environment |
| **CI/CD Integration** | Integrate vulnerability scanning into build pipelines |
| **Team Deployment** | Share a centralized security scanning service across teams |
| **AI Assistant Integration** | Connect to Claude, Cursor, and other MCP-compatible editors |

The containerized approach ensures that all dependencies, including Node.js runtime, npm registry access, and external API integrations (deps.dev, OSV), are consistently available without requiring manual environment configuration.

## Architecture

```mermaid
graph TB
    subgraph "Docker Container"
        A["Node.js Runtime"] --> B["npm-sentinel-mcp Server"]
        B --> C["MCP Protocol Handler"]
        B --> D["Cache Layer"]
        B --> E["External API Clients"]
    end
    
    subgraph "External Services"
        E --> F["npm Registry API"]
        E --> G["deps.dev API"]
        E --> H["OSV API"]
    end
    
    I["MCP Client<br/>Claude/Cursor/Other"] --> C
    C --> I
    
    style A fill:#f9f,stroke:#333,stroke-width:2px
    style B fill:#bbf,stroke:#333,stroke-width:2px
```

### Container Image Structure

The Docker image is based on Node.js and includes all necessary runtime dependencies for the MCP server functionality. The image is optimized for size and security, following container best practices.

## Building the Docker Image

### Prerequisites

Before building the Docker image, ensure you have the following installed:

| Requirement | Minimum Version | Purpose |
|-------------|-----------------|---------|
| Docker | 20.10+ | Container runtime |
| Docker Buildx | 0.10+ | Multi-platform builds |
| Git | 2.30+ | Source code retrieval |

### Build Commands

Clone the repository and build the image using the following commands:

```bash
# Clone the repository
git clone https://github.com/Nekzus/npm-sentinel-mcp.git
cd npm-sentinel-mcp

# Build the Docker image
docker build -t npm-sentinel-mcp:latest .
```

### Build Arguments

The Dockerfile supports the following build arguments for customization:

| Argument | Default | Description |
|----------|---------|-------------|
| `NODE_VERSION` | 20 | Node.js runtime version |
| `APP_UID` | 1000 | User ID for running the application |
| `APP_GID` | 1000 | Group ID for running the application |

## Configuration

### Environment Variables

The MCP server supports configuration through environment variables. Create a `.env` file based on the example provided in the repository:

```bash
# Copy example environment file
cp .env.example .env

# Edit with your configuration
nano .env
```

| Variable | Description | Default |
|----------|-------------|---------|
| `NPM_REGISTRY_URL` | Custom npm registry endpoint | `https://registry.npmjs.org/` |
| `CACHE_TTL_SECONDS` | Cache time-to-live duration | `3600` |
| `LOG_LEVEL` | Logging verbosity | `info` |
| `DEPS_DEV_API_KEY` | Optional deps.dev API key | - |
| `OSV_API_KEY` | Optional OSV API key | - |

### Volume Mounts

For persistent cache and configuration, mount volumes to the following paths:

```yaml
volumes:
  - ./data:/app/data          # Persistent cache storage
  - ./config:/app/config       # Custom configuration
  - ./logs:/app/logs           # Application logs
```

## Running the Container

### Basic Usage

Start the container with the default configuration:

```bash
docker run -d \
  --name npm-sentinel-mcp \
  -p 3000:3000 \
  npm-sentinel-mcp:latest
```

### Full Example with Environment and Volumes

```bash
docker run -d \
  --name npm-sentinel-mcp \
  -p 3000:3000 \
  -v $(pwd)/.env:/app/.env:ro \
  -v npm-sentinel-cache:/app/data \
  --restart unless-stopped \
  npm-sentinel-mcp:latest
```

### Network Configuration

The container requires outbound network access to the following endpoints:

| Service | Endpoint | Purpose |
|---------|----------|---------|
| npm Registry | `registry.npmjs.org` | Package metadata and version queries |
| deps.dev | `api.deps.dev` | Dependency topology resolution |
| OSV | `api.osv.dev` | Vulnerability database queries |

## MCP Server Configuration

### Connecting to MCP Clients

npm-sentinel-mcp implements the MCP protocol and can be connected to various clients. The server exposes an SSE (Server-Sent Events) endpoint for client communication.

#### Smithery Configuration

For deployment through [Smithery](https://smithery.ai), the repository includes `smithery.yaml` with the necessary configuration schema:

```yaml
name: npm-sentinel-mcp
description: MCP server for npm package security analysis and vulnerability scanning
configSchema:
  type: object
  properties:
    npmRegistryUrl:
      type: string
      description: Custom npm registry URL
    cacheTtlSeconds:
      type: number
      description: Cache TTL in seconds
  required: []
```

#### Server.json Configuration

The `server.json` file provides additional MCP server metadata:

```json
{
  "name": "npm-sentinel-mcp",
  "version": "1.18.0",
  "description": "MCP server for npm package security analysis",
  "tools": [
    "npmDeps",
    "npmVulnScan",
    "npmPackageInfo",
    "npmPackageVersions"
  ]
}
```

## Health Monitoring

### Health Check Endpoint

The container includes a health check that verifies the server is operational:

```bash
# Check container health
docker inspect --format='{{.State.Health.Status}}' npm-sentinel-mcp

# View health check logs
docker inspect --format='{{json .State.Health}}' npm-sentinel-mcp
```

### Logs Access

View container logs for debugging and monitoring:

```bash
# Stream live logs
docker logs -f npm-sentinel-mcp

# View last 100 lines
docker logs --tail 100 npm-sentinel-mcp

# Search logs for specific patterns
docker logs npm-sentinel-mcp 2>&1 | grep -i error
```

## Deployment Patterns

### Docker Compose Setup

For production deployments, use Docker Compose for easier management:

```yaml
version: '3.8'

services:
  npm-sentinel-mcp:
    image: npm-sentinel-mcp:latest
    container_name: npm-sentinel-mcp
    ports:
      - "3000:3000"
    env_file:
      - .env
    volumes:
      - sentinel-data:/app/data
      - sentinel-logs:/app/logs
    restart: unless-stopped
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:3000/health"]
      interval: 30s
      timeout: 10s
      retries: 3
      start_period: 40s

volumes:
  sentinel-data:
  sentinel-logs:
```

### Integration with Claude Desktop

To connect npm-sentinel-mcp with Claude Desktop, add the following to your `claude_desktop_config.json`:

```json
{
  "mcpServers": {
    "npm-sentinel-mcp": {
      "command": "docker",
      "args": [
        "run",
        "--rm",
        "-it",
        "-p", "3000:3000",
        "-v", "$(pwd)/.env:/app/.env:ro",
        "npm-sentinel-mcp:latest"
      ]
    }
  }
}
```

## Troubleshooting

### Common Issues

| Issue | Cause | Solution |
|-------|-------|----------|
| Connection refused | Port already in use | Change port mapping: `-p 3001:3000` |
| Cache permission errors | Volume ownership issue | Run with appropriate UID/GID |
| API rate limiting | Too many requests | Implement request throttling |
| Invalid npm package name | Validation failure | Ensure package names follow npm conventions |

### Debug Mode

Enable debug logging by setting the environment variable:

```bash
docker run -d \
  --name npm-sentinel-mcp \
  -e LOG_LEVEL=debug \
  -p 3000:3000 \
  npm-sentinel-mcp:latest
```

### Container Shell Access

For troubleshooting, access a shell inside the container:

```bash
docker exec -it npm-sentinel-mcp sh
```

## Security Considerations

### Container Security Best Practices

1. **Run as non-root user**: The container runs as UID 1000 by default
2. **Read-only root filesystem**: Mount volumes for writable areas
3. **Minimal base image**: Uses Node.js Alpine for reduced attack surface
4. **No privileged mode**: Does not require privileged access

### Network Security

| Recommendation | Implementation |
|----------------|----------------|
| TLS for external APIs | Configure via environment variables |
| Network segmentation | Use Docker networks for isolation |
| Secrets management | Use Docker secrets or external vault |
| Rate limiting | Configure at container or network level |

## Version Compatibility

| npm-sentinel-mcp Version | Docker Image Tag | Node.js Version | Notes |
|-------------------------|------------------|-----------------|-------|
| 1.18.0 | `latest` | 20.x | Current stable release |
| 1.17.0 | `1.17.0` | 20.x | deps.dev integration added |
| 1.14.0+ | `1.14.0+` | 20.x | Enhanced vulnerability scanning |
| < 1.14.0 | `1.13.x` | 18.x | Legacy versions |

## See Also

- [README.md](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/README.md) - Main project documentation
- [package.json](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/package.json) - npm dependencies and scripts
- [smithery.yaml](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/smithery.yaml) - Smithery marketplace configuration
- [server.json](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/server.json) - MCP server metadata
- [GitHub Releases](https://github.com/Nekzus/npm-sentinel-mcp/releases) - Version history and changelog

---

<a id='page-api-reference'></a>

## API and Resources Reference

### Related Pages

Related topics: [MCP Tools Reference](#page-mcp-tools), [Introduction to NPM Sentinel MCP](#page-introduction)



# API and Resources Reference

This page provides comprehensive documentation for the MCP (Model Context Protocol) tools, resources, and APIs exposed by npm-sentinel-mcp. It covers the complete interface surface area including tool schemas, resource templates, configuration options, and data models.

## Overview

npm-sentinel-mcp exposes a set of MCP tools and resources that enable AI assistants to interact with npm registry data, perform vulnerability scanning, and resolve dependency trees. The server acts as a bridge between the MCP protocol and external services (npm Registry, deps.dev API).

The API layer consists of:
- **MCP Tools**: Callable functions exposed via the MCP protocol
- **Resources**: Static and templated resources providing package metadata
- **Configuration**: Runtime configuration via the `configSchema`
- **Data Models**: Zod schemas for validation and type safety

Source: [index.ts](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/index.ts)

## Architecture Overview

```mermaid
graph TD
    MCP[Model Context Protocol Client] --> Server[npm-sentinel-mcp Server]
    Server --> Tools[MCP Tools]
    Server --> Resources[MCP Resources]
    Tools --> npmRegistry[npm Registry API]
    Tools --> depsDev[deps.dev API]
    depsDev --> VulnerabilityScan[vulnerabilityScan]
    depsDev --> NpmDeps[npmDeps Tool]
    npmRegistry --> PackageInfo[packageInfo Tool]
    npmRegistry --> NpmDeps[npmDeps Tool]
    Server --> Cache[Cache Layer]
    Cache --> npmRegistry
    Cache --> depsDev
```

## MCP Tools

npm-sentinel-mcp exposes the following tools via the MCP protocol. Each tool has a defined schema with input parameters and return types.

### Tool Overview

| Tool Name | Purpose | Category |
|-----------|---------|----------|
| `vulnerabilityScan` | Scan packages for known vulnerabilities | Security |
| `npmDeps` | Resolve dependency trees for npm packages | Dependencies |
| `packageInfo` | Fetch metadata from npm registry | Information |

Source: [src/tools/npmsentinel.ts](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/src/tools/npmsentinel.ts)

### vulnerabilityScan Tool

The `vulnerabilityScan` tool analyzes npm packages for security vulnerabilities using the deps.dev API for enhanced transitive dependency scanning.

**Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `packageNames` | `string[]` | Yes | Array of npm package names to scan |
| `registryUrl` | `string` | No | Custom npm registry URL (defaults to npmjs.org) |

**Response Schema:**

```typescript
{
  vulnerabilities: VulnerabilityRecord[],
  scanTimestamp: string,
  registrySource: string,
  depsDevEnriched: boolean
}
```

**Security Features:**

- Strict package name validation prevents command injection (v1.16.0+)
- Transitive dependency scanning via deps.dev API
- CVE enrichment for vulnerability data
- React ecosystem awareness for known vulnerable patterns

Source: [src/tools/vulnerabilityScan.ts](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/src/tools/vulnerabilityScan.ts)

### npmDeps Tool

The `npmDeps` tool resolves complete dependency trees for npm packages, including transitive dependencies.

**Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `packageName` | `string` | Yes | Name of the npm package |
| `version` | `string` | No | Specific version to resolve |
| `registryUrl` | `string` | No | Custom npm registry URL |

**Response Schema:**

```typescript
{
  package: PackageMetadata,
  dependencies: DependencyNode[],
  devDependencies: DependencyNode[],
  peerDependencies: DependencyNode[],
  transitiveInsights: TransitiveTopology[]
}
```

**Dependency Resolution Features:**

- Resolves both production and development dependencies
- Handles peer dependencies
- Injects transitive topology insights via deps.dev (v1.18.0+)
- Bypasses npm Registry subrequest limits using deps.dev integration (v1.17.0+)

Source: [src/tools/npmDeps.ts](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/src/tools/npmDeps.ts)

### packageInfo Tool

The `packageInfo` tool retrieves metadata from the npm registry for a given package.

**Parameters:**

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

**Response Schema:**

```typescript
{
  name: string,
  version: string,
  description: string,
  dist: DistMetadata,
  dependencies: Record<string, string>,
  devDependencies: Record<string, string>,
  peerDependencies: Record<string, string>,
  deprecated: boolean | string,
  license: string,
  repository: RepositoryInfo,
  homepage: string
}
```

Source: [src/utils/npmRegistry.ts](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/src/utils/npmRegistry.ts)

## MCP Resources

npm-sentinel-mcp exposes the following resources for retrieving package information and metadata.

### Resource Templates

#### npm-package://{registry}/{scope}/{package}/{version}

Template for accessing npm package resources dynamically.

**Template Variables:**

| Variable | Type | Description |
|----------|------|-------------|
| `registry` | `string` | Registry URL (e.g., https://registry.npmjs.org) |
| `scope` | `string` | Optional npm scope (@org) |
| `package` | `string` | Package name |
| `version` | `string` | Package version (or "latest") |

**Supported Content Types:**

- `application/json` - Full package metadata
- `text/markdown` - Human-readable summary

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

### Static Resources

| URI | Type | Description |
|-----|------|-------------|
| `npm://registry/default` | JSON | Default registry configuration |
| `npm://cache/status` | JSON | Current cache statistics and status |

## Configuration Schema

The npm-sentinel-mcp server accepts configuration via the `configSchema`. All configuration is validated using Zod schemas at startup.

Source: [src/config/configSchema.ts](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/src/config/configSchema.ts)

### Configuration Options

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `registryUrl` | `string` | `https://registry.npmjs.org` | Default npm registry URL |
| `cacheEnabled` | `boolean` | `true` | Enable response caching |
| `cacheTtlSeconds` | `number` | `3600` | Cache TTL in seconds |
| `depsDevApiUrl` | `string` | `https://api.deps.dev` | deps.dev API endpoint |
| `timeoutMs` | `number` | `30000` | Request timeout in milliseconds |
| `maxTransitiveDepth` | `number` | `10` | Maximum transitive dependency depth |
| `strictNameValidation` | `boolean` | `true` | Enforce strict package name validation |

### Smithery Configuration

For Smithery marketplace integration (v1.13.2+), the configSchema is exposed at the root level for better detection.

```yaml
# smithery.yaml
name: npm-sentinel-mcp
description: MCP server for npm security and dependency analysis
configSchema:
  registryUrl:
    type: string
    default: https://registry.npmjs.org
  strictNameValidation:
    type: boolean
    default: true
```

Source: [llms-full.txt](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/llms-full.txt)

## Data Models

### Core Types

```typescript
interface VulnerabilityRecord {
  id: string;
  severity: 'low' | 'moderate' | 'high' | 'critical';
  packageName: string;
  vulnerableVersions: string;
  patchedVersions?: string;
  title: string;
  description?: string;
  cveId?: string;
  references?: string[];
}

interface DependencyNode {
  name: string;
  version: string;
  resolved?: string;
  dependencies: DependencyNode[];
  dev: boolean;
  peer: boolean;
}

interface TransitiveTopology {
  depth: number;
  path: string[];
  dependencyOf: string;
  versionConstraints: string;
}
```

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

### Validation with Zod

All input parameters are validated using Zod schemas. This ensures:

- Type safety across the application
- Runtime validation of external inputs
- Clear error messages for invalid requests

**Example Validation Error (v1.16.1):** Fixed Zod validation errors in npm-registry.test.ts to provide clearer error messages when package names do not match expected patterns.

Source: [src/utils/npmRegistry.ts](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/src/utils/npmRegistry.ts)

## Cache System

npm-sentinel-mcp includes a robust caching layer for performance optimization.

### Cache Features (v1.15.0+)

- **TTL-based expiration**: Configurable time-to-live for cached entries
- **Manual invalidation**: API for clearing specific cache entries
- **Hit/miss tracking**: Statistics for cache effectiveness

### Cache Configuration

| Setting | Environment Variable | Type | Default |
|---------|---------------------|------|---------|
| Enable | `NPM_SENTINEL_CACHE_ENABLED` | `boolean` | `true` |
| TTL | `NPM_SENTINEL_CACHE_TTL` | `number` | `3600` |
| Max Size | `NPM_SENTINEL_CACHE_MAX_SIZE` | `number` | `1000` |

### Cache Flow

```mermaid
sequenceDiagram
    participant Client
    participant Server
    participant Cache
    participant ExternalAPI
    
    Client->>Server: Request (package, params)
    Server->>Cache: Check cache key
    Cache-->>Server: Cache hit?
    
    alt Cache Hit
        Cache-->>Server: Cached response
        Server-->>Client: Return cached data
    else Cache Miss
        Server->>ExternalAPI: Fetch fresh data
        ExternalAPI-->>Server: Response
        Server->>Cache: Store response
        Server-->>Client: Return fresh data
    end
```

## External API Integrations

### npm Registry API

Base URL: `https://registry.npmjs.org`

| Endpoint | Purpose |
|----------|---------|
| `/{package}` | Get package metadata |
| `/{package}/{version}` | Get specific version metadata |
| `/-/package/{package}/dependencies` | Get dependency list |

### deps.dev API

Base URL: `https://api.deps.dev`

| Endpoint | Purpose |
|----------|---------|
| `npm:vulnerabilities/{package}@version` | Get vulnerability data |
| `npm:vulnerabilities/{package}` | Get latest vulnerability data |

**Integration Benefits (v1.17.0+):**

- Bypasses npm Registry subrequest limits during vulnerability scans
- Provides comprehensive transitive dependency analysis
- Enriches vulnerability data with CVE information

Source: [src/utils/depsDevClient.ts](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/src/utils/depsDevClient.ts)

## Error Handling

### Error Response Format

```typescript
interface ErrorResponse {
  error: {
    code: string;
    message: string;
    details?: Record<string, unknown>;
  };
}
```

### Error Codes

| Code | HTTP Status | Description |
|------|-------------|-------------|
| `PACKAGE_NOT_FOUND` | 404 | Package does not exist in registry |
| `INVALID_PACKAGE_NAME` | 400 | Package name fails validation |
| `REGISTRY_ERROR` | 502 | npm Registry returned an error |
| `DEPSDEV_ERROR` | 502 | deps.dev API returned an error |
| `VALIDATION_ERROR` | 400 | Input parameters failed Zod validation |
| `TIMEOUT_ERROR` | 504 | Request exceeded timeout threshold |

### Common Failure Modes

1. **Network Timeouts**: Registry requests that exceed `timeoutMs` configuration
2. **Invalid Package Names**: Names that don't conform to npm naming conventions (strict validation enabled by default)
3. **Rate Limiting**: Too many requests to npm Registry or deps.dev
4. **Version Not Found**: Requested version doesn't exist for the package
5. **Cache Corruption**: Stale cache entries causing incorrect responses (addressed by v1.15.0+ invalidation)

## Security Considerations

### Package Name Validation (v1.16.0+)

Strict package name validation is enforced across all tools to prevent:

- Command injection attacks
- Path traversal vulnerabilities
- Malformed input handling

Validation follows npm naming conventions:

- Scoped packages: `@scope/package-name`
- Unscoped packages: `package-name`
- No special characters except hyphens and underscores

### Transitive Scanning Security

- Vulnerability scanning includes transitive dependencies
- React ecosystem patterns are specifically analyzed
- CVE data is enriched from multiple sources

## Version History

| Version | Date | API Changes |
|---------|------|-------------|
| 1.18.0 | 2026-02-22 | Added transitive topology insights via deps.dev |
| 1.17.0 | 2026-02-22 | Integrated deps.dev for bypass of subrequest limits |
| 1.16.0 | 2026-01-02 | Enforced strict package name validation |
| 1.15.0 | 2025-12-30 | Implemented robust cache invalidation |
| 1.14.0 | 2025-12-24 | Enhanced vulnerability detection with transitive scanning |
| 1.13.2 | 2025-12-24 | Exposed configSchema at root for Smithery |

## See Also

- [Installation Guide](installation) - Setting up npm-sentinel-mcp
- [Configuration Reference](configuration) - Detailed configuration options
- [Troubleshooting](troubleshooting) - Common issues and solutions
- [Changelog](https://github.com/Nekzus/npm-sentinel-mcp/releases) - Version history

---

<a id='page-input-validation'></a>

## Input Validation and Type Safety

### Related Pages

Related topics: [Security Features](#page-security)



# Input Validation and Type Safety

This document describes the input validation and type safety mechanisms implemented in npm-sentinel-mcp, a Model Context Protocol (MCP) server for npm package security operations. The system enforces strict validation at multiple layers to ensure reliable and secure operations when querying npm registry data, scanning for vulnerabilities, and resolving package dependencies.

## Overview

npm-sentinel-mcp implements a multi-layered validation strategy that combines runtime type checking with schema-based validation. This approach provides defense in depth against malformed inputs, prevents security vulnerabilities, and ensures consistent data structures throughout the application lifecycle.

The validation system serves three primary purposes:

1. **Security Enforcement**: Prevents injection attacks and malicious package name patterns
2. **Data Integrity**: Ensures responses from external APIs conform to expected structures
3. **Developer Experience**: Provides clear, actionable error messages when validation fails

## Architecture

### Validation Layers

The validation architecture operates across three distinct layers, each with specific responsibilities and failure modes.

```mermaid
graph TD
    A[Tool Input Parameters] --> B[Package Name Validator]
    B --> C[Zod Schema Validation]
    C --> D[Runtime Type Guards]
    D --> E[External API Response Validation]
    E --> F[Cache Key Generation]
    F --> G[Processed Result]
    
    B -.->|Invalid| H[Security Error]
    C -.->|Invalid| I[Schema Error]
    D -.->|Invalid| J[Type Error]
    E -.->|Invalid| K[Data Integrity Error]
```

### Component Responsibilities

| Layer | Component | Purpose | Failure Mode |
|-------|-----------|---------|--------------|
| Input | `packageName.ts` | Package name format validation | Security Error |
| Schema | `schemas.ts` | Zod schema definitions | Validation Error |
| Runtime | Type Guards | Runtime type narrowing | Type Error |
| Response | `npmRegistry.ts` | API response validation | Data Integrity Error |

## Package Name Validation

As of v1.16.0, npm-sentinel-mcp enforces strict package name validation across all tools. This security enhancement prevents various attack vectors including:

- Directory traversal attempts via `..` patterns
- Environment variable injection via `$` characters
- Command injection through special shell characters
- Prototype pollution via `__proto__` or `constructor` properties

### Validation Rules

The `packageName.ts` validator implements the following validation rules:

```typescript
// Validation rule implementation
const FORBIDDEN_PATTERNS = [
  '..',           // Directory traversal
  '__proto__',    // Prototype pollution
  'constructor',  // Prototype pollution
  '$',            // Environment variable injection
  '\\n',          // Newline injection
  '&&',           // Command chaining
  '||',           // Command chaining
  ';',            // Command separator
  '`',            // Command substitution
];
```

Source: [src/validators/packageName.ts]()

### npm Registry Naming Specification

Package names must conform to the npm registry specification, which defines:

| Rule | Requirement | Example |
|------|-------------|---------|
| Scope | Optional, prefixed with `@` | `@types/node` |
| Scope Length | 1-128 characters | `@angular` |
| Package Length | 1-214 characters (unscoped) | `lodash` |
| Allowed Characters | Alphanumeric, hyphens, underscores | `my-package_123` |
| Disallowed | Leading hyphens, URL encoding | `-invalid`, `%20` |

Source: [src/validators/packageName.ts]()

### Validation Flow

```mermaid
sequenceDiagram
    participant Client
    participant Validator
    participant Registry
    
    Client->>Validator: packageName: "lodash"
    Validator->>Validator: Check length constraints
    Validator->>Validator: Scan for forbidden patterns
    Validator->>Validator: Validate scope format
    Validator->>Validator: Check npm naming spec compliance
    alt Valid
        Validator-->>Registry: Proceed with request
        Registry-->>Client: Package data
    else Invalid
        Validator-->>Client: ValidationError with details
    end
```

## Zod Schema Validation

npm-sentinel-mcp uses [Zod](https://zod.dev) for schema-based validation of both input parameters and external API responses. Zod provides compile-time type inference combined with runtime validation, ensuring type safety throughout the application.

### Core Schemas

The `schemas.ts` module defines validation schemas for all tool inputs and API responses:

#### Tool Input Schemas

| Schema | Purpose | Key Fields |
|--------|---------|------------|
| `NpmDepsInputSchema` | Package dependency query | `packageName`, `version` |
| `NpmVulnInputSchema` | Vulnerability lookup | `packageName`, `ecosystem` |
| `NpmVulnScanInputSchema` | Full vulnerability scan | `packageName`, `manifestContent` |

Source: [src/validators/schemas.ts]()

### Schema Validation Example

The following demonstrates the typical validation flow for tool inputs:

```typescript
import { z } from 'zod';
import { validatePackageName } from './packageName';
import { NpmDepsInputSchema } from './schemas';

async function handleNpmDepsTool(input: unknown) {
  // Step 1: Schema validation with Zod
  const parseResult = NpmDepsInputSchema.safeParse(input);
  
  if (!parseResult.success) {
    return {
      content: [{
        type: 'text',
        text: `Validation failed: ${formatZodError(parseResult.error)}`
      }]
    };
  }
  
  const { packageName } = parseResult.data;
  
  // Step 2: Security-focused package name validation
  const validationResult = validatePackageName(packageName);
  
  if (!validationResult.valid) {
    return {
      content: [{
        type: 'text',
        text: `Security validation failed: ${validationResult.reason}`
      }]
    };
  }
  
  // Proceed with validated input
  return executeDepsQuery(packageName);
}
```

Source: [src/tools/npmDeps.ts]()

### Error Handling

When Zod validation fails, the system provides detailed error messages:

```typescript
interface ValidationError {
  issues: Array<{
    path: string[];
    message: string;
    code: string;
  }>;
}
```

Common validation error codes include:

| Code | Description | Resolution |
|------|-------------|------------|
| `invalid_type` | Expected type mismatch | Check parameter type |
| `invalid_string` | String format violation | Verify string content |
| `too_small` | Minimum length not met | Provide required value |
| `too_big` | Maximum length exceeded | Shorten input |
| `custom_error` | Custom validation failure | See error message details |

Source: [src/validators/schemas.ts]()

## Type Safety Mechanisms

### Runtime Type Guards

Beyond compile-time TypeScript types, npm-sentinel-mcp employs runtime type guards to validate data structures returned from external APIs. This catches inconsistencies between API providers and expected schemas.

```typescript
function isValidPackageMetadata(obj: unknown): obj is PackageMetadata {
  if (typeof obj !== 'object' || obj === null) return false;
  
  const pkg = obj as Record<string, unknown>;
  return (
    typeof pkg.name === 'string' &&
    typeof pkg.version === 'string' &&
    (typeof pkg.dist === 'object' || pkg.dist === undefined)
  );
}
```

Source: [src/utils/npmRegistry.ts]()

### Response Validation Pipeline

External API responses undergo multi-stage validation:

```mermaid
graph LR
    A[API Response] --> B[HTTP Status Check]
    B --> C[Content-Type Check]
    C --> D[Schema Structure]
    D --> E[Field Type Guards]
    E --> F[Business Logic Validation]
    F --> G[Cache Store]
    
    B -.->|Non-2xx| H[Network Error]
    C -.->|Wrong Type| I[Parse Error]
    D -.->|Missing Fields| J[Schema Error]
    E -.->|Type Mismatch| K[Type Error]
```

Source: [src/utils/npmRegistry.ts]()

## Configuration Options

### Validation Configuration

The validation system behavior can be configured via the server configuration schema:

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `strictValidation` | `boolean` | `true` | Enable strict validation mode |
| `allowDevDependencies` | `boolean` | `true` | Include dev dependencies in scans |
| `allowOptionalDependencies` | `boolean` | `true` | Include optional dependencies |
| `cacheTimeout` | `number` | `300000` | Cache TTL in milliseconds |

Source: [src/index.ts](), [package.json](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/package.json)

### Environment Variables

Validation behavior can be modified through environment variables:

```bash
# Enable debug logging for validation failures
DEBUG=validation

# Increase cache timeout for high-latency scenarios  
NPM_SENTINEL_CACHE_TTL=600000

# Disable strict mode (not recommended for production)
NPM_SENTINEL_STRICT=false
```

## Common Failure Modes

### Invalid Package Name

**Symptom**: `ValidationError: Invalid package name format`

**Cause**: Package name contains forbidden characters or violates npm naming conventions

**Resolution**: Ensure package names conform to npm registry specification:

```typescript
// Valid package names
const validNames = ['lodash', '@types/node', 'my-package'];

// Invalid package names
const invalidNames = ['../etc/passwd', '$ENV_VAR', '..\\..\\windows'];
```

### Zod Schema Mismatch

**Symptom**: `ValidationError: Expected object, received array`

**Cause**: Input data structure doesn't match expected schema

**Resolution**: Check the schema definition and ensure input matches expected structure. This was addressed in v1.16.1 for npm-registry tests.

Source: [v1.16.1 Release Notes](https://github.com/Nekzus/npm-sentinel-mcp/releases/tag/v1.16.1)

### Cache Inconsistency

**Symptom**: Stale validation results after schema updates

**Cause**: Cached data from previous schema versions

**Resolution**: v1.15.0 introduced robust cache invalidation mechanisms. Clear the cache or wait for TTL expiration.

Source: [v1.15.0 Release Notes](https://github.com/Nekzus/npm-sentinel-mcp/releases/tag/v1.15.0)

## Testing Validation

The validation system includes comprehensive test coverage using Jest:

```bash
# Run validation-specific tests
npm test -- --testPathPattern=validators

# Run package name validation tests
npm test -- --testNamePattern="packageName"

# Run schema validation tests
npm test -- --testNamePattern="schemas"
```

Source: [src/validators/packageName.ts](), [src/validators/schemas.ts]()

## Best Practices

### Input Sanitization

Always sanitize user input before passing to tools:

```typescript
// DO: Validate and sanitize
const sanitized = sanitizeInput(userInput);
const result = await tools.npmDeps({ packageName: sanitized });

// DON'T: Pass unsanitized input directly
const result = await tools.npmDeps({ packageName: userInput });
```

### Error Handling

Implement proper error handling for validation failures:

```typescript
try {
  const result = await tools.npmDeps({ packageName });
} catch (error) {
  if (error instanceof z.ZodError) {
    // Handle validation errors gracefully
    logger.warn('Validation failed', { errors: error.errors });
  }
  throw error;
}
```

### Type Safety

Leverage TypeScript's type inference with Zod:

```typescript
// Type is automatically inferred from schema
const schema = z.object({
  packageName: z.string(),
  version: z.string().optional()
});

type ToolInput = z.infer<typeof schema>;
```

## See Also

- [Getting Started](Getting-Started) - Setup and installation instructions
- [Security Features](Security-Features) - Security mechanisms overview
- [Caching System](Caching-System) - Cache invalidation and management
- [API Reference](API-Reference) - Complete tool API documentation
- [Troubleshooting](Troubleshooting) - Common issues and solutions

---

<a id='page-troubleshooting'></a>

## Troubleshooting

### Related Pages

Related topics: [Installation and Configuration](#page-installation), [Caching System](#page-caching), [Docker Deployment](#page-docker)



# Troubleshooting

This page provides comprehensive guidance for diagnosing and resolving common issues encountered when using **npm-sentinel-mcp**, a Model Context Protocol (MCP) server designed for npm package security analysis, dependency management, and vulnerability scanning.

## Overview

npm-sentinel-mcp integrates with the npm registry, deps.dev API, and various vulnerability databases to provide security insights for npm packages. Troubleshooting this system requires understanding its layered architecture and the external dependencies it relies upon.

```mermaid
graph TD
    subgraph "Client Layer"
        A[MCP Client] --> B[Request Handler]
    end
    
    subgraph "Core Engine"
        B --> C[Security Scanner]
        C --> D[Dependency Resolver]
        D --> E[Cache Manager]
    end
    
    subgraph "External Services"
        E --> F[npm Registry API]
        E --> G[deps.dev API]
        E --> H[Vulnerability Databases]
    end
    
    subgraph "Failure Points"
        F --> I1[Rate Limiting]
        F --> I2[Network Timeout]
        G --> I3[API Errors]
        H --> I4[Stale Data]
    end
```

Source: [src/index.ts](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/src/index.ts)

## Common Issues and Resolutions

### Connection and Network Problems

| Issue | Symptom | Resolution |
|-------|---------|------------|
| Network Timeout | Request hangs for >30s | Check firewall rules and proxy settings |
| Rate Limiting | `429 Too Many Requests` errors | Implement request throttling; retry after backoff |
| DNS Resolution | `ENOTFOUND` errors | Verify network configuration and DNS servers |
| SSL/TLS Errors | Certificate validation failures | Update CA certificates; check corporate proxy |

Source: [src/mcp/NpmRegistry.ts](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/src/mcp/NpmRegistry.ts)

#### Diagnosing Network Issues

```bash
# Test npm registry connectivity
curl -I https://registry.npmjs.org/

# Test deps.dev connectivity  
curl -I https://deps.dev/

# Check for proxy environment variables
env | grep -i proxy
```

### Package Name Validation Failures

Starting with v1.16.0, npm-sentinel-mcp enforces strict package name validation across all tools. Invalid package names will be rejected before any API calls are made.

```mermaid
graph LR
    A[Input Package Name] --> B{Valid Format?}
    B -->|No| C[Validation Error]
    B -->|Yes| D[Query Registry]
    D --> E[Package Exists?]
    E -->|No| F[Not Found Error]
    E -->|Yes| G[Return Metadata]
```

Source: [src/config.ts](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/src/config.ts)

**Common validation errors:**

| Error | Cause | Fix |
|-------|-------|-----|
| Invalid scope format | Scope must start with `@` | Ensure scoped packages use `@scope/name` format |
| Reserved characters | Package names cannot contain URL-unsafe characters | Use URL-encoded names or verify package exists |
| Length violation | Package names must be ≤214 characters | Use a valid package name |

### Cache-Related Problems

npm-sentinel-mcp implements robust cache invalidation mechanisms (v1.15.0) to optimize repeated queries.

```mermaid
graph TD
    A[Incoming Request] --> B{Cache Hit?}
    B -->|Yes| C[Return Cached Data]
    B -->|No| D[Fetch from API]
    D --> E{Data Changed?}
    E -->|Yes| F[Invalidate Cache]
    E -->|No| G[Update TTL]
    F --> H[Store Fresh Data]
    G --> H
    H --> C
```

Source: [src/mcp/NpmRegistry.ts](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/src/mcp/NpmRegistry.ts)

#### Cache Troubleshooting Steps

1. **Clear all cached data:** Restart the MCP server to reset in-memory cache
2. **Force fresh fetch:** Use a unique query parameter to bypass cache
3. **Check TTL settings:** Verify cache expiration is configured correctly

```typescript
// Example cache configuration in config.ts
const cacheConfig = {
  ttl: 3600000,        // 1 hour default TTL
  maxSize: 1000,        // Maximum cached entries
  staleWhileRevalidate: true
};
```

## Error Reference

### Error Codes and Messages

| Code | Message Pattern | Likely Cause | Resolution |
|------|-----------------|--------------|------------|
| `E_NPM_REGISTRY` | Registry connection failed | Network issue or npm down | Check `https://registry.npmjs.org/` status |
| `E_PACKAGE_NOT_FOUND` | Package `{name}` does not exist | Typo or package deleted | Verify package name on npm |
| `E_RATE_LIMIT` | Too many requests | Exceeded API limits | Implement exponential backoff |
| `E_DEPS_DEV` | deps.dev API error | Service unavailable | Check `https://deps.dev/` status |
| `E_VALIDATION` | Invalid package name | Format violation | Review npm naming conventions |
| `E_TIMEOUT` | Request timed out | Slow network or large response | Increase timeout threshold |

Source: [src/mcp/NpmRegistry.ts](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/src/mcp/NpmRegistry.ts)

### Zod Validation Errors

Version v1.16.1 addressed Zod validation errors in the npm registry module. If you encounter validation errors:

1. Ensure your input conforms to expected schema
2. Check that package metadata from npm is well-formed
3. Update to the latest version of npm-sentinel-mcp

Source: [vitest.config.ts](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/vitest.config.ts)

## Debugging Procedures

### Enabling Debug Mode

Debug mode provides verbose logging for troubleshooting complex issues.

```json
// server.json configuration
{
  "command": "npx",
  "args": ["-y", "npm-sentinel-mcp"],
  "env": {
    "DEBUG": "npm-sentinel-mcp:*",
    "LOG_LEVEL": "debug"
  }
}
```

Source: [server.json](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/server.json)

### Diagnostic Commands

```bash
# Check Node.js version compatibility
node --version  # Must be v20 or compatible

# Verify package installation
npm list npm-sentinel-mcp

# Check for conflicting dependencies
npm ls --all | grep -A5 "npm-sentinel-mcp"
```

### Smithery Configuration Issues

If deploying via Smithery (v1.13.3 fixed configSchema detection):

1. Ensure `smithery.yaml` is present at project root
2. Verify `configSchema` is defined at the root level
3. Check that `server.json` includes proper entry point

```yaml
# smithery.yaml example
name: npm-sentinel-mcp
description: npm security analysis via MCP
configSchema:
  type: object
  properties:
    npmRegistryUrl:
      type: string
      default: https://registry.npmjs.org/
```

Source: [smithery.yaml](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/smithery.yaml)

## Vulnerability Scanning Issues

### Transitive Dependency Scanning Failures

Version v1.14.0 enhanced vulnerability detection with transitive scanning. If scanning fails:

1. **Missing transitive data:** Check deps.dev API connectivity
2. **Incomplete tree:** Large dependency trees may timeout; consider scanning specific scopes
3. **CVE enrichment failures:** Verify vulnerability database accessibility

```mermaid
graph TD
    A[Scan Request] --> B[Fetch Direct Dependencies]
    B --> C[Query deps.dev]
    C --> D[Resolve Transitive Tree]
    D --> E{Vulnerability Found?}
    E -->|Yes| F[Enrich with CVE Data]
    E -->|No| G[Return Clean]
    F --> H[Generate Report]
    H --> I{Has Errors?}
    I -->|Yes| J[Log & Continue]
    I -->|No| K[Complete]
```

Source: [src/index.ts](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/src/index.ts)

### React Ecosystem Awareness Issues

npm-sentinel-mcp includes React ecosystem awareness for better vulnerability detection. If React-specific vulnerabilities are missed:

1. Verify the package is correctly identified as React-related
2. Check that React version detection is working
3. Ensure vulnerability database includes React advisories

## Performance Troubleshooting

### Slow Response Times

| Cause | Diagnosis | Solution |
|-------|-----------|----------|
| Large dependency tree | Check response size | Limit scan scope |
| Network latency | Ping registry APIs | Use regional registry mirror |
| Cache miss | Monitor cache hit rate | Warm cache for frequent queries |
| CPU-bound processing | Profile server | Optimize dependency resolution |

### Memory Issues

npm-sentinel-mcp may consume significant memory when processing large dependency trees:

```javascript
// Recommended memory settings for large scans
process.env.NODE_OPTIONS = '--max-old-space-size=4096';
```

## Version-Specific Issues

### Upgrading from v1.15.x to v1.16.x

Version v1.16.0 introduced **strict package name validation**. Existing integrations may fail if:

- Package names contain special characters not validated before
- Scoped packages use incorrect format
- Dynamically generated package names bypass validation

**Migration steps:**

1. Review package name inputs for format compliance
2. Add input sanitization in calling code
3. Test with invalid package names to confirm rejection

### Node.js Compatibility

- **v1.15.1** downgraded `semantic-release-github` to v10 for Node 20 compatibility
- Ensure you are running Node.js v20 or v22 LTS
- Avoid Node.js v21+ until compatibility is confirmed

```bash
# Check Node version requirement
cat package.json | grep '"engines"'
```

Source: [package.json](https://github.com/Nekzus/npm-sentinel-mcp/blob/main/package.json)

## Getting Help

If troubleshooting steps do not resolve your issue:

1. **Check the GitHub Issues page** for known issues and workarounds
2. **Enable debug logging** and capture error traces
3. **Reproduce with minimal configuration** to isolate the problem
4. **Submit an issue** with:
   - npm-sentinel-mcp version
   - Node.js version
   - Operating system
   - Complete error message and stack trace
   - Minimal reproduction case

## See Also

- [Installation Guide](Installation) — Getting started with npm-sentinel-mcp
- [Configuration Reference](Configuration) — Complete configuration options
- [API Reference](API) — Tool definitions and usage
- [Security Features](Security-Features) — Vulnerability scanning details
- [Architecture Overview](Architecture) — System design documentation

---

<!-- evidence_pipeline_checked: true -->
<!-- evidence_injected: true -->

---

## Pitfall Log

Project: nekzus/npm-sentinel-mcp

Summary: Found 7 structured pitfall item(s), including 0 high/blocking item(s). Top priority: Identity risk - Identity risk requires verification.

## 1. Identity risk - Identity risk requires verification

- Severity: medium
- Evidence strength: runtime_trace
- Finding: Project evidence flags a identity 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.
- Repro command: `npx @nekzus/mcp-server`
- Evidence: identity.distribution | mcp_registry:io.github.Nekzus/npm-sentinel-mcp:1.18.0 | https://registry.modelcontextprotocol.io/v0.1/servers/io.github.Nekzus%2Fnpm-sentinel-mcp/versions/1.18.0

## 2. 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.Nekzus/npm-sentinel-mcp:1.18.0 | https://registry.modelcontextprotocol.io/v0.1/servers/io.github.Nekzus%2Fnpm-sentinel-mcp/versions/1.18.0

## 3. 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.Nekzus/npm-sentinel-mcp:1.18.0 | https://registry.modelcontextprotocol.io/v0.1/servers/io.github.Nekzus%2Fnpm-sentinel-mcp/versions/1.18.0

## 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: downstream_validation.risk_items | mcp_registry:io.github.Nekzus/npm-sentinel-mcp:1.18.0 | https://registry.modelcontextprotocol.io/v0.1/servers/io.github.Nekzus%2Fnpm-sentinel-mcp/versions/1.18.0

## 5. 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.Nekzus/npm-sentinel-mcp:1.18.0 | https://registry.modelcontextprotocol.io/v0.1/servers/io.github.Nekzus%2Fnpm-sentinel-mcp/versions/1.18.0

## 6. 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.Nekzus/npm-sentinel-mcp:1.18.0 | https://registry.modelcontextprotocol.io/v0.1/servers/io.github.Nekzus%2Fnpm-sentinel-mcp/versions/1.18.0

## 7. 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.Nekzus/npm-sentinel-mcp:1.18.0 | https://registry.modelcontextprotocol.io/v0.1/servers/io.github.Nekzus%2Fnpm-sentinel-mcp/versions/1.18.0

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