Doramagic Project Pack · Human Manual

npm-run-mcp-server

npm-run-mcp-server is a Node.js-based MCP server published to npm. It requires Node.js = 18.18.0 and communicates with AI clients via the stdio transport protocol. Source: package.json:29

Quick Start Guide

Related topics: Installation Methods, Configuration Guide

Section Related Pages

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

Section No Install Required

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

Related topics: Installation Methods, Configuration Guide

Quick Start Guide

This guide provides everything you need to get npm-run-mcp-server running with your AI assistant in minutes. The server bridges your project's package.json scripts to your AI agent using the Model Context Protocol (MCP), enabling your AI to execute build, test, and deployment commands directly.

Prerequisites

Before using npm-run-mcp-server, ensure your environment meets the following requirements:

RequirementVersionNotes
Node.js≥ 18.18.0Required for running the server binary Source: package.json:28
npm, pnpm, yarn, or bunAny recent versionPackage manager is auto-detected Source: src/index.ts:147-153
MCP-compatible AI clientClaude Desktop, Cursor, or VS Code with Copilot

The server uses the Stdio transport for MCP protocol communication, which is the standard transport for local AI integrations. Source: server.json:15-16

Installation

npm-run-mcp-server requires no global installation. The server is executed on-demand via npx, which downloads and runs the package automatically.

No Install Required

Simply reference the package name in your client configuration:

npx -y npm-run-mcp-server

The -y flag automatically confirms the download. Source: README.md:45-51

Client Setup

This section covers configuration for popular MCP-compatible AI clients. Choose your client below:

Source: https://github.com/fstubner/npm-run-mcp-server / Human Manual

Installation Methods

Related topics: Quick Start Guide, CLI Reference

Section Related Pages

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

Section Command Structure

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

Section Configuration Example

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

Section Running After Global Install

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

Related topics: Quick Start Guide, CLI Reference

Installation Methods

This page documents all supported methods for installing and configuring the npm-run-mcp-server MCP server. The server bridges your project's package.json scripts to AI assistants via the Model Context Protocol (MCP), enabling agents like Claude, Cursor, and GitHub Copilot to execute your existing npm scripts directly.

Overview

npm-run-mcp-server is a Node.js-based MCP server published to npm. It requires Node.js >= 18.18.0 and communicates with AI clients via the stdio transport protocol. Source: package.json:29

graph TD
    A[AI Client<br/>Claude, Cursor, Copilot] -->|stdio MCP| B[npm-run-mcp-server]
    B -->|Reads| C[package.json]
    B -->|Reads| D[npm-run-mcp.config.json<br/>Optional]
    C -->|Discovers| E[Scripts: build, test, lint...]
    B -->|Executes via| F[Package Manager<br/>npm, pnpm, yarn, bun]
    
    style A fill:#e1f5fe
    style B fill:#fff3e0
    style F fill:#e8f5e9

Method 1: npx (Zero-Install)

The fastest way to use npm-run-mcp-server without any installation. The AI client invokes the server via npx, which downloads and caches the package automatically.

Command Structure

npx -y npm-run-mcp-server [options]
ArgumentPurpose
-ySkip confirmation prompt for npx
npm-run-mcp-serverPackage name on npm

This is the recommended approach for most users as it requires no upfront setup and always uses the latest version. Source: README.md

Configuration Example

Add the following to your AI client's MCP server configuration:

{
  "mcpServers": {
    "npm-scripts": {
      "command": "npx",
      "args": ["-y", "npm-run-mcp-server"]
    }
  }
}

Method 2: Global NPM Installation

For developers who prefer a persistent installation or need to run the server from the command line directly, install globally via npm:

npm install -g npm-run-mcp-server

Running After Global Install

Once installed globally, the server can be invoked directly:

# List all available scripts
npm-run-mcp-server --list-scripts

# Run the server
npm-run-mcp-server

Source: package.json:7

graph LR
    A[Global Install] --> B[npm install -g]
    B --> C[/usr/local/bin/npm-run-mcp-server]
    C --> D[Direct CLI Usage]
    C --> E[MCP Client Connection]
    
    style B fill:#fff3e0

Method 3: Per-Project Installation

For reproducible setups, install npm-run-mcp-server as a project dependency:

npm install --save-dev npm-run-mcp-server

Advantages of Per-Project Installation

  • Version Locking: Ensures the same server version across all team members
  • CI/CD Compatible: Predictable behavior in automated environments
  • No External Dependencies: Everything is managed within the project

Source: package.json

Package Manager Detection

The server automatically detects which package manager your project uses:

graph TD
    A[Check package.json<br/>packageManager field] --> B{Found?}
    B -->|Yes| C[Use specified PM]
    B -->|No| D[Check lockfiles]
    D --> E{pnpm-lock.yaml?}
    E -->|Yes| F[pnpm]
    E -->|No| G{yarn.lock?}
    G -->|Yes| H[yarn]
    G -->|No| I{bun.lock[b]?}
    I -->|Yes| J[bun]
    I -->|No| K[npm default]
    
    style F fill:#e8f5e9
    style H fill:#e8f5e9
    style J fill:#e8f5e9
    style K fill:#e8f5e9

Priority order for package manager detection:

  1. Explicit --pm CLI argument (highest priority)
  2. packageManager field in package.json
  3. Lockfile detection: pnpm-lock.yaml, yarn.lock, bun.lock/bun.lockb
  4. Default to npm (lowest priority)

Source: src/index.ts - detectPackageManager function

AI Client Integration

Claude Desktop

Add the server configuration to your Claude Desktop config file:

Config File Location:

  • macOS/Linux: ~/Library/Application Support/Claude/claude_desktop_config.json
  • Windows: %APPDATA%\Claude\claude_desktop_config.json
{
  "mcpServers": {
    "npm-scripts": {
      "command": "npx",
      "args": ["-y", "npm-run-mcp-server"]
    }
  }
}

After editing, restart Claude Desktop to load the new configuration.

Source: README.md

Cursor

  1. Open SettingsFeaturesMCP Servers
  2. Click + Add New MCP Server
  3. Enter the following details:
FieldValue
Typecommand
Namenpm-scripts
Commandnpx
Args-y npm-run-mcp-server

Alternatively, add directly to your workspace .vscode/settings.json:

{
  "mcpServers": {
    "npm-scripts": {
      "command": "npx",
      "args": ["-y", "npm-run-mcp-server"]
    }
  }
}

Source: README.md

VS Code (GitHub Copilot Chat)

Add the configuration to your workspace .vscode/settings.json:

{
  "github.copilot.chat.mcpServers": {
    "npm-scripts": {
      "command": "npx",
      "args": ["-y", "npm-run-mcp-server"]
    }
  }
}

Source: README.md

Command-Line Options

The server accepts several CLI flags for customization:

FlagDescriptionExample
--cwd <path>Set the working directory for the server--cwd /path/to/project
--pm <manager>Force a specific package manager--pm pnpm
--config <path>Path to a custom config file--config ./my-config.json
--verboseEnable debug logging to stderr--verbose
--list-scriptsPrint available scripts and exit--list-scripts

Working Directory Detection

The server automatically searches for package.json starting from the current working directory. It also intelligently handles VS Code and Cursor workspace folders:

# Run in a specific directory
npx npm-run-mcp-server --cwd /path/to/project

# Run with verbose logging
npx npm-run-mcp-server --verbose

# Force pnpm package manager
npx npm-run-mcp-server --pm pnpm

Source: src/index.ts - CLI argument parsing section

Verbose Mode

Enable verbose logging to debug server behavior:

npx npm-run-mcp-server --verbose

Verbose output includes:

  • Detected working directory
  • Package manager selection
  • Config file location
  • Script filtering details

You can also enable verbose mode via environment variables:

MCP_VERBOSE=1 npx npm-run-mcp-server
# or
DEBUG=mcp npx npm-run-mcp-server

Source: src/index.ts - verbose flag handling

Configuration Files

After installation, you can create a per-project configuration file to control which scripts are exposed:

Config File NamePriority
npm-run-mcp.config.jsonPrimary
.npm-run-mcp.jsonFallback

Both JSON and JSONC (JSON with Comments) formats are supported. Source: npm-run-mcp.config.schema.json

Example Configuration

{
  "include": ["test", "lint", "build", "start"],
  "exclude": ["eject", "publish"],
  "scripts": {
    "test": {
      "description": "Run the test suite",
      "inputSchema": {
        "properties": {
          "watch": {
            "type": "boolean",
            "description": "Watch files for changes"
          }
        }
      }
    }
  }
}

Config Schema Properties

PropertyTypeDescription
includestring[]Whitelist of script names to expose
excludestring[]Blacklist of script names to hide
scriptsobjectPer-script metadata overrides

For detailed schema information, see the Configuration Schema Reference. Source: npm-run-mcp.config.schema.json

MCP Server Manifest

The package includes a server.json manifest for MCP registry integration:

{
  "name": "io.github.fstubner/npm-run-mcp-server",
  "description": "An MCP server that exposes package.json scripts as tools for agents.",
  "version": "0.2.13",
  "packages": [{
    "registryType": "npm",
    "identifier": "npm-run-mcp-server",
    "transport": {
      "type": "stdio"
    }
  }]
}

Source: server.json

Installation Troubleshooting

Common Issues

IssueCauseSolution
Server not respondingWrong working directoryUse --cwd to specify project path
Wrong package managerAuto-detection failedUse --pm <manager> to override
Config file not foundWrong filename or pathUse --config <path> to specify
No scripts visibleEmpty include/exclude filterCheck configuration file settings

Verification Steps

``bash npx npm-run-mcp-server --list-scripts ``

  1. List scripts manually:

``bash npx npm-run-mcp-server --verbose ``

  1. Run with verbose logging:

``bash ls -la package.json ``

  1. Verify package.json exists:

Source: src/index.ts - list-scripts and verbose handling

Dependencies

The server has the following runtime dependencies:

PackageVersionPurpose
@modelcontextprotocol/sdk^1.25.1MCP protocol implementation
cross-spawn^7.0.5Cross-platform script execution
jsonc-parser^3.3.1JSONC parsing (config files)
zod^3.23.8Schema validation

Source: package.json:20-24

Summary

MethodBest ForSetup Required
npxQuick testing, demosNone
Global npmCLI usage, multiple projectsYes (one-time)
Per-project dev depTeam consistency, CI/CDYes (per-project)
Claude DesktopClaude AI integrationYes (config file)
CursorCursor IDE integrationYes (settings UI)
VS Code CopilotGitHub Copilot integrationYes (settings.json)

See Also

Source: https://github.com/fstubner/npm-run-mcp-server / Human Manual

Configuration Guide

Related topics: CLI Reference, Tool Schema and MCP Integration

Section Related Pages

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

Related topics: CLI Reference, Tool Schema and MCP Integration

Configuration Guide

This guide covers all configuration options for npm-run-mcp-server, enabling you to control which package.json scripts are exposed to AI agents and customize their behavior.

Overview

npm-run-mcp-server works without any configuration out of the box, automatically detecting your project's package.json and exposing all scripts. However, in most production scenarios, you'll want to restrict which scripts are available to your AI assistant for security and usability reasons.

The configuration system provides:

  • Script filtering: Whitelist (include) or blacklist (exclude) specific scripts
  • Per-script metadata: Customize tool names, descriptions, and input schemas
  • JSONC support: Use comments and trailing commas in config files
  • CLI overrides: Override config file settings via command-line flags

