# Mcp Secure Server

> A universal security-by-default framework for Model Context Protocol (MCP) servers that provides multi-layered defense against traditional attacks.

- **Type:** MCP server
- **Install:** `agentstack add mcp-aself101-mcp-secure-server`
- **Verified:** Pending review
- **Seller:** [aself101](https://agentstack.voostack.com/s/aself101)
- **Installs:** 0
- **Category:** [Integrations](https://agentstack.voostack.com/c/integrations)
- **Latest version:** 0.1.0
- **License:** MIT
- **Upstream author:** [aself101](https://github.com/aself101)
- **Source:** https://github.com/aself101/mcp-secure-server

## Install

```sh
agentstack add mcp-aself101-mcp-secure-server
```

Requires the [AgentStack CLI](https://agentstack.voostack.com/docs/cli). Works with Claude Code, Cursor, and any MCP-compatible agent.

## About

# MCP Security Framework

[](https://www.npmjs.com/package/mcp-secure-server)
[](LICENSE)
[](https://nodejs.org)
[](https://www.typescriptlang.org/)
[](test/)
[](test/)

A secure-by-default MCP server built on the official SDK with 5-layer validation. Provides defense-in-depth against traditional attacks and AI-driven threats.

This framework implements defense-in-depth security with zero configuration required, protecting MCP servers from path traversal, command injection, SQL injection, XSS, prototype pollution, SSRF, and 20+ additional attack vectors.

## Quick Start

### Installation

```bash
npm install mcp-secure-server
```

### Basic Usage

```typescript
import { SecureMcpServer } from 'mcp-secure-server';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import { z } from 'zod';

// Create secure server with a security preset
const server = new SecureMcpServer(
  { name: 'my-server', version: '1.0.0' },
  { securityLevel: 'standard' }  // 'basic' | 'standard' | 'paranoid' | 'custom'
);

// Register tools exactly like McpServer
server.tool('calculator', 'Basic calculator', {
  expression: z.string()
}, async ({ expression }) => {
  // Security framework automatically blocks malicious inputs
  // NOTE: eval() used for demo only - use a safe math parser in production
  return { content: [{ type: 'text', text: `Result: ${eval(expression)}` }] };
});

// Connect - transport is automatically wrapped with security
const transport = new StdioServerTransport();
await server.connect(transport);
```

### Security Presets

Choose your security level with a single option:

```typescript
// Development: relaxed limits, minimal validation
const devServer = new SecureMcpServer(
  { name: 'dev', version: '1.0.0' },
  { securityLevel: 'basic' }
);

// Production: balanced security (default)
const prodServer = new SecureMcpServer(
  { name: 'prod', version: '1.0.0' },
  { securityLevel: 'standard' }
);

// High-security: maximum protection
const secureServer = new SecureMcpServer(
  { name: 'secure', version: '1.0.0' },
  { securityLevel: 'paranoid' }
);

// Custom: override specific values within a preset
const customServer = new SecureMcpServer(
  { name: 'custom', version: '1.0.0' },
  {
    securityLevel: 'standard',
    maxRequestsPerMinute: 60  // Override just this value
  }
);
```

| Preset | Use Case | Message Size | Rate Limit | Burst | Automation Detection |
|--------|----------|--------------|------------|-------|---------------------|
| `basic` | Development, testing | 100KB | 120/min | 30/10s | Disabled |
| `standard` | Production (default) | 50KB | 30/min | 10/10s | Enabled |
| `paranoid` | High-risk, compliance | 25KB | 15/min | 5/5s | Enabled (strict) |
| `custom` | Full control | You decide | You decide | You decide | You decide |

### Programmatic Preset Access

Access preset configurations programmatically for dynamic configuration, validation, or custom tooling:

```typescript
import {
  SECURITY_PRESETS,
  resolvePreset,
  getDefaultPreset,
  isValidPreset
} from 'mcp-secure-server';

// Get the default preset name
const defaultName = getDefaultPreset();  // 'standard'

// Validate user input
const userInput = 'paranoid';
if (isValidPreset(userInput)) {
  const config = resolvePreset(userInput);
  console.log(config.maxMessageSize);      // 25600
  console.log(config.maxRequestsPerMinute); // 15
}

// Iterate all presets for documentation or UI
for (const [name, config] of Object.entries(SECURITY_PRESETS)) {
  console.log(`${name}: ${config.maxRequestsPerMinute} req/min`);
}

// Build dynamic configuration
function createServer(env: string) {
  const level = env === 'production' ? 'paranoid' : 'basic';
  return new SecureMcpServer(
    { name: 'dynamic', version: '1.0.0' },
    { securityLevel: level }
  );
}
```

### With Logging (Opt-in)

```typescript
const server = new SecureMcpServer(
  { name: 'my-server', version: '1.0.0' },
  {
    securityLevel: 'standard',
    enableLogging: true,
    verboseLogging: true,
    logPerformanceMetrics: true,
    logLevel: 'debug'
  }
);
```

Full TypeScript support with exported types for all parameters, configurations, and responses.

## Table of Contents

- [Overview](#overview)
- [Architecture](#architecture)
- [Security Layers](#security-layers)
- [Installation](#installation)
- [TypeScript Support](#typescript-support)
- [Quick Start](#quick-start)
- [Configuration](#configuration)
- [Tool Policies Configuration](#tool-policies-configuration)
- [API Reference](#api-reference)
- [HTTP Transport](#http-transport)
- [Layer 5 Customization](#layer-5-customization)
- [Security Features](#security-features)
- [Attack Coverage](#attack-coverage)
- [Error Handling](#error-handling)
- [Claude Desktop Integration](#claude-desktop-integration)
- [Development](#development)
- [Troubleshooting](#troubleshooting)
- [Cookbook Examples](#cookbook-examples)

## Cookbook Examples

Example MCP servers demonstrating the security framework. Each server includes input validation and attack prevention.

| Server | Description | Tools | Auth |
|--------|-------------|-------|------|
| [advanced-validation-server](cookbook/advanced-validation-server) | Layer 5 custom validators (PII detection, geofencing, business hours, egress tracking) | Financial query, batch process, export data, API call | None |
| [api-wrapper-server](cookbook/api-wrapper-server) | Safe REST API wrapping with domain restrictions and rate limiting | Weather, currency conversion, news headlines | None |
| [cli-wrapper-server](cookbook/cli-wrapper-server) | Safe CLI tool wrapping with command injection prevention | Git status, image resize, PDF metadata, video encode | None |
| [database-server](cookbook/database-server) | Secure database operations with SQL injection prevention | User queries, order creation, report generation | None |
| [filesystem-server](cookbook/filesystem-server) | Protected file system access with path traversal prevention | Read files, list directories, search files | None |
| [http-server](cookbook/http-server) | Simple HTTP transport with `createHttpServer()` | Calculator, echo | None |
| [image-gen-server](cookbook/image-gen-server) | Unified image generation across 5 providers (BFL, Google, Ideogram, OpenAI, Stability) | Generate, edit, upscale, describe images | API keys |
| [kenpom-server](cookbook/kenpom-server) | College basketball analytics and efficiency ratings | Ratings, schedules, scouting reports, player stats | KenPom login |
| [monitoring-server](cookbook/monitoring-server) | Observability with metrics, audit logging, and alerts | Security metrics, audit log, alerts, Prometheus export | None |
| [multi-endpoint-server](cookbook/multi-endpoint-server) | Multiple HTTP endpoints with `createSecureHttpHandler()` | Admin (list-users, system-stats), Public (health, status) | None |
| [nba-server](cookbook/nba-server) | NBA stats, live scores, and player data | Player stats, box scores, live scoreboard | None |
| [transaction-server](cookbook/transaction-server) | Method chaining enforcement for secure transaction workflows | Session, accounts, prepare/confirm/execute transactions | None |

See the [cookbook README](cookbook/README.md) for setup instructions and detailed documentation.

## Overview

The MCP Security Framework acts as a universal wrapper for any MCP server, providing comprehensive security validation through a multi-layered architecture. It implements:

- **5-Layer Defense Pipeline** - Structure, Content, Behavior, Semantics, and Contextual validation
- **Zero Configuration** - Security enabled by default with sensible defaults
- **Universal Compatibility** - Works with any MCP server using @modelcontextprotocol/sdk
- **Extensible Layer 5** - Add custom validators, domain restrictions, OAuth validation
- **Tested** - 1134 tests with 86% coverage
- **Opt-in Logging** - Quiet by default for production use
- **Performance Optimized** - Content caching and efficient pattern detection
- **Full TypeScript Support** - Complete type definitions with strict mode

## Architecture

```
Request → Layer 1 → Layer 2 → Layer 3 → Layer 4 → Layer 5 → MCP Server
           │          │          │          │          │
        Structure  Content   Behavior  Semantics  Contextual
        Validation Validation Validation Validation Validation
```

### Visual Overview

```
                          MCP Security Framework (5 Layers by Default)
                                          │
    ┌─────────────┬─────────────┬─────────────┬─────────────┬─────────────┐
    │             │             │             │             │             │
┌───▼────┐  ┌─────▼─────┐  ┌────▼────┐  ┌────▼─────┐  ┌─────▼──────┐
│ Layer 1│  │  Layer 2  │  │ Layer 3 │  │  Layer 4 │  │  Layer 5   │
│ Struct.│  │  Content  │  │ Behavior│  │ Semantics│  │ Contextual │
└────────┘  └───────────┘  └─────────┘  └──────────┘  └────────────┘
│JSON-RPC│  │Injection  │  │Rate     │  │Tool      │  │Custom      │
│Format  │  │Detection  │  │Limiting │  │Contracts │  │Validators  │
│Size    │  │XSS/SQLi   │  │Burst    │  │Quotas    │  │Domain/OAuth│
│Encoding│  │Path Trav. │  │Patterns │  │Policies  │  │Response Val│
└────────┘  └───────────┘  └─────────┘  └──────────┘  └────────────┘
```

## Security Layers

### Layer 1 - Structure Validation

Validates the fundamental structure of incoming JSON-RPC messages.

**Protections:**
- JSON-RPC 2.0 format validation
- Request size limits (default: 50KB)
- Message encoding validation
- Parameter count limits
- Per-string parameter length limits (default: 5,000 chars)
- Method name length limits

**Configuration:**
```typescript
{
  maxMessageSize: 50000,      // Maximum message size in bytes
  maxParamCount: 100,         // Maximum recursive parameter count (set to Infinity to disable)
  maxStringLength: 5000,      // Maximum length of any single string parameter value (chars)
  maxMethodLength: 256        // Maximum method name length
}
```

> **Note:** `maxMessageSize` must leave headroom above `maxStringLength` — the message
> envelope is larger than the string it carries, and the message-size check fires first.

### Layer 2 - Content Validation

Detects and blocks malicious content patterns in request parameters.

**Protections:** Path traversal, command injection, SQL/NoSQL injection, XSS, prototype pollution, XML entity attacks (XXE), CRLF injection, SSRF, CSV injection, LOLBins, GraphQL introspection, deserialization attacks, JNDI/Log4Shell, buffer overflow patterns, and more.

See [SECURITY.md](https://github.com/aself101/mcp-secure-server/blob/main/SECURITY.md#attack-vectors) for the complete list of 200+ attack patterns with examples.

**Configuration:**
```typescript
{
  contentValidation: {
    enabled: true,
    debugMode: false          // Enable for detailed pattern match info
  }
}
```

### Layer 3 - Behavior Validation

Rate limiting and request pattern analysis to prevent abuse.

**Protections:**
- Requests per minute rate limiting
- Requests per hour rate limiting
- Burst detection (configurable time window)
- Automation detection via timing analysis
- Large message flagging

**Configuration:**
```typescript
{
  maxRequestsPerMinute: 30,   // Rate limit per minute
  maxRequestsPerHour: 500,    // Rate limit per hour
  burstThreshold: 10,         // Max requests in burst window
  burstWindowMs: 10000,       // Burst detection window in ms (default: 10s)
  suspiciousMessageSize: 20000, // Flag messages larger than this (bytes)
  automationDetection: {
    enabled: true,            // Enable timing-based automation detection
    sampleSize: 5,            // Number of requests to analyze
    maxVariance: 50,          // Max timing variance (ms) before flagging
    minInterval: 100,         // Min avg interval (ms) to flag as automation
    maxInterval: 2000         // Max avg interval (ms) to flag as automation
  }
}
```

**Automation Detection:** Analyzes request timing patterns to detect automated scripts. When enabled, it monitors the variance in request intervals - suspiciously consistent timing (low variance) indicates automation rather than human interaction.

### Layer 4 - Semantic Validation

Tool contract enforcement and resource access policies.

**Protections:**
- Tool argument validation against schemas
- Response size limits (egress control)
- Per-tool quota enforcement
- Side effect declarations
- Filesystem access control via resource policies
- Session management
- Method chaining enforcement (opt-in)

**Configuration:**
```typescript
{
  toolRegistry: [
    {
      name: 'my-database-tool',
      sideEffects: 'write',       // 'none' | 'read' | 'write' | 'network'
      maxArgsSize: 5000,          // Max argument size in bytes
      maxEgressBytes: 100000,     // Max response size
      quotaPerMinute: 30,
      quotaPerHour: 500,
      argsShape: {                // Expected argument schema
        query: { type: 'string' },
        limit: { type: 'number' }
      }
    }
  ],
  resourcePolicy: {
    allowedSchemes: ['file'],
    rootDirs: ['./data', './public'],
    denyGlobs: ['/etc/**', '**/*.key', '**/.env'],
    maxPathLength: 4096,
    maxReadBytes: 2000000         // 2MB max file read
  },
  maxSessions: 5000,
  sessionTtlMs: 1800000            // 30 minutes
}
```

#### Method Chaining Enforcement

Layer 4 can enforce valid method call sequences to prevent abuse patterns like calling dangerous tools without proper initialization.

**Enable chaining enforcement:**
```typescript
{
  enforceChaining: true,           // Enable method chaining (default: false)
  chainingDefaultAction: 'deny',   // 'allow' | 'deny' when no rule matches
  chainingRules: [
    // Allow any method to call initialize
    { from: '*', to: 'initialize' },
    // After initialize, can list tools or resources
    { from: 'initialize', to: 'tools/list' },
    { from: 'initialize', to: 'resources/list' },
    // After listing tools, can call them
    { from: 'tools/list', to: 'tools/call' },
    // Tool-to-tool calls allowed
    { from: 'tools/call', to: 'tools/call' },
  ]
}
```

**ChainingRule type:**
```typescript
interface ChainingRule {
  from: string;              // Method to transition from ('*' for any)
  to: string;                // Method to transition to ('*' for any)
  fromTool?: string;         // Tool name glob pattern (e.g., 'file-*', '*-http*')
  toTool?: string;           // Tool name glob pattern
  fromSideEffect?: SideEffects;  // 'none' | 'read' | 'write' | 'network'
  toSideEffect?: SideEffects;
  action?: 'allow' | 'deny'; // Default: 'allow'
  id?: string;               // Rule identifier for logging
  description?: string;      // Human-readable description
}
```

**Advanced example - block dangerous transitions:**
```typescript
{
  enforceChaining: true,
  chainingDefaultAction: 'allow',  // Allow by default
  chainingRules: [
    // Block read tools from calling write tools directly
    {
      from: 'tools/call',
      to: 'tools/call',
      fromSideEffect: 'read',
      toSideEffect: 'write',
      action: 'deny',
      id: 'no-read-to-write'
    },
    // Block file-* tools from calling *-http* tools
    {
      from: 'tools/call',
      to: 'tools/call',
      fromTool: 'file-*',
      toTool: '*-http*',
      action: 'deny',
      id: 'no-file-to-http'
    }
  ]
}
```

Rules are evaluated first-match-wins. Tool patterns use simple glob matching (`*` = any chars, `?` = single char).

### Layer 5 - Contextual Validation

Custom validators, domain restrictions, and response filtering. Fu

…

## Source & license

This open-source MCP server is cataloged on AgentStack and links to its original source — we do not rehost the code.

- **Author:** [aself101](https://github.com/aself101)
- **Source:** [aself101/mcp-secure-server](https://github.com/aself101/mcp-secure-server)
- **License:** MIT

Install and usage instructions live in the source repository linked above.

## Pricing

- **Free** — Free

## Security capabilities

Automated source analysis of v0.1.0 — what this tool can access:

- **Network access:** yes
- **Filesystem access:** no
- **Shell / process execution:** no
- **Environment & secrets:** yes
- **Dynamic code execution:** yes

*"Yes" means the capability is present in the source — more access means more to trust, not that it is unsafe.*


## Versions

- **0.1.0** — security scan: flagged — Imported from the upstream source.

## Links

- Listing page: https://agentstack.voostack.com/l/mcp-aself101-mcp-secure-server
- Seller: https://agentstack.voostack.com/s/aself101
- Browse the marketplace: https://agentstack.voostack.com/browse

---
Listed on AgentStack — the marketplace for AI agent skills and MCP servers. Every listing is security-reviewed. Creators keep 70%.
