npm package: @m4cd4r4/mcpshield
Description: Zero-trust security proxy for MCP servers. Logging, rate limiting, injection detection, and policy enforcement.
Author: Macdara
Latest version: 0.2.0

# MCP Shield

[![npm version](https://img.shields.io/npm/v/@m4cd4r4/mcpshield.svg)](https://www.npmjs.com/package/@m4cd4r4/mcpshield)
[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
[![Node.js](https://img.shields.io/badge/node-%3E%3D18-brightgreen.svg)](https://nodejs.org)

Zero-trust security proxy for MCP (Model Context Protocol) servers. Drop-in protection for any AI agent tool integration.

```
npm install -g @m4cd4r4/mcpshield
```

## Why MCP Shield?

Every MCP tool call is a potential attack surface. An AI agent can be tricked into:

- **Prompt injection** — malicious input that hijacks the agent's behavior
- **Tool poisoning (rug pulls)** — MCP servers silently changing tool definitions
- **Data exfiltration** — extracting secrets, credentials, or sensitive files
- **Unrestricted access** — calling destructive tools without guardrails

MCP Shield sits between your AI client and MCP servers, intercepting every tool call with a configurable middleware chain:

- **Audit Logging** — Every tool call recorded to SQLite with full request/response
- **Rate Limiting** — Prevent agents from making excessive tool calls
- **Policy Engine** — Allow/deny tools, validate arguments with pattern rules
- **Injection Detection** — Block prompt injection attempts in tool arguments
- **Rug Pull Detection** — Alert when MCP servers change their tool definitions

## Quick Start

### 1. Wrap any MCP server

Add MCP Shield in front of any existing MCP server — just prepend `@m4cd4r4/mcpshield` and `--` to your args:

<details>
<summary><strong>Claude Desktop</strong> (claude_desktop_config.json)</summary>

```json
{
  "mcpServers": {
    "filesystem": {
      "command": "npx",
      "args": [
        "-y", "@m4cd4r4/mcpshield",
        "--",
        "npx", "-y", "@modelcontextprotocol/server-filesystem", "/home/user/projects"
      ]
    }
  }
}
```
</details>

<details>
<summary><strong>Claude Code</strong> (.mcp.json)</summary>

```json
{
  "mcpServers": {
    "filesystem": {
      "command": "npx",
      "args": [
        "-y", "@m4cd4r4/mcpshield",
        "--",
        "npx", "-y", "@modelcontextprotocol/server-filesystem", "/home/user/projects"
      ]
    }
  }
}
```
</details>

<details>
<summary><strong>Cursor / Windsurf / VS Code</strong></summary>

Same pattern — prepend `@m4cd4r4/mcpshield --` before your server command in your MCP configuration.
</details>

That's it. Every tool call is now logged, rate-limited, and scanned.

### 2. Add a config file (optional)

Create `mcpshield.yml` in your project root:

```yaml
version: 1

log:
  level: info

rules:
  # Rate limit all tools
  - type: rate-limit
    tool: "*"
    max: 100
    window: 60s

  # Block destructive tools
  - type: deny
    tools: [delete_file, execute_command]
    message: "Destructive tool blocked by policy"

  # Validate file paths
  - type: validate
    tool: read_file
    args:
      path:
        not_contains: ["../..", "/etc/passwd", ".env"]
```

See [mcpshield.example.yml](mcpshield.example.yml) for a full example.

## CLI Options

```
Usage: mcpshield [options] -- <command> [args...]

Options:
  -c, --config <path>           Path to mcpshield.yml config file
  -l, --log-level <level>       Log level: debug, info, warn, error (default: "info")
  --no-audit                    Disable audit logging to SQLite
  --no-injection-detection      Disable prompt injection detection
  --no-rug-pull-detection       Disable rug pull detection
  -V, --version                 Output version number
  -h, --help                    Display help
```

## Security Features

### Audit Logging

Every `tools/call` request is logged to a local SQLite database (`mcpshield.db`) with:
- Timestamp, tool name, arguments
- Response content and error status
- Duration in milliseconds
- Block reason (if blocked by a middleware)

### Rate Limiting

Configurable per-tool rate limits with sliding window:

```yaml
rules:
  - type: rate-limit
    tool: "*"           # Wildcard: all tools
    max: 100
    window: 60s

  - type: rate-limit
    tool: api_call      # Specific tool
    max: 10
    window: 5m
```

### Policy Engine

**Allow list** — Only permit specific tools:
```yaml
rules:
  - type: allow
    tools: [read_file, search, list_directory]
```

**Deny list** — Block specific tools:
```yaml
rules:
  - type: deny
    tools: [delete_file, execute_command]
    message: "Blocked by MCP Shield"
```

**Argument validation** — Check tool arguments against patterns:
```yaml
rules:
  - type: validate
    tool: read_file
    args:
      path:
        not_contains: ["../..", "/etc/shadow"]
        max_length: 500
        matches: "^/home/user/.*"    # Regex
```

### Prompt Injection Detection

Built-in pattern matching detects common injection techniques:
- System prompt overrides ("ignore previous instructions")
- Role manipulation ("you are now a...")
- Data exfiltration attempts ("show all API keys")
- Command injection (`; rm -rf /`)
- Path traversal (`../../../../etc/passwd`)
- Encoding evasion (base64 payloads, unicode tricks)

### Rug Pull Detection

Snapshots the tool list on first `tools/list` call. On subsequent calls, detects and warns about:
- New tools added (potential tool poisoning)
- Tools removed
- Tool descriptions changed (instruction hijacking)
- Input schema changes

## Programmatic API

Use MCP Shield as a library in your own tools:

```typescript
import {
  MiddlewareChain,
  InjectionDetectorMiddleware,
  RateLimiterMiddleware,
} from "@m4cd4r4/mcpshield/middleware";

const chain = new MiddlewareChain();
chain.add(new RateLimiterMiddleware([{ tool: "*", max: 50, window: "60s" }]));
chain.add(new InjectionDetectorMiddleware({ minSeverity: "high" }));

const action = await chain.processToolCall({
  tool: "read_file",
  arguments: { path: "/etc/passwd" },
  timestamp: Date.now(),
  requestId: "req-1",
});

if (action.type === "block") {
  console.log(`Blocked: ${action.reason}`);
}
```

## Architecture

```
AI Client (Claude / Cursor / Windsurf)
    |
    |  stdio (stdin/stdout)
    v
┌──────────────────────────────┐
│  MCP Shield Proxy            │
│                              │
│  ┌────────────────────────┐  │
│  │ Middleware Chain        │  │
│  │  1. Audit Logger       │  │
│  │  2. Rate Limiter       │  │
│  │  3. Policy Engine      │  │
│  │  4. Injection Detector │  │
│  │  5. Rug Pull Detector  │  │
│  └────────────────────────┘  │
│                              │
│  MCP Client ─────────────────│──→ Real MCP Server (subprocess)
└──────────────────────────────┘
```

The proxy is transparent: it forwards all MCP capabilities (tools, resources, prompts, completions, logging) from the upstream server. The middleware chain inspects `tools/call` requests and responses, blocking or modifying as configured.

## Compatibility

Works with any MCP client and server that uses stdio transport:
- **Clients:** Claude Desktop, Claude Code, Cursor, Windsurf, VS Code Copilot
- **Servers:** Any stdio-based MCP server (filesystem, GitHub, Slack, databases, etc.)

## Development

```bash
git clone https://github.com/m4cd4r4/mcpshield.git
cd mcpshield
npm install
npm run build
npm test             # Run unit + integration tests
npm run dev          # Watch mode
```

## License

MIT