`mcpctl config claude --project X` writes user scope and never rewrites a checkout's `.mcp.json`. The status line, however, preferred that file unconditionally — so a legacy project-named entry an older mcpctl left behind (`homeautomation` -> `mcpctl mcp -p homeautomation`) kept naming the old project for good, and every switch looked like it had done nothing. Reproduced live: with user scope on `sre`, `mcpctl statusline --directory ~/developer/michalzxc/claude/debug` printed `mcpctl:homeautomation` — a project Claude Code also had in `disabledMcpServers` for that directory, so the line named a server that was not even mounted. Rank the sources by how deliberate each one is instead: a canonical `mcpctl` pin, then user scope, then legacy residue, then the marker. A pin is a decision and still wins; residue is not and no longer does. At every step, skip a server Claude Code has switched off for that directory. `config claude` now also warns when the working directory's `.mcp.json` contradicts the switch, naming the file — the two scopes are merged rather than chosen between, so nothing else would tell you. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019wUmrfkVQR6CKcYKxENq7k
405 lines
17 KiB
TypeScript
405 lines
17 KiB
TypeScript
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
|
import { writeFileSync, readFileSync, mkdtempSync, rmSync, existsSync, mkdirSync } from 'node:fs';
|
|
import { join } from 'node:path';
|
|
import { tmpdir } from 'node:os';
|
|
import { createConfigCommand } from '../../src/commands/config.js';
|
|
import type { ApiClient } from '../../src/api-client.js';
|
|
import { saveCredentials, loadCredentials } from '../../src/auth/index.js';
|
|
|
|
function mockClient(): ApiClient {
|
|
return {
|
|
get: vi.fn(async () => ({})),
|
|
post: vi.fn(async () => ({ token: 'impersonated-tok', user: { email: 'other@test.com' } })),
|
|
put: vi.fn(async () => ({})),
|
|
delete: vi.fn(async () => {}),
|
|
} as unknown as ApiClient;
|
|
}
|
|
|
|
describe('config claude', () => {
|
|
let client: ReturnType<typeof mockClient>;
|
|
let output: string[];
|
|
let tmpDir: string;
|
|
const log = (...args: string[]) => output.push(args.join(' '));
|
|
|
|
/**
|
|
* Claude Code's config dir, redirected per test.
|
|
*
|
|
* Without this the suite writes a SessionStart hook, a status line and a
|
|
* slash command into the developer's real ~/.claude — which is exactly how an
|
|
* untagged duplicate of the skills-sync hook ended up there.
|
|
*/
|
|
let claudeDir: string;
|
|
let priorClaudeConfigDir: string | undefined;
|
|
|
|
beforeEach(() => {
|
|
client = mockClient();
|
|
output = [];
|
|
tmpDir = mkdtempSync(join(tmpdir(), 'mcpctl-config-claude-'));
|
|
claudeDir = join(tmpDir, 'claude-home');
|
|
priorClaudeConfigDir = process.env['CLAUDE_CONFIG_DIR'];
|
|
process.env['CLAUDE_CONFIG_DIR'] = claudeDir;
|
|
});
|
|
|
|
afterEach(() => {
|
|
rmSync(tmpDir, { recursive: true, force: true });
|
|
if (priorClaudeConfigDir === undefined) delete process.env['CLAUDE_CONFIG_DIR'];
|
|
else process.env['CLAUDE_CONFIG_DIR'] = priorClaudeConfigDir;
|
|
});
|
|
|
|
it('generates .mcp.json with mcpctl mcp bridge entry', async () => {
|
|
const outPath = join(tmpDir, '.mcp.json');
|
|
const cmd = createConfigCommand(
|
|
{ configDeps: { configDir: tmpDir }, log },
|
|
{ client, credentialsDeps: { configDir: tmpDir }, log },
|
|
);
|
|
// PR-5: --skip-skills bypasses the new sync + SessionStart hook side
|
|
// effects so this test stays focused on .mcp.json generation. The new
|
|
// sync flow has its own tests under src/cli/tests/utils/.
|
|
await cmd.parseAsync(['claude', '--project', 'homeautomation', '-o', outPath, '--skip-skills'], { from: 'user' });
|
|
|
|
// No API call should be made when --skip-skills is set.
|
|
expect(client.get).not.toHaveBeenCalled();
|
|
|
|
const written = JSON.parse(readFileSync(outPath, 'utf-8'));
|
|
expect(written.mcpServers['mcpctl']).toEqual({
|
|
command: 'mcpctl',
|
|
args: ['mcp', '-p', 'homeautomation'],
|
|
});
|
|
expect(output.join('\n')).toContain('1 server(s)');
|
|
});
|
|
|
|
it('prints to stdout with --stdout', async () => {
|
|
const cmd = createConfigCommand(
|
|
{ configDeps: { configDir: tmpDir }, log },
|
|
{ client, credentialsDeps: { configDir: tmpDir }, log },
|
|
);
|
|
await cmd.parseAsync(['claude', '--project', 'myproj', '--stdout'], { from: 'user' });
|
|
|
|
const parsed = JSON.parse(output[0]);
|
|
expect(parsed.mcpServers['mcpctl']).toEqual({
|
|
command: 'mcpctl',
|
|
args: ['mcp', '-p', 'myproj'],
|
|
});
|
|
});
|
|
|
|
it('always merges with existing .mcp.json', async () => {
|
|
const outPath = join(tmpDir, '.mcp.json');
|
|
writeFileSync(outPath, JSON.stringify({
|
|
mcpServers: { 'existing--server': { command: 'echo', args: [] } },
|
|
}));
|
|
|
|
const cmd = createConfigCommand(
|
|
{ configDeps: { configDir: tmpDir }, log },
|
|
{ client, credentialsDeps: { configDir: tmpDir }, log },
|
|
);
|
|
await cmd.parseAsync(['claude', '--project', 'proj-1', '-o', outPath], { from: 'user' });
|
|
|
|
const written = JSON.parse(readFileSync(outPath, 'utf-8'));
|
|
expect(written.mcpServers['existing--server']).toBeDefined();
|
|
expect(written.mcpServers['mcpctl']).toEqual({
|
|
command: 'mcpctl',
|
|
args: ['mcp', '-p', 'proj-1'],
|
|
});
|
|
expect(output.join('\n')).toContain('2 server(s)');
|
|
});
|
|
|
|
it('adds inspect MCP server with --inspect', async () => {
|
|
const outPath = join(tmpDir, '.mcp.json');
|
|
const cmd = createConfigCommand(
|
|
{ configDeps: { configDir: tmpDir }, log },
|
|
{ client, credentialsDeps: { configDir: tmpDir }, log },
|
|
);
|
|
await cmd.parseAsync(['claude', '--inspect', '-o', outPath], { from: 'user' });
|
|
|
|
const written = JSON.parse(readFileSync(outPath, 'utf-8'));
|
|
expect(written.mcpServers['mcpctl-inspect']).toEqual({
|
|
command: 'mcpctl',
|
|
args: ['console', '--stdin-mcp'],
|
|
});
|
|
expect(output.join('\n')).toContain('1 server(s)');
|
|
});
|
|
|
|
it('adds both project and inspect with --project --inspect', async () => {
|
|
const outPath = join(tmpDir, '.mcp.json');
|
|
const cmd = createConfigCommand(
|
|
{ configDeps: { configDir: tmpDir }, log },
|
|
{ client, credentialsDeps: { configDir: tmpDir }, log },
|
|
);
|
|
await cmd.parseAsync(['claude', '--project', 'ha', '--inspect', '-o', outPath], { from: 'user' });
|
|
|
|
const written = JSON.parse(readFileSync(outPath, 'utf-8'));
|
|
expect(written.mcpServers['mcpctl']).toBeDefined();
|
|
expect(written.mcpServers['mcpctl-inspect']).toBeDefined();
|
|
expect(output.join('\n')).toContain('2 server(s)');
|
|
});
|
|
|
|
it('backward compat: claude-generate still works', async () => {
|
|
const outPath = join(tmpDir, '.mcp.json');
|
|
const cmd = createConfigCommand(
|
|
{ configDeps: { configDir: tmpDir }, log },
|
|
{ client, credentialsDeps: { configDir: tmpDir }, log },
|
|
);
|
|
await cmd.parseAsync(['claude-generate', '--project', 'proj-1', '-o', outPath], { from: 'user' });
|
|
|
|
const written = JSON.parse(readFileSync(outPath, 'utf-8'));
|
|
expect(written.mcpServers['mcpctl']).toEqual({
|
|
command: 'mcpctl',
|
|
args: ['mcp', '-p', 'proj-1'],
|
|
});
|
|
});
|
|
|
|
it('uses one constant server key, whatever the project is called', async () => {
|
|
// The key used to be the project name, so `config claude` for a second
|
|
// project left the first one mounted too — every project ever configured
|
|
// stayed connected, with duplicate tool names.
|
|
const outPath = join(tmpDir, '.mcp.json');
|
|
const cmd = createConfigCommand({ configDeps: { configDir: tmpDir }, log });
|
|
await cmd.parseAsync(['claude', '--project', 'my-fancy-project', '-o', outPath, '--skip-skills'], { from: 'user' });
|
|
|
|
const written = JSON.parse(readFileSync(outPath, 'utf-8'));
|
|
expect(Object.keys(written.mcpServers)).toEqual(['mcpctl']);
|
|
expect(written.mcpServers['mcpctl'].args).toEqual(['mcp', '-p', 'my-fancy-project']);
|
|
});
|
|
|
|
it('switching projects replaces the mount instead of stacking a second one', async () => {
|
|
const outPath = join(tmpDir, '.mcp.json');
|
|
const cmd = createConfigCommand({ configDeps: { configDir: tmpDir }, log });
|
|
await cmd.parseAsync(['claude', '--project', 'first', '-o', outPath, '--skip-skills'], { from: 'user' });
|
|
await cmd.parseAsync(['claude', '--project', 'second', '-o', outPath, '--skip-skills'], { from: 'user' });
|
|
|
|
const written = JSON.parse(readFileSync(outPath, 'utf-8'));
|
|
expect(Object.keys(written.mcpServers)).toEqual(['mcpctl']);
|
|
expect(written.mcpServers['mcpctl'].args).toEqual(['mcp', '-p', 'second']);
|
|
});
|
|
|
|
it('retires a legacy project-named entry left by an older CLI', async () => {
|
|
const outPath = join(tmpDir, '.mcp.json');
|
|
writeFileSync(outPath, JSON.stringify({
|
|
mcpServers: {
|
|
homeautomation: { command: 'mcpctl', args: ['mcp', '-p', 'homeautomation'] },
|
|
'my-own-server': { command: 'echo', args: [] },
|
|
},
|
|
}));
|
|
const cmd = createConfigCommand({ configDeps: { configDir: tmpDir }, log });
|
|
await cmd.parseAsync(['claude', '--project', 'docmost', '-o', outPath, '--skip-skills'], { from: 'user' });
|
|
|
|
const written = JSON.parse(readFileSync(outPath, 'utf-8'));
|
|
expect(Object.keys(written.mcpServers).sort()).toEqual(['mcpctl', 'my-own-server']);
|
|
expect(output.join('\n')).toContain('Retired legacy per-project entry: homeautomation');
|
|
});
|
|
|
|
it('--dry-run reports the plan and writes nothing', async () => {
|
|
const outPath = join(tmpDir, '.mcp.json');
|
|
const cmd = createConfigCommand({ configDeps: { configDir: tmpDir }, log });
|
|
await cmd.parseAsync(['claude', '--project', 'p', '-o', outPath, '--dry-run'], { from: 'user' });
|
|
|
|
const plan = JSON.parse(output.join('\n'));
|
|
expect(plan.claude.server).toBe('mcpctl');
|
|
expect(plan.claude.entry.args).toEqual(['mcp', '-p', 'p']);
|
|
expect(existsSync(outPath)).toBe(false);
|
|
});
|
|
});
|
|
|
|
describe('config impersonate', () => {
|
|
let client: ReturnType<typeof mockClient>;
|
|
let output: string[];
|
|
let tmpDir: string;
|
|
const log = (...args: string[]) => output.push(args.join(' '));
|
|
|
|
beforeEach(() => {
|
|
client = mockClient();
|
|
output = [];
|
|
tmpDir = mkdtempSync(join(tmpdir(), 'mcpctl-config-impersonate-'));
|
|
});
|
|
|
|
afterEach(() => {
|
|
rmSync(tmpDir, { recursive: true, force: true });
|
|
});
|
|
|
|
it('impersonates a user and saves backup', async () => {
|
|
saveCredentials({ token: 'admin-tok', mcpdUrl: 'http://localhost:3100', user: 'admin@test.com' }, { configDir: tmpDir });
|
|
|
|
const cmd = createConfigCommand(
|
|
{ configDeps: { configDir: tmpDir }, log },
|
|
{ client, credentialsDeps: { configDir: tmpDir }, log },
|
|
);
|
|
await cmd.parseAsync(['impersonate', 'other@test.com'], { from: 'user' });
|
|
|
|
expect(client.post).toHaveBeenCalledWith('/api/v1/auth/impersonate', { email: 'other@test.com' });
|
|
expect(output.join('\n')).toContain('Impersonating other@test.com');
|
|
|
|
const creds = loadCredentials({ configDir: tmpDir });
|
|
expect(creds!.user).toBe('other@test.com');
|
|
expect(creds!.token).toBe('impersonated-tok');
|
|
|
|
// Backup exists
|
|
const backup = JSON.parse(readFileSync(join(tmpDir, 'credentials-backup'), 'utf-8'));
|
|
expect(backup.user).toBe('admin@test.com');
|
|
});
|
|
|
|
it('quits impersonation and restores backup', async () => {
|
|
// Set up current (impersonated) credentials
|
|
saveCredentials({ token: 'impersonated-tok', mcpdUrl: 'http://localhost:3100', user: 'other@test.com' }, { configDir: tmpDir });
|
|
// Set up backup (original) credentials
|
|
writeFileSync(join(tmpDir, 'credentials-backup'), JSON.stringify({
|
|
token: 'admin-tok', mcpdUrl: 'http://localhost:3100', user: 'admin@test.com',
|
|
}));
|
|
|
|
const cmd = createConfigCommand(
|
|
{ configDeps: { configDir: tmpDir }, log },
|
|
{ client, credentialsDeps: { configDir: tmpDir }, log },
|
|
);
|
|
await cmd.parseAsync(['impersonate', '--quit'], { from: 'user' });
|
|
|
|
expect(output.join('\n')).toContain('Returned to admin@test.com');
|
|
|
|
const creds = loadCredentials({ configDir: tmpDir });
|
|
expect(creds!.user).toBe('admin@test.com');
|
|
expect(creds!.token).toBe('admin-tok');
|
|
});
|
|
|
|
it('errors when not logged in', async () => {
|
|
const cmd = createConfigCommand(
|
|
{ configDeps: { configDir: tmpDir }, log },
|
|
{ client, credentialsDeps: { configDir: tmpDir }, log },
|
|
);
|
|
await cmd.parseAsync(['impersonate', 'other@test.com'], { from: 'user' });
|
|
|
|
expect(output.join('\n')).toContain('Not logged in');
|
|
});
|
|
|
|
it('errors when quitting with no backup', async () => {
|
|
const cmd = createConfigCommand(
|
|
{ configDeps: { configDir: tmpDir }, log },
|
|
{ client, credentialsDeps: { configDir: tmpDir }, log },
|
|
);
|
|
await cmd.parseAsync(['impersonate', '--quit'], { from: 'user' });
|
|
|
|
expect(output.join('\n')).toContain('No impersonation session to quit');
|
|
});
|
|
});
|
|
|
|
describe('config claude — user scope', () => {
|
|
let output: string[];
|
|
let tmpDir: string;
|
|
let claudeDir: string;
|
|
let prior: string | undefined;
|
|
const log = (...args: string[]): void => { output.push(args.join(' ')); };
|
|
const claudeJson = (): string => join(claudeDir, '.claude.json');
|
|
|
|
beforeEach(() => {
|
|
output = [];
|
|
tmpDir = mkdtempSync(join(tmpdir(), 'mcpctl-claude-user-'));
|
|
claudeDir = join(tmpDir, 'claude-home');
|
|
mkdirSync(claudeDir, { recursive: true });
|
|
prior = process.env['CLAUDE_CONFIG_DIR'];
|
|
process.env['CLAUDE_CONFIG_DIR'] = claudeDir;
|
|
});
|
|
afterEach(() => {
|
|
rmSync(tmpDir, { recursive: true, force: true });
|
|
if (prior === undefined) delete process.env['CLAUDE_CONFIG_DIR'];
|
|
else process.env['CLAUDE_CONFIG_DIR'] = prior;
|
|
});
|
|
|
|
const cmd = () => createConfigCommand({ configDeps: {}, log });
|
|
|
|
it('registers in .claude.json by default, not a per-directory .mcp.json', async () => {
|
|
// The whole point: wire it once, not in every checkout you open.
|
|
await cmd().parseAsync(['claude', '--project', 'homeautomation', '--skip-skills', '--skip-ui'], { from: 'user' });
|
|
const parsed = JSON.parse(readFileSync(claudeJson(), 'utf-8'));
|
|
expect(parsed.mcpServers.mcpctl).toEqual({ command: 'mcpctl', args: ['mcp', '-p', 'homeautomation'] });
|
|
expect(output.join('\n')).toContain('every directory');
|
|
});
|
|
|
|
it('preserves everything else in .claude.json', async () => {
|
|
// That file also holds onboarding state, caches and the per-project map.
|
|
writeFileSync(claudeJson(), JSON.stringify({
|
|
numStartups: 42,
|
|
mcpServers: { 'taskmaster-ai': { type: 'stdio', command: 'task-master-ai' } },
|
|
projects: { '/some/repo': { allowedTools: [] } },
|
|
}));
|
|
await cmd().parseAsync(['claude', '--project', 'p', '--skip-skills', '--skip-ui'], { from: 'user' });
|
|
const parsed = JSON.parse(readFileSync(claudeJson(), 'utf-8'));
|
|
expect(parsed.numStartups).toBe(42);
|
|
expect(parsed.projects).toEqual({ '/some/repo': { allowedTools: [] } });
|
|
expect(parsed.mcpServers['taskmaster-ai']).toBeDefined();
|
|
expect(parsed.mcpServers.mcpctl.args).toEqual(['mcp', '-p', 'p']);
|
|
});
|
|
|
|
it('switching re-points the one entry', async () => {
|
|
await cmd().parseAsync(['claude', '--project', 'a', '--skip-skills', '--skip-ui'], { from: 'user' });
|
|
await cmd().parseAsync(['claude', '--project', 'b', '--skip-skills', '--skip-ui'], { from: 'user' });
|
|
const parsed = JSON.parse(readFileSync(claudeJson(), 'utf-8'));
|
|
expect(Object.keys(parsed.mcpServers)).toEqual(['mcpctl']);
|
|
expect(parsed.mcpServers.mcpctl.args).toEqual(['mcp', '-p', 'b']);
|
|
});
|
|
|
|
it('writes no .mcpctl-project marker — user scope is not directory-specific', async () => {
|
|
// A marker beside .claude.json would sit in $HOME and scope every repo under it.
|
|
const cwd = process.cwd();
|
|
process.chdir(tmpDir);
|
|
try {
|
|
await cmd().parseAsync(['claude', '--project', 'p', '--skip-ui'], { from: 'user' });
|
|
expect(existsSync(join(tmpDir, '.mcpctl-project'))).toBe(false);
|
|
expect(output.join('\n')).toContain('not directory-specific');
|
|
} finally { process.chdir(cwd); }
|
|
});
|
|
|
|
it('an explicit --output still means the per-directory file', async () => {
|
|
const outPath = join(tmpDir, '.mcp.json');
|
|
await cmd().parseAsync(['claude', '--project', 'p', '-o', outPath, '--skip-skills', '--skip-ui'], { from: 'user' });
|
|
expect(existsSync(outPath)).toBe(true);
|
|
expect(existsSync(claudeJson())).toBe(false);
|
|
});
|
|
|
|
it('rejects an unknown scope instead of silently picking one', async () => {
|
|
const prevExit = process.exitCode;
|
|
await cmd().parseAsync(['claude', '--project', 'p', '--scope', 'global', '--skip-skills'], { from: 'user' });
|
|
expect(process.exitCode).toBe(1);
|
|
process.exitCode = prevExit;
|
|
expect(output.join('\n')).toContain("unknown --scope 'global'");
|
|
});
|
|
|
|
// A user-scope switch never rewrites a directory's .mcp.json, so anything of
|
|
// ours left in one keeps answering in that directory. Saying so is the only
|
|
// way the user finds out — the switch otherwise reports plain success.
|
|
describe('warns when the working directory contradicts the switch', () => {
|
|
const switchTo = async (project: string): Promise<string> => {
|
|
await createConfigCommand({ configDeps: {}, log, cwd: () => tmpDir })
|
|
.parseAsync(['claude', '--project', project, '--skip-skills', '--skip-ui'], { from: 'user' });
|
|
return output.join('\n');
|
|
};
|
|
|
|
it('names a legacy entry that stays mounted alongside the new project', async () => {
|
|
writeFileSync(join(tmpDir, '.mcp.json'), JSON.stringify({
|
|
mcpServers: { homeautomation: { command: 'mcpctl', args: ['mcp', '-p', 'homeautomation'] } },
|
|
}));
|
|
const out = await switchTo('sre');
|
|
expect(out).toContain(join(tmpDir, '.mcp.json'));
|
|
expect(out).toContain("'homeautomation'");
|
|
expect(out).toContain('mounted alongside');
|
|
});
|
|
|
|
it('says a canonical pin overrides the switch in that directory', async () => {
|
|
writeFileSync(join(tmpDir, '.mcp.json'), JSON.stringify({
|
|
mcpServers: { mcpctl: { command: 'mcpctl', args: ['mcp', '-p', 'docmost'] } },
|
|
}));
|
|
expect(await switchTo('sre')).toContain('overrides the switch here');
|
|
});
|
|
|
|
it('stays quiet when the directory already agrees, or wires nothing of ours', async () => {
|
|
writeFileSync(join(tmpDir, '.mcp.json'), JSON.stringify({
|
|
mcpServers: {
|
|
mcpctl: { command: 'mcpctl', args: ['mcp', '-p', 'sre'] },
|
|
'their-server': { command: 'docker', args: ['run', 'x'] },
|
|
},
|
|
}));
|
|
expect(await switchTo('sre')).not.toContain('Warning:');
|
|
});
|
|
|
|
it('stays quiet when there is no .mcp.json at all', async () => {
|
|
expect(await switchTo('sre')).not.toContain('Warning:');
|
|
});
|
|
});
|
|
});
|