Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 54 additions & 19 deletions src/cli/commands/setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -426,23 +426,53 @@ export function buildMemorixServer(mcp: Exclude<SetupMcpTransport, 'none'>): MCP
};
}

function toHttpMemorixServer(existing: Record<string, unknown>): Record<string, unknown> {
const next: Record<string, unknown> = { url: MEMORIX_HTTP_MCP_URL };
const HTTP_MCP_TYPE_REQUIRED_AGENTS = new Set<AgentName>(['claude', 'codebuddy']);

export interface RewriteBundledMcpOptions {
agent?: AgentName;
}

function shouldWriteHttpMcpType(
root: string,
fileName: string,
options?: RewriteBundledMcpOptions,
): boolean {
if (fileName !== '.mcp.json') return false;
if (options?.agent !== undefined) {
return HTTP_MCP_TYPE_REQUIRED_AGENTS.has(options.agent);
}
return (
existsSync(path.join(root, '.claude-plugin', 'plugin.json')) ||
existsSync(path.join(root, '.codebuddy-plugin', 'plugin.json'))
);
}

function toHttpMemorixServer(
existing: Record<string, unknown>,
requireHttpType = false,
): Record<string, unknown> {
const next: Record<string, unknown> = {};
if (requireHttpType || typeof existing.type === 'string') {
next.type = 'http';
}
next.url = MEMORIX_HTTP_MCP_URL;
if (existing.alwaysLoad === true) next.alwaysLoad = true;
if (typeof existing.type === 'string') next.type = 'http';
return next;
}

/**
* Rewrite a copied plugin/extension MCP manifest from stdio `memorix serve`
* to the shared HTTP control plane. Leaves unrelated keys intact.
*/
export async function rewriteBundledMemorixMcpToHttp(root: string): Promise<string[]> {
const candidates = ['.mcp.json', 'mcp_config.json', 'gemini-extension.json']
.map((name) => path.join(root, name));
export async function rewriteBundledMemorixMcpToHttp(
root: string,
options?: RewriteBundledMcpOptions,
): Promise<string[]> {
const candidates = ['.mcp.json', 'mcp_config.json', 'gemini-extension.json'];
const rewritten: string[] = [];

for (const filePath of candidates) {
for (const fileName of candidates) {
const filePath = path.join(root, fileName);
if (!existsSync(filePath)) continue;
let doc: unknown;
try {
Expand All @@ -457,7 +487,8 @@ export async function rewriteBundledMemorixMcpToHttp(root: string): Promise<stri
const serverMap = servers as Record<string, unknown>;
const existing = serverMap.memorix;
if (!existing || typeof existing !== 'object' || Array.isArray(existing)) continue;
serverMap.memorix = toHttpMemorixServer(existing as Record<string, unknown>);
const requireHttpType = shouldWriteHttpMcpType(root, fileName, options);
serverMap.memorix = toHttpMemorixServer(existing as Record<string, unknown>, requireHttpType);
await writeFile(filePath, JSON.stringify(record, null, 2) + '\n', 'utf-8');
rewritten.push(filePath);
}
Expand Down Expand Up @@ -1491,7 +1522,14 @@ export async function installAgentSetup(agent: AgentName, plan: SetupPlan, globa
const wantsMcpConfig = plan.mcp !== 'none'
&& !(agent === 'codex' && !global)
&& !(agent === 'grok' && plan.mcp !== 'http');
const bundledMcpRoots: string[] = [];
const rewrittenBundledMcpFiles: string[] = [];
const registerBundledMcpRoot = async (root: string): Promise<void> => {
if (wantsMcpConfig && plan.mcp === 'http') {
// Rewrite before host plugin CLIs snapshot or validate the copied bundle.
const rewritten = await rewriteBundledMemorixMcpToHttp(root, { agent });
rewrittenBundledMcpFiles.push(...rewritten);
}
};

if (PLUGIN_PACKAGE_AGENTS.has(agent) && plan.includePlugin && !global) {
p.log.info(`${agent}: project setup leaves user-level plugins untouched. Run \`memorix setup --agent ${agent} --global\` to install its plugin, skills, and lifecycle hooks.`);
Expand All @@ -1502,7 +1540,7 @@ export async function installAgentSetup(agent: AgentName, plan: SetupPlan, globa
agent: agent as PluginInstallOptions['agent'],
includeHooks: plan.includeHooks,
});
bundledMcpRoots.push(result.pluginPath);
await registerBundledMcpRoot(result.pluginPath);
p.log.success(`${agent}: plugin package -> ${result.pluginPath}`);
if (result.marketplacePath) {
p.log.info(`${agent}: marketplace -> ${result.marketplacePath}`);
Expand Down Expand Up @@ -1534,7 +1572,7 @@ export async function installAgentSetup(agent: AgentName, plan: SetupPlan, globa

if (hasCodeBuddyPlugin) {
const result = await installCodeBuddyPluginPackage({ includeHooks: plan.includeHooks });
bundledMcpRoots.push(result.pluginPath);
await registerBundledMcpRoot(result.pluginPath);
p.log.success(`${agent}: plugin -> ${result.pluginPath}`);
p.log.info(`${agent}: marketplace -> ${result.marketplacePath}`);
const install = tryInstallCodeBuddyPlugin(result.marketplaceRoot);
Expand All @@ -1546,7 +1584,7 @@ export async function installAgentSetup(agent: AgentName, plan: SetupPlan, globa

if (hasExtensionPackage) {
const result = await installGeminiExtensionPackage();
bundledMcpRoots.push(result.extensionPath);
await registerBundledMcpRoot(result.extensionPath);
p.log.success(`${agent}: extension package -> ${result.extensionPath}`);
p.log.info(result.installHint);
}
Expand All @@ -1562,7 +1600,7 @@ export async function installAgentSetup(agent: AgentName, plan: SetupPlan, globa

if (hasOpenClawBundle) {
const result = await installOpenClawBundlePackage({ includeHooks: plan.includeHooks });
bundledMcpRoots.push(result.bundlePath);
await registerBundledMcpRoot(result.bundlePath);
p.log.success(`${agent}: compatible bundle -> ${result.bundlePath}`);
if (plan.includeHooks) {
const install = tryInstallOpenClawBundle(result.bundlePath);
Expand All @@ -1576,7 +1614,7 @@ export async function installAgentSetup(agent: AgentName, plan: SetupPlan, globa

if (hasAntigravityPlugin) {
const result = await installAntigravityPluginPackage({ global, projectRoot: targetRoot, includeHooks: plan.includeHooks });
bundledMcpRoots.push(result.pluginPath);
await registerBundledMcpRoot(result.pluginPath);
p.log.success(`${agent}: plugin -> ${result.pluginPath}`);
if (!plan.includeHooks) {
p.log.info(`${agent}: hooks.json skipped because --noHooks was selected`);
Expand Down Expand Up @@ -1623,11 +1661,8 @@ export async function installAgentSetup(agent: AgentName, plan: SetupPlan, globa
: 'plugin package';
p.log.info(`${agent}: stdio MCP is bundled in the ${packageLabel}`);
} else if (mcpOwnedByPackage && plan.mcp === 'http') {
for (const root of bundledMcpRoots) {
const rewritten = await rewriteBundledMemorixMcpToHttp(root);
for (const filePath of rewritten) {
p.log.success(`${agent}: plugin MCP -> HTTP ${filePath}`);
}
for (const filePath of rewrittenBundledMcpFiles) {
p.log.success(`${agent}: plugin MCP -> HTTP ${filePath}`);
}
} else {
const mcp = plan.mcp === 'http' ? 'http' : 'stdio';
Expand Down
100 changes: 100 additions & 0 deletions tests/cli/setup-command.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -489,9 +489,28 @@ describe('plugin package installer', () => {
);
const mcp = JSON.parse(await fs.readFile(mcpPath, 'utf-8'));
expect(mcp.mcpServers.memorix).toEqual({
type: 'http',
url: 'http://localhost:3211/mcp',
alwaysLoad: true,
});
const cachedMcpPath = path.join(
tmpDir,
'.claude',
'plugins',
'cache',
'memorix-local',
'memorix',
getCliVersion(),
'.mcp.json',
);
const cachedMcp = await fs.readFile(cachedMcpPath, 'utf-8').catch(() => null);
if (cachedMcp) {
expect(JSON.parse(cachedMcp).mcpServers.memorix).toEqual({
type: 'http',
url: 'http://localhost:3211/mcp',
alwaysLoad: true,
});
}
// A real Claude CLI may create its own user config while registering the
// local marketplace. Memorix must not add a second standalone MCP entry.
const claudeConfig = await fs.readFile(path.join(tmpDir, '.claude.json'), 'utf8').catch(() => null);
Expand All @@ -508,6 +527,87 @@ describe('plugin package installer', () => {
}
});

it('writes type "http" for Claude and CodeBuddy plugin .mcp.json while keeping other formats unchanged', async () => {
const tmpDir = makeTmpDir();
try {
const claudePlugin = await installPluginPackage({ agent: 'claude', homeDir: tmpDir });
await rewriteBundledMemorixMcpToHttp(claudePlugin.pluginPath);
const claudeMcp = JSON.parse(await fs.readFile(path.join(claudePlugin.pluginPath, '.mcp.json'), 'utf-8'));
expect(claudeMcp.mcpServers.memorix).toEqual({
type: 'http',
url: 'http://localhost:3211/mcp',
alwaysLoad: true,
});

const codebuddyRoot = path.join(tmpDir, 'codebuddy-without-type');
await fs.mkdir(path.join(codebuddyRoot, '.codebuddy-plugin'), { recursive: true });
await fs.writeFile(path.join(codebuddyRoot, '.codebuddy-plugin', 'plugin.json'), '{"name":"memorix"}\n', 'utf-8');
await fs.writeFile(
path.join(codebuddyRoot, '.mcp.json'),
JSON.stringify({
mcpServers: {
memorix: { command: 'memorix', args: ['serve', '--mode', 'lite'] },
},
}, null, 2),
'utf-8',
);
await rewriteBundledMemorixMcpToHttp(codebuddyRoot);
const codebuddyMcp = JSON.parse(await fs.readFile(path.join(codebuddyRoot, '.mcp.json'), 'utf-8'));
expect(codebuddyMcp.mcpServers.memorix).toEqual({
type: 'http',
url: 'http://localhost:3211/mcp',
});

const codebuddyExplicit = path.join(tmpDir, 'codebuddy-explicit');
await fs.mkdir(codebuddyExplicit, { recursive: true });
await fs.writeFile(
path.join(codebuddyExplicit, '.mcp.json'),
JSON.stringify({
mcpServers: {
memorix: { command: 'memorix', args: ['serve', '--mode', 'lite'] },
},
}, null, 2),
'utf-8',
);
await rewriteBundledMemorixMcpToHttp(codebuddyExplicit, { agent: 'codebuddy' });
const codebuddyExplicitMcp = JSON.parse(await fs.readFile(path.join(codebuddyExplicit, '.mcp.json'), 'utf-8'));
expect(codebuddyExplicitMcp.mcpServers.memorix).toEqual({
type: 'http',
url: 'http://localhost:3211/mcp',
});

const codexPlugin = await installPluginPackage({ agent: 'codex', homeDir: tmpDir });
await rewriteBundledMemorixMcpToHttp(codexPlugin.pluginPath, { agent: 'codex' });
const codexMcp = JSON.parse(await fs.readFile(path.join(codexPlugin.pluginPath, '.mcp.json'), 'utf-8'));
expect(codexMcp.mcpServers.memorix).toEqual({
url: 'http://localhost:3211/mcp',
});

const geminiExt = await installGeminiExtensionPackage({ homeDir: tmpDir });
await rewriteBundledMemorixMcpToHttp(geminiExt.extensionPath, { agent: 'gemini-cli' });
const geminiMcp = JSON.parse(await fs.readFile(path.join(geminiExt.extensionPath, 'gemini-extension.json'), 'utf-8'));
expect(geminiMcp.mcpServers.memorix).toEqual({
url: 'http://localhost:3211/mcp',
});

const openclawBundle = await installOpenClawBundlePackage({ homeDir: tmpDir });
await rewriteBundledMemorixMcpToHttp(openclawBundle.bundlePath, { agent: 'openclaw' });
const openclawMcp = JSON.parse(await fs.readFile(path.join(openclawBundle.bundlePath, '.mcp.json'), 'utf-8'));
expect(openclawMcp.mcpServers.memorix).toEqual({
url: 'http://localhost:3211/mcp',
});

const antigravityPlugin = await installAntigravityPluginPackage({ homeDir: tmpDir });
await rewriteBundledMemorixMcpToHttp(antigravityPlugin.pluginPath, { agent: 'antigravity' });
const antigravityMcp = JSON.parse(await fs.readFile(path.join(antigravityPlugin.pluginPath, 'mcp_config.json'), 'utf-8'));
expect(antigravityMcp.mcpServers.memorix).toEqual({
url: 'http://localhost:3211/mcp',
});
} finally {
await cleanup(tmpDir);
}
});

});

describe('Codex legacy integration migration', () => {
Expand Down