🌊 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): flag handler errors in tool result envelopes
Rudy Celekli60be23230212
diff --git a/v3/@claude-flow/cli/__tests__/mcp-fast-path-error-envelope.test.ts b/v3/@claude-flow/cli/__tests__/mcp-fast-path-error-envelope.test.tsnew file mode 100644index 0000000000..1307a891cb--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/mcp-fast-path-error-envelope.test.ts@@ -0,0 +1,26 @@+import { afterAll, describe, expect, it } from 'vitest';+import { copyFileSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { execFileSync } from 'node:child_process';+const root = mkdtempSync(join(tmpdir(), 'ruflo-mcp-error-'));+mkdirSync(join(root, 'bin'));+mkdirSync(join(root, 'dist/src/mcp-tools'), { recursive: true });+copyFileSync(new URL('../bin/cli.js', import.meta.url), join(root, 'bin/cli.js'));+writeFileSync(join(root, 'package.json'), '{"type":"module"}');+writeFileSync(join(root, 'dist/src/mcp-client.js'), 'export const hasTool = () => true; export const listMCPTools = () => []; export const callMCPTool = async (_name, input) => input.payload;');+writeFileSync(join(root, 'dist/src/mcp-tools/policy-enforcer.js'), 'export const isPolicyEnforcementEnabled = () => false; export const loadMcpPolicy = () => ({}); export const evaluateToolCall = () => ({allowed:true});');+afterAll(() => rmSync(root, { recursive: true, force: true }));++describe('executable MCP fast path tool errors', () => {+ it.each([+ [{ success: false, error: 'invalid input' }, true],+ [{ success: false, recorded: true }, false],+ ])('uses the protocol error flag without losing output', (payload, isError) => {+ const request = { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'fixture', arguments: { payload } } };+ const stdout = execFileSync(process.execPath, [join(root, 'bin/cli.js')], { input: `${JSON.stringify(request)}\n`, encoding: 'utf8', timeout: 5000, stdio: ['pipe', 'pipe', 'pipe'] });+ const response = JSON.parse(stdout.trim());+ expect(response.result.isError === true).toBe(isError);+ expect(JSON.parse(response.result.content[0].text)).toEqual(payload);+ });+});diff --git a/v3/@claude-flow/cli/__tests__/mcp-tool-error-envelope.test.ts b/v3/@claude-flow/cli/__tests__/mcp-tool-error-envelope.test.tsnew file mode 100644index 0000000000..d9417fa58b--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/mcp-tool-error-envelope.test.ts@@ -0,0 +1,38 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+const callMCPTool = vi.fn();+const trackRequest = vi.fn();+vi.mock('../src/mcp-client.js', () => ({ callMCPTool, hasTool: (name: string) => name === 'test_tool', listMCPTools: () => [] }));+vi.mock('../src/mcp-tools/request-tracker.js', () => ({ trackRequest }));+vi.mock('../src/mcp-tools/policy-enforcer.js', () => ({ isPolicyEnforcementEnabled: () => false }));+const { MCPServerManager } = await import('../src/mcp-server.js');+const manager = new MCPServerManager({ transport: 'stdio' });+const call = () => (manager as any).handleMCPMessage({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'test_tool', arguments: {} } }, 'test-session');+beforeEach(() => { callMCPTool.mockReset(); trackRequest.mockClear(); });++describe('CLI MCP tool error envelope', () => {+ it.each([{ success: false, error: 'key is required' }, { results: [], error: 'database unavailable' }])('marks in-band handler failures as tool errors', async (payload) => {+ callMCPTool.mockResolvedValue(payload);+ const response = await call();+ expect(response.error).toBeUndefined();+ expect(response.result.isError).toBe(true);+ expect(JSON.parse(response.result.content[0].text)).toEqual(payload);+ expect(trackRequest).toHaveBeenCalledWith('test_tool', false);+ });+ it('does not confuse a recorded failed task outcome with tool failure', async () => {+ callMCPTool.mockResolvedValue({ success: false, recorded: true });+ const response = await call();+ expect(response.result.isError).not.toBe(true);+ expect(trackRequest).toHaveBeenCalledWith('test_tool', true);+ });+ it('preserves successful tool output', async () => {+ callMCPTool.mockResolvedValue({ success: true, result: 42 });+ const response = await call();+ expect(response.result.isError).not.toBe(true);+ expect(JSON.parse(response.result.content[0].text)).toEqual({ success: true, result: 42 });+ });+ it('keeps unknown tools as protocol errors', async () => {+ const response = await (manager as any).handleMCPMessage({ jsonrpc: '2.0', id: 2, method: 'tools/call', params: { name: 'missing' } }, 'test-session');+ expect(response.error.code).toBe(-32601);+ expect(callMCPTool).not.toHaveBeenCalled();+ });+});diff --git a/v3/@claude-flow/cli/bin/cli.js b/v3/@claude-flow/cli/bin/cli.jsindex 531424b2b3..bbcf42aab3 100755--- a/v3/@claude-flow/cli/bin/cli.js+++ b/v3/@claude-flow/cli/bin/cli.js@@ -302,10 +302,13 @@ if (isMCPMode) {try {const result = await callMCPTool(toolName, toolParams, { sessionId });+ // Failed task outcomes are data; an explicit handler error is a tool failure.+ const isError = result !== null && typeof result === 'object'+ && typeof result.error === 'string' && result.error.trim().length > 0;return {jsonrpc: '2.0',id: message.id,- result: { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] },+ result: { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }], isError },};} catch (error) {return {diff --git a/v3/@claude-flow/cli/src/mcp-server.ts b/v3/@claude-flow/cli/src/mcp-server.tsindex 5cbcd9382e..5b6fc562a2 100644--- a/v3/@claude-flow/cli/src/mcp-server.ts+++ b/v3/@claude-flow/cli/src/mcp-server.ts@@ -33,6 +33,13 @@ import {evaluateToolCall,} from './mcp-tools/policy-enforcer.js';+/** A failed task can be valid data; only an explicit error denotes tool failure. */+function hasToolError(result: unknown): boolean {+ return result !== null && typeof result === 'object'+ && typeof (result as { error?: unknown }).error === 'string'+ && (result as { error: string }).error.trim().length > 0;+}+// ESM-compatible __dirnameconst __filename = fileURLToPath(import.meta.url);const __dirname = dirname(__filename);@@ -842,11 +849,12 @@ export class MCPServerManager extends EventEmitter {try {const result = await callMCPTool(toolName, toolParams, { sessionId });- trackRequest(toolName, true);+ const isError = hasToolError(result);+ trackRequest(toolName, !isError);return {jsonrpc: '2.0',id: message.id,- result: { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] },+ result: { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }], isError },};} catch (error) {trackRequest(toolName, false);@@ -930,7 +938,7 @@ export class MCPServerManager extends EventEmitter {(input as Record<string, unknown>) || {},{ sessionId: context?.sessionId || fallbackSessionId });- trackRequest(tool.name, true);+ trackRequest(tool.name, !hasToolError(result));return result;} catch (error) {trackRequest(tool.name, false);diff --git a/v3/@claude-flow/mcp/__tests__/tool-registry-error-result.test.ts b/v3/@claude-flow/mcp/__tests__/tool-registry-error-result.test.tsnew file mode 100644index 0000000000..0c9e7999f9--- /dev/null+++ b/v3/@claude-flow/mcp/__tests__/tool-registry-error-result.test.ts@@ -0,0 +1,22 @@+import { describe, expect, it, vi } from 'vitest';+import { createToolRegistry } from '../src/tool-registry.js';+const logger = { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() };++describe('handler-declared tool errors', () => {+ it.each([{ success: false, error: 'invalid key' }, { results: [], error: 'storage unavailable' }])('preserves error payloads and records failure', async (payload) => {+ const registry = createToolRegistry(logger);+ registry.register({ name: 'failing_tool', description: 'test', inputSchema: { type: 'object', properties: {} }, handler: async () => payload });+ const completed = vi.fn();+ registry.on('tool:completed', completed);+ const result = await registry.execute('failing_tool', {});+ expect(result.isError).toBe(true);+ expect(registry.getMetadata('failing_tool')?.errorCount).toBe(1);+ expect(JSON.parse(result.content[0].text!)).toEqual(payload);+ expect(completed).toHaveBeenCalledWith(expect.objectContaining({ success: false }));+ });+ it('does not interpret recorded negative task outcomes as tool errors', async () => {+ const registry = createToolRegistry(logger);+ registry.register({ name: 'record', description: 'test', inputSchema: { type: 'object', properties: {} }, handler: async () => ({ success: false, recorded: true }) });+ expect((await registry.execute('record', {})).isError).toBe(false);+ });+});diff --git a/v3/@claude-flow/mcp/src/tool-registry.ts b/v3/@claude-flow/mcp/src/tool-registry.tsindex 15ab910660..4cf17100c5 100644--- a/v3/@claude-flow/mcp/src/tool-registry.ts+++ b/v3/@claude-flow/mcp/src/tool-registry.ts@@ -372,23 +372,30 @@ export class ToolRegistry extends EventEmitter {const result = await metadata.tool.handler(input, execContext);+ // CLI handlers return validation/runtime failures in-band. Preserve their+ // payload while exposing the failure in the MCP envelope and metrics.+ // A recorded task outcome with success:false alone is still valid data.+ const isError = result !== null && typeof result === 'object'+ && typeof (result as { error?: unknown }).error === 'string'+ && (result as { error: string }).error.trim().length > 0;+ if (isError) metadata.errorCount++;const duration = performance.now() - startTime;this.updateAverageExecutionTime(metadata, duration);this.logger.debug('Tool executed', {name,duration: `${duration.toFixed(2)}ms`,- success: true,+ success: !isError,});- this.emit('tool:completed', { name, duration, success: true });+ this.emit('tool:completed', { name, duration, success: !isError });return {content: [{type: 'text',text: typeof result === 'string' ? result : JSON.stringify(result, null, 2),}],- isError: false,+ isError,};} catch (error) {const duration = performance.now() - startTime;