Source: https://github.com/fstubner/npm-run-mcp-server / Human Manual

CLI Reference

Related topics: Configuration Guide, Troubleshooting

Section Related Pages

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

Section Entry Point

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

Section Requirements

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

Section Synopsis

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

Related topics: Configuration Guide, Troubleshooting

CLI Reference

This page documents the command-line interface for npm-run-mcp-server, a Model Context Protocol server that exposes package.json scripts as tools for AI agents.

Overview

The npm-run-mcp-server CLI provides a bridge between your project's npm scripts and AI assistants via the MCP protocol. It auto-detects your project context, package manager, and available scripts without requiring any configuration. Source: src/index.ts:1-50

Entry Point

The CLI binary is defined in package.json and can be invoked via npx or direct execution:

# Via npx (recommended)
npx npm-run-mcp-server [options]

# Direct execution after global/local install
npm-run-mcp-server [options]

# Via Node.js
node ./dist/index.js [options]

Source: package.json:10-12

Requirements

  • Node.js: >=18.18.0
  • Package Manager: npm, pnpm, yarn, or bun

Source: package.json:29

Command Line Options

Synopsis

npm-run-mcp-server [options]
npm-run-mcp-server --cwd <path> --pm <manager> --config <file> --verbose
npm-run-mcp-server --list-scripts

Options

OptionDescriptionDefault
--cwd <path>Set the working directory for script executionCurrent working directory
--pm <manager>Force a specific package manager (npm, pnpm, yarn, bun)Auto-detected
--config <path>Path to a specific JSON configuration fileAuto-discovered
--verboseEnable verbose debug logging to stderrDisabled
--list-scriptsPrint available scripts and exitDisabled

Source: README.md:58-68

`--cwd` Option

Sets the working directory where the server looks for package.json and executes scripts. If not specified, the server uses the current working directory and attempts to find a suitable parent directory if running within the MCP server's own directory.

# Run in a specific project directory
npx npm-run-mcp-server --cwd /path/to/project

# Run in the current directory
npx npm-run-mcp-server --cwd .

The server implements intelligent workspace detection:

graph TD
    A[Start] --> B{Running in MCP server dir?}
    B -->|Yes| C[Search parent dirs for package.json]
    C --> D{Found within 5 levels?}
    D -->|Yes| E[Use found directory]
    D -->|No| F[Use current directory]
    B -->|No| G[Use current directory]
    E --> H[Load package.json]
    F --> H
    G --> H

Source: src/index.ts:48-69

`--pm` Option

Forces a specific package manager for script execution, bypassing auto-detection.

# Force pnpm
npx npm-run-mcp-server --pm pnpm

# Force yarn
npx npm-run-mcp-server --pm yarn

Supported values: npm, pnpm, yarn, bun

Source: src/index.ts:146-158

`--config` Option

Specifies a path to a custom configuration file, overriding the default config file discovery.

# Use a specific config file
npx npm-run-mcp-server --config /path/to/custom-config.json

The config file supports both JSON and JSONC (JSON with Comments) formats, allowing trailing commas and comments.

Source: src/index.ts:190-210

`--verbose` Option

Enables detailed debug logging to stderr, useful for troubleshooting configuration issues.

# Enable verbose logging
npx npm-run-mcp-server --verbose

Verbose output includes:

  • Detected working directory and workspace folder
  • Located package.json path
  • Loaded server name and version
  • Detected package manager
  • Configuration file path (if used)
  • Number of registered tools

Source: src/index.ts:27-44

`--list-scripts` Option

Lists all available scripts based on current configuration (respects include/exclude filters) and exits immediately. Useful for debugging configuration.

npx npm-run-mcp-server --list-scripts

Output format:

<script-name>: <script-command>

Example output:

dev: vite
build: vite build
test: vitest run
lint: eslint src

Source: src/index.ts:238-243

Package Manager Detection

The server automatically detects which package manager your project uses based on a priority order.

Detection Priority

graph LR
    A[Detect Package Manager] --> B{Override --pm flag?}
    B -->|Yes| Z[Use specified manager]
    B -->|No| C{packageManager field?}
    C -->|Yes| Y[Use packageManager value]
    C -->|No| D{pnpm-lock.yaml?}
    D -->|Yes| X[Use pnpm]
    D -->|No| E{yarn.lock?}
    E -->|Yes| W[Use yarn]
    E -->|No| F{bun.lock/bun.lockb?}
    F -->|Yes| V[Use bun]
    F -->|No| U[Default to npm]

Source: src/index.ts:146-158

Lockfile Heuristics

The server checks for lockfiles in the project directory:

LockfilePackage Manager
pnpm-lock.yamlpnpm
yarn.lockyarn
bun.lock or bun.lockbbun
None foundnpm (default)

Source: src/index.ts:150-157

`packageManager` Field Support

If your package.json contains a packageManager field (used by corepack), it takes precedence over lockfile detection:

{
  "packageManager": "[email protected]"
}

The server extracts the package manager name from this field, supporting npm, pnpm, yarn, and bun.

Source: src/index.ts:148-149

Configuration File Options

The server supports per-project configuration to control which scripts are exposed and their metadata.

Configuration File Discovery

The server searches for configuration files in this order:

  1. Path specified via --config <path> CLI flag
  2. npm-run-mcp.config.json in project root
  3. .npm-run-mcp.json in project root

Source: src/index.ts:190-210

Configuration Schema

FieldTypeDescription
includestring[]Exact script names to include. If omitted, all scripts are eligible (subject to exclude).
excludestring[]Exact script names to exclude.
scriptsobjectPer-script tool metadata overrides.

Source: npm-run-mcp.config.schema.json:8-28

