Rate limit dynamic client registration per source address

Replace the process-wide registration counter used without Redis with a
shared per-key fixed-window limiter, so one requester can no longer
exhaust the registration budget for every other client on the process.
The in-memory fallback is bounded (expired windows are swept, then the
oldest keys are shed) so memory stays constant under key churn.

Also fixes checkMcpRateLimit inverting redis.rateLimit's result: it
resolves true once the counter reaches its threshold, so with Redis the
MCP endpoint was denying requests below the limit and allowing those
above it. Both call sites now share the same limiter and semantics.
This commit is contained in:
Mike Cao committed 2026-09-05 17:57:20 -07:00
1 parent 67449d76ef
commit d2b4aa174e
5 files changed
+229 -60

No files matched your search

+5 -33
View File
@@ -1,9 +1,7 @@
import redis from '@/lib/redis';
import { checkRateLimit, resetRateLimits } from '@/lib/rate-limit';
export const MCP_RATE_LIMIT_WINDOW_SECONDS = 60;
const memory = new Map<string, { count: number; resetAt: number }>();
export function getMcpRateLimit() {
const configured = Number(process.env.MCP_RATE_LIMIT);
@@ -12,43 +10,17 @@ export function getMcpRateLimit() {
/**
* Per-user, per-client limit for MCP requests. Keyed by identity rather than IP because remote
* MCP platforms share egress addresses. Uses Redis when available, otherwise a process-local
* fixed window (sufficient for single-instance self-hosted deployments).
* MCP platforms share egress addresses. Resolves `true` while the request is within the limit.
*/
export async function checkMcpRateLimit(
export function checkMcpRateLimit(
userId: string,
clientId: string,
limit = getMcpRateLimit(),
windowSeconds = MCP_RATE_LIMIT_WINDOW_SECONDS,
): Promise<boolean> {
const key = `mcp:rate:${userId}:${clientId}`;
if (redis.enabled) {
return redis.client.rateLimit(key, limit, windowSeconds);
}
const now = Date.now();
const entry = memory.get(key);
if (!entry || entry.resetAt <= now) {
memory.set(key, { count: 1, resetAt: now + windowSeconds * 1000 });
if (memory.size > 10_000) {
for (const [k, v] of memory) {
if (v.resetAt <= now) {
memory.delete(k);
}
}
}
return true;
}
entry.count += 1;
return entry.count <= limit;
return checkRateLimit(`mcp:rate:${userId}:${clientId}`, limit, windowSeconds);
}
export function resetMcpRateLimits() {
memory.clear();
resetRateLimits();
}