Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated

feat(mcp): make HTTP and session rate limits configurable (#3694)

stanleycf8b6928efa2
diff --git a/v3/@claude-flow/cli/__tests__/mcp-start-rate-limit-3157.test.ts b/v3/@claude-flow/cli/__tests__/mcp-start-rate-limit-3157.test.ts
new file mode 100644
index 0000000000..f17213d5e6
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/mcp-start-rate-limit-3157.test.ts
@@ -0,0 +1,166 @@
+// #3157: `mcp start` exposes the HTTP per-IP and per-session rate limits that
+// @claude-flow/mcp used to hardcode. Out-of-range values are refused before the
+// server starts; valid ones reach MCPServerManager options.
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const h = vi.hoisted(() => ({
+ manager: {
+ on: vi.fn(),
+ start: vi.fn(),
+ stop: vi.fn(async () => {}),
+ checkHealth: vi.fn(async () => ({ healthy: true })),
+ },
+ getServerManager: vi.fn(),
+ createMCPServer: vi.fn(),
+}));
+
+vi.mock('@claude-flow/mcp', () => ({ createMCPServer: h.createMCPServer }));
+
+vi.mock('../src/mcp-server.js', () => ({
+ MCPServerManager: class {},
+ createMCPServerManager: vi.fn(),
+ getServerManager: h.getServerManager,
+ startMCPServer: vi.fn(),
+ stopMCPServer: vi.fn(),
+ getMCPServerStatus: vi.fn(async () => ({ running: false })),
+ filterAdvertisedMcpTools: (tools: unknown[]) => tools,
+ parseMcpToolSelection: () => 'all',
+ resolveMcpHttpAuthToken: () => undefined,
+}));
+
+vi.mock('../src/mcp-client.js', () => ({
+ listMCPTools: () => [],
+ callMCPTool: vi.fn(),
+ hasTool: vi.fn(),
+ getToolMetadata: vi.fn(),
+}));
+
+vi.mock('../src/runtime/parent-death-watchdog.js', () => ({ installParentDeathWatchdog: vi.fn() }));
+vi.mock('../src/prompt.js', () => ({ select: vi.fn(), confirm: vi.fn() }));
+vi.mock('../src/output.js', () => ({
+ output: {
+ writeln: vi.fn(),
+ printInfo: vi.fn(),
+ printWarning: vi.fn(),
+ printError: vi.fn(),
+ printSuccess: vi.fn(),
+ printTable: vi.fn(),
+ dim: (value: string) => value,
+ success: (value: string) => value,
+ bold: (value: string) => value,
+ },
+}));
+
+import { mcpCommand } from '../src/commands/mcp.js';
+
+describe('mcp start rate limit options (#3157)', () => {
+ const start = mcpCommand.subcommands!.find((command) => command.name === 'start')!;
+ const run = (flags: Record<string, unknown>) =>
+ start.action!({ args: [], flags, interactive: false } as never);
+
+ beforeEach(() => {
+ h.manager.start.mockReset().mockImplementation(() => new Promise(() => {}));
+ h.getServerManager.mockReset().mockReturnValue(h.manager);
+ });
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ });
+
+ it.each([
+ ['rate-limit-per-ip', 0],
+ ['rate-limit-per-ip', 100_001],
+ ['rate-limit-window-ms', 999],
+ ['rate-limit-window-ms', Number.NaN],
+ ['rate-limit-per-session', -1],
+ ['rate-limit-per-session', 1.5],
+ ['rate-limit-global-rps', 10_001],
+ ['rate-limit-global-burst', 0],
+ ])('refuses --%s %s', async (flag, value) => {
+ const result = await run({ transport: 'http', [flag]: value });
+
+ expect(result).toMatchObject({ success: false, exitCode: 1 });
+ expect(h.getServerManager).not.toHaveBeenCalled();
+ });
+
+ it('refuses an invalid value from the environment', async () => {
+ vi.stubEnv('RUFLO_MCP_RATE_LIMIT_PER_SESSION', 'lots');
+ const result = await run({ transport: 'http' });
+
+ expect(result).toMatchObject({ success: false, exitCode: 1 });
+ });
+
+ it('passes flag and environment values to the server manager', async () => {
+ vi.stubEnv('RUFLO_MCP_RATE_LIMIT_PER_SESSION', '200');
+ void run({ transport: 'http', rateLimitPerIp: 600, 'rate-limit-window-ms': 30_000, rateLimitGlobalBurst: 1000 });
+ await vi.waitFor(() => expect(h.manager.start).toHaveBeenCalled());
+
+ expect(h.getServerManager).toHaveBeenCalledWith(expect.objectContaining({
+ rateLimitPerIp: 600,
+ rateLimitWindowMs: 30_000,
+ rateLimitPerSession: 200,
+ rateLimitGlobalBurst: 1000,
+ }));
+ });
+});
+
+describe('MCPServerManager rate limit mapping (#3157)', () => {
+ const startHttp = async (options: Record<string, unknown>) => {
+ const { MCPServerManager } = await vi.importActual<typeof import('../src/mcp-server.js')>('../src/mcp-server.js');
+ h.createMCPServer.mockReset().mockReturnValue({
+ registerTools: () => ({ failed: [] }),
+ start: async () => {},
+ });
+ await (new MCPServerManager({ transport: 'http', ...options }) as any).startHttpServer();
+ return h.createMCPServer.mock.calls[0][0];
+ };
+
+ it('maps the options onto the MCP server config', async () => {
+ const config = await startHttp({ rateLimitPerIp: 600, rateLimitPerSession: 500, rateLimitGlobalBurst: 1000 });
+
+ expect(config.rateLimit).toStrictEqual({ limit: 600 });
+ expect(config.sessionRateLimit).toStrictEqual({ perSessionLimit: 500, burstSize: 1000 });
+ });
+
+ it('leaves the limits unset by default', async () => {
+ const config = await startHttp({});
+
+ expect(config.rateLimit).toBeUndefined();
+ expect(config.sessionRateLimit).toBeUndefined();
+ });
+
+ describe('on a non-loopback host', () => {
+ const token = 'a'.repeat(32);
+
+ beforeEach(() => {
+ vi.stubEnv('RUFLO_MCP_ALLOW_UNAUTHENTICATED_HTTP', '1');
+ });
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ });
+
+ it.each([
+ [{ rateLimitPerIp: 121 }],
+ [{ rateLimitWindowMs: 59_999 }],
+ [{ rateLimitPerSession: 51 }],
+ [{ rateLimitGlobalRps: 101 }],
+ [{ rateLimitGlobalBurst: 201 }],
+ ])('refuses %o above the defaults without a token', async (limits) => {
+ await expect(startHttp({ host: '0.0.0.0', ...limits })).rejects.toThrow(/Refusing to raise MCP rate limits/);
+ expect(h.createMCPServer).not.toHaveBeenCalled();
+ });
+
+ it('accepts limits at or below the defaults without a token', async () => {
+ const config = await startHttp({ host: '0.0.0.0', rateLimitPerIp: 120, rateLimitWindowMs: 120_000, rateLimitPerSession: 10 });
+
+ expect(config.rateLimit).toStrictEqual({ windowMs: 120_000, limit: 120 });
+ });
+
+ it('accepts raised limits with a token', async () => {
+ const config = await startHttp({ host: '0.0.0.0', authToken: token, rateLimitPerIp: 600, rateLimitGlobalBurst: 1000 });
+
+ expect(config.rateLimit).toStrictEqual({ limit: 600 });
+ expect(config.sessionRateLimit).toStrictEqual({ burstSize: 1000 });
+ });
+ });
+});
diff --git a/v3/@claude-flow/cli/src/commands/mcp.ts b/v3/@claude-flow/cli/src/commands/mcp.ts
index b1f33b3ba7..75dd584fd2 100644
--- a/v3/@claude-flow/cli/src/commands/mcp.ts
+++ b/v3/@claude-flow/cli/src/commands/mcp.ts
@@ -52,6 +52,16 @@ function formatUptime(seconds: number): string {
return `${hours}h ${mins}m`;
}
+function readIntegerOption(flags: CommandContext['flags'], name: string, envName: string): number | undefined {
+ const camelName = name.replace(/-([a-z])/g, (_, c: string) => c.toUpperCase());
+ const input = flags[camelName] ?? flags[name] ?? process.env[envName];
+ return input === undefined ? undefined : Number(input);
+}
+
+function isOutOfRange(value: number | undefined, min: number, max: number): boolean {
+ return value !== undefined && (!Number.isSafeInteger(value) || value < min || value > max);
+}
+
// Start MCP server
const startCommand: Command = {
name: 'start',
@@ -89,6 +99,31 @@ const startCommand: Command = {
description: 'HTTP request timeout in milliseconds (default 30000; env RUFLO_MCP_REQUEST_TIMEOUT_MS)',
type: 'number'
},
+ {
+ name: 'rate-limit-per-ip',
+ description: 'HTTP requests allowed per client IP per window (env RUFLO_MCP_RATE_LIMIT_PER_IP)',
+ type: 'number'
+ },
+ {
+ name: 'rate-limit-window-ms',
+ description: 'HTTP rate limit window in milliseconds (env RUFLO_MCP_RATE_LIMIT_WINDOW_MS)',
+ type: 'number'
+ },
+ {
+ name: 'rate-limit-per-session',
+ description: 'Request burst allowed per MCP session, refilled over 10s; also bounded by the server-wide bucket (env RUFLO_MCP_RATE_LIMIT_PER_SESSION)',
+ type: 'number'
+ },
+ {
+ name: 'rate-limit-global-rps',
+ description: 'Server-wide requests per second across all sessions (env RUFLO_MCP_RATE_LIMIT_GLOBAL_RPS)',
+ type: 'number'
+ },
+ {
+ name: 'rate-limit-global-burst',
+ description: 'Server-wide request burst across all sessions (env RUFLO_MCP_RATE_LIMIT_GLOBAL_BURST)',
+ type: 'number'
+ },
{
name: 'auth-token-file',
description: 'Read the HTTP bearer token from this file (http transport). Preferred over --auth-token; env RUFLO_MCP_HTTP_TOKEN also works',
@@ -118,6 +153,7 @@ const startCommand: Command = {
{ command: 'claude-flow mcp start', description: 'Start with defaults (stdio)' },
{ command: 'claude-flow mcp start -p 8080 -t http', description: 'Start HTTP server' },
{ command: 'claude-flow mcp start -t http --request-timeout-ms 120000', description: 'Allow slower cold-start HTTP tools' },
+ { command: 'claude-flow mcp start -t http --rate-limit-per-ip 600 --rate-limit-per-session 500 --rate-limit-global-burst 1000', description: 'Raise rate limits for a shared control plane' },
{ command: 'RUFLO_MCP_HTTP_TOKEN=<16+ chars> claude-flow mcp start -t http', description: 'HTTP server requiring "Authorization: Bearer <token>" on every request (except GET /health)' },
{ command: 'RUFLO_MCP_HTTP_TOKEN=<16+ chars> claude-flow mcp start -t http --host 0.0.0.0', description: 'Non-loopback bind: allowed only with a token (or RUFLO_MCP_ALLOW_UNAUTHENTICATED_HTTP=1)' },
{ command: 'claude-flow mcp start -d', description: 'Start as daemon' },
@@ -130,15 +166,36 @@ const startCommand: Command = {
const tools = (ctx.flags.tools as string | undefined)
|| process.env.CLAUDE_FLOW_MCP_TOOLS
|| 'all';
- const timeoutInput = ctx.flags.requestTimeoutMs
- ?? ctx.flags['request-timeout-ms']
- ?? process.env.RUFLO_MCP_REQUEST_TIMEOUT_MS;
- const requestTimeoutMs = timeoutInput === undefined ? undefined : Number(timeoutInput);
- if (requestTimeoutMs !== undefined &&
- (!Number.isSafeInteger(requestTimeoutMs) || requestTimeoutMs < 1 || requestTimeoutMs > 3_600_000)) {
+ const requestTimeoutMs = readIntegerOption(ctx.flags, 'request-timeout-ms', 'RUFLO_MCP_REQUEST_TIMEOUT_MS');
+ if (isOutOfRange(requestTimeoutMs, 1, 3_600_000)) {
output.printError('Request timeout must be an integer from 1 to 3600000 milliseconds');
return { success: false, exitCode: 1 };
}
+ const rateLimitPerIp = readIntegerOption(ctx.flags, 'rate-limit-per-ip', 'RUFLO_MCP_RATE_LIMIT_PER_IP');
+ if (isOutOfRange(rateLimitPerIp, 1, 100_000)) {
+ output.printError('HTTP rate limit must be an integer from 1 to 100000 requests per window');
+ return { success: false, exitCode: 1 };
+ }
+ const rateLimitWindowMs = readIntegerOption(ctx.flags, 'rate-limit-window-ms', 'RUFLO_MCP_RATE_LIMIT_WINDOW_MS');
+ if (isOutOfRange(rateLimitWindowMs, 1000, 3_600_000)) {
+ output.printError('Rate limit window must be an integer from 1000 to 3600000 milliseconds');
+ return { success: false, exitCode: 1 };
+ }
+ const rateLimitPerSession = readIntegerOption(ctx.flags, 'rate-limit-per-session', 'RUFLO_MCP_RATE_LIMIT_PER_SESSION');
+ if (isOutOfRange(rateLimitPerSession, 1, 10_000)) {
+ output.printError('Session rate limit must be an integer from 1 to 10000 requests');
+ return { success: false, exitCode: 1 };
+ }
+ const rateLimitGlobalRps = readIntegerOption(ctx.flags, 'rate-limit-global-rps', 'RUFLO_MCP_RATE_LIMIT_GLOBAL_RPS');
+ if (isOutOfRange(rateLimitGlobalRps, 1, 10_000)) {
+ output.printError('Global rate limit must be an integer from 1 to 10000 requests per second');
+ return { success: false, exitCode: 1 };
+ }
+ const rateLimitGlobalBurst = readIntegerOption(ctx.flags, 'rate-limit-global-burst', 'RUFLO_MCP_RATE_LIMIT_GLOBAL_BURST');
+ if (isOutOfRange(rateLimitGlobalBurst, 1, 20_000)) {
+ output.printError('Global rate limit burst must be an integer from 1 to 20000 requests');
+ return { success: false, exitCode: 1 };
+ }
let authToken: string | undefined;
try {
authToken = resolveMcpHttpAuthToken({
@@ -210,6 +267,11 @@ const startCommand: Command = {
port,
tools: !tools || tools === 'all' ? 'all' : tools.split(','),
...(requestTimeoutMs === undefined ? {} : { requestTimeoutMs }),
+ ...(rateLimitPerIp === undefined ? {} : { rateLimitPerIp }),
+ ...(rateLimitWindowMs === undefined ? {} : { rateLimitWindowMs }),
+ ...(rateLimitPerSession === undefined ? {} : { rateLimitPerSession }),
+ ...(rateLimitGlobalRps === undefined ? {} : { rateLimitGlobalRps }),
+ ...(rateLimitGlobalBurst === undefined ? {} : { rateLimitGlobalBurst }),
...(authToken ? { authToken } : {}),
daemonize: daemon,
};
diff --git a/v3/@claude-flow/cli/src/mcp-server.ts b/v3/@claude-flow/cli/src/mcp-server.ts
index 4d81d97e29..ef0a80f4f7 100644
--- a/v3/@claude-flow/cli/src/mcp-server.ts
+++ b/v3/@claude-flow/cli/src/mcp-server.ts
@@ -57,6 +57,11 @@ export interface MCPServerOptions {
daemonize?: boolean;
timeout?: number;
requestTimeoutMs?: number;
+ rateLimitPerIp?: number;
+ rateLimitWindowMs?: number;
+ rateLimitPerSession?: number;
+ rateLimitGlobalRps?: number;
+ rateLimitGlobalBurst?: number;
/**
* Bearer token every HTTP request must present (`Authorization: Bearer <token>`).
* http transport only. Prefer RUFLO_MCP_HTTP_TOKEN / a token file over this
@@ -180,6 +185,18 @@ function processStartToken(pid: number): string | undefined {
}
}
+type RateLimitOption =
+ | 'rateLimitPerIp'
+ | 'rateLimitWindowMs'
+ | 'rateLimitPerSession'
+ | 'rateLimitGlobalRps'
+ | 'rateLimitGlobalBurst';
+
+function definedFields<T extends Record<string, number | undefined>>(fields: T): Partial<T> | undefined {
+ const entries = Object.entries(fields).filter(([, value]) => value !== undefined);
+ return entries.length === 0 ? undefined : Object.fromEntries(entries) as Partial<T>;
+}
+
/**
* Hosts treated as same-machine-only for MCP HTTP tool-call authorization
* purposes (see startHttpServer's non-loopback authorization gate below).
@@ -219,6 +236,28 @@ export function shouldRefuseUnauthenticatedHttp(
return !isLoopbackHost(host) && !authenticated && !isUnauthenticatedHttpAllowed(env);
}
+/** The limits @claude-flow/mcp applies when a rate limit option is unset. */
+const DEFAULT_RATE_LIMITS = {
+ rateLimitPerIp: 120,
+ rateLimitPerSession: 50,
+ rateLimitGlobalRps: 100,
+ rateLimitGlobalBurst: 200,
+} as const;
+const DEFAULT_RATE_LIMIT_WINDOW_MS = 60_000;
+
+/**
+ * Rate limit options that are looser than the @claude-flow/mcp defaults. A
+ * shorter window counts as looser.
+ */
+function raisedRateLimits(options: Pick<MCPServerOptions, RateLimitOption>): RateLimitOption[] {
+ const raised = (Object.keys(DEFAULT_RATE_LIMITS) as (keyof typeof DEFAULT_RATE_LIMITS)[])
+ .filter((name) => (options[name] ?? 0) > DEFAULT_RATE_LIMITS[name]) as RateLimitOption[];
+ if ((options.rateLimitWindowMs ?? DEFAULT_RATE_LIMIT_WINDOW_MS) < DEFAULT_RATE_LIMIT_WINDOW_MS) {
+ raised.push('rateLimitWindowMs');
+ }
+ return raised;
+}
+
/** Printable ASCII without space (RFC 6750 token-ish), 16-512 chars. */
const AUTH_TOKEN_PATTERN = /^[\x21-\x7e]{16,512}$/;
@@ -260,9 +299,11 @@ export function resolveMcpHttpAuthToken(
}
/**
- * Default configuration
+ * Default configuration. Rate limits are left unset so @claude-flow/mcp
+ * applies its own defaults.
*/
-type ResolvedMCPServerOptions = Required<Omit<MCPServerOptions, 'authToken'>> & { authToken?: string };
+type ResolvedMCPServerOptions = Required<Omit<MCPServerOptions, RateLimitOption | 'authToken'>> &
+ Pick<MCPServerOptions, RateLimitOption | 'authToken'>;
const DEFAULT_OPTIONS: ResolvedMCPServerOptions = {
transport: 'stdio',
@@ -1034,6 +1075,17 @@ export class MCPServerManager extends EventEmitter {
'(e.g. when a trusted reverse proxy or network boundary already enforces auth).'
);
}
+ const raised = raisedRateLimits(this.options);
+ if (raised.length > 0 && !isLoopbackHost(this.options.host) && !authToken) {
+ // RUFLO_MCP_ALLOW_UNAUTHENTICATED_HTTP=1 lets an open server start, but
+ // anyone who can reach it should not also get more than the default
+ // request budget.
+ throw new Error(
+ `Refusing to raise MCP rate limits (${raised.join(', ')}) above the defaults on non-loopback ` +
+ `host "${this.options.host}" without a bearer token. Set RUFLO_MCP_HTTP_TOKEN (or ` +
+ '--auth-token-file), or bind to a loopback host (127.0.0.1, ::1, or localhost).'
+ );
+ }
// Dynamically import the MCP server package
// FIX for issue #942: Use proper package import instead of broken relative path
const { createMCPServer } = await import('@claude-flow/mcp');
@@ -1086,6 +1138,12 @@ export class MCPServerManager extends EventEmitter {
enableMetrics: true,
enableCaching: true,
requestTimeout: this.options.requestTimeoutMs,
+ rateLimit: definedFields({ windowMs: this.options.rateLimitWindowMs, limit: this.options.rateLimitPerIp }),
+ sessionRateLimit: definedFields({
+ requestsPerSecond: this.options.rateLimitGlobalRps,
+ burstSize: this.options.rateLimitGlobalBurst,
+ perSessionLimit: this.options.rateLimitPerSession,
+ }),
auth: authToken
? { enabled: true, method: 'token', tokens: [authToken] }
: undefined,
diff --git a/v3/@claude-flow/mcp/__tests__/rate-limit-config-3157.test.ts b/v3/@claude-flow/mcp/__tests__/rate-limit-config-3157.test.ts
new file mode 100644
index 0000000000..813f75ba41
--- /dev/null
+++ b/v3/@claude-flow/mcp/__tests__/rate-limit-config-3157.test.ts
@@ -0,0 +1,99 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { createServer, type AddressInfo } from 'node:net';
+import type { Server } from 'node:http';
+import { HttpTransport } from '../src/transport/http.js';
+import { createMCPServer, type MCPServer } from '../src/server.js';
+import type { ILogger } from '../src/types.js';
+
+const freePort = () => new Promise<number>((resolve) => {
+ const probe = createServer().listen(0, '127.0.0.1', () => {
+ const { port } = probe.address() as AddressInfo;
+ probe.close(() => resolve(port));
+ });
+});
+
+const post = (port: number, id: number) => fetch(`http://127.0.0.1:${port}/rpc`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ jsonrpc: '2.0', id, method: 'ping' }),
+});
+
+describe('configurable rate limits (#3157)', () => {
+ const logger: ILogger = {
+ debug: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ };
+ let transport: HttpTransport | undefined;
+ let server: MCPServer | undefined;
+
+ afterEach(async () => {
+ await transport?.stop();
+ await server?.stop();
+ transport = undefined;
+ server = undefined;
+ vi.clearAllMocks();
+ });
+
+ it('keeps 120 per window by default', async () => {
+ transport = new HttpTransport(logger, { host: '127.0.0.1', port: 0, corsEnabled: false });
+ transport.onRequest(async (request) => ({ jsonrpc: '2.0', id: request.id, result: {} }));
+ await transport.start();
+ const port = ((transport as unknown as { server: Server }).server.address() as AddressInfo).port;
+
+ for (let id = 1; id <= 120; id++) {
+ expect((await post(port, id)).status).toBe(200);
+ }
+ const rejected = await post(port, 121);
+ expect(rejected.status).toBe(429);
+ expect(await rejected.json()).toEqual({
+ jsonrpc: '2.0',
+ id: null,
+ error: { code: -32000, message: 'Rate limit exceeded' },
+ });
+ });
+
+ it('keeps the default session buckets when none are configured', () => {
+ server = createMCPServer({ transport: 'in-process' }, logger);
+
+ expect(server.getRateLimiter().getStats().config).toMatchObject({
+ requestsPerSecond: 100,
+ burstSize: 200,
+ perSessionLimit: 50,
+ });
+ });
+
+ it('lets a session burst past 200 when the global burst is raised', () => {
+ server = createMCPServer({
+ transport: 'in-process',
+ sessionRateLimit: { perSessionLimit: 500, burstSize: 1000 },
+ }, logger);
+ const limiter = server.getRateLimiter();
+
+ for (let i = 0; i < 300; i++) {
+ expect(limiter.check('session-1').allowed).toBe(true);
+ limiter.consume('session-1');
+ }
+ });
+
+ it('passes configured HTTP and session limits through MCPServerConfig', async () => {
+ const port = await freePort();
+ server = createMCPServer({
+ transport: 'http',
+ host: '127.0.0.1',
+ port,
+ rateLimit: { limit: 3 },
+ sessionRateLimit: { perSessionLimit: 500 },
+ }, logger);
+ await server.start();
+
+ expect(server.getRateLimiter().getStats().config.perSessionLimit).toBe(500);
+ for (let id = 1; id <= 3; id++) {
+ expect((await post(port, id)).status).not.toBe(429);
+ }
+ const rejected = await post(port, 4);
+ expect(rejected.status).toBe(429);
+ expect(await rejected.json()).toMatchObject({ error: { code: -32000 } });
+ });
+});
diff --git a/v3/@claude-flow/mcp/src/server.ts b/v3/@claude-flow/mcp/src/server.ts
index dac96641a3..71865a9c68 100644
--- a/v3/@claude-flow/mcp/src/server.ts
+++ b/v3/@claude-flow/mcp/src/server.ts
@@ -142,10 +142,11 @@ export class MCPServer extends EventEmitter implements IMCPServer {
taskTimeout: 300000,
});
this.transportManager = createTransportManager(logger);
+ const sessionRateLimit = this.config.sessionRateLimit;
this.rateLimiter = createRateLimiter(logger, {
- requestsPerSecond: 100,
- burstSize: 200,
- perSessionLimit: 50,
+ requestsPerSecond: sessionRateLimit?.requestsPerSecond ?? 100,
+ burstSize: sessionRateLimit?.burstSize ?? 200,
+ perSessionLimit: sessionRateLimit?.perSessionLimit ?? 50,
});
this.samplingManager = createSamplingManager(logger);
@@ -229,6 +230,7 @@ export class MCPServer extends EventEmitter implements IMCPServer {
auth: this.config.auth,
maxRequestSize: String(this.config.maxRequestSize),
requestTimeout: this.config.requestTimeout,
+ rateLimit: this.config.rateLimit,
} as any));
for (const transport of transports) {
diff --git a/v3/@claude-flow/mcp/src/types.ts b/v3/@claude-flow/mcp/src/types.ts
index 99604c69b9..b9b6bc3ee1 100644
--- a/v3/@claude-flow/mcp/src/types.ts
+++ b/v3/@claude-flow/mcp/src/types.ts
@@ -113,6 +113,17 @@ export interface MCPServerConfig {
corsOrigins?: string[];
maxRequestSize?: number;
requestTimeout?: number;
+ /** Per-client-IP limit on HTTP /rpc and /mcp (default 120 requests per 60s). */
+ rateLimit?: {
+ windowMs?: number;
+ limit?: number;
+ };
+ /** Token buckets checked per request (defaults 100/s with burst 200 server-wide, 50 per session). */
+ sessionRateLimit?: {
+ requestsPerSecond?: number;
+ burstSize?: number;
+ perSessionLimit?: number;
+ };
enableMetrics?: boolean;
enableCaching?: boolean;
cacheTTL?: number;