🌊 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
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
fix(mcp): prevent late HTTP timeout responses
Rudy Celekli9ba1cfda7541
diff --git a/v3/@claude-flow/cli/src/commands/mcp.ts b/v3/@claude-flow/cli/src/commands/mcp.tsindex 13a36d889a..0c44ccd81c 100644--- a/v3/@claude-flow/cli/src/commands/mcp.ts+++ b/v3/@claude-flow/cli/src/commands/mcp.ts@@ -82,6 +82,11 @@ const startCommand: Command = {description: 'Tools to advertise (comma-separated categories, prefixes, exact names, or "all")',type: 'string'},+ {+ name: 'request-timeout-ms',+ description: 'HTTP request timeout in milliseconds (default 30000; env RUFLO_MCP_REQUEST_TIMEOUT_MS)',+ type: 'number'+ },{name: 'daemon',short: 'd',@@ -100,6 +105,7 @@ const startCommand: Command = {examples: [{ 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 -d', description: 'Start as daemon' },{ command: 'claude-flow mcp start -f', description: 'Force restart (kill existing)' }],@@ -110,6 +116,15 @@ 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)) {+ output.printError('Request timeout must be an integer from 1 to 3600000 milliseconds');+ return { success: false, exitCode: 1 };+ }const daemon = (ctx.flags.daemon as boolean) ?? false;const force = (ctx.flags.force as boolean) ?? false;@@ -163,6 +178,7 @@ const startCommand: Command = {host,port,tools: !tools || tools === 'all' ? 'all' : tools.split(','),+ ...(requestTimeoutMs === undefined ? {} : { requestTimeoutMs }),daemonize: daemon,};diff --git a/v3/@claude-flow/cli/src/mcp-server.ts b/v3/@claude-flow/cli/src/mcp-server.tsindex 1c3f229f3c..b1963cb283 100644--- a/v3/@claude-flow/cli/src/mcp-server.ts+++ b/v3/@claude-flow/cli/src/mcp-server.ts@@ -49,6 +49,7 @@ export interface MCPServerOptions {tools?: string[] | 'all';daemonize?: boolean;timeout?: number;+ requestTimeoutMs?: number;}/**@@ -82,6 +83,7 @@ const DEFAULT_OPTIONS: Required<MCPServerOptions> = {tools: 'all',daemonize: false,timeout: 30000,+ requestTimeoutMs: 30000,};export function parseMcpToolSelection(value: string | undefined): string[] | 'all' {@@ -774,6 +776,7 @@ export class MCPServerManager extends EventEmitter {port: this.options.port,enableMetrics: true,enableCaching: true,+ requestTimeout: this.options.requestTimeoutMs,},logger);diff --git a/v3/@claude-flow/mcp/__tests__/http-transport-timeout-3158.test.ts b/v3/@claude-flow/mcp/__tests__/http-transport-timeout-3158.test.tsnew file mode 100644index 0000000000..0370094fc9--- /dev/null+++ b/v3/@claude-flow/mcp/__tests__/http-transport-timeout-3158.test.ts@@ -0,0 +1,87 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import type { AddressInfo } from 'node:net';+import type { Server } from 'node:http';+import { HttpTransport } from '../src/transport/http.js';+import type { ILogger, MCPResponse } from '../src/types.js';++describe('HTTP request timeout (#3158)', () => {+ const logger: ILogger = {+ debug: vi.fn(),+ info: vi.fn(),+ warn: vi.fn(),+ error: vi.fn(),+ };+ let transport: HttpTransport | undefined;++ afterEach(async () => {+ await transport?.stop();+ transport = undefined;+ vi.clearAllMocks();+ });++ it('sends one timeout response and ignores a tool result that arrives afterward', async () => {+ transport = new HttpTransport(logger, {+ host: '127.0.0.1',+ port: 0,+ corsEnabled: false,+ requestTimeout: 100,+ });+ let finish!: (response: MCPResponse) => void;+ const work = new Promise<MCPResponse>((resolve) => { finish = resolve; });+ transport.onRequest(async () => await work);+ await transport.start();++ const port = ((transport as unknown as { server: Server }).server.address() as AddressInfo).port;+ const url = `http://127.0.0.1:${port}/rpc`;+ const request = { jsonrpc: '2.0', id: 17, method: 'tools/call', params: { name: 'memory_store' } };+ const timedOut = await fetch(url, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify(request),+ });+ expect(timedOut.status).toBe(408);+ const timeoutBody = await timedOut.json();++ finish({ jsonrpc: '2.0', id: 17, result: { stored: true } });+ await new Promise<void>((resolve) => setImmediate(resolve));+ expect(logger.error).not.toHaveBeenCalled();+ expect(timeoutBody).toMatchObject({ id: 17, error: { code: -32000, message: 'Request timeout' } });+ expect((await transport.getHealthStatus()).metrics?.messagesSent).toBe(0);++ // The timed-out request must not poison the next HTTP request.+ transport.onRequest(async (next) => ({ jsonrpc: '2.0', id: next.id, result: { ok: true } }));+ const followUp = await fetch(url, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ ...request, id: 18 }),+ });+ expect(followUp.status).toBe(200);+ expect(await followUp.json()).toMatchObject({ id: 18, result: { ok: true } });+ });++ it('does not try to send a second error when a timed-out tool rejects', async () => {+ transport = new HttpTransport(logger, {+ host: '127.0.0.1',+ port: 0,+ corsEnabled: false,+ requestTimeout: 100,+ });+ let fail!: (error: Error) => void;+ const work = new Promise<MCPResponse>((_resolve, reject) => { fail = reject; });+ transport.onRequest(async () => await work);+ await transport.start();++ const port = ((transport as unknown as { server: Server }).server.address() as AddressInfo).port;+ const response = await fetch(`http://127.0.0.1:${port}/mcp`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ jsonrpc: '2.0', id: 19, method: 'tools/call' }),+ });+ expect(response.status).toBe(408);+ await response.json();++ fail(new Error('late tool failure'));+ await new Promise<void>((resolve) => setImmediate(resolve));+ expect(logger.error).not.toHaveBeenCalled();+ });+});diff --git a/v3/@claude-flow/mcp/src/transport/http.ts b/v3/@claude-flow/mcp/src/transport/http.tsindex e9a611ea5d..77cb22e5e1 100644--- a/v3/@claude-flow/mcp/src/transport/http.ts+++ b/v3/@claude-flow/mcp/src/transport/http.ts@@ -239,9 +239,11 @@ export class HttpTransport extends EventEmitter implements ITransport {if (this.config.requestTimeout) {this.app.use((req, res, next) => {res.setTimeout(this.config.requestTimeout!, () => {+ // A handler may have completed just as the socket timeout fired.+ if (res.headersSent || res.writableEnded || res.destroyed) return;res.status(408).json({jsonrpc: '2.0',- id: null,+ id: req.body?.id ?? null,error: { code: -32000, message: 'Request timeout' },});});@@ -331,6 +333,7 @@ export class HttpTransport extends EventEmitter implements ITransport {this.app.use((err: Error, req: Request, res: Response, next: NextFunction) => {this.logger.error('Express error', { error: err });this.errors++;+ if (res.headersSent || res.writableEnded || res.destroyed) return;res.status(500).json({jsonrpc: '2.0',id: null,@@ -450,6 +453,7 @@ export class HttpTransport extends EventEmitter implements ITransport {if (this.notificationHandler) {await this.notificationHandler(message as MCPNotification);}+ if (res.headersSent || res.writableEnded || res.destroyed) return;res.status(sseResponse ? 202 : 204).end();} else {if (!this.requestHandler) {@@ -463,6 +467,9 @@ export class HttpTransport extends EventEmitter implements ITransport {try {const response = await this.requestHandler(message as MCPRequest);+ // A timed-out request can still finish its tool work; its HTTP reply+ // already belongs to the timeout path and must not be written again.+ if (res.headersSent || res.writableEnded || res.destroyed) return;if (sseResponse) {sseResponse.write(`event: message\ndata: ${JSON.stringify(response)}\n\n`);res.status(202).end();@@ -472,6 +479,7 @@ export class HttpTransport extends EventEmitter implements ITransport {this.messagesSent++;} catch (error) {this.errors++;+ if (res.headersSent || res.writableEnded || res.destroyed) return;res.status(500).json({jsonrpc: '2.0',id: message.id,