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
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
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:
| Requirement | Version | Notes |
|---|---|---|
| Node.js | ≥ 18.18.0 | Required for running the server binary Source: package.json:28 |
| npm, pnpm, yarn, or bun | Any recent version | Package manager is auto-detected Source: src/index.ts:147-153 |
| MCP-compatible AI client | — | Claude 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
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
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:#e8f5e9Method 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]
| Argument | Purpose |
|---|---|
-y | Skip confirmation prompt for npx |
npm-run-mcp-server | Package 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:#fff3e0Method 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:#e8f5e9Priority order for package manager detection:
- Explicit
--pmCLI argument (highest priority) packageManagerfield inpackage.json- Lockfile detection:
pnpm-lock.yaml,yarn.lock,bun.lock/bun.lockb - 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
- Open Settings → Features → MCP Servers
- Click + Add New MCP Server
- Enter the following details:
| Field | Value |
|---|---|
| Type | command |
| Name | npm-scripts |
| Command | npx |
| 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:
| Flag | Description | Example |
|---|---|---|
--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 |
--verbose | Enable debug logging to stderr | --verbose |
--list-scripts | Print 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 Name | Priority |
|---|---|
npm-run-mcp.config.json | Primary |
.npm-run-mcp.json | Fallback |
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
| Property | Type | Description |
|---|---|---|
include | string[] | Whitelist of script names to expose |
exclude | string[] | Blacklist of script names to hide |
scripts | object | Per-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
| Issue | Cause | Solution |
|---|---|---|
| Server not responding | Wrong working directory | Use --cwd to specify project path |
| Wrong package manager | Auto-detection failed | Use --pm <manager> to override |
| Config file not found | Wrong filename or path | Use --config <path> to specify |
| No scripts visible | Empty include/exclude filter | Check configuration file settings |
Verification Steps
``bash npx npm-run-mcp-server --list-scripts ``
- List scripts manually:
``bash npx npm-run-mcp-server --verbose ``
- Run with verbose logging:
``bash ls -la package.json ``
- Verify package.json exists:
Source: src/index.ts - list-scripts and verbose handling
Dependencies
The server has the following runtime dependencies:
| Package | Version | Purpose |
|---|---|---|
@modelcontextprotocol/sdk | ^1.25.1 | MCP protocol implementation |
cross-spawn | ^7.0.5 | Cross-platform script execution |
jsonc-parser | ^3.3.1 | JSONC parsing (config files) |
zod | ^3.23.8 | Schema validation |
Source: package.json:20-24
Summary
| Method | Best For | Setup Required |
|---|---|---|
| npx | Quick testing, demos | None |
| Global npm | CLI usage, multiple projects | Yes (one-time) |
| Per-project dev dep | Team consistency, CI/CD | Yes (per-project) |
| Claude Desktop | Claude AI integration | Yes (config file) |
| Cursor | Cursor IDE integration | Yes (settings UI) |
| VS Code Copilot | GitHub Copilot integration | Yes (settings.json) |
See Also
- Configuration Guide - Detailed configuration options
- Configuration Schema - JSON Schema reference
- Architecture Overview - Internal server architecture
- Usage Examples - Common usage patterns
- MCP Protocol Documentation - MCP specification
Source: https://github.com/fstubner/npm-run-mcp-server / Human Manual
Configuration Guide
Related topics: CLI Reference, Tool Schema and MCP Integration
Continue reading this section for the full explanation and source context.
Related Pages
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
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
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
| Option | Description | Default |
|---|---|---|
--cwd <path> | Set the working directory for script execution | Current working directory |
--pm <manager> | Force a specific package manager (npm, pnpm, yarn, bun) | Auto-detected |
--config <path> | Path to a specific JSON configuration file | Auto-discovered |
--verbose | Enable verbose debug logging to stderr | Disabled |
--list-scripts | Print available scripts and exit | Disabled |
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 --> HSource: 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.jsonpath - 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:
| Lockfile | Package Manager |
|---|---|
pnpm-lock.yaml | pnpm |
yarn.lock | yarn |
bun.lock or bun.lockb | bun |
| None found | npm (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:
- Path specified via
--config <path>CLI flag npm-run-mcp.config.jsonin project root.npm-run-mcp.jsonin project root
Source: src/index.ts:190-210
Configuration Schema
| Field | Type | Description |
|---|---|---|
include | string[] | Exact script names to include. If omitted, all scripts are eligible (subject to exclude). |
exclude | string[] | Exact script names to exclude. |
scripts | object | Per-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:
| Field | Type | Description |
|---|---|---|
toolName | string | Override the tool name (after sanitization). |
description | string | Custom description for the tool. |
inputSchema | object | JSON Schema for additional tool inputs (converted to CLI args). |
argsDescription | string | Description 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:
- Convert to lowercase
- Replace any non-alphanumeric character (except
_and-) with underscore_ - If the result is empty, use
scriptas 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
| Variable | Description |
|---|---|
MCP_VERBOSE | Set to any value to enable verbose logging |
DEBUG | If contains mcp (case-insensitive), enables verbose logging |
Source: src/index.ts:27-28
Workspace Detection
| Variable | Description |
|---|---|
VSCODE_WORKSPACE_FOLDER | VS Code workspace folder (for verbose logging) |
CURSOR_WORKSPACE_FOLDER | Cursor 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 buildpnpm run test -- --watchyarn 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
| Code | Description |
|---|---|
0 | Success (or --list-scripts completed) |
1 | Error (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 0SIGTERM: Clean up watchers, exit 0
Source: src/index.ts:348-357
See Also
- Home - Overview of npm-run-mcp-server
- Configuration Guide - Detailed configuration examples
- MCP Integration - Setting up with AI clients
- @modelcontextprotocol/sdk - MCP SDK documentation
Source: https://github.com/fstubner/npm-run-mcp-server / Human Manual
System Architecture
Related topics: Package Manager Detection, Tool Schema and MCP Integration
Continue reading this section for the full explanation and source context.
Related Pages
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
Continue reading this section for the full explanation and source context.
Related Pages
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
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
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.jsonscripts - 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| OCore Components
| Component | Responsibility | Location |
|---|---|---|
McpServer | MCP protocol server from SDK | @modelcontextprotocol/sdk |
StdioServerTransport | Communication via stdio | @modelcontextprotocol/sdk |
| Tool Registry | Maps scripts to MCP tools | src/index.ts |
| Schema Builder | Converts JSON Schema to Zod | src/index.ts:normalizeToolName |
| File Watcher | Hot reload on config changes | src/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 resultStep-by-Step Process
- Startup: Server initializes and connects stdio transport
- Package Detection: Locates
package.jsonand detects package manager - Config Loading: Reads
npm-run-mcp.config.jsonor.npm-run-mcp.json - Script Filtering: Applies
include/excluderules - Tool Registration: Registers each script as an MCP tool with schema
- 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 Keyword | Zod Equivalent | Notes |
|---|---|---|
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 |
properties | Chained .shape() | Object structure |
required | Chained .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:
- Path specified via
--configCLI flag npm-run-mcp.config.jsonin project root.npm-run-mcp.jsonin project root
Config Schema Properties
| Property | Type | Description |
|---|---|---|
include | string[] | Whitelist of script names to expose |
exclude | string[] | Blacklist of script names to hide |
scripts | Record<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
};
| Field | Purpose | Example |
|---|---|---|
toolName | Custom MCP tool name | "run_tests" instead of "test" |
description | Human-readable tool description | "Run the test suite with coverage" |
argsDescription | Description for CLI args field | "Pass --watch for interactive mode" |
inputSchema | Define 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 Script | Normalized Tool Name | Notes |
|---|---|---|
test | test | No change needed |
test:unit | test_unit | Colon replaced |
build:prod | build_prod | Colon replaced |
lint-fix | lint_fix | Hyphen to underscore |
TEST | test | Lowercased |
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[] }
| Parameter | Type | Description | |||
|---|---|---|---|---|---|
pm | `npm \ | pnpm \ | yarn \ | bun` | Package manager to use |
scriptName | string | Script name from package.json | |||
extraArgs | string[] | Additional arguments from tool input |
Example outputs:
| Package Manager | Script | Args | Command |
|---|---|---|---|
| npm | test | ["--watch"] | npm run test -- --watch |
| pnpm | build | [] | pnpm run build |
| yarn | lint | ["--fix"] | yarn run lint --fix |
| bun | dev | ["--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
| File | Watch Condition |
|---|---|
package.json | Found during startup |
npm-run-mcp.config.json | Found during startup |
.npm-run-mcp.json | Found 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
| Dependency | Version | Purpose |
|---|---|---|
@modelcontextprotocol/sdk | ^1.25.1 | MCP protocol implementation |
Source: package.json
Error Handling
Common Error Scenarios
| Scenario | Error Message | Resolution |
|---|---|---|
| No scripts in package.json | No scripts found in <path> | Add scripts to package.json |
| No scripts after filtering | No scripts selected for exposure | Check include/exclude config |
| Config parse error | Failed to read config file: <message> | Validate JSON/JSONC syntax |
| Tool name collision | Tool name collisions detected | Set scripts.<name>.toolName |
| Script timeout | Command timed out after 30s | Reduce 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
| Flag | Description | Default | |||
|---|---|---|---|---|---|
--cwd <path> | Working directory for script execution | Current directory | |||
| `--pm <npm\ | pnpm\ | yarn\ | bun>` | Force specific package manager | Auto-detected |
--config <path> | Path to config file | Search default locations | |||
--verbose | Enable debug logging | false | |||
--list-scripts | Print discovered scripts and exit | false |
Package Manager Detection
The package manager is detected in priority order:
--pmCLI flag (if provided)packageManagerfield inpackage.json- Lockfile presence:
pnpm-lock.yaml→pnpmyarn.lock→yarnbun.lockborbun.lock→bun- Default →
npm
Source: src/index.ts:detectPackageManager
See Also
- README.md - Main project documentation with quick start guides
- npm-run-mcp.config.schema.json - JSON Schema for configuration files
- server.json - MCP server manifest for registry listing
- Model Context Protocol Specification - Official MCP documentation
Source: https://github.com/fstubner/npm-run-mcp-server / Human Manual
Troubleshooting
Related topics: CLI Reference, Integration Testing
Continue reading this section for the full explanation and source context.
Related Pages
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
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
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 --> ITest Script Configuration
The integration tests are defined in package.json under the scripts section:
| Script Command | Purpose | Source |
|---|---|---|
npm run test | Full test suite (build, list-scripts, integration) | package.json:11 |
npm run test:integration | Run integration tests only | package.json:10 |
npm run build | Build TypeScript to JavaScript | package.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:
- Build the TypeScript source to JavaScript
- List available scripts from the MCP server
- Run the integration test suite
- 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 pointindex.d.ts- TypeScript declarationsindex.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:
- The server builds successfully on multiple Node.js versions
- Integration tests pass on Linux, macOS, and Windows
- Package manager detection works across different environments
Source: README.md
Workflow Badges
The repository displays workflow status badges showing the current test status:
| Badge | Meaning |
|---|---|
| Test | Integration and unit tests pass |
| Build & Publish | Build process completes successfully |
Source: README.md
Test Scenarios
Configuration Validation
Integration tests validate the configuration system by testing:
- Per-project config file loading (
npm-run-mcp.config.json/.npm-run-mcp.json) - JSONC parsing support (comments and trailing commas)
- Include/exclude script filtering
- Per-script metadata overrides
Source: npm-run-mcp.config.schema.json
Package Manager Detection
Tests validate that the server correctly detects the package manager from:
- The
packageManagerfield in package.json - Lockfile presence (pnpm-lock.yaml, yarn.lock, bun.lockb)
- 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
Recommended Test-Driven Development
- Make changes to source code in
src/index.ts - Run
npm run buildto compile TypeScript - Run
npm run testto validate changes - Iterate until all tests pass
Testing Config Changes
When modifying the config schema or parsing logic:
- Update
npm-run-mcp.config.schema.jsonwith new schema definitions - Create or modify test config files
- Run
npm run test:integrationto validate parsing - Use
--verboseflag for detailed error output
See Also
- README.md - Main project documentation
- src/index.ts - Server implementation source
- npm-run-mcp.config.schema.json - Configuration schema
- GitHub Actions Test Workflow - CI/CD pipeline configuration
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.
The project should not be treated as fully validated until this signal is reviewed.
Users cannot judge support quality until recent activity, releases, and issue response are checked.
The project may affect permissions, credentials, data exposure, or host boundaries.
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.
Count of project-level external discussion links exposed on this manual page.
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.
- v0.2.13 - github / github_release
- v0.2.10 - github / github_release
- npm-run-mcp-server v0.1.0 - github / github_release
- README/documentation is current enough for a first validation pass. - GitHub / issue
Source: Project Pack community evidence and pitfall evidence