feat(opencode): native opencode integration — /mcpctl switcher, live project switching, footer indicator
Adds `mcpctl config opencode`, two opencode plugins and an `opencode` skills
sync target, so an mcpctl project can be switched from inside opencode's TUI
and the active one is visible at a glance.
Unlike `config claude` / `config prime-agent`, this writes NO MCP entry into
the host's config. opencode exposes an HTTP API for its own MCP registry
(`POST /mcp`), so the project is mounted through the running app:
- the token stays in ~/.mcpctl/opencode-state.json (0600) instead of a
mode-0644 opencode.json users paste into bug reports;
- switching projects takes effect on the next turn, with no restart.
Inside opencode:
/mcpctl filterable project picker; switches live
/mcpctl-status active project, mount state, gateway URL
/mcpctl-skills re-sync this project's skills
plus a `mcpctl:<project>` indicator in the prompt footer, next to the model
name and one line above the token counter.
Design notes:
- the MCP server is registered under a constant name, so tools keep a stable
`mcpctl_*` prefix and opencode's per-request tool resolution shows the new
project's tools by itself — no "your old tool names are dead" message to
the model, unlike the pi extension;
- an unchanged mount is never re-registered: mcp.add rebuilds the connection
and mcplocal binds a gated project's unlocked state to that connection's
mcp-session-id, so re-adding would re-lock a project begin_session had just
opened;
- the server plugin does not mount during setup — setup runs before the
server accepts connections and mcp.add calls back into it, which hangs
opencode on a blank screen before the TUI draws;
- the switcher shells out to this CLI (--skip-plugin --skip-marker) so token
minting, state and skills stay in one place;
- no usable credential aborts non-zero with the state file untouched, so a
failed switch leaves the previous project working rather than swapping it
for a mount that 401s.
`skills sync --agent opencode` installs into ~/.config/opencode/skill (XDG
aware) with the same shared-tree semantics as pi and prime-agent. The
credential plumbing shared with `config prime-agent` is lifted to one place and
parameterised by agent rather than copied.
The plugin sources are embedded in the CLI (generated, freshness-tested) so an
installed binary with no source tree can provision them, and are typechecked
against the real @opencode-ai/plugin types.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BVwuCjuMoA13gmzYEfcrNP
This commit is contained in:
210
src/cli/tests/commands/config-opencode.test.ts
Normal file
210
src/cli/tests/commands/config-opencode.test.ts
Normal file
@@ -0,0 +1,210 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { mkdtempSync, rmSync, readFileSync, writeFileSync, 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';
|
||||
|
||||
interface ClientCalls { posts: Array<{ path: string; body?: unknown }> }
|
||||
|
||||
/**
|
||||
* @param tokens what `GET /api/v1/mcptokens` reports as existing for a project
|
||||
*/
|
||||
function mockClient(calls: ClientCalls, tokens: unknown[] = []): ApiClient {
|
||||
return {
|
||||
get: vi.fn(async (path: string) => {
|
||||
if (path.startsWith('/api/v1/mcptokens')) return tokens;
|
||||
if (path.endsWith('/skills/visible')) return [];
|
||||
return {};
|
||||
}),
|
||||
post: vi.fn(async (path: string, body?: unknown) => {
|
||||
calls.posts.push({ path, body });
|
||||
if (path === '/api/v1/mcptokens') return { token: 'mcpctl_pat_MINTED0000000000' };
|
||||
return {};
|
||||
}),
|
||||
put: vi.fn(async () => ({})),
|
||||
delete: vi.fn(async () => {}),
|
||||
} as unknown as ApiClient;
|
||||
}
|
||||
|
||||
describe('config opencode', () => {
|
||||
let output: string[];
|
||||
let tmpDir: string;
|
||||
let ocDir: string;
|
||||
let calls: ClientCalls;
|
||||
const log = (...args: string[]): void => { output.push(args.join(' ')); };
|
||||
const statePath = (): string => join(ocDir, 'mcpctl-state.json');
|
||||
|
||||
/** Pre-existing state, as a machine that has already run this command has. */
|
||||
function seedState(value: unknown): void {
|
||||
mkdirSync(ocDir, { recursive: true });
|
||||
writeFileSync(statePath(), JSON.stringify(value));
|
||||
}
|
||||
|
||||
function command(client: ApiClient) {
|
||||
return createConfigCommand(
|
||||
{ configDeps: { configDir: tmpDir }, log },
|
||||
{ client, credentialsDeps: { configDir: tmpDir }, log },
|
||||
);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
output = [];
|
||||
calls = { posts: [] };
|
||||
tmpDir = mkdtempSync(join(tmpdir(), 'mcpctl-config-oc-'));
|
||||
ocDir = join(tmpDir, 'opencode');
|
||||
});
|
||||
afterEach(() => { rmSync(tmpDir, { recursive: true, force: true }); });
|
||||
|
||||
it('requires a project', async () => {
|
||||
await command(mockClient(calls)).parseAsync(
|
||||
['opencode', '--opencode-dir', ocDir, '--skip-skills'], { from: 'user' });
|
||||
expect(output.join('\n')).toContain('--project is required');
|
||||
expect(existsSync(statePath())).toBe(false);
|
||||
});
|
||||
|
||||
it('installs both plugins, registers the TUI one and writes the state file', async () => {
|
||||
await command(mockClient(calls)).parseAsync(
|
||||
['opencode', '--project', 'docmost', '--opencode-dir', ocDir,
|
||||
'--gateway-url', 'https://gw.example', '--token', 'mcpctl_pat_SUPPLIED000000',
|
||||
'--skip-skills', '--skip-marker'],
|
||||
{ from: 'user' });
|
||||
|
||||
expect(existsSync(join(ocDir, 'plugin', 'mcpctl.ts'))).toBe(true);
|
||||
expect(existsSync(join(ocDir, 'mcpctl', 'mcpctl-tui.tsx'))).toBe(true);
|
||||
|
||||
const tui = JSON.parse(readFileSync(join(ocDir, 'tui.json'), 'utf-8'));
|
||||
expect(tui.plugin).toEqual([join(ocDir, 'mcpctl', 'mcpctl-tui.tsx')]);
|
||||
|
||||
const state = JSON.parse(readFileSync(statePath(), 'utf-8'));
|
||||
expect(state).toEqual({
|
||||
project: 'docmost',
|
||||
gatewayUrl: 'https://gw.example',
|
||||
tokens: { docmost: 'mcpctl_pat_SUPPLIED000000' },
|
||||
});
|
||||
});
|
||||
|
||||
it('strips a trailing slash from the gateway URL so the mount URL stays canonical', async () => {
|
||||
await command(mockClient(calls)).parseAsync(
|
||||
['opencode', '--project', 'p', '--opencode-dir', ocDir, '--gateway-url', 'https://gw.example/',
|
||||
'--token', 't', '--skip-skills', '--skip-marker'],
|
||||
{ from: 'user' });
|
||||
expect(JSON.parse(readFileSync(statePath(), 'utf-8')).gatewayUrl).toBe('https://gw.example');
|
||||
});
|
||||
|
||||
it('--token never mints', async () => {
|
||||
await command(mockClient(calls)).parseAsync(
|
||||
['opencode', '--project', 'p', '--opencode-dir', ocDir, '--token', 't',
|
||||
'--skip-skills', '--skip-marker'],
|
||||
{ from: 'user' });
|
||||
expect(calls.posts.filter((c) => c.path === '/api/v1/mcptokens')).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('mints a uniquely-named opencode token when none is stored', async () => {
|
||||
await command(mockClient(calls)).parseAsync(
|
||||
['opencode', '--project', 'p', '--opencode-dir', ocDir, '--skip-skills', '--skip-marker'],
|
||||
{ from: 'user' });
|
||||
const mint = calls.posts.find((c) => c.path === '/api/v1/mcptokens');
|
||||
expect(mint).toBeDefined();
|
||||
// A fixed name could only ever be minted once per project: McpToken is
|
||||
// unique on (name, projectId) and revoke is a soft delete.
|
||||
expect((mint?.body as { name: string }).name).toMatch(/^opencode-/);
|
||||
expect(JSON.parse(readFileSync(statePath(), 'utf-8')).tokens.p).toBe('mcpctl_pat_MINTED0000000000');
|
||||
});
|
||||
|
||||
it('reuses a stored token that the server still reports as active', async () => {
|
||||
// 16-char prefix is what the server exposes; the secret is never re-sent.
|
||||
const stored = 'mcpctl_pat_STORED000000000';
|
||||
seedState({ project: 'p', gatewayUrl: 'https://gw', tokens: { p: stored } });
|
||||
const client = mockClient(calls, [{ id: '1', name: 'opencode-x', status: 'active', tokenPrefix: stored.slice(0, 16) }]);
|
||||
await command(client).parseAsync(
|
||||
['opencode', '--project', 'p', '--opencode-dir', ocDir, '--skip-skills', '--skip-marker'],
|
||||
{ from: 'user' });
|
||||
expect(calls.posts.filter((c) => c.path === '/api/v1/mcptokens')).toHaveLength(0);
|
||||
expect(output.join('\n')).toContain('already present');
|
||||
});
|
||||
|
||||
it('re-mints when the stored token has been revoked server-side', async () => {
|
||||
const stored = 'mcpctl_pat_REVOKED00000000';
|
||||
seedState({ project: 'p', gatewayUrl: 'https://gw', tokens: { p: stored } });
|
||||
const client = mockClient(calls, [{ id: '1', name: 'opencode-x', status: 'revoked', tokenPrefix: stored.slice(0, 16) }]);
|
||||
await command(client).parseAsync(
|
||||
['opencode', '--project', 'p', '--opencode-dir', ocDir, '--skip-skills', '--skip-marker'],
|
||||
{ from: 'user' });
|
||||
expect(calls.posts.filter((c) => c.path === '/api/v1/mcptokens')).toHaveLength(1);
|
||||
expect(JSON.parse(readFileSync(statePath(), 'utf-8')).tokens.p).toBe('mcpctl_pat_MINTED0000000000');
|
||||
});
|
||||
|
||||
it('leaves the previous project mounted when no credential can be provisioned', async () => {
|
||||
// A switch with no usable credential is a FAILURE: exiting 0 here would
|
||||
// have the /mcpctl switcher report success over a project with no tools.
|
||||
seedState({ project: 'old', gatewayUrl: 'https://gw', tokens: { old: 'tok-old' } });
|
||||
const client = {
|
||||
get: vi.fn(async () => []),
|
||||
post: vi.fn(async () => ({})), // mint returns no token
|
||||
put: vi.fn(async () => ({})),
|
||||
delete: vi.fn(async () => {}),
|
||||
} as unknown as ApiClient;
|
||||
const prevExit = process.exitCode;
|
||||
await command(client).parseAsync(
|
||||
['opencode', '--project', 'new', '--opencode-dir', ocDir, '--skip-skills', '--skip-marker'],
|
||||
{ from: 'user' });
|
||||
expect(process.exitCode).toBe(1);
|
||||
process.exitCode = prevExit;
|
||||
expect(JSON.parse(readFileSync(statePath(), 'utf-8')).project).toBe('old');
|
||||
expect(output.join('\n')).toContain('Aborted');
|
||||
});
|
||||
|
||||
it('--skip-plugin updates state without touching the loaded plugin files', async () => {
|
||||
// This is the path the /mcpctl switcher takes: rewriting the very file
|
||||
// opencode has already loaded buys nothing.
|
||||
await command(mockClient(calls)).parseAsync(
|
||||
['opencode', '--project', 'p', '--opencode-dir', ocDir, '--token', 't',
|
||||
'--skip-plugin', '--skip-skills', '--skip-marker'],
|
||||
{ from: 'user' });
|
||||
expect(existsSync(join(ocDir, 'plugin', 'mcpctl.ts'))).toBe(false);
|
||||
expect(existsSync(join(ocDir, 'tui.json'))).toBe(false);
|
||||
expect(JSON.parse(readFileSync(statePath(), 'utf-8')).project).toBe('p');
|
||||
});
|
||||
|
||||
it('--dry-run reports the plan and writes nothing', async () => {
|
||||
await command(mockClient(calls)).parseAsync(
|
||||
['opencode', '--project', 'p', '--opencode-dir', ocDir, '--dry-run'], { from: 'user' });
|
||||
const plan = JSON.parse(output.join('\n'));
|
||||
expect(plan.opencode.mcpUrl).toContain('/projects/p/mcp');
|
||||
expect(plan.opencode.statePath).toBe(statePath());
|
||||
expect(existsSync(ocDir)).toBe(false);
|
||||
expect(calls.posts).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('--skip-marker leaves the working directory unscoped', async () => {
|
||||
const cwd = process.cwd();
|
||||
const workDir = join(tmpDir, 'work');
|
||||
mkdirSync(workDir, { recursive: true });
|
||||
process.chdir(workDir);
|
||||
try {
|
||||
await command(mockClient(calls)).parseAsync(
|
||||
['opencode', '--project', 'p', '--opencode-dir', ocDir, '--token', 't',
|
||||
'--skip-skills', '--skip-marker'],
|
||||
{ from: 'user' });
|
||||
expect(existsSync(join(workDir, '.mcpctl-project'))).toBe(false);
|
||||
} finally {
|
||||
process.chdir(cwd);
|
||||
}
|
||||
});
|
||||
|
||||
it('writes a .mcpctl-project marker by default', async () => {
|
||||
const cwd = process.cwd();
|
||||
const workDir = join(tmpDir, 'work2');
|
||||
mkdirSync(workDir, { recursive: true });
|
||||
process.chdir(workDir);
|
||||
try {
|
||||
await command(mockClient(calls)).parseAsync(
|
||||
['opencode', '--project', 'p', '--opencode-dir', ocDir, '--token', 't', '--skip-skills'],
|
||||
{ from: 'user' });
|
||||
expect(readFileSync(join(workDir, '.mcpctl-project'), 'utf-8')).toContain('p');
|
||||
} finally {
|
||||
process.chdir(cwd);
|
||||
}
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user