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

fix(mcp): share state across HTTP transports

dajiaohuang6b8f0d0b5ac6
diff --git a/v3/@claude-flow/cli/__tests__/mcp-http-protocol-tools-2990.test.ts b/v3/@claude-flow/cli/__tests__/mcp-http-protocol-tools-2990.test.ts
index 252f118d66..a737101a8a 100644
--- a/v3/@claude-flow/cli/__tests__/mcp-http-protocol-tools-2990.test.ts
+++ b/v3/@claude-flow/cli/__tests__/mcp-http-protocol-tools-2990.test.ts
@@ -4,7 +4,7 @@
// dependency pinning, HTTP registration, dispatch, and the default bind are
// covered together.
-import { afterEach, describe, expect, it } from 'vitest';
+import { afterEach, beforeAll, describe, expect, it } from 'vitest';
import { spawn, type ChildProcessWithoutNullStreams } from 'node:child_process';
import * as fs from 'node:fs';
import * as path from 'node:path';
@@ -54,8 +54,8 @@ function waitForOutput(
});
}
-async function postJson(port: number, endpoint: string, body: unknown): Promise<any> {
- const response = await fetch(`http://127.0.0.1:${port}${endpoint}`, {
+async function postJson(port: number, endpoint: string, body: unknown, host = '127.0.0.1'): Promise<any> {
+ const response = await fetch(`http://${host.includes(':') ? `[${host}]` : host}:${port}${endpoint}`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(body),
@@ -79,7 +79,13 @@ async function startHttpCli(port: number, tools: string): Promise<void> {
await waitForOutput(child, 'MCP Server started', 20_000);
}
-describe.skipIf(!CLI_BUILT)('MCP HTTP protocol and tool registry (#2990, end-to-end)', () => {
+describe('MCP HTTP protocol and tool registry (#2990, end-to-end)', () => {
+ beforeAll(() => {
+ if (!CLI_BUILT) {
+ throw new Error(`Built CLI required for end-to-end coverage: ${CLI}`);
+ }
+ });
+
it('serves a spec-valid protocol string and the executable CLI tools on both RPC paths', async () => {
const port = 34000 + Math.floor(Math.random() * 4000);
await startHttpCli(port, 'all');
@@ -89,33 +95,33 @@ describe.skipIf(!CLI_BUILT)('MCP HTTP protocol and tool registry (#2990, end-to-
const ipv6Health = await fetch(`http://[::1]:${port}/health`);
expect(ipv6Health.status).toBe(200);
- for (const endpoint of ['/mcp', '/rpc']) {
- const initialized = await postJson(port, endpoint, {
- jsonrpc: '2.0',
- id: 1,
- method: 'initialize',
- params: {
- protocolVersion: '2024-11-05',
- capabilities: {},
- clientInfo: { name: 'ruflo-http-regression', version: '1.0.0' },
- },
- });
- expect(initialized.result.protocolVersion).toBe('2025-11-25');
+ const initialized = await postJson(port, '/mcp', {
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'initialize',
+ params: {
+ protocolVersion: '2024-11-05',
+ capabilities: {},
+ clientInfo: { name: 'ruflo-http-regression', version: '1.0.0' },
+ },
+ });
+ expect(initialized.result.protocolVersion).toBe('2025-11-25');
- const listed = await postJson(port, endpoint, {
- jsonrpc: '2.0',
- id: 2,
- method: 'tools/list',
- });
- const names = listed.result.tools.map((tool: { name: string }) => tool.name);
- expect(names.length).toBeGreaterThan(300);
- expect(names).toEqual(expect.arrayContaining([
- 'agent_spawn',
- 'swarm_init',
- 'memory_store',
- 'system_info',
- ]));
- }
+ // Initialize through IPv4, then call the alternate RPC path through IPv6.
+ // Independent server instances would reject this as an uninitialized session.
+ const listed = await postJson(port, '/rpc', {
+ jsonrpc: '2.0',
+ id: 2,
+ method: 'tools/list',
+ }, '::1');
+ const names = listed.result.tools.map((tool: { name: string }) => tool.name);
+ expect(names.length).toBeGreaterThan(300);
+ expect(names).toEqual(expect.arrayContaining([
+ 'agent_spawn',
+ 'swarm_init',
+ 'memory_store',
+ 'system_info',
+ ]));
const called = await postJson(port, '/mcp', {
jsonrpc: '2.0',
@@ -154,4 +160,48 @@ describe.skipIf(!CLI_BUILT)('MCP HTTP protocol and tool registry (#2990, end-to-
expect(names).toContain('memory_store');
expect(names).not.toContain('agent_spawn');
}, 30_000);
+
+ it('supports the legacy SSE fallback on GET /mcp', async () => {
+ const port = 32000 + Math.floor(Math.random() * 1500);
+ await startHttpCli(port, 'memory');
+
+ const controller = new AbortController();
+ const streamResponse = await fetch(`http://127.0.0.1:${port}/mcp`, {
+ headers: { accept: 'text/event-stream' },
+ signal: controller.signal,
+ });
+ expect(streamResponse.status).toBe(200);
+ expect(streamResponse.headers.get('content-type')).toContain('text/event-stream');
+ const reader = streamResponse.body!.getReader();
+ const decoder = new TextDecoder();
+ let received = decoder.decode((await reader.read()).value, { stream: true });
+ expect(received).toContain('event: endpoint');
+ const endpoint = received.match(/data: (\/mcp\?sessionId=[^\r\n]+)/)?.[1];
+ expect(endpoint).toBeTruthy();
+
+ const accepted = await fetch(`http://127.0.0.1:${port}${endpoint}`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'initialize',
+ params: {
+ protocolVersion: '2024-11-05',
+ capabilities: {},
+ clientInfo: { name: 'ruflo-sse-regression', version: '1.0.0' },
+ },
+ }),
+ });
+ expect(accepted.status).toBe(202);
+
+ while (!received.includes('event: message')) {
+ const chunk = await reader.read();
+ if (chunk.done) break;
+ received += decoder.decode(chunk.value, { stream: true });
+ }
+ expect(received).toContain('event: message');
+ expect(received).toContain('"protocolVersion":"2025-11-25"');
+ controller.abort();
+ }, 30_000);
});
diff --git a/v3/@claude-flow/cli/src/mcp-server.ts b/v3/@claude-flow/cli/src/mcp-server.ts
index 248ee3e00d..efe115d92f 100644
--- a/v3/@claude-flow/cli/src/mcp-server.ts
+++ b/v3/@claude-flow/cli/src/mcp-server.ts
@@ -744,46 +744,30 @@ export class MCPServerManager extends EventEmitter {
},
}));
- // A hostname often resolves to only one address when passed to listen().
- // Bind both loopback families for the default without exposing the server
- // on external interfaces. Explicit --host values retain single-bind
- // semantics.
- const hosts = this.options.host === 'localhost'
- ? ['127.0.0.1', '::1']
- : [this.options.host];
- const servers = hosts.map((host) => {
- const server = createMCPServer(
- {
- name: 'Claude-Flow MCP Server V3',
- version: '3.0.0',
- transport: this.options.transport as 'http' | 'websocket',
- host,
- port: this.options.port,
- enableMetrics: true,
- enableCaching: true,
- },
- logger
- );
- const registration = server.registerTools(
- cliTools as Parameters<typeof server.registerTools>[0]
- );
- if (registration.failed.length > 0) {
- throw new Error(`Failed to register MCP tools: ${registration.failed.join(', ')}`);
- }
- return server;
- });
-
- const startedServers: typeof servers = [];
- try {
- for (const server of servers) {
- await server.start();
- startedServers.push(server);
- }
- } catch (error) {
- await Promise.all(startedServers.map((server) => server.stop()));
- throw error;
+ // Use one MCP server with two HTTP transports for the localhost default.
+ // Both loopback sockets therefore share sessions, tools, and notifications.
+ const dualLoopback = this.options.host === 'localhost';
+ const mcpServer = createMCPServer(
+ {
+ name: 'Claude-Flow MCP Server V3',
+ version: '3.0.0',
+ transport: this.options.transport as 'http' | 'websocket',
+ host: dualLoopback ? '127.0.0.1' : this.options.host,
+ additionalHosts: dualLoopback && this.options.transport === 'http' ? ['::1'] : undefined,
+ port: this.options.port,
+ enableMetrics: true,
+ enableCaching: true,
+ },
+ logger
+ );
+ const registration = mcpServer.registerTools(
+ cliTools as Parameters<typeof mcpServer.registerTools>[0]
+ );
+ if (registration.failed.length > 0) {
+ throw new Error(`Failed to register MCP tools: ${registration.failed.join(', ')}`);
}
- this.mcpServers = startedServers;
+ await mcpServer.start();
+ this.mcpServers = [mcpServer];
}
/**
diff --git a/v3/@claude-flow/mcp/src/server.ts b/v3/@claude-flow/mcp/src/server.ts
index 9f4f74edc3..dac96641a3 100644
--- a/v3/@claude-flow/mcp/src/server.ts
+++ b/v3/@claude-flow/mcp/src/server.ts
@@ -80,7 +80,7 @@ export class MCPServer extends EventEmitter implements IMCPServer {
private readonly transportManager: TransportManager;
private readonly rateLimiter: RateLimiter;
private readonly samplingManager: SamplingManager;
- private transport?: ITransport;
+ private transports: ITransport[] = [];
private running = false;
private startTime?: Date;
private startupDuration?: number;
@@ -217,26 +217,38 @@ export class MCPServer extends EventEmitter implements IMCPServer {
});
try {
- this.transport = createTransport(this.config.transport, this.logger, {
+ const hosts = this.config.transport === 'http'
+ ? [...new Set([this.config.host, ...(this.config.additionalHosts ?? [])])]
+ : [this.config.host];
+ const transports = hosts.map((host) => createTransport(this.config.transport, this.logger, {
type: this.config.transport,
- host: this.config.host,
+ host,
port: this.config.port,
corsEnabled: this.config.corsEnabled,
corsOrigins: this.config.corsOrigins,
auth: this.config.auth,
maxRequestSize: String(this.config.maxRequestSize),
requestTimeout: this.config.requestTimeout,
- } as any);
+ } as any));
- this.transport.onRequest(async (request) => {
- return await this.handleRequest(request);
- });
-
- this.transport.onNotification(async (notification) => {
- await this.handleNotification(notification);
- });
+ for (const transport of transports) {
+ transport.onRequest(async (request) => await this.handleRequest(request));
+ transport.onNotification(async (notification) => {
+ await this.handleNotification(notification);
+ });
+ }
- await this.transport.start();
+ const started: ITransport[] = [];
+ try {
+ for (const transport of transports) {
+ await transport.start();
+ started.push(transport);
+ }
+ } catch (error) {
+ await Promise.all(started.map((transport) => transport.stop()));
+ throw error;
+ }
+ this.transports = started;
await this.registerBuiltInTools();
this.running = true;
@@ -266,9 +278,10 @@ export class MCPServer extends EventEmitter implements IMCPServer {
this.logger.info('Stopping MCP server');
try {
- if (this.transport) {
- await this.transport.stop();
- this.transport = undefined;
+ if (this.transports.length > 0) {
+ const transports = this.transports;
+ this.transports = [];
+ await Promise.all(transports.map((transport) => transport.stop()));
}
this.sessionManager.clearAll();
@@ -317,9 +330,9 @@ export class MCPServer extends EventEmitter implements IMCPServer {
metrics?: Record<string, number>;
}> {
try {
- const transportHealth = this.transport
- ? await this.transport.getHealthStatus()
- : { healthy: false, error: 'Transport not initialized' };
+ const transportHealth = this.transports.length > 0
+ ? await Promise.all(this.transports.map((transport) => transport.getHealthStatus()))
+ : [{ healthy: false, error: 'Transport not initialized' }];
const sessionMetrics = this.sessionManager.getSessionMetrics();
const poolStats = this.connectionPool?.getStats();
@@ -331,7 +344,7 @@ export class MCPServer extends EventEmitter implements IMCPServer {
failedRequests: this.requestStats.failed,
totalSessions: sessionMetrics.total,
activeSessions: sessionMetrics.active,
- ...(transportHealth.metrics || {}),
+ ...Object.assign({}, ...transportHealth.map((health) => health.metrics || {})),
};
if (poolStats) {
@@ -341,8 +354,8 @@ export class MCPServer extends EventEmitter implements IMCPServer {
}
return {
- healthy: this.running && transportHealth.healthy,
- error: transportHealth.error,
+ healthy: this.running && transportHealth.every((health) => health.healthy),
+ error: transportHealth.map((health) => health.error).filter(Boolean).join('; ') || undefined,
metrics,
};
@@ -1016,13 +1029,11 @@ export class MCPServer extends EventEmitter implements IMCPServer {
// ============================================================================
private async sendNotification(method: string, params?: Record<string, unknown>): Promise<void> {
- if (this.transport?.sendNotification) {
- await this.transport.sendNotification({
- jsonrpc: '2.0',
- method,
- params,
- });
- }
+ await Promise.all(this.transports.map(async (transport) => {
+ if (transport.sendNotification) {
+ await transport.sendNotification({ jsonrpc: '2.0', method, params });
+ }
+ }));
}
private getOrCreateSession(): MCPSession {
diff --git a/v3/@claude-flow/mcp/src/transport/http.ts b/v3/@claude-flow/mcp/src/transport/http.ts
index 6426f664ff..a01c2ac909 100644
--- a/v3/@claude-flow/mcp/src/transport/http.ts
+++ b/v3/@claude-flow/mcp/src/transport/http.ts
@@ -10,6 +10,7 @@ import { createServer, Server } from 'http';
import { WebSocketServer, WebSocket } from 'ws';
import cors from 'cors';
import helmet from 'helmet';
+import { randomUUID } from 'crypto';
import type {
ITransport,
TransportType,
@@ -46,6 +47,7 @@ export class HttpTransport extends EventEmitter implements ITransport {
private wss?: WebSocketServer;
private running = false;
private activeConnections = new Set<WebSocket>();
+ private sseClients = new Map<string, Response>();
private messagesReceived = 0;
private messagesSent = 0;
@@ -112,6 +114,11 @@ export class HttpTransport extends EventEmitter implements ITransport {
}
this.activeConnections.clear();
+ for (const response of this.sseClients.values()) {
+ response.end();
+ }
+ this.sseClients.clear();
+
if (this.wss) {
this.wss.close();
this.wss = undefined;
@@ -163,6 +170,11 @@ export class HttpTransport extends EventEmitter implements ITransport {
this.errors++;
}
}
+
+ for (const response of this.sseClients.values()) {
+ response.write(`event: message\ndata: ${message}\n\n`);
+ this.messagesSent++;
+ }
}
private setupMiddleware(): void {
@@ -246,6 +258,34 @@ export class HttpTransport extends EventEmitter implements ITransport {
await this.handleHttpRequest(req, res);
});
+ // Legacy MCP clients fall back to the HTTP+SSE transport when
+ // Streamable HTTP negotiation fails. Advertise this same POST endpoint
+ // and route its responses back over the established event stream.
+ this.app.get('/mcp', (req, res) => {
+ if (this.config.auth?.enabled) {
+ const authResult = this.validateAuth(req);
+ if (!authResult.valid) {
+ res.status(401).json({ error: authResult.error || 'Unauthorized' });
+ return;
+ }
+ }
+
+ const sessionId = randomUUID();
+ res.status(200);
+ res.setHeader('Content-Type', 'text/event-stream');
+ res.setHeader('Cache-Control', 'no-cache, no-transform');
+ res.setHeader('Connection', 'keep-alive');
+ res.flushHeaders();
+ this.sseClients.set(sessionId, res);
+ res.write(`event: endpoint\ndata: /mcp?sessionId=${encodeURIComponent(sessionId)}\n\n`);
+
+ res.on('close', () => {
+ if (this.sseClients.get(sessionId) === res) {
+ this.sseClients.delete(sessionId);
+ }
+ });
+ });
+
this.app.post('/mcp', async (req, res) => {
await this.handleHttpRequest(req, res);
});
@@ -384,11 +424,14 @@ export class HttpTransport extends EventEmitter implements ITransport {
return;
}
+ const sseSessionId = typeof req.query.sessionId === 'string' ? req.query.sessionId : undefined;
+ const sseResponse = sseSessionId ? this.sseClients.get(sseSessionId) : undefined;
+
if (message.id === undefined) {
if (this.notificationHandler) {
await this.notificationHandler(message as MCPNotification);
}
- res.status(204).end();
+ res.status(sseResponse ? 202 : 204).end();
} else {
if (!this.requestHandler) {
res.status(500).json({
@@ -401,7 +444,12 @@ export class HttpTransport extends EventEmitter implements ITransport {
try {
const response = await this.requestHandler(message as MCPRequest);
- res.json(response);
+ if (sseResponse) {
+ sseResponse.write(`event: message\ndata: ${JSON.stringify(response)}\n\n`);
+ res.status(202).end();
+ } else {
+ res.json(response);
+ }
this.messagesSent++;
} catch (error) {
this.errors++;
diff --git a/v3/@claude-flow/mcp/src/types.ts b/v3/@claude-flow/mcp/src/types.ts
index e660f4fa03..99604c69b9 100644
--- a/v3/@claude-flow/mcp/src/types.ts
+++ b/v3/@claude-flow/mcp/src/types.ts
@@ -100,6 +100,8 @@ export interface MCPServerConfig {
version: string;
transport: TransportType;
host?: string;
+ /** Additional HTTP bind addresses that share the same MCP server state. */
+ additionalHosts?: string[];
port?: number;
tlsEnabled?: boolean;
tlsCert?: string;