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): enforce opt-in policy in shipped stdio launchers

Rudy Celekliea4661f81560
diff --git a/.github/workflows/v3-ci.yml b/.github/workflows/v3-ci.yml
index 05c025a7b1..1eb4045302 100644
--- a/.github/workflows/v3-ci.yml
+++ b/.github/workflows/v3-ci.yml
@@ -347,6 +347,10 @@ jobs:
working-directory: v3
run: pnpm install --frozen-lockfile
+ - name: Verify opt-in MCP policy through both shipped stdio launchers
+ working-directory: v3/@claude-flow/cli
+ run: node scripts/test-mcp-policy-stdio.mjs
+
- name: Build (so workspace dist/ exists for runtime imports)
# Some test suites do `await import('@claude-flow/X')` and Vite's
# import-analysis pass needs dist/ files at the resolved path.
diff --git a/v3/@claude-flow/cli/bin/cli.js b/v3/@claude-flow/cli/bin/cli.js
index d190e4d5dc..531424b2b3 100755
--- a/v3/@claude-flow/cli/bin/cli.js
+++ b/v3/@claude-flow/cli/bin/cli.js
@@ -164,6 +164,8 @@ const isMCPMode = !process.stdin.isTTY
if (isMCPMode) {
// Run MCP server mode
const { listMCPTools, callMCPTool, hasTool } = await import('../dist/src/mcp-client.js');
+ const { isPolicyEnforcementEnabled, loadMcpPolicy, evaluateToolCall } =
+ await import('../dist/src/mcp-tools/policy-enforcer.js');
const VERSION = '3.0.0';
const sessionId = `mcp-${Date.now()}-${randomUUID().slice(0, 8)}`;
@@ -287,6 +289,17 @@ if (isMCPMode) {
};
}
+ if (isPolicyEnforcementEnabled()) {
+ const check = evaluateToolCall(loadMcpPolicy(), sessionId, toolName);
+ if (!check.allowed) {
+ return {
+ jsonrpc: '2.0',
+ id: message.id,
+ error: { code: -32001, message: `Policy denied: ${check.reason}` },
+ };
+ }
+ }
+
try {
const result = await callMCPTool(toolName, toolParams, { sessionId });
return {
diff --git a/v3/@claude-flow/cli/bin/mcp-server.js b/v3/@claude-flow/cli/bin/mcp-server.js
index 121c779dcf..5991bd054c 100755
--- a/v3/@claude-flow/cli/bin/mcp-server.js
+++ b/v3/@claude-flow/cli/bin/mcp-server.js
@@ -28,6 +28,11 @@ console.log = (...args) => {
};
import { listMCPTools, callMCPTool, hasTool } from '../dist/src/mcp-client.js';
+import {
+ isPolicyEnforcementEnabled,
+ loadMcpPolicy,
+ evaluateToolCall,
+} from '../dist/src/mcp-tools/policy-enforcer.js';
const VERSION = '3.0.0';
const sessionId = `mcp-${Date.now()}-${randomUUID().slice(0, 8)}`;
@@ -173,6 +178,17 @@ async function handleMessage(message) {
};
}
+ if (isPolicyEnforcementEnabled()) {
+ const check = evaluateToolCall(loadMcpPolicy(), sessionId, toolName);
+ if (!check.allowed) {
+ return {
+ jsonrpc: '2.0',
+ id: message.id,
+ error: { code: -32001, message: `Policy denied: ${check.reason}` },
+ };
+ }
+ }
+
try {
const result = await callMCPTool(toolName, toolParams, { sessionId });
return {
diff --git a/v3/@claude-flow/cli/scripts/test-mcp-policy-stdio.mjs b/v3/@claude-flow/cli/scripts/test-mcp-policy-stdio.mjs
new file mode 100644
index 0000000000..88cab2d1c4
--- /dev/null
+++ b/v3/@claude-flow/cli/scripts/test-mcp-policy-stdio.mjs
@@ -0,0 +1,131 @@
+#!/usr/bin/env node
+// Exercise the shipped stdio launchers, not MCPServerManager's in-process handler.
+// Only the large tool registry is stubbed; the policy module is transpiled from
+// the same TypeScript source that the package build ships.
+import assert from 'node:assert/strict';
+import { spawn } from 'node:child_process';
+import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+import { createInterface } from 'node:readline';
+import { fileURLToPath } from 'node:url';
+import test from 'node:test';
+import ts from 'typescript';
+
+const packageDir = dirname(dirname(fileURLToPath(import.meta.url)));
+const policySource = readFileSync(join(packageDir, 'src/mcp-tools/policy-enforcer.ts'), 'utf8');
+const policyJavaScript = ts.transpileModule(policySource, {
+ compilerOptions: { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.ES2022 },
+}).outputText;
+const toolStub = `
+import { appendFileSync } from 'node:fs';
+export const hasTool = (name) => name === 'demo_tool';
+export const listMCPTools = () => [{ name: 'demo_tool', description: 'test', inputSchema: {} }];
+export async function callMCPTool(name) {
+ appendFileSync('executions.txt', name + '\\n');
+ return { ran: true };
+}
+`;
+
+async function runSession(entry, { policy, enforce = true, calls = 1, badAuditPath = false }) {
+ const project = mkdtempSync(join(tmpdir(), 'ruflo-stdio-policy-'));
+ let child;
+ try {
+ const bin = join(project, 'bin');
+ const dist = join(project, 'dist/src');
+ mkdirSync(bin);
+ mkdirSync(join(dist, 'mcp-tools'), { recursive: true });
+ writeFileSync(join(project, 'package.json'), '{"type":"module"}');
+ copyFileSync(join(packageDir, 'bin', entry), join(bin, entry));
+ writeFileSync(join(dist, 'mcp-client.js'), toolStub);
+ writeFileSync(join(dist, 'mcp-tools/policy-enforcer.js'), policyJavaScript);
+ if (policy !== undefined) {
+ mkdirSync(join(project, '.harness'));
+ writeFileSync(join(project, '.harness/mcp-policy.json'), policy);
+ }
+
+ child = spawn(process.execPath, [join(bin, entry), ...(entry === 'cli.js' ? ['mcp', 'start'] : [])], {
+ cwd: project,
+ env: {
+ ...process.env,
+ RUFLO_MCP_ENFORCE_POLICY: enforce ? '1' : '0',
+ TMPDIR: badAuditPath ? join(project, 'unwritable-audit-dir') : project,
+ },
+ stdio: ['pipe', 'pipe', 'pipe'],
+ });
+ let stderr = '';
+ child.stderr.setEncoding('utf8');
+ child.stderr.on('data', chunk => { stderr += chunk; });
+ const output = createInterface({ input: child.stdout })[Symbol.asyncIterator]();
+ const closed = new Promise((resolve, reject) => {
+ child.once('error', reject);
+ child.once('close', resolve);
+ });
+ const responses = [];
+ for (let id = 1; id <= calls; id++) {
+ child.stdin.write(JSON.stringify({
+ jsonrpc: '2.0', id, method: 'tools/call',
+ params: { name: 'demo_tool', arguments: {} },
+ }) + '\n');
+ let timeout;
+ const line = await Promise.race([
+ output.next(),
+ new Promise((_, reject) => {
+ timeout = setTimeout(() => reject(new Error(`${entry} timed out: ${stderr}`)), 5000);
+ }),
+ ]).finally(() => clearTimeout(timeout));
+ assert.equal(line.done, false, `${entry} exited before responding: ${stderr}`);
+ responses.push(JSON.parse(line.value));
+ }
+ child.stdin.end();
+ assert.equal(await closed, 0, `${entry} exited abnormally: ${stderr}`);
+ const executionsPath = join(project, 'executions.txt');
+ const auditPath = join(project, 'ruflo-mcp-audit.jsonl');
+ return {
+ responses,
+ executions: existsSync(executionsPath) ? readFileSync(executionsPath, 'utf8').trim().split('\n') : [],
+ audit: existsSync(auditPath) ? readFileSync(auditPath, 'utf8').trim().split('\n').map(JSON.parse) : [],
+ };
+ } finally {
+ if (child && child.exitCode === null) child.kill();
+ rmSync(project, { recursive: true, force: true });
+ }
+}
+
+for (const entry of ['cli.js', 'mcp-server.js']) {
+ test(`${entry}: disabled policy leaves calls working without a policy file`, async () => {
+ const result = await runSession(entry, { enforce: false });
+ assert.equal(result.responses[0].result.content[0].type, 'text');
+ assert.deepEqual(result.executions, ['demo_tool']);
+ assert.deepEqual(result.audit, []);
+ });
+
+ test(`${entry}: enabled policy denies a missing or malformed file before execution`, async () => {
+ for (const policy of [undefined, '{ malformed']) {
+ const result = await runSession(entry, { policy });
+ assert.equal(result.responses[0].error.code, -32001);
+ assert.match(result.responses[0].error.message, /missing or invalid.*failing closed/i);
+ assert.deepEqual(result.executions, []);
+ }
+ });
+
+ test(`${entry}: audit and sliding call budget govern real stdio requests`, async () => {
+ const result = await runSession(entry, {
+ policy: JSON.stringify({ auditLog: true, maxToolCallsPerTurn: 1 }), calls: 2,
+ });
+ assert.equal(result.responses[0].result.content[0].type, 'text');
+ assert.equal(result.responses[1].error.code, -32001);
+ assert.match(result.responses[1].error.message, /maxToolCallsPerTurn/);
+ assert.deepEqual(result.executions, ['demo_tool']);
+ assert.deepEqual(result.audit.map(record => record.allowed), [true, false]);
+ });
+
+ test(`${entry}: mandatory audit failure denies before execution`, async () => {
+ const result = await runSession(entry, {
+ policy: JSON.stringify({ auditLog: true }), badAuditPath: true,
+ });
+ assert.equal(result.responses[0].error.code, -32001);
+ assert.match(result.responses[0].error.message, /audit log write failed.*failing closed/i);
+ assert.deepEqual(result.executions, []);
+ });
+}
diff --git a/v3/@claude-flow/cli/src/mcp-tools/policy-enforcer.ts b/v3/@claude-flow/cli/src/mcp-tools/policy-enforcer.ts
index 95b3261118..bc03b99e8b 100644
--- a/v3/@claude-flow/cli/src/mcp-tools/policy-enforcer.ts
+++ b/v3/@claude-flow/cli/src/mcp-tools/policy-enforcer.ts
@@ -30,10 +30,10 @@
* misconfiguration defeats the feature. See `evaluateToolCall()`.
*
* Known scope limits (disclosed, not fixed here):
- * - Only wired into the stdio `tools/call` dispatch
- * (`MCPServerManager.handleMCPMessage`). The separate HTTP/websocket
- * path (`startHttpServer()`, via `@claude-flow/mcp`) does not call
- * this module and is unaffected even when this flag is set.
+ * - Wired into all three stdio `tools/call` dispatchers: the CLI fast
+ * path, the standalone MCP launcher, and MCPServerManager. The separate
+ * HTTP/websocket path (`startHttpServer()`, via `@claude-flow/mcp`)
+ * does not call this module and is unaffected even when this flag is set.
*
* `maxToolCallsPerTurn` reset semantics (dream-cycle 2026-09-01, follow-up
* to 2026-08-31 review round 1): despite the field's name, the original