SecurityTraffic Control

Rate Limits

Dual-layer rate limiting combining per-user application sliding windows, isolated Nginx IP zones, and trusted-proxy Cloudflare IP restoration.

Per-user application sliding windows

Authenticated MCP tool traffic is bucketed per verified ctx.userId inside mcp/src/security/rateLimit.ts using sliding 60-second windows segmented by operational risk class. Because buckets are keyed by userId rather than client session, rotating tokens or opening parallel AI sessions cannot multiply throughput.

BucketWindow LimitCovered Operations
read60 requests / minuteAll mcp:read tools (discovery, configuration reads, preview_setup, setup status, logs/analytics)
write20 requests / minuteStandard configure_* tools and non-destructive apply_setup mutations
deploy10 requests / minutedeploy_discord_panel (panel deployments, edits, test dispatches, rules ingestion sync)
destructive5 requests / minutePanel/command/item deletions and structural Discord auto-setup executions
RATE_LIMITED tool response payloadjson
{
  "ok": false,
  "error": {
    "code": "RATE_LIMITED",
    "message": "Too many requests in a short period. Please wait a moment and try again.",
    "retryAfterSeconds": 18
  }
}

Nginx edge rate-limit zones

Before requests reach Node.js on 127.0.0.1:4130, nginx/mcp.taicket.xyz.conf applies two isolated limit_req_zone buckets keyed by real client IP ($binary_remote_addr) with HTTP 429 responses (limit_req_status 429).

Nginx ZoneSustained RateBurstApplied Locations
taicket_mcp_limit25 req/s per IP50 nodelay (/mcp, /), 30 nodelay (/.well-known/)/mcp, /.well-known/*, /, /docs/*, /health
taicket_mcp_oauth_limit10 req/s per IP20 nodelay/oauth/*, /account, /account/*
Rate limit zones in nginx/mcp.taicket.xyz.conftext
limit_req_zone $binary_remote_addr zone=taicket_mcp_limit:10m rate=25r/s;
limit_req_zone $binary_remote_addr zone=taicket_mcp_oauth_limit:10m rate=10r/s;

location = /mcp {
    limit_req zone=taicket_mcp_limit burst=50 nodelay;
    limit_req_status 429;
}

location ^~ /oauth/ {
    limit_req zone=taicket_mcp_oauth_limit burst=20 nodelay;
    limit_req_status 429;
}

Trusted-proxy Cloudflare IP handling

Rate limiting and audit IP hashing depend on accurate client IP extraction that cannot be spoofed by untrusted callers injecting fake CF-Connecting-IP or X-Forwarded-For headers.

  • Cloudflare CIDR validation at Nginx:: nginx/mcp.taicket.xyz.conf declares set_real_ip_from for all 15 official Cloudflare IPv4 CIDRs and 7 official Cloudflare IPv6 CIDRs alongside real_ip_header CF-Connecting-IP. Nginx then sets proxy_set_header CF-Connecting-IP $remote_addr, overwriting any spoofed header from direct-to-origin traffic.
  • Loopback-only trust in Express:: Inside mcp/src/security/rateLimit.ts, the requestIp helper inspects req.socket.remoteAddress. It honors CF-Connecting-IP or X-Forwarded-For ONLY when the TCP peer is loopback (127.0.0.1, ::1, or ::ffff:127.0.0.1). Any direct non-loopback connection ignores proxy headers completely.
Loopback-restricted client IP extractiontypescript
import type { Request } from 'express';

const LOOPBACK_PEERS = new Set(['127.0.0.1', '::1', '::ffff:127.0.0.1']);

export function extractClientIp(req: Request): string {
  const peer = req.socket.remoteAddress ?? '';
  if (LOOPBACK_PEERS.has(peer)) {
    const cfIp = req.header('cf-connecting-ip')?.trim();
    if (cfIp) return cfIp;
    const xff = req.header('x-forwarded-for')?.split(',')[0]?.trim();
    if (xff) return xff;
  }
  return peer || 'unknown';
}

Client retry and backoff guidance

Integrations that encounter HTTP 429 from Nginx or a RATE_LIMITED tool response should honor retryAfterSeconds and apply jittered exponential backoff rather than tight retry loops.

Python client handling HTTP 429 and RATE_LIMITED responsespython
import time
import random
import urllib.request
import urllib.error
import json

def call_mcp_with_backoff(url: str, token: str, payload: dict, max_attempts: int = 4) -> dict:
    body = json.dumps(payload).encode("utf-8")
    for attempt in range(max_attempts):
        req = urllib.request.Request(
            url,
            data=body,
            headers={
                "Authorization": f"Bearer {token}",
                "Content-Type": "application/json",
                "Accept": "application/json, text/event-stream",
            },
            method="POST",
        )
        try:
            with urllib.request.urlopen(req, timeout=30) as resp:
                return json.loads(resp.read().decode("utf-8"))
        except urllib.error.HTTPError as exc:
            if exc.code == 429 and attempt < max_attempts - 1:
                retry_after = float(exc.headers.get("Retry-After", 2 ** attempt))
                time.sleep(retry_after + random.uniform(0.1, 0.5))
                continue
            raise
    raise RuntimeError("Exceeded maximum retry attempts")

Related documentation