Per-Script Configuration

Inside the scripts object, map script names to their configuration:

FieldTypeDescription
toolNamestringOverride the tool name (after sanitization).
descriptionstringCustom description for the tool.
inputSchemaobjectJSON Schema for additional tool inputs (converted to CLI args).
argsDescriptionstringDescription for the args input field.

Source: npm-run-mcp.config.schema.json:30-45

Example Configuration

{
  "include": ["test", "lint", "build", "start"],
  "exclude": ["publish", "eject"],
  "scripts": {
    "test": {
      "description": "Run the test suite. Use --watch for interactive mode.",
      "inputSchema": {
        "properties": {
          "watch": { "type": "boolean", "description": "Watch files for changes" }
        }
      }
    },
    "build:prod": {
      "toolName": "build_production"
    }
  }
}

Source: README.md:80-95

Tool Name Normalization

MCP tools have naming constraints—they can only contain lowercase letters, numbers, underscores, and hyphens: [a-z0-9_-].

Normalization Rules

The server sanitizes script names automatically:

  1. Convert to lowercase
  2. Replace any non-alphanumeric character (except _ and -) with underscore _
  3. If the result is empty, use script as fallback
// Examples:
"test:unit"     → "test_unit"
"build:prod"    → "build_prod"
"lint-fix"      → "lint_fix"
"@scope/script" → "_scope_script"

Source: src/index.ts:220-222

Tool Name Collisions

If two scripts normalize to the same tool name, the server exits with an error:

npm-run-mcp-server: Tool name collisions detected. Set "scripts.<name>.toolName" in npm-run-mcp.config.json to disambiguate.
  normalized_name: script1, script2

To resolve collisions, use the toolName override in your config:

{
  "scripts": {
    "script-one": { "toolName": "run_script_one" },
    "script_1": { "toolName": "run_script_1" }
  }
}

Source: src/index.ts:224-234

Environment Variables

Verbose Logging

VariableDescription
MCP_VERBOSESet to any value to enable verbose logging
DEBUGIf contains mcp (case-insensitive), enables verbose logging

Source: src/index.ts:27-28

Workspace Detection

VariableDescription
VSCODE_WORKSPACE_FOLDERVS Code workspace folder (for verbose logging)
CURSOR_WORKSPACE_FOLDERCursor IDE workspace folder (for verbose logging)

Source: src/index.ts:31

Command Execution

Running Scripts

When an AI agent invokes a tool, the server executes the corresponding npm script:

<package-manager> run <script-name> [-- <extra-args>]

Examples:

  • npm run build
  • pnpm run test -- --watch
  • yarn dev

Source: src/index.ts:160-166

Command Builder

The buildRunCommand function constructs the spawn command:

// Without extra args
{ command: "npm", args: ["run", "build"] }

// With extra args
{ command: "npm", args: ["run", "test", "--", "--watch"] }

Source: src/index.ts:160-166

Tool Input to CLI Args

When a tool receives input matching the configured inputSchema, those inputs are converted to CLI arguments:

// inputSchema:
{
  "properties": {
    "watch": { "type": "boolean" }
  }
}

// Tool call with { watch: true }
→ CLI args: ["--watch"]

Source: src/index.ts:180-188

Timeout Handling

The server has a default timeout for script execution. If a script times out, the response includes:

Command timed out after <timeout> seconds: <command> <args>

Source: src/index.ts:280-282

Exit Codes

CodeDescription
0Success (or --list-scripts completed)
1Error (invalid config, collision, missing package.json)

Error Scenarios

No package.json found:

npm-run-mcp-server: No package.json found starting from <path>

No scripts selected:

npm-run-mcp-server: No scripts selected for exposure. Check your config "include"/"exclude" settings.

Tool name collision:

npm-run-mcp-server: Tool name collisions detected. Set "scripts.<name>.toolName"...

Invalid config file:

npm-run-mcp-server: Failed to read config file <path>: <error-message>

Source: src/index.ts:70-75, 83-90, 198-209, 224-234

File Watching

The server watches package.json and the config file for changes. When a change is detected, the server exits gracefully (exit code 0) to allow the MCP client to restart it with the updated configuration.

graph LR
    A[Start Server] --> B[Register Tools]
    B --> C[Watch package.json]
    C --> D[Watch config file?]
    D -->|Yes| E[Watch config]
    D -->|No| F[Await requests]
    E --> F
    F --> G{File changed?}
    G -->|Yes| H[Exit 0]
    G -->|No| F
    H --> I[Client restarts server]

Source: src/index.ts:330-360

Signal Handling

The server handles termination signals gracefully:

  • SIGINT: Clean up watchers, exit 0
  • SIGTERM: Clean up watchers, exit 0

Source: src/index.ts:348-357

See Also

Source: https://github.com/fstubner/npm-run-mcp-server / Human Manual

System Architecture

Related topics: Package Manager Detection, Tool Schema and MCP Integration

Section Related Pages

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

Related topics: Package Manager Detection, Tool Schema and MCP Integration

System Architecture

npm-run-mcp-server is a Model Context Protocol (MCP) server that bridges package.json scripts to AI agents. This page describes the internal architecture, component relationships, and data flows that enable this functionality.

Source: https://github.com/fstubner/npm-run-mcp-server / Human Manual

Package Manager Detection

Related topics: System Architecture, CLI Reference

Section Related Pages

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

Related topics: System Architecture, CLI Reference

Package Manager Detection

Overview

The npm-run-mcp-server provides automatic package manager detection to execute package.json scripts using the appropriate package manager for your project. This feature ensures seamless integration with any Node.js project regardless of whether it uses npm, pnpm, yarn, or bun as its package manager.

The detection mechanism is designed to be intelligent yet predictable, following a clear hierarchy of preference that prioritizes explicit configuration over file-based heuristics.

Key capabilities:

  • Automatic detection from lockfiles and package configuration
  • CLI override option for explicit control
  • Support for all major Node.js package managers
  • Verbose logging for debugging detection issues

Source: src/index.ts:1-50

Source: https://github.com/fstubner/npm-run-mcp-server / Human Manual

Tool Schema and MCP Integration

Related topics: System Architecture, Configuration Guide

Section Related Pages

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

Section Core Components

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

Section Step-by-Step Process

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

Section Default Schema Generation

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

Related topics: System Architecture, Configuration Guide

Tool Schema and MCP Integration

This page documents how npm-run-mcp-server bridges package.json scripts to the Model Context Protocol (MCP), including tool schema generation, input validation, and the MCP server lifecycle.

Overview

npm-run-mcp-server exposes package.json scripts as MCP tools that AI agents can invoke. The tool schema system transforms script definitions into structured MCP tool interfaces with input validation, custom descriptions, and runtime argument handling.

Key capabilities:

  • Automatic tool registration from package.json scripts
  • JSON Schema-based input definitions per script
  • Zod schema generation for runtime validation
  • Configurable tool names, descriptions, and argument schemas
  • File watcher for hot-reload on config changes

Source: src/index.ts:1-50

Architecture

graph TD
    A[package.json] --> B[Script Discovery]
    C[npm-run-mcp.config.json] --> D[Config Parsing]
    B --> E[Script Filtering]
    D --> E
    E --> F[Tool Registration]
    F --> G[McpServer]
    G --> H[StdioServerTransport]
    H --> I[MCP Client<br/>Claude/Cursor/Copilot]
    
    J[AI Agent] --> K[Tool Call]
    K --> G
    G --> L[Script Execution]
    L --> M[npm/pnpm/yarn/bun]
    
    N[File Watcher] -.->|package.json change| O[Server Restart]
    N -->|config change| O

Core Components

ComponentResponsibilityLocation
McpServerMCP protocol server from SDK@modelcontextprotocol/sdk
StdioServerTransportCommunication via stdio@modelcontextprotocol/sdk
Tool RegistryMaps scripts to MCP toolssrc/index.ts
Schema BuilderConverts JSON Schema to Zodsrc/index.ts:normalizeToolName
File WatcherHot reload on config changessrc/index.ts

Source: src/index.ts:1-30

Tool Registration Flow

The server follows a defined sequence to register scripts as MCP tools:

sequenceDiagram
    participant Client as MCP Client
    participant Server as McpServer
    participant Registry as Tool Registry
    participant Watcher as File Watcher
    
    Note over Server: Server starts
    Server->>Server: Load package.json
    Server->>Server: Detect package manager
    Server->>Server: Load MCP config
    Server->>Registry: Filter scripts
    Registry->>Registry: Register tools
    Server->>Watcher: Watch config files
    Server->>Client: Ready (stdio connected)
    
    Note over Client,Server: Tool invocation cycle
    Client->>Server: call_tool (tool_name, args)
    Server->>Server: Validate input (Zod)
    Server->>Registry: Execute script
    Server->>Client: Tool result

Step-by-Step Process

  1. Startup: Server initializes and connects stdio transport
  2. Package Detection: Locates package.json and detects package manager
  3. Config Loading: Reads npm-run-mcp.config.json or .npm-run-mcp.json
  4. Script Filtering: Applies include/exclude rules
  5. Tool Registration: Registers each script as an MCP tool with schema
  6. File Watching: Sets up watchers for hot-reload capability

Source: src/index.ts:50-100

Tool Schema Definition

Default Schema Generation

When no custom schema is provided, the server generates a standard input schema for each tool:

{
  description: string,        // "Run npm script "test": npm test"
  inputSchema: {
    type: "object",
    properties: {
      args: {
        type: "string",
        description: "Additional arguments to pass to the script"
      }
    }
  }
}

Source: src/index.ts:buildToolInputSchema

Input Schema Schema

The inputSchema field in npm-run-mcp.config.json supports a subset of JSON Schema for defining tool inputs. The server converts these to Zod schemas for validation.

Supported Schema Types:

JSON Schema KeywordZod EquivalentNotes
type: "string"z.string()Basic string input
type: "number"z.number()Numeric input
type: "boolean"z.boolean()Toggle/flag input
type: "array"z.array()Array input
type: "object"z.object()Nested object input
enum: [...]z.enum([...])Constrained choices
propertiesChained .shape()Object structure
requiredChained .required()Mandatory fields

Source: src/index.ts:jsonSchemaToZod

Schema Conversion Examples

String with description:

{
  "type": "string",
  "description": "File path to process"
}
z.string().describe("File path to process")

Enum (choice):

{
  "enum": ["development", "staging", "production"]
}
z.enum(["development", "staging", "production"])

Object with properties:

{
  "type": "object",
  "properties": {
    "watch": { "type": "boolean" },
    "verbose": { "type": "boolean" }
  },
  "required": ["watch"]
}
z.object({
  watch: z.boolean(),
  verbose: z.boolean()
}).required().shape({ watch: z.boolean() })

Source: src/index.ts:jsonSchemaToZod:140-170

Configuration Schema

Configuration File Location

The server searches for config files in order:

  1. Path specified via --config CLI flag
  2. npm-run-mcp.config.json in project root
  3. .npm-run-mcp.json in project root

Config Schema Properties

PropertyTypeDescription
includestring[]Whitelist of script names to expose
excludestring[]Blacklist of script names to hide
scriptsRecord<string, ScriptConfig>Per-script metadata overrides

Source: npm-run-mcp.config.schema.json

Per-Script Configuration

type McpScriptConfig = {
  toolName?: string;           // Override generated tool name
  description?: string;         // Override tool description
  argsDescription?: string;    // Description for the args field
  inputSchema?: unknown;       // JSON Schema for tool inputs
};
FieldPurposeExample
toolNameCustom MCP tool name"run_tests" instead of "test"
descriptionHuman-readable tool description"Run the test suite with coverage"
argsDescriptionDescription for CLI args field"Pass --watch for interactive mode"
inputSchemaDefine structured inputs{"type": "object", "properties": {...}}

Source: npm-run-mcp.config.schema.json

Example Configuration

{
  "include": ["test", "lint", "build"],
  "exclude": ["postinstall", "prepublishOnly"],
  "scripts": {
    "test": {
      "description": "Run the test suite with Vitest",
      "inputSchema": {
        "type": "object",
        "properties": {
          "watch": {
            "type": "boolean",
            "description": "Watch files for changes"
          },
          "coverage": {
            "type": "boolean",
            "description": "Generate coverage report"
          },
          "grep": {
            "type": "string",
            "description": "Run only tests matching pattern"
          }
        }
      }
    },
    "lint": {
      "toolName": "run_linter",
      "description": "Run ESLint on source files",
      "argsDescription": "Additional ESLint flags"
    }
  }
}

Source: npm-run-mcp.config.schema.json

Tool Name Normalization

MCP tool names have strict constraints: only lowercase letters (a-z), digits (0-9), underscores (_), and hyphens (-) are allowed.

Normalization Rules

The server sanitizes script names to valid tool names:

Original ScriptNormalized Tool NameNotes
testtestNo change needed
test:unittest_unitColon replaced
build:prodbuild_prodColon replaced
lint-fixlint_fixHyphen to underscore
TESTtestLowercased
build(/*)build____Invalid chars replaced

Source: src/index.ts:normalizeToolName

Tool Name Collisions

If two scripts normalize to the same tool name, the server exits with an error:

npm-run-mcp-server: Tool name collisions detected. 
Set "scripts.<name>.toolName" in npm-run-mcp.config.json to disambiguate.
  build_prod: build:prod, build.prod

Source: src/index.ts:collision-detection

Tool Execution Pipeline

graph LR
    A[Tool Call] --> B[Input Validation<br/>Zod Schema]
    B -->|Valid| C[Parse Arguments]
    B -->|Invalid| D[Error Response]
    C --> E[buildRunCommand]
    E --> F[cross-spawn]
    F --> G[Script Execution]
    G --> H{Exit Code?}
    H -->|0| I[Success Result<br/>stdout + stderr]
    H -->|Non-zero| J[Error Result<br/>exit code + signal]

Argument Processing

The toolInputToExtraArgs function transforms validated inputs into CLI arguments:

// Input schema:
{
  "watch": { "type": "boolean" },
  "grep": { "type": "string" }
}

// Tool call input:
{ watch: true, grep: "auth" }

// Resulting CLI args:
["--watch", "--grep", "auth"]

Source: src/index.ts:toolInputToExtraArgs

Command Building

function buildRunCommand(
  pm: PackageManager,
  scriptName: string,
  extraArgs: string[]
): { command: string; args: string[] }
ParameterTypeDescription
pm`npm \pnpm \yarn \bun`Package manager to use
scriptNamestringScript name from package.json
extraArgsstring[]Additional arguments from tool input

Example outputs:

Package ManagerScriptArgsCommand
npmtest["--watch"]npm run test -- --watch
pnpmbuild[]pnpm run build
yarnlint["--fix"]yarn run lint --fix
bundev["--port", "3000"]bun run dev --port 3000

Source: src/index.ts:buildRunCommand

Hot Reload with File Watchers

The server monitors package.json and config files for changes and exits gracefully when detected, allowing the MCP client to restart the server with updated tool definitions.

graph TD
    A[File Change Detected] --> B{Which file?}
    B -->|package.json| C[Informs MCP Client]
    B -->|config.json| C
    C --> D[Cleanup Watchers]
    D --> E[Exit Process]
    F[MCP Client] -->|Restarts| G[Server with new config]

Watched Files

FileWatch Condition
package.jsonFound during startup
npm-run-mcp.config.jsonFound during startup
.npm-run-mcp.jsonFound during startup

Signal Handling

The server properly cleans up file watchers on termination:

process.on('SIGINT', () => {
  cleanup();
  process.exit(0);
});

process.on('SIGTERM', () => {
  cleanup();
  process.exit(0);
});

Source: src/index.ts:watcher-cleanup

MCP SDK Integration

Server Initialization

const server = new McpServer({ 
  name: serverName, 
  version: serverVersion 
});

const transport = new StdioServerTransport();
await server.connect(transport);

Tool Registration

server.registerTool(
  toolName,
  {
    description: string,
    inputSchema: ZodSchema
  },
  async (input) => {
    // Execution handler
    return { content: [...] };
  }
);

SDK Version

DependencyVersionPurpose
@modelcontextprotocol/sdk^1.25.1MCP protocol implementation

Source: package.json

Error Handling

Common Error Scenarios

ScenarioError MessageResolution
No scripts in package.jsonNo scripts found in <path>Add scripts to package.json
No scripts after filteringNo scripts selected for exposureCheck include/exclude config
Config parse errorFailed to read config file: <message>Validate JSON/JSONC syntax
Tool name collisionTool name collisions detectedSet scripts.<name>.toolName
Script timeoutCommand timed out after 30sReduce script complexity

Validation Errors

When tool input validation fails, the MCP client receives an error response:

{
  "content": [
    {
      "type": "text",
      "text": "Invalid input: ..."
    }
  ],
  "isError": true
}

Verbose Logging

Enable debug output via:

npx npm-run-mcp-server --verbose

Or via environment:

MCP_VERBOSE=1 npx npm-run-mcp-server
DEBUG=mcp npx npm-run-mcp-server

Verbose output includes:

  • Detected workspace folder
  • Package.json location
  • Detected package manager
  • Config file path
  • Number of registered tools

Source: src/index.ts:verbose-logging

JSONC Support

The config file parser supports JSONC (JSON with Comments), allowing:

Comments

{
  // Include only safe scripts
  "include": ["test", "lint", "build"],
  "exclude": ["postinstall"]
}

Trailing Commas

{
  "scripts": {
    "test": {
      "description": "Run tests",
    },  // <-- trailing comma allowed
  }
}

Source: src/index.ts:parseJsonOrJsonc

CLI Options

FlagDescriptionDefault
--cwd <path>Working directory for script executionCurrent directory
`--pm <npm\pnpm\yarn\bun>`Force specific package managerAuto-detected
--config <path>Path to config fileSearch default locations
--verboseEnable debug loggingfalse
--list-scriptsPrint discovered scripts and exitfalse

Package Manager Detection

The package manager is detected in priority order:

  1. --pm CLI flag (if provided)
  2. packageManager field in package.json
  3. Lockfile presence:

Source: src/index.ts:detectPackageManager

See Also

Source: https://github.com/fstubner/npm-run-mcp-server / Human Manual

Troubleshooting

Related topics: CLI Reference, Integration Testing

Section Related Pages

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

Related topics: CLI Reference, Integration Testing

Troubleshooting

This page covers common issues, error messages, and resolution strategies for npm-run-mcp-server. The server is designed to fail gracefully with informative error messages, but understanding the underlying causes helps resolve issues faster.

Source: https://github.com/fstubner/npm-run-mcp-server / Human Manual

Integration Testing

Related topics: Troubleshooting, System Architecture

Section Related Pages

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

Section Test Execution Flow

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

Section Test Script Configuration

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

Section Full Test Suite

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

Related topics: Troubleshooting, System Architecture

Integration Testing

This page documents the integration testing approach for npm-run-mcp-server, covering how the MCP server is validated as a complete system through end-to-end test scenarios.

Overview

Integration testing in npm-run-mcp-server validates that the MCP server functions correctly as a complete system. The tests verify that the server properly exposes package.json scripts as MCP tools, executes scripts through various package managers, and handles configuration correctly. Source: package.json:11

The integration test suite is the primary mechanism for validating the server's behavior in realistic usage scenarios, complementing any unit-level validations that may exist in the codebase.

Test Architecture

Test Execution Flow

graph TD
    A[Start Integration Test] --> B[Build Server: node scripts/build.cjs]
    B --> C[Start MCP Server: node dist/index.js --list-scripts]
    C --> D[Validate Script Discovery]
    D --> E[Run Integration Tests: node scripts/integration-test.mjs]
    E --> F{All Tests Pass?}
    F -->|Yes| G[Echo: 'MCP server test completed successfully']
    F -->|No| H[Test Failure + Exit Code]
    G --> I[Exit 0]
    H --> I

Test Script Configuration

The integration tests are defined in package.json under the scripts section:

Script CommandPurposeSource
npm run testFull test suite (build, list-scripts, integration)package.json:11
npm run test:integrationRun integration tests onlypackage.json:10
npm run buildBuild TypeScript to JavaScriptpackage.json:9

Running Integration Tests

Full Test Suite

To run the complete test suite including build, script listing, and integration tests:

npm run test

This executes three sequential steps:

  1. Build the TypeScript source to JavaScript
  2. List available scripts from the MCP server
  3. Run the integration test suite
  4. Print success message upon completion

Source: package.json:11

Integration Tests Only

To run only the integration tests without rebuilding:

npm run test:integration

Manual Server Testing

You can also manually verify server functionality using the --list-scripts flag:

node dist/index.js --list-scripts

This command starts the MCP server and lists all discovered package.json scripts, which is useful for debugging script detection.

Source: src/index.ts:88

Test Infrastructure Components

Test Script Entry Point

The integration test file is located at scripts/integration-test.mjs. This file contains the end-to-end test scenarios that validate:

  • MCP server startup and initialization
  • Script discovery from package.json
  • Tool registration with the MCP protocol
  • Script execution through the stdio transport

Source: scripts/integration-test.mjs

Build System

The build process uses a custom CommonJS script (scripts/build.cjs) to compile TypeScript:

node scripts/build.cjs

The compiled output is placed in the dist/ directory, which contains:

  • index.js - Main server entry point
  • index.d.ts - TypeScript declarations
  • index.d.ts.map - Source map for debugging

Source: package.json:9

CI/CD Integration

GitHub Actions Workflow

Integration tests run automatically via GitHub Actions on every push and pull request. The test workflow validates that:

  1. The server builds successfully on multiple Node.js versions
  2. Integration tests pass on Linux, macOS, and Windows
  3. Package manager detection works across different environments

Source: README.md

Workflow Badges

The repository displays workflow status badges showing the current test status:

BadgeMeaning
TestIntegration and unit tests pass
Build & PublishBuild process completes successfully

Source: README.md

Test Scenarios

Configuration Validation

Integration tests validate the configuration system by testing:

Source: npm-run-mcp.config.schema.json

Package Manager Detection

Tests validate that the server correctly detects the package manager from:

  1. The packageManager field in package.json
  2. Lockfile presence (pnpm-lock.yaml, yarn.lock, bun.lockb)
  3. Default fallback to npm

Source: src/index.ts

Verbose Testing

For debugging test failures, enable verbose logging:

MCP_VERBOSE=1 npm run test
# or
DEBUG=mcp npm run test

Verbose mode outputs detailed diagnostic information to stderr including:

  • Server startup parameters
  • Detected workspace folder
  • Package.json location
  • Package manager detection results
  • Registered tool count

Source: src/index.ts:24-35

Common Test Failures

Missing package.json

If no package.json is found in the project directory, the server starts with no tools registered. The test should handle this gracefully by either skipping relevant tests or validating the empty state.

Source: src/index.ts:58-71

No Scripts Found

When package.json exists but has no scripts defined, the server logs a warning but continues running:

npm-run-mcp-server: No scripts found in /path/to/package.json

Source: src/index.ts:82-84

Config File Parse Errors

If the config file contains invalid JSON or JSONC syntax, the server exits with an error message:

npm-run-mcp-server: Failed to read config file /path/to/config.json: <error message>

Source: src/index.ts

Tool Name Collisions

When multiple scripts resolve to the same normalized tool name, the server exits with a collision report listing the conflicting scripts.

Source: src/index.ts

Development Workflow

  1. Make changes to source code in src/index.ts
  2. Run npm run build to compile TypeScript
  3. Run npm run test to validate changes
  4. Iterate until all tests pass

Testing Config Changes

When modifying the config schema or parsing logic:

  1. Update npm-run-mcp.config.schema.json with new schema definitions
  2. Create or modify test config files
  3. Run npm run test:integration to validate parsing
  4. Use --verbose flag for detailed error output

See Also

Source: https://github.com/fstubner/npm-run-mcp-server / Human Manual

Doramagic Pitfall Log

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

medium README/documentation is current enough for a first validation pass.

The project should not be treated as fully validated until this signal is reviewed.

medium Maintainer activity is unknown

Users cannot judge support quality until recent activity, releases, and issue response are checked.

medium no_demo

The project may affect permissions, credentials, data exposure, or host boundaries.

medium No sandbox install has been executed yet; downstream must verify before user use.

The project may affect permissions, credentials, data exposure, or host boundaries.

Doramagic Pitfall Log

Doramagic extracted 7 source-linked risk signals. Review them before installing or handing real data to the project.

1. Capability assumption: README/documentation is current enough for a first validation pass.

  • Severity: medium
  • Finding: README/documentation is current enough for a first validation pass.
  • User impact: The project should not be treated as fully validated until this signal is reviewed.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: capability.assumptions | mcp_registry:io.github.fstubner/npm-run-mcp-server:0.2.13 | https://registry.modelcontextprotocol.io/v0.1/servers/io.github.fstubner%2Fnpm-run-mcp-server/versions/0.2.13 | README/documentation is current enough for a first validation pass.

2. Maintenance risk: Maintainer activity is unknown

  • Severity: medium
  • Finding: Maintenance risk is backed by a source signal: Maintainer activity is unknown. Treat it as a review item until the current version is checked.
  • User impact: Users cannot judge support quality until recent activity, releases, and issue response are checked.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: evidence.maintainer_signals | mcp_registry:io.github.fstubner/npm-run-mcp-server:0.2.13 | https://registry.modelcontextprotocol.io/v0.1/servers/io.github.fstubner%2Fnpm-run-mcp-server/versions/0.2.13 | last_activity_observed missing

3. Security or permission risk: no_demo

  • Severity: medium
  • Finding: no_demo
  • User impact: The project may affect permissions, credentials, data exposure, or host boundaries.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: downstream_validation.risk_items | mcp_registry:io.github.fstubner/npm-run-mcp-server:0.2.13 | https://registry.modelcontextprotocol.io/v0.1/servers/io.github.fstubner%2Fnpm-run-mcp-server/versions/0.2.13 | no_demo; severity=medium

4. Security or permission risk: No sandbox install has been executed yet; downstream must verify before user use.

  • Severity: medium
  • Finding: No sandbox install has been executed yet; downstream must verify before user use.
  • User impact: The project may affect permissions, credentials, data exposure, or host boundaries.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: risks.safety_notes | mcp_registry:io.github.fstubner/npm-run-mcp-server:0.2.13 | https://registry.modelcontextprotocol.io/v0.1/servers/io.github.fstubner%2Fnpm-run-mcp-server/versions/0.2.13 | No sandbox install has been executed yet; downstream must verify before user use.

5. Security or permission risk: no_demo

  • Severity: medium
  • Finding: no_demo
  • User impact: The project may affect permissions, credentials, data exposure, or host boundaries.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: risks.scoring_risks | mcp_registry:io.github.fstubner/npm-run-mcp-server:0.2.13 | https://registry.modelcontextprotocol.io/v0.1/servers/io.github.fstubner%2Fnpm-run-mcp-server/versions/0.2.13 | no_demo; severity=medium

6. Maintenance risk: issue_or_pr_quality=unknown

  • Severity: low
  • Finding: issue_or_pr_quality=unknown。
  • User impact: Users cannot judge support quality until recent activity, releases, and issue response are checked.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: evidence.maintainer_signals | mcp_registry:io.github.fstubner/npm-run-mcp-server:0.2.13 | https://registry.modelcontextprotocol.io/v0.1/servers/io.github.fstubner%2Fnpm-run-mcp-server/versions/0.2.13 | issue_or_pr_quality=unknown

7. Maintenance risk: release_recency=unknown

  • Severity: low
  • Finding: release_recency=unknown。
  • User impact: Users cannot judge support quality until recent activity, releases, and issue response are checked.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: evidence.maintainer_signals | mcp_registry:io.github.fstubner/npm-run-mcp-server:0.2.13 | https://registry.modelcontextprotocol.io/v0.1/servers/io.github.fstubner%2Fnpm-run-mcp-server/versions/0.2.13 | release_recency=unknown

Source: Doramagic discovery, validation, and Project Pack records

Community Discussion Evidence

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

Sources 4

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

Use Review before install

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

Community Discussion Evidence

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

Source: Project Pack community evidence and pitfall evidence