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): start the MCP server in the session project, fix win32 home guard

Marius Carlsson966d8a0645df
diff --git a/plugins/ruflo-core/scripts/mcp-launch.cjs b/plugins/ruflo-core/scripts/mcp-launch.cjs
index bea4112e4b..732a3cdeb4 100644
--- a/plugins/ruflo-core/scripts/mcp-launch.cjs
+++ b/plugins/ruflo-core/scripts/mcp-launch.cjs
@@ -27,13 +27,58 @@
* RUFLO_MCP_SKIP_NPX=1 rejects an unpinned fallback.
*/
-const { existsSync } = require('fs');
-const { join, dirname, resolve, isAbsolute, delimiter } = require('path');
+const { existsSync, statSync } = require('fs');
+const { join, dirname, resolve, isAbsolute, delimiter, parse } = require('path');
const { spawn } = require('child_process');
const os = require('os');
const MCP_ARGS = ['mcp', 'start'];
+function comparablePath(p) {
+ // resolve() normalises separators and drops trailing slashes (except on a root).
+ const r = resolve(p);
+ return process.platform === 'win32' ? r.toLowerCase() : r;
+}
+
+/**
+ * A directory that cannot be a project root: a filesystem root ('/', 'C:\')
+ * or the user's home directory. Home is compared against os.homedir() as well
+ * as $HOME/$USERPROFILE because $HOME is normally unset on Windows, which made
+ * a $HOME-only guard a no-op there.
+ */
+function isNonProjectDir(dir, home, env = process.env) {
+ const target = comparablePath(dir);
+ if (target === comparablePath(parse(target).root)) return true;
+ for (const h of [home, env.HOME, env.USERPROFILE]) {
+ if (h && comparablePath(h) === target) return true;
+ }
+ return false;
+}
+
+function isDirectory(dir) {
+ try {
+ return statSync(dir).isDirectory();
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * The directory the MCP server should treat as the project. Claude Code
+ * exposes the session's project as CLAUDE_PROJECT_DIR; an explicit
+ * CLAUDE_FLOW_CWD is honoured next; the launcher's own cwd is the
+ * backwards-compatible fallback. Home/root/missing values are skipped so a
+ * stale global variable cannot redirect every session into ~/.claude-flow.
+ */
+function resolveProjectDir(env = process.env, cwd = process.cwd(), home = os.homedir()) {
+ for (const candidate of [env.CLAUDE_PROJECT_DIR, env.CLAUDE_FLOW_CWD]) {
+ if (!candidate) continue;
+ const dir = resolve(cwd, candidate);
+ if (isDirectory(dir) && !isNonProjectDir(dir, home, env)) return dir;
+ }
+ return resolve(cwd);
+}
+
function isRunnableCli(candidate) {
try {
const distEntry = join(dirname(candidate), '..', 'dist', 'src', 'index.js');
@@ -86,9 +131,15 @@ function resolveLocalCliBin(cwd, home, env = process.env) {
return null;
}
-function buildLaunchSpec(localBin, env = process.env) {
+function buildLaunchSpec(localBin, env = process.env, projectDir = null) {
+ // Start the server *in* the project and say so explicitly: tools built on
+ // getProjectCwd() read CLAUDE_FLOW_CWD, tools that call process.cwd() read
+ // the spawn cwd. Both must match the folder the CLI writes state to.
+ const placement = projectDir
+ ? { cwd: projectDir, env: { ...env, CLAUDE_FLOW_CWD: projectDir } }
+ : {};
if (localBin) {
- return { command: process.execPath, args: [localBin, ...MCP_ARGS], shell: false };
+ return { command: process.execPath, args: [localBin, ...MCP_ARGS], shell: false, ...placement };
}
if (env.RUFLO_MCP_SKIP_NPX === '1') {
throw new Error('No built local CLI found and RUFLO_MCP_SKIP_NPX=1 forbids the @latest fallback');
@@ -102,11 +153,12 @@ function buildLaunchSpec(localBin, env = process.env) {
command: npxCmd,
args: ['-y', '@claude-flow/cli@latest', ...MCP_ARGS],
shell: process.platform === 'win32',
+ ...placement,
};
}
-function launch({ command, args, shell }) {
- const child = spawn(command, args, { stdio: 'inherit', env: process.env, shell });
+function launch({ command, args, shell, cwd, env }) {
+ const child = spawn(command, args, { stdio: 'inherit', env: env || process.env, shell, cwd });
// Forward termination signals so Claude Code can stop the MCP server the
// same way it would if it had spawned the real binary directly.
@@ -130,12 +182,22 @@ function launch({ command, args, shell }) {
if (require.main === module) {
try {
- const localBin = resolveLocalCliBin(process.cwd(), os.homedir());
- launch(buildLaunchSpec(localBin));
+ const home = os.homedir();
+ const projectDir = resolveProjectDir(process.env, process.cwd(), home);
+ if (isNonProjectDir(projectDir, home)) {
+ // stderr only: stdout is the MCP stdio channel.
+ process.stderr.write(
+ `[mcp-launch] warning: no project directory (session started in ${projectDir}); ` +
+ 'MCP state will be kept there, not in folders CLI commands run from. ' +
+ 'Start Claude Code inside the project or set CLAUDE_FLOW_CWD.\n',
+ );
+ }
+ const localBin = resolveLocalCliBin(projectDir, home);
+ launch(buildLaunchSpec(localBin, process.env, projectDir));
} catch (error) {
process.stderr.write(`[mcp-launch] ${error.message}\n`);
process.exitCode = 1;
}
}
-module.exports = { resolveLocalCliBin, buildLaunchSpec, MCP_ARGS };
+module.exports = { resolveLocalCliBin, resolveProjectDir, isNonProjectDir, buildLaunchSpec, MCP_ARGS };
diff --git a/plugins/ruflo-core/scripts/mcp-launch.test.cjs b/plugins/ruflo-core/scripts/mcp-launch.test.cjs
index 40d6b4426d..5fce1dea6c 100644
--- a/plugins/ruflo-core/scripts/mcp-launch.test.cjs
+++ b/plugins/ruflo-core/scripts/mcp-launch.test.cjs
@@ -161,3 +161,87 @@ test('RUFLO_MCP_SKIP_NPX=1 refuses an unpinned fallback', () => {
/RUFLO_MCP_SKIP_NPX=1 forbids/,
);
});
+
+// ---------------------------------------------------------------------------
+// Project-directory resolution (split-brain fix).
+//
+// Claude Code starts one MCP server per session. Before this fix the launcher
+// spawned `mcp start` with its own process.cwd() and never consulted the
+// session's project directory, so MCP state (.claude-flow/hive-mind,
+// memory, swarm) could land in a different folder than the CLI's.
+// ---------------------------------------------------------------------------
+const { execFileSync } = require('child_process');
+const LAUNCHER = path.join(__dirname, 'mcp-launch.cjs');
+
+function samePath(a, b) {
+ const norm = (p) => {
+ const r = fs.realpathSync.native(p);
+ return process.platform === 'win32' ? r.toLowerCase() : r;
+ };
+ return norm(a) === norm(b);
+}
+
+function makeEchoCli(root) {
+ // A "built" CLI fixture that reports where it was started.
+ const bin = makeCliInstall(root);
+ fs.writeFileSync(
+ bin,
+ 'process.stdout.write(JSON.stringify({ cwd: process.cwd(), flowCwd: process.env.CLAUDE_FLOW_CWD || null, args: process.argv.slice(2) }));\n',
+ );
+ return bin;
+}
+
+test('end-to-end: the MCP server is started in CLAUDE_PROJECT_DIR, not the launcher cwd', () => {
+ const sessionCwd = fs.mkdtempSync(path.join(os.tmpdir(), 'mcp-launch-session-'));
+ const project = fs.mkdtempSync(path.join(os.tmpdir(), 'mcp-launch-project-'));
+ const cliRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'mcp-launch-cli-'));
+ try {
+ const bin = makeEchoCli(cliRoot);
+ const env = { ...process.env, RUFLO_MCP_CLI_OVERRIDE: bin, CLAUDE_PROJECT_DIR: project };
+ delete env.CLAUDE_FLOW_CWD;
+ const out = JSON.parse(execFileSync(process.execPath, [LAUNCHER], { cwd: sessionCwd, env, encoding: 'utf8' }));
+ assert.deepEqual(out.args, MCP_ARGS);
+ assert.ok(samePath(out.cwd, project), `server cwd ${out.cwd} should be project ${project}`);
+ assert.ok(out.flowCwd && samePath(out.flowCwd, project), `CLAUDE_FLOW_CWD ${out.flowCwd} should be project ${project}`);
+ } finally {
+ for (const d of [sessionCwd, project, cliRoot]) fs.rmSync(d, { recursive: true, force: true });
+ }
+});
+
+test('end-to-end: without CLAUDE_PROJECT_DIR the launcher cwd is kept (backwards compatible)', () => {
+ const sessionCwd = fs.mkdtempSync(path.join(os.tmpdir(), 'mcp-launch-session-'));
+ const cliRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'mcp-launch-cli-'));
+ try {
+ const bin = makeEchoCli(cliRoot);
+ const env = { ...process.env, RUFLO_MCP_CLI_OVERRIDE: bin };
+ delete env.CLAUDE_PROJECT_DIR;
+ delete env.CLAUDE_FLOW_CWD;
+ const out = JSON.parse(execFileSync(process.execPath, [LAUNCHER], { cwd: sessionCwd, env, encoding: 'utf8' }));
+ assert.ok(samePath(out.cwd, sessionCwd));
+ } finally {
+ for (const d of [sessionCwd, cliRoot]) fs.rmSync(d, { recursive: true, force: true });
+ }
+});
+
+test('resolveProjectDir: CLAUDE_PROJECT_DIR > CLAUDE_FLOW_CWD > cwd; home, root and missing dirs are not projects', () => {
+ const { resolveProjectDir } = require(LAUNCHER);
+ assert.equal(typeof resolveProjectDir, 'function');
+ const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'mcp-launch-cwd-'));
+ const a = fs.mkdtempSync(path.join(os.tmpdir(), 'mcp-launch-a-'));
+ const b = fs.mkdtempSync(path.join(os.tmpdir(), 'mcp-launch-b-'));
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'mcp-launch-home-'));
+ try {
+ assert.equal(resolveProjectDir({ CLAUDE_PROJECT_DIR: a, CLAUDE_FLOW_CWD: b }, cwd, home), path.resolve(a));
+ assert.equal(resolveProjectDir({ CLAUDE_FLOW_CWD: b }, cwd, home), path.resolve(b));
+ assert.equal(resolveProjectDir({}, cwd, home), path.resolve(cwd));
+ // A project dir equal to the home directory is "no project" (Windows: HOME
+ // is usually unset, so this must work off the supplied home/USERPROFILE).
+ assert.equal(resolveProjectDir({ CLAUDE_PROJECT_DIR: home, CLAUDE_FLOW_CWD: b }, cwd, home), path.resolve(b));
+ const homeVariant = process.platform === 'win32' ? home.toUpperCase() + path.sep : home + path.sep;
+ assert.equal(resolveProjectDir({ CLAUDE_PROJECT_DIR: homeVariant }, cwd, home), path.resolve(cwd));
+ assert.equal(resolveProjectDir({ CLAUDE_PROJECT_DIR: path.parse(cwd).root }, cwd, home), path.resolve(cwd));
+ assert.equal(resolveProjectDir({ CLAUDE_PROJECT_DIR: path.join(a, 'does-not-exist') }, cwd, home), path.resolve(cwd));
+ } finally {
+ for (const d of [cwd, a, b, home]) fs.rmSync(d, { recursive: true, force: true });
+ }
+});
diff --git a/v3/@claude-flow/cli-core/__tests__/project-cwd-home-guard.test.ts b/v3/@claude-flow/cli-core/__tests__/project-cwd-home-guard.test.ts
new file mode 100644
index 0000000000..cdd42324b0
--- /dev/null
+++ b/v3/@claude-flow/cli-core/__tests__/project-cwd-home-guard.test.ts
@@ -0,0 +1,58 @@
+/**
+ * getProjectCwd() home/root guard (MCP split-brain fix).
+ *
+ * CLAUDE_FLOW_CWD pointing at the home directory or a filesystem root means
+ * "no project" and must fall back to process.cwd(). The previous guard only
+ * compared against '/' and process.env.HOME — HOME is normally unset on
+ * Windows (USERPROFILE is used) and 'C:\' is not '/', so both checks were
+ * no-ops there and MCP tools wrote project state under the user's home.
+ */
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { homedir, tmpdir } from 'node:os';
+import { join, parse, sep } from 'node:path';
+import { getProjectCwd } from '../src/mcp-tools/types.js';
+
+const SAVED = { ...process.env };
+
+describe('getProjectCwd home/root guard', () => {
+ let project: string;
+
+ beforeEach(() => {
+ project = mkdtempSync(join(tmpdir(), 'project-cwd-'));
+ });
+
+ afterEach(() => {
+ process.env = { ...SAVED };
+ rmSync(project, { recursive: true, force: true });
+ });
+
+ it('honours CLAUDE_FLOW_CWD when it names a real project directory', () => {
+ process.env.CLAUDE_FLOW_CWD = project;
+ expect(getProjectCwd()).toBe(project);
+ });
+
+ it('ignores CLAUDE_FLOW_CWD equal to os.homedir() even when $HOME is unset (Windows)', () => {
+ const home = homedir();
+ delete process.env.HOME;
+ process.env.CLAUDE_FLOW_CWD = home;
+ expect(getProjectCwd()).toBe(process.cwd());
+ });
+
+ it('ignores home spelled with a trailing separator, or different case on win32', () => {
+ const home = homedir();
+ delete process.env.HOME;
+ process.env.CLAUDE_FLOW_CWD = (process.platform === 'win32' ? home.toUpperCase() : home) + sep;
+ expect(getProjectCwd()).toBe(process.cwd());
+ });
+
+ it('ignores a filesystem root on every platform (C:\\ as well as /)', () => {
+ process.env.CLAUDE_FLOW_CWD = parse(project).root;
+ expect(getProjectCwd()).toBe(process.cwd());
+ });
+
+ it('falls back to process.cwd() when CLAUDE_FLOW_CWD is unset', () => {
+ delete process.env.CLAUDE_FLOW_CWD;
+ expect(getProjectCwd()).toBe(process.cwd());
+ });
+});
diff --git a/v3/@claude-flow/cli-core/src/mcp-tools/types.ts b/v3/@claude-flow/cli-core/src/mcp-tools/types.ts
index 076b69be1c..a66aa07104 100644
--- a/v3/@claude-flow/cli-core/src/mcp-tools/types.ts
+++ b/v3/@claude-flow/cli-core/src/mcp-tools/types.ts
@@ -4,6 +4,9 @@
* Local type definitions to avoid external imports outside package boundary.
*/
+import * as os from 'node:os';
+import * as path from 'node:path';
+
export interface MCPToolInputSchema {
type: 'object';
properties: Record<string, unknown>;
@@ -20,14 +23,36 @@ export interface MCPToolResult {
isError?: boolean;
}
+function comparablePath(p: string): string {
+ // resolve() normalises separators and drops trailing slashes (except on a root).
+ const r = path.resolve(p);
+ return process.platform === 'win32' ? r.toLowerCase() : r;
+}
+
+/**
+ * True when `dir` cannot be a project root: a filesystem root ('/', 'C:\')
+ * or the user's home directory. Home is checked via os.homedir() as well as
+ * $HOME/$USERPROFILE — $HOME is normally unset on Windows, so a $HOME-only
+ * comparison never matched there.
+ */
+export function isNonProjectDir(dir: string): boolean {
+ const target = comparablePath(dir);
+ if (target === comparablePath(path.parse(target).root)) return true;
+ for (const home of [os.homedir(), process.env.HOME, process.env.USERPROFILE]) {
+ if (home && comparablePath(home) === target) return true;
+ }
+ return false;
+}
+
/**
* Returns the effective project working directory.
- * Prefers CLAUDE_FLOW_CWD (set by the install script for global/MCP installs
- * where process.cwd() may resolve to '/') over the real process.cwd().
+ * Prefers CLAUDE_FLOW_CWD (set by the MCP launcher / install script for
+ * global and MCP installs where process.cwd() may not be the project) over
+ * the real process.cwd(), unless it names a root or home directory.
*/
export function getProjectCwd(): string {
const envCwd = process.env.CLAUDE_FLOW_CWD;
- if (envCwd && envCwd !== '/' && envCwd !== process.env.HOME) {
+ if (envCwd && !isNonProjectDir(envCwd)) {
return envCwd;
}
return process.cwd();