🌊 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): restore HTTP protocol and CLI tools
dajiaohuang2dbb790a0b8a
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.tsnew file mode 100644index 0000000000..252f118d66--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/mcp-http-protocol-tools-2990.test.ts@@ -0,0 +1,157 @@+// #2990: the published HTTP transport completed startup but returned an+// object-valued protocolVersion and exposed only @claude-flow/mcp's four+// built-in diagnostic tools. This end-to-end test exercises the built CLI so+// dependency pinning, HTTP registration, dispatch, and the default bind are+// covered together.++import { afterEach, 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';+import { fileURLToPath } from 'node:url';++const HERE = path.dirname(fileURLToPath(import.meta.url));+const CLI = path.resolve(HERE, '..', 'bin', 'cli.js');+const CLI_BUILT = fs.existsSync(CLI);+const TEST_TMP = path.resolve(HERE, '..', '..', '..', '..', '.tmp-2990', 'test-runtime');++let child: ChildProcessWithoutNullStreams | undefined;++afterEach(() => {+ if (child && child.exitCode === null && child.signalCode === null) {+ child.kill('SIGKILL');+ }+ child = undefined;+});++function waitForOutput(+ proc: ChildProcessWithoutNullStreams,+ match: string,+ timeoutMs: number,+): Promise<void> {+ return new Promise((resolve, reject) => {+ let stdout = '';+ let stderr = '';+ const timer = setTimeout(() => {+ reject(new Error(`timed out waiting for "${match}"\nstdout: ${stdout}\nstderr: ${stderr}`));+ }, timeoutMs);+ const onStdout = (chunk: Buffer) => {+ stdout += chunk.toString();+ if (stdout.includes(match)) {+ clearTimeout(timer);+ proc.stdout.off('data', onStdout);+ resolve();+ }+ };+ proc.stdout.on('data', onStdout);+ proc.stderr.on('data', (chunk: Buffer) => {+ stderr += chunk.toString();+ });+ proc.once('exit', (code, signal) => {+ clearTimeout(timer);+ reject(new Error(`process exited before startup (code=${code}, signal=${signal})\nstdout: ${stdout}\nstderr: ${stderr}`));+ });+ });+}++async function postJson(port: number, endpoint: string, body: unknown): Promise<any> {+ const response = await fetch(`http://127.0.0.1:${port}${endpoint}`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify(body),+ });+ expect(response.status).toBe(200);+ return await response.json();+}++async function startHttpCli(port: number, tools: string): Promise<void> {+ fs.mkdirSync(TEST_TMP, { recursive: true });+ child = spawn('node', [CLI, 'mcp', 'start', '-t', 'http', '--port', String(port)], {+ env: {+ ...process.env,+ CLAUDE_FLOW_MCP_TOOLS: tools,+ RUFLO_DAEMON_AUTOSTART: '0',+ TEMP: TEST_TMP,+ TMP: TEST_TMP,+ },+ stdio: ['ignore', 'pipe', 'pipe'],+ });+ await waitForOutput(child, 'MCP Server started', 20_000);+}++describe.skipIf(!CLI_BUILT)('MCP HTTP protocol and tool registry (#2990, end-to-end)', () => {+ 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');++ const health = await fetch(`http://127.0.0.1:${port}/health`);+ expect(health.status).toBe(200);+ 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 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',+ ]));+ }++ const called = await postJson(port, '/mcp', {+ jsonrpc: '2.0',+ id: 3,+ method: 'tools/call',+ params: { name: 'system_info', arguments: {} },+ });+ expect(called.result.isError).toBe(false);+ const systemInfo = JSON.parse(called.result.content[0].text);+ expect(systemInfo).toMatchObject({+ nodeVersion: process.version,+ platform: process.platform,+ });+ }, 30_000);++ it('applies CLAUDE_FLOW_MCP_TOOLS to the bridged HTTP catalogue', async () => {+ const port = 38000 + Math.floor(Math.random() * 2000);+ await startHttpCli(port, 'memory');++ await postJson(port, '/mcp', {+ jsonrpc: '2.0',+ id: 1,+ method: 'initialize',+ params: {+ protocolVersion: '2024-11-05',+ capabilities: {},+ clientInfo: { name: 'ruflo-http-filter-regression', version: '1.0.0' },+ },+ });+ const listed = await postJson(port, '/mcp', {+ jsonrpc: '2.0',+ id: 2,+ method: 'tools/list',+ });+ const names = listed.result.tools.map((tool: { name: string }) => tool.name);+ expect(names).toContain('memory_store');+ expect(names).not.toContain('agent_spawn');+ }, 30_000);+});diff --git a/v3/@claude-flow/cli/package.json b/v3/@claude-flow/cli/package.jsonindex b52f9e9e58..329fc85a2a 100644--- a/v3/@claude-flow/cli/package.json+++ b/v3/@claude-flow/cli/package.json@@ -99,7 +99,7 @@"dependencies": {"@claude-flow/cli-core": "3.7.0-alpha.5","@claude-flow/codex": "3.0.3",- "@claude-flow/mcp": "3.0.0-alpha.8",+ "@claude-flow/mcp": "3.0.0-alpha.10","@claude-flow/neural": "3.0.0-alpha.9","@claude-flow/plugin-agent-federation": "1.0.0-alpha.18","@claude-flow/security": "3.0.0-alpha.14",diff --git a/v3/@claude-flow/cli/src/commands/mcp.ts b/v3/@claude-flow/cli/src/commands/mcp.tsindex 6cf0877d29..d86cf7372d 100644--- a/v3/@claude-flow/cli/src/commands/mcp.ts+++ b/v3/@claude-flow/cli/src/commands/mcp.ts@@ -78,8 +78,7 @@ const startCommand: Command = {{name: 'tools',description: 'Tools to advertise (comma-separated categories, prefixes, exact names, or "all")',- type: 'string',- default: 'all'+ type: 'string'},{name: 'daemon',@@ -106,7 +105,9 @@ const startCommand: Command = {const port = (ctx.flags.port as number) ?? 3000;const host = (ctx.flags.host as string) ?? 'localhost';const transport = (ctx.flags.transport as 'stdio' | 'http' | 'websocket') ?? 'stdio';- const tools = (ctx.flags.tools as string) || 'all';+ const tools = (ctx.flags.tools as string | undefined)+ || process.env.CLAUDE_FLOW_MCP_TOOLS+ || 'all';const daemon = (ctx.flags.daemon as boolean) ?? false;const force = (ctx.flags.force as boolean) ?? false;diff --git a/v3/@claude-flow/cli/src/mcp-server.ts b/v3/@claude-flow/cli/src/mcp-server.tsindex 3cd340e47c..248ee3e00d 100644--- a/v3/@claude-flow/cli/src/mcp-server.ts+++ b/v3/@claude-flow/cli/src/mcp-server.ts@@ -154,6 +154,7 @@ export class MCPServerManager extends EventEmitter {private server?: Server;private startTime?: Date;private healthCheckInterval?: NodeJS.Timeout;+ private mcpServers: Array<{ stop(): Promise<void> }> = [];constructor(options: MCPServerOptions = {}) {super();@@ -256,6 +257,12 @@ export class MCPServerManager extends EventEmitter {this.server = undefined;}+ if (this.mcpServers.length > 0) {+ const servers = this.mcpServers;+ this.mcpServers = [];+ await Promise.all(servers.map((server) => server.stop()));+ }+// Remove PID fileawait this.removePidFile();@@ -710,23 +717,73 @@ export class MCPServerManager extends EventEmitter {error: (msg: string, data?: unknown) => this.emit('log', { level: 'error', msg, data }),};- const mcpServer = createMCPServer(- {- name: 'Claude-Flow MCP Server V3',- version: '3.0.0',- transport: this.options.transport as 'http' | 'websocket',- host: this.options.host,- port: this.options.port,- enableMetrics: true,- enableCaching: true,+ const { listMCPTools, callMCPTool } = await import('./mcp-client.js');+ const fallbackSessionId = `http-${randomUUID()}`;+ const cliTools = filterAdvertisedMcpTools(listMCPTools(), this.options.tools).map((tool) => ({+ name: tool.name,+ description: tool.description,+ inputSchema: tool.inputSchema,+ category: tool.category,+ tags: tool.tags,+ version: tool.version,+ cacheable: tool.cacheable,+ cacheTTL: tool.cacheTTL,+ handler: async (input: unknown, context?: { sessionId?: string }) => {+ try {+ const result = await callMCPTool(+ tool.name,+ (input as Record<string, unknown>) || {},+ { sessionId: context?.sessionId || fallbackSessionId }+ );+ trackRequest(tool.name, true);+ return result;+ } catch (error) {+ trackRequest(tool.name, false);+ throw error;+ }},- logger- );+ }));- await mcpServer.start();+ // 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;+ });- // Store reference for stopping- (this as any)._mcpServer = mcpServer;+ 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;+ }+ this.mcpServers = startedServers;}/**diff --git a/v3/@claude-flow/mcp/__tests__/tool-registry-json-schema.test.ts b/v3/@claude-flow/mcp/__tests__/tool-registry-json-schema.test.tsnew file mode 100644index 0000000000..e093df4c73--- /dev/null+++ b/v3/@claude-flow/mcp/__tests__/tool-registry-json-schema.test.ts@@ -0,0 +1,40 @@+import { describe, expect, it, vi } from 'vitest';+import { createToolRegistry } from '../src/tool-registry.js';+import type { ILogger } from '../src/types.js';++const logger: ILogger = {+ debug: vi.fn(),+ info: vi.fn(),+ warn: vi.fn(),+ error: vi.fn(),+};++describe('ToolRegistry JSON Schema compatibility (#2990)', () => {+ it.each([+ ['string', 'plain text'],+ ['object', { nested: true }],+ ['array', ['one', 2]],+ ['number', 42],+ ['boolean', false],+ ['null', null],+ ])('accepts an unconstrained property with a %s value', async (_kind, value) => {+ const registry = createToolRegistry(logger);+ expect(registry.register({+ name: 'store_value',+ description: 'Store any JSON value',+ inputSchema: {+ type: 'object',+ properties: {+ key: { type: 'string' },+ value: { description: 'Any JSON value' },+ },+ required: ['key', 'value'],+ },+ handler: async (input) => ({ value: input.value }),+ })).toBe(true);++ const result = await registry.execute('store_value', { key: 'test', value });+ expect(result.isError).toBe(false);+ expect(JSON.parse(result.content[0].text!)).toEqual({ value });+ });+});diff --git a/v3/@claude-flow/mcp/package.json b/v3/@claude-flow/mcp/package.jsonindex c6253f2409..d8125c66aa 100644--- a/v3/@claude-flow/mcp/package.json+++ b/v3/@claude-flow/mcp/package.json@@ -1,6 +1,6 @@{"name": "@claude-flow/mcp",- "version": "3.0.0-alpha.9",+ "version": "3.0.0-alpha.10","type": "module","description": "Standalone MCP (Model Context Protocol) server - stdio/http/websocket transports, connection pooling, tool registry","main": "dist/index.js",diff --git a/v3/@claude-flow/mcp/src/tool-registry.ts b/v3/@claude-flow/mcp/src/tool-registry.tsindex 1b812d2037..15ab910660 100644--- a/v3/@claude-flow/mcp/src/tool-registry.ts+++ b/v3/@claude-flow/mcp/src/tool-registry.ts@@ -477,10 +477,6 @@ export class ToolRegistry extends EventEmitter {private validateSchema(schema: JSONSchema, path = ''): string[] {const errors: string[] = [];- if (!schema.type) {- errors.push(`${path || 'schema'}: type is required`);- }-if (schema.type === 'object' && schema.properties) {for (const [key, propSchema] of Object.entries(schema.properties)) {const propPath = path ? `${path}.${key}` : key;diff --git a/v3/pnpm-lock.yaml b/v3/pnpm-lock.yamlindex 14a8769e9c..7a6cfcdf41 100644--- a/v3/pnpm-lock.yaml+++ b/v3/pnpm-lock.yaml@@ -121,8 +121,8 @@ importers:specifier: 3.0.3version: link:../codex'@claude-flow/mcp':- specifier: 3.0.0-alpha.8- version: 3.0.0-alpha.8+ specifier: 3.0.0-alpha.10+ version: link:../mcp'@claude-flow/neural':specifier: 3.0.0-alpha.9version: link:../neural@@ -882,20 +882,6 @@ packages:resolution: {integrity: sha512-k7vvKPbf7J2fZ5klGRD9AeKfUvojuZIQ3BT5u7Jfv+puwXkUBUT5PVyMDfJZpy30CBDXGMgw7fguK/lpOMBvgw==}requiresBuild: true- /@claude-flow/[email protected]:- resolution: {integrity: sha512-lP1t8GMWDl9RxnwMZrjMukZkyglhge7Znhj1PbUiUQ94kHcN+dAxUkA75HM1n7BONbIDcE/CS8qN2ril5KgzNg==}- dependencies:- ajv: 8.18.0- cors: 2.8.6- express: 5.2.1- helmet: 7.2.0- ws: 8.21.1- transitivePeerDependencies:- - bufferutil- - supports-color- - utf-8-validate- dev: false-/@claude-flow/[email protected]:resolution: {integrity: sha512-5iehTHguBFjlyZqy+fRoKfZVL/nFeE93A94nUUKJvu8y7AmhfpVqtQAZbmKztwQGJ5rv7iBb3Kwl1MUo3K5QkA==}dependencies: