Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(mcp): make rate-limit configurable via MCP_RATE_LIMIT_MAX / MCP_RATE_LIMIT_WINDOW_MS
Yudhi Armyndharis8dcef655d5f8
diff --git a/.env.example b/.env.exampleindex 02a45b33b..fb56ee1f3 100644--- a/.env.example+++ b/.env.example@@ -201,6 +201,21 @@ RATE_LIMIT_MEDIUM_LIMIT=100 # max requests per window# RATE_LIMIT_LONG_TTL=3600000 # 1h window (default)# RATE_LIMIT_LONG_LIMIT=1000+# =============================================================================+# MCP (Model Context Protocol) — Agent / AI-assistant tool server+# =============================================================================+# Off by default. When enabled, mounts a stateless Streamable-HTTP MCP server+# at POST /mcp on the same port. See docs/24-mcp-integration.md for details.+# MCP_ENABLED=true++# Mount read-only tools only (no sends, no mutations). Recommended for observer agents.+# MCP_READONLY=true++# Per-key sliding-window rate limit for tool calls.+# Any blank/non-positive/non-numeric value falls back to the default.+# MCP_RATE_LIMIT_MAX=60 # max tool calls per key per window (default 60)+# MCP_RATE_LIMIT_WINDOW_MS=60000 # window size in ms (default 60000 = 1 min)+# =============================================================================# PLUGINS# =============================================================================diff --git a/docs/24-mcp-integration.md b/docs/24-mcp-integration.mdindex 50b07ff60..7081e0bcd 100644--- a/docs/24-mcp-integration.md+++ b/docs/24-mcp-integration.md@@ -25,7 +25,7 @@| **Read-only mode** | ✅ Implemented | `MCP_READONLY=true` mounts read tools only || **OAuth 2.1 (public exposure)** | 🔜 Planned | Static API key is used today (suitable for self-hosted/internal) || **Agent-action audit provenance** | 🔜 Planned | Mark audited actions as agent-initiated |-| **Env-tunable rate limits** | 🔜 Planned | Limits are currently fixed defaults |+| **Env-tunable rate limits** | ✅ Implemented | `MCP_RATE_LIMIT_MAX` / `MCP_RATE_LIMIT_WINDOW_MS` || **Additional tool domains** | 🔜 Planned | labels / templates / channels / catalog / status as an opt-in expansion |---@@ -150,6 +150,9 @@ posture when an agent only needs to observe.MCP.- **Rate limiting.** A per-key limiter (keyed by the *authenticated* key id) bounds toolcalls. Buckets are pruned when idle. This is independent of the REST throttler.+ Tune with `MCP_RATE_LIMIT_MAX` (default `60`) and `MCP_RATE_LIMIT_WINDOW_MS`+ (default `60000`). Any missing, blank, non-positive, or non-numeric value falls back+ to the default.- **Response parity.** Tools reuse the REST response DTOs, so sensitive fields the RESTAPI strips (e.g. webhook HMAC secrets and custom headers, session proxy URLs and engineconfig) are **not** exposed over MCP.@@ -163,6 +166,8 @@ posture when an agent only needs to observe.MCP_ENABLED=true npm run start:prod # or set MCP_ENABLED in your .env / compose# optional:MCP_READONLY=true # read tools only+MCP_RATE_LIMIT_MAX=60 # max tool calls per key per window (default 60)+MCP_RATE_LIMIT_WINDOW_MS=60000 # sliding window in ms (default 60000 = 1 min)```Point an MCP client at `POST /mcp`. For Claude Code, a `.mcp.json` at your project root@@ -217,7 +222,6 @@ Guidelines:intended for self-hosted/internal use).- **Agent-action audit provenance** — record that an audited action was agent-initiatedand by which key.-- **Env-tunable rate limits** — the per-key limit is a fixed default today.- **Expansion-pack tool domains** — labels, templates, channels, catalog, and status arenot in the default surface yet.- **Stateful MCP sessions / SSE reconnect, prompts, elicitation** — out of scope; thediff --git a/src/modules/mcp/mcp-rate-limit.spec.ts b/src/modules/mcp/mcp-rate-limit.spec.tsindex 18917d4b8..52f176ccd 100644--- a/src/modules/mcp/mcp-rate-limit.spec.ts+++ b/src/modules/mcp/mcp-rate-limit.spec.ts@@ -1,4 +1,45 @@-import { KeyRateLimiter } from './mcp-rate-limit';+import { KeyRateLimiter, readRateLimitConfig } from './mcp-rate-limit';++describe('readRateLimitConfig', () => {+ it('returns defaults for an empty env', () => {+ expect(readRateLimitConfig({})).toEqual({ max: 60, windowMs: 60_000 });+ });++ it('parses valid numeric env values', () => {+ expect(readRateLimitConfig({ MCP_RATE_LIMIT_MAX: '120', MCP_RATE_LIMIT_WINDOW_MS: '30000' })).toEqual({+ max: 120,+ windowMs: 30_000,+ });+ });++ it('falls back to defaults for non-numeric values', () => {+ expect(readRateLimitConfig({ MCP_RATE_LIMIT_MAX: 'abc', MCP_RATE_LIMIT_WINDOW_MS: 'abc' })).toEqual({+ max: 60,+ windowMs: 60_000,+ });+ });++ it('falls back to defaults for zero', () => {+ expect(readRateLimitConfig({ MCP_RATE_LIMIT_MAX: '0', MCP_RATE_LIMIT_WINDOW_MS: '0' })).toEqual({+ max: 60,+ windowMs: 60_000,+ });+ });++ it('falls back to defaults for negative values', () => {+ expect(readRateLimitConfig({ MCP_RATE_LIMIT_MAX: '-5', MCP_RATE_LIMIT_WINDOW_MS: '-5' })).toEqual({+ max: 60,+ windowMs: 60_000,+ });+ });++ it('falls back to defaults for blank strings', () => {+ expect(readRateLimitConfig({ MCP_RATE_LIMIT_MAX: '', MCP_RATE_LIMIT_WINDOW_MS: '' })).toEqual({+ max: 60,+ windowMs: 60_000,+ });+ });+});describe('KeyRateLimiter', () => {it('allows up to max per window, then throws 429', () => {diff --git a/src/modules/mcp/mcp-rate-limit.ts b/src/modules/mcp/mcp-rate-limit.tsindex c6bc413d7..ef0d7ff57 100644--- a/src/modules/mcp/mcp-rate-limit.ts+++ b/src/modules/mcp/mcp-rate-limit.ts@@ -1,5 +1,26 @@import { HttpException, HttpStatus } from '@nestjs/common';+const DEFAULT_MAX = 60;+const DEFAULT_WINDOW_MS = 60_000;++/**+ * Read MCP rate-limit configuration from the environment.+ * Falls back to the default for any missing, blank, non-positive, or non-numeric value.+ */+export function readRateLimitConfig(env: NodeJS.ProcessEnv = process.env): { max: number; windowMs: number } {+ const parsePositiveInt = (raw: string | undefined, fallback: number): number => {+ if (!raw || raw.trim() === '') return fallback;+ const n = Number(raw);+ if (!Number.isFinite(n) || n <= 0) return fallback;+ return Math.trunc(n);+ };++ return {+ max: parsePositiveInt(env['MCP_RATE_LIMIT_MAX'], DEFAULT_MAX),+ windowMs: parsePositiveInt(env['MCP_RATE_LIMIT_WINDOW_MS'], DEFAULT_WINDOW_MS),+ };+}+/*** Per-API-key sliding window rate limiter.* The inherited IP-keyed throttler collapses all MCP calls into one 127.0.0.1 bucket,diff --git a/src/modules/mcp/mcp.module.ts b/src/modules/mcp/mcp.module.tsindex 3a9294282..a0b6c4f38 100644--- a/src/modules/mcp/mcp.module.ts+++ b/src/modules/mcp/mcp.module.ts@@ -2,14 +2,12 @@ import { type DynamicModule, Module, type MiddlewareConsumer, type NestModule }import { HttpAdapterHost } from '@nestjs/core';import { ToolRegistryService } from '../../core/agent-tools/tool-registry.service';import { AuthService } from '../auth/auth.service';-import { KeyRateLimiter } from './mcp-rate-limit';+import { KeyRateLimiter, readRateLimitConfig } from './mcp-rate-limit';import { mountMcpServer } from './mcp.server';export interface McpModuleOptions {basePath?: string;serverInfo?: { name: string; version: string };- rateLimitMax?: number;- rateLimitWindowMs?: number;}// Module-level options store: set by forRoot(), read by configure().@@ -40,8 +38,9 @@ export class McpModule implements NestModule {if (!httpAdapter) {throw new Error('McpModule: HttpAdapterHost.httpAdapter is not available.');}- const { rateLimitMax, rateLimitWindowMs, basePath, serverInfo } = _moduleOptions;- const rateLimiter = new KeyRateLimiter(rateLimitMax, rateLimitWindowMs);+ const { basePath, serverInfo } = _moduleOptions;+ const { max, windowMs } = readRateLimitConfig();+ const rateLimiter = new KeyRateLimiter(max, windowMs);mountMcpServer(httpAdapter, this.registry, this.authService, rateLimiter, { basePath, serverInfo });}}