Skip to content

MCP Gateway

scarecr0w12 edited this page Jun 19, 2026 · 2 revisions

MCP Gateway

Enterprise multi-server MCP (Model Context Protocol) gateway providing centralized health monitoring, rate limiting, audit logging, and approval workflows for managed MCP servers.

Architecture

Four files in src/mcp-gateway/:

File Purpose
types.ts Data types: McpServerEntry, HealthCheckResult, AuditLogEntry, ApprovalRequest, GatewayConfig
gateway.ts Core gateway: rate limiter, health checks, audit logging, risk assessment
registry.ts Server registry: CRUD, filtering by tag/transport/health status
mod.ts Module barrel exports

Health Checks

healthCheck() probes each registered HTTP MCP server by sending a tools/list JSON-RPC call. Results include:

Status Criteria
healthy Server responds and tool count matches registered count
degraded Server responds but tool count differs
unhealthy Server unreachable or returns error
unknown Stdio transport (not checkable via HTTP)

Health check timeout: 10 seconds. Latency is recorded for each check.

Rate Limiting

Token bucket rate limiter (createRateLimiter()):

Parameter Description
maxRequestsPerMinute Maximum requests per minute per key
Tokens refill At rate of maxRequestsPerMinute / 60 per second
Key Arbitrary string (typically client ID or server ID)
const limiter = createRateLimiter({ maxRequestsPerMinute: 60 });
limiter.allowRequest("client-abc"); // → boolean
limiter.getAvailableTokens("client-abc"); // → number

Audit Logging

All tool calls through the gateway are logged:

Field Description
id UUID
timestamp ISO 8601
serverId MCP server ID
toolName Executed tool
clientId Requesting client
success Whether execution succeeded
latencyMs Response latency
errorCode Error code if failed
tokensUsed LLM tokens consumed

In-memory ring buffer with 10,000 entry cap. Filterable by serverId.

Approval Workflow

Risk Levels

assessRiskLevel() evaluates tool calls against pattern matching:

Level Criteria
low Read-only tools, safe operations
medium Tools containing write, delete, shell, exec
high rm -rf, DROP TABLE, DELETE FROM, format, shutdown, kill, terminate
critical DROP DATABASE, rm -rf /, TRUNCATE

Approval Requests

Field Description
id UUID
serverId Target server
toolName Tool being invoked
args Tool arguments
riskLevel Assessed risk
requestedBy Client identifier
status pending / approved / denied / expired

Configure which risk levels require approval: approvalRequiredForRisk: ["medium", "high", "critical"].

Server Registry

In-memory registry with CRUD operations:

Function Description
registerServer(entry) Add server
getServer(id) Get by ID
listServers() All servers
findServersByTag(tag) Filter by tag
updateServer(id, updates) Partial update
removeServer(id) Delete
getHealthyServers() Status === healthy
getDegradedServers() Status === degraded or unhealthy
getServersByTransport(type) Filter by stdio or http

MCP Auto-Discovery

Gateway-managed servers expose their tools through the MCP protocol. The gateway discovers available tools by calling tools/list on each registered server during health checks, storing discovered tool names and counts.

Configuration

{
  "mcpGateway": {
    "enabled": true,
    "defaultRateLimit": {
      "maxRequestsPerMinute": 60,
      "burstSize": 10
    },
    "auditEnabled": true,
    "approvalRequiredForRisk": ["high", "critical"]
  }
}

McpServerEntry Schema

{
  id: string;
  name: string;
  endpoint: string;
  transport: "stdio" | "http";
  status: "healthy" | "degraded" | "unhealthy" | "unknown";
  lastHealthCheck: string;          // ISO 8601
  authType?: "none" | "oauth2" | "apiKey" | "bearer";
  authConfig?: Record<string, string>;
  tools: string[];                  // Discovered tool names
  toolCount: number;
  rateLimit?: RateLimitConfig;
  tags?: string[];
  createdAt: string;
  updatedAt: string;
}

REST API Endpoints

Method Path Description
GET /api/mcp-gateway/servers List all registered servers
POST /api/mcp-gateway/servers Register new server
GET /api/mcp-gateway/servers/:id Get server details
PUT /api/mcp-gateway/servers/:id Update server
DELETE /api/mcp-gateway/servers/:id Remove server
POST /api/mcp-gateway/servers/:id/health Trigger health check
GET /api/mcp-gateway/audit Get audit logs (filter: ?serverId=)
POST /api/mcp-gateway/approvals Submit approval decision

See Also

Clone this wiki locally