MCP Servers

模型上下文协议服务器、框架、SDK 和模板的综合目录。

M
MCP Http Security Ts

Secure HTTP transport for MCP servers with API key authentication, IP/origin allowlisting, and middleware support

创建于 1/10/2026
更新于 about 18 hours ago
Repository documentation and setup instructions

mcp-http-security

Secure HTTP transport for MCP (Model Context Protocol) servers with API key authentication, IP/origin allowlisting, and Express-compatible middleware.

Installation

npm install @codewheel/mcp-http-security

Features

  • API Key Management - Create, validate, and revoke API keys with scopes and TTL
  • Secure Hashing - SHA-256 with pepper for timing-safe secret validation
  • IP Allowlisting - CIDR notation support for IPv4 and IPv6
  • Origin Validation - Hostname validation with wildcard subdomain support
  • Express Middleware - Drop-in security middleware for Express-style apps
  • Pluggable Storage - Memory, file, or custom storage backends
  • Zero Runtime Dependencies - Only Node.js crypto module

Quick Start

Basic Setup with Express

import express from 'express';
import {
  ApiKeyManager,
  MemoryStorage,
  RequestValidator,
  SecurityConfig,
  createSecurityMiddleware,
} from '@codewheel/mcp-http-security';

const app = express();

// Create storage and API key manager
const storage = new MemoryStorage();
const apiKeyManager = new ApiKeyManager(storage, 'your-secret-pepper');

// Create request validator
const requestValidator = new RequestValidator({
  allowedIps: ['127.0.0.1', '192.168.0.0/16'],
  allowedOrigins: ['example.com', '*.example.com'],
});

// Apply security middleware
app.use(createSecurityMiddleware({
  apiKeyManager,
  requestValidator,
  config: new SecurityConfig({
    requireAuth: true,
    allowedScopes: ['read', 'write'],
  }),
}));

// Your routes here
app.get('/api/data', (req, res) => {
  res.json({ message: 'Authenticated!' });
});

Creating API Keys

import { ApiKeyManager, FileStorage } from '@codewheel/mcp-http-security';

const storage = new FileStorage('./api-keys.json');
const manager = new ApiKeyManager(storage, 'your-secret-pepper');

// Create a key with scopes
const { apiKey, metadata } = await manager.createKey({
  label: 'Production API Key',
  scopes: ['read', 'write'],
  ttlSeconds: 86400 * 30, // 30 days
});

console.log('API Key:', apiKey); // mcp.abc123def456.secret...
console.log('Expires:', new Date(metadata.expires! * 1000));

Validating API Keys

try {
  const key = await manager.validate(apiKey);
  console.log('Valid key:', key.label);
  console.log('Scopes:', key.scopes);
  console.log('Has write access:', key.hasScope('write'));
} catch (error) {
  if (error instanceof AuthenticationException) {
    console.log('Invalid or expired key');
  }
}

IP Validation

import { IpValidator } from '@codewheel/mcp-http-security';

const validator = new IpValidator([
  '127.0.0.1',           // Single IP
  '192.168.0.0/16',      // IPv4 CIDR
  '10.0.0.0/8',
  '::1',                  // IPv6 localhost
  '2001:db8::/32',       // IPv6 CIDR
]);

validator.isAllowed('192.168.1.100'); // true
validator.isAllowed('8.8.8.8');       // false

Origin Validation

import { OriginValidator } from '@codewheel/mcp-http-security';

const validator = new OriginValidator([
  'example.com',
  '*.example.com',  // Matches foo.example.com
  'localhost',
]);

validator.isAllowed('example.com');      // true
validator.isAllowed('api.example.com');  // true
validator.isAllowed('other.com');        // false

API Reference

ApiKeyManager

new ApiKeyManager(storage: StorageInterface, pepper: string, options?: {
  clock?: Clock;
  keyPrefix?: string;
})

// Methods
createKey(options: CreateKeyOptions): Promise<CreateKeyResult>
listKeys(): Promise<ApiKeyMetadata[]>
getKey(keyId: string): Promise<ApiKeyMetadata | undefined>
revokeKey(keyId: string): Promise<boolean>
validate(apiKey: string): Promise<ApiKey>

ApiKey

// Properties
keyId: string
label: string
scopes: readonly string[]
created: number
lastUsed?: number
expires?: number

// Methods
hasScope(scope: string): boolean
hasAnyScope(scopes: string[]): boolean
hasAllScopes(scopes: string[]): boolean
isExpired(currentTime?: number): boolean
toMetadata(): ApiKeyMetadata

RequestValidator

new RequestValidator(options?: {
  allowedIps?: string[];
  allowedOrigins?: string[];
  ipValidator?: IpValidator;
  originValidator?: OriginValidator;
})

// Methods
validate(request: ValidatableRequest): void  // throws ValidationException
isValid(request: ValidatableRequest): boolean
getClientIp(request: ValidatableRequest): string | null
getRequestHostname(request: ValidatableRequest): string | null

SecurityConfig

new SecurityConfig(options?: {
  requireAuth?: boolean;       // default: true
  allowedScopes?: string[];    // default: []
  authHeader?: string;         // default: "Authorization"
  apiKeyHeader?: string;       // default: "X-MCP-Api-Key"
  scopesAttribute?: string;    // default: "mcp.scopes"
  keyAttribute?: string;       // default: "mcp.key"
  silentFail?: boolean;        // default: false
})

Storage Backends

// In-memory (for testing)
new MemoryStorage()

// File-based (JSON)
new FileStorage(filePath: string)

// Custom storage: implement StorageInterface
interface StorageInterface {
  getAll(): Promise<Map<string, ApiKeyData>>;
  setAll(keys: Map<string, ApiKeyData>): Promise<void>;
  get(keyId: string): Promise<ApiKeyData | undefined>;
  set(keyId: string, data: ApiKeyData): Promise<void>;
  delete(keyId: string): Promise<boolean>;
}

Exceptions

SecurityException        // base class, HTTP 403
AuthenticationException  // HTTP 401
AuthorizationException   // HTTP 403, includes requiredScopes/actualScopes
ValidationException      // HTTP 404
RateLimitException       // HTTP 429, includes retryAfterSeconds

Cross-Language Support

This package is part of the MCP security ecosystem:

| Language | Package | |----------|---------| | TypeScript | @codewheel/mcp-http-security | | PHP | code-wheel/mcp-http-security |

All packages maintain API parity for consistent security handling across your stack.

License

MIT

快速设置
此服务器的安装指南

安装包 (如果需要)

npx @modelcontextprotocol/server-mcp-http-security-ts

Cursor 配置 (mcp.json)

{ "mcpServers": { "code-wheel-mcp-http-security-ts": { "command": "npx", "args": [ "code-wheel-mcp-http-security-ts" ] } } }