Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

feat(open-knowledge): preview_url auto-starts the OK backend on demand (#1793)

mike-inkeepc50ac604d22b
diff --git a/.changeset/preview-url-demand-starts-backend.md b/.changeset/preview-url-demand-starts-backend.md
new file mode 100644
index 000000000..1218e55cb
--- /dev/null
+++ b/.changeset/preview-url-demand-starts-backend.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+`preview_url` now treats a preview request as demand for a backend. When no Open Knowledge server is running for the project, the tool auto-starts one through the same machinery the read/write tools use (`OK_MCP_AUTOSTART` gate, spawn timeout, spawn-error log) and waits briefly for the preview UI sibling to bind, so an agent whose first action is "open the preview" gets a working URL instead of `running: false`. The ensure also runs when a UI is already up, which revives the backend for a surviving preview UI whose server idle-shut-down. When no UI can be reached the recovery hint now names the right command for the actual state: `ok start` when nothing is running (previously the hint said `ok ui`, which produces a backend-less UI shell in that state) and `ok ui` when the server is alive but no UI is bound. Auto-start opt-out (`OK_MCP_AUTOSTART=0`) keeps today's soft not-running answer; spawn failures surface as tool errors with the spawn log attached.
diff --git a/.changeset/worktree-sticky-cwd.md b/.changeset/worktree-sticky-cwd.md
new file mode 100644
index 000000000..0e829150b
--- /dev/null
+++ b/.changeset/worktree-sticky-cwd.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+MCP project routing now sticks to the worktree you name. Pass `cwd` once on an OK tool call and later `cwd`-less calls in the same session reuse it, so an agent working in a git worktree no longer has its reads, writes, and preview silently target the main checkout. When a `cwd`-less call resolves into a repo that has multiple git worktrees via the client's single advertised root, the server emits a one-time, non-blocking nudge to pass `cwd` — it does not refuse, so working in the main checkout while feature worktrees exist is unaffected.
diff --git a/packages/cli/src/mcp/server.test.ts b/packages/cli/src/mcp/server.test.ts
index f93bfed6e..54b3bdd9a 100644
--- a/packages/cli/src/mcp/server.test.ts
+++ b/packages/cli/src/mcp/server.test.ts
@@ -5,8 +5,9 @@ import { tmpdir } from 'node:os';
import { resolve } from 'node:path';
import { sanitizeClientName } from '@inkeep/open-knowledge-server';
import {
+ countWorktrees,
findProjectDir,
- resolveCwdWithFallback,
+ resolveStickyProjectDir,
rootUriToFsPath,
tryListRootsFallback,
} from './server.ts';
@@ -243,7 +244,7 @@ describe('tryListRootsFallback', () => {
});
});
-describe('resolveCwdWithFallback', () => {
+describe('resolveStickyProjectDir', () => {
let tmpDir: string;
beforeEach(async () => {
@@ -256,46 +257,82 @@ describe('resolveCwdWithFallback', () => {
await rm(tmpDir, { recursive: true, force: true });
});
- test('prefers explicit cwd over the fallback', async () => {
+ test('explicit cwd wins over the fallback and becomes the next sticky anchor', async () => {
let fallbackCalls = 0;
- const result = await resolveCwdWithFallback(tmpDir, async () => {
+ const r = await resolveStickyProjectDir(tmpDir, undefined, async () => {
fallbackCalls += 1;
return undefined;
});
- expect(result).toBe(resolve(tmpDir));
+ expect(r.projectDir).toBe(resolve(tmpDir));
+ expect(r.viaRootGuess).toBe(false);
+ expect(r.nextSticky).toBe(resolve(tmpDir));
expect(fallbackCalls).toBe(0);
});
- test('uses the fallback when cwd is omitted', async () => {
- const result = await resolveCwdWithFallback(undefined, async () => tmpDir);
- expect(result).toBe(resolve(tmpDir));
+ test('reuses the sticky anchor when cwd is omitted, never consulting the fallback', async () => {
+ let fallbackCalls = 0;
+ const r = await resolveStickyProjectDir(undefined, resolve(tmpDir), async () => {
+ fallbackCalls += 1;
+ return undefined;
+ });
+ expect(r.projectDir).toBe(resolve(tmpDir));
+ expect(r.viaRootGuess).toBe(false); // sticky is the agent's named intent, not a guess
+ expect(r.nextSticky).toBe(resolve(tmpDir));
+ expect(fallbackCalls).toBe(0);
+ });
+
+ test('falls through to the root guess only with no explicit and no sticky, flagging viaRootGuess; a guess never sticks', async () => {
+ const r = await resolveStickyProjectDir(undefined, undefined, async () => tmpDir);
+ expect(r.projectDir).toBe(resolve(tmpDir));
+ expect(r.viaRootGuess).toBe(true);
+ expect(r.nextSticky).toBeUndefined();
});
- test('throws when cwd is omitted and the fallback returns undefined', async () => {
- await expect(resolveCwdWithFallback(undefined, async () => undefined)).rejects.toThrow(
- /`cwd` is required/,
- );
+ test('returns no project (no throw) when cwd omitted, no sticky, and the fallback returns undefined', async () => {
+ const r = await resolveStickyProjectDir(undefined, undefined, async () => undefined);
+ expect(r.projectDir).toBeUndefined();
+ expect(r.viaRootGuess).toBe(false);
+ expect(r.nextSticky).toBeUndefined();
});
test('throws (via findProjectDir) when explicit cwd has no .ok ancestor', async () => {
const noOkDir = await mkdtemp(resolve(tmpdir(), 'ok-mcp-no-project-'));
try {
- await expect(resolveCwdWithFallback(noOkDir, async () => undefined)).rejects.toThrow(
- /No Open Knowledge project found/,
- );
+ await expect(
+ resolveStickyProjectDir(noOkDir, undefined, async () => undefined),
+ ).rejects.toThrow(/No Open Knowledge project found/);
} finally {
await rm(noOkDir, { recursive: true, force: true });
}
});
- test('throws (via findProjectDir) when the fallback returns a non-OK path', async () => {
+ test('throws (via findProjectDir) when the root guess returns a non-OK path', async () => {
const noOkDir = await mkdtemp(resolve(tmpdir(), 'ok-mcp-fallback-no-project-'));
try {
- await expect(resolveCwdWithFallback(undefined, async () => noOkDir)).rejects.toThrow(
- /No Open Knowledge project found/,
- );
+ await expect(
+ resolveStickyProjectDir(undefined, undefined, async () => noOkDir),
+ ).rejects.toThrow(/No Open Knowledge project found/);
} finally {
await rm(noOkDir, { recursive: true, force: true });
}
});
+
+ test('re-validates the sticky anchor on reuse: a deleted sticky path throws instead of resolving silently', async () => {
+ const goneDir = await mkdtemp(resolve(tmpdir(), 'ok-mcp-sticky-gone-'));
+ await rm(goneDir, { recursive: true, force: true });
+ await expect(
+ resolveStickyProjectDir(undefined, goneDir, async () => undefined),
+ ).rejects.toThrow(/No Open Knowledge project found/);
+ });
+});
+
+describe('countWorktrees', () => {
+ test('returns 0 for a non-git directory (no ambiguity → no nudge)', async () => {
+ const dir = await mkdtemp(resolve(tmpdir(), 'ok-mcp-no-git-'));
+ try {
+ expect(await countWorktrees(dir)).toBe(0);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+ });
});
diff --git a/packages/cli/src/mcp/server.ts b/packages/cli/src/mcp/server.ts
index 0499340d7..fcc1c190c 100644
--- a/packages/cli/src/mcp/server.ts
+++ b/packages/cli/src/mcp/server.ts
@@ -1,7 +1,9 @@
+import { execFile } from 'node:child_process';
import { randomUUID } from 'node:crypto';
import { realpathSync, statSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
+import { promisify } from 'node:util';
import { OK_PROJECT_MARKER } from '@inkeep/open-knowledge-core';
import { type KeepaliveHandle, startKeepalive } from '@inkeep/open-knowledge-core/keepalive';
import {
@@ -32,6 +34,19 @@ import { parseSpawnTimeoutEnv, resolveMcpHttpUrl, resolveMcpKeepaliveWsUrl } fro
const BUNDLE_IDENTITY_ANCHOR = fileURLToPath(import.meta.url);
+const execFileAsync = promisify(execFile);
+
+export async function countWorktrees(dir: string): Promise<number> {
+ try {
+ const { stdout } = await execFileAsync('git', ['-C', dir, 'worktree', 'list', '--porcelain'], {
+ timeout: 2000,
+ });
+ return stdout.split('\n').filter((line) => line.startsWith('worktree ')).length;
+ } catch {
+ return 0;
+ }
+}
+
interface StartGlobalMcpServerOptions {
startupCwd: string;
startupConfig: Config;
@@ -90,18 +105,44 @@ export async function tryListRootsFallback(opts: {
return fsPath;
}
-export async function resolveCwdWithFallback(
+export interface StickyProjectResolution {
+ /** Resolved OK project root, or `undefined` when nothing resolves. The
+ * caller decides whether `undefined` throws (`resolveCwd`) or yields no
+ * server URL (`resolveServerUrlForCwd`). */
+ projectDir: string | undefined;
+ /** True only when resolution fell through to the MCP client's single-root
+ * guess — the one rung where a silent wrong-project is possible, so the
+ * only rung the worktree-ambiguity nudge fires on. */
+ viaRootGuess: boolean;
+ /** Project root to remember as the new sticky anchor: set by an explicit
+ * `cwd` (and unchanged on sticky reuse); a root guess never sticks. */
+ nextSticky: string | undefined;
+}
+
+export async function resolveStickyProjectDir(
explicit: string | undefined,
- fallback: () => Promise<string | undefined>,
-): Promise<string> {
- if (explicit !== undefined) return findProjectDir(explicit);
- const fromRoots = await fallback();
- if (fromRoots !== undefined) return findProjectDir(fromRoots);
- throw new Error(
- '`cwd` is required for tool calls against the global MCP server. Pass an absolute path inside an Open Knowledge project, or have the MCP client advertise a single root.',
- );
+ sticky: string | undefined,
+ rootsFallback: () => Promise<string | undefined>,
+ findProject: (startCwd: string) => string = findProjectDir,
+): Promise<StickyProjectResolution> {
+ if (explicit !== undefined) {
+ const pd = findProject(explicit);
+ return { projectDir: pd, viaRootGuess: false, nextSticky: pd };
+ }
+ if (sticky !== undefined) {
+ const pd = findProject(sticky);
+ return { projectDir: pd, viaRootGuess: false, nextSticky: pd };
+ }
+ const fromRoots = await rootsFallback();
+ if (fromRoots === undefined) {
+ return { projectDir: undefined, viaRootGuess: false, nextSticky: undefined };
+ }
+ return { projectDir: findProject(fromRoots), viaRootGuess: true, nextSticky: undefined };
}
+const CWD_REQUIRED_MESSAGE =
+ '`cwd` is required for tool calls against the global MCP server. Pass an absolute path inside an Open Knowledge project, or have the MCP client advertise a single root.';
+
export async function startGlobalMcpServer(
opts: StartGlobalMcpServerOptions,
): Promise<StartGlobalMcpServerHandle> {
@@ -159,18 +200,42 @@ export async function startGlobalMcpServer(
log: (msg) => stderr.write(`[mcp] ${msg}\n`),
});
- const resolveCwd = (explicit?: string): Promise<string> =>
- resolveCwdWithFallback(explicit, rootsFallback);
+ let stickyProjectDir: string | undefined;
+ let warnedWorktreeAmbiguity = false;
- const resolveServerUrlForCwd = async (cwd?: string): Promise<string | undefined> => {
- let projectDir: string;
- if (cwd === undefined) {
- const fromRoots = await rootsFallback();
- if (fromRoots === undefined) return undefined;
- projectDir = findProjectDir(fromRoots);
- } else {
- projectDir = findProjectDir(cwd);
+ const maybeWarnWorktreeAmbiguity = async (projectDir: string): Promise<void> => {
+ if (warnedWorktreeAmbiguity) return;
+ warnedWorktreeAmbiguity = true;
+ const count = await countWorktrees(projectDir);
+ if (count <= 1) {
+ warnedWorktreeAmbiguity = false;
+ return;
}
+ const msg =
+ `Routed to ${projectDir} from the MCP client's single advertised root, but this repo ` +
+ `has ${count} git worktrees. If you are working in a worktree, pass its path as \`cwd\` on ` +
+ `OK tool calls once — it sticks for the session, so reads, writes, and the preview all ` +
+ `target that worktree instead of this checkout.`;
+ try {
+ stderr.write(`[mcp] ${msg}\n`);
+ await server.server.sendLoggingMessage({ level: 'warning', data: msg });
+ } catch {}
+ };
+
+ const resolveCwd = async (explicit?: string): Promise<string> => {
+ const r = await resolveStickyProjectDir(explicit, stickyProjectDir, rootsFallback);
+ stickyProjectDir = r.nextSticky ?? stickyProjectDir;
+ if (r.projectDir === undefined) throw new Error(CWD_REQUIRED_MESSAGE);
+ if (r.viaRootGuess) void maybeWarnWorktreeAmbiguity(r.projectDir);
+ return r.projectDir;
+ };
+
+ const resolveServerUrlForCwd = async (cwd?: string): Promise<string | undefined> => {
+ const r = await resolveStickyProjectDir(cwd, stickyProjectDir, rootsFallback);
+ stickyProjectDir = r.nextSticky ?? stickyProjectDir;
+ if (r.projectDir === undefined) return undefined;
+ if (r.viaRootGuess) void maybeWarnWorktreeAmbiguity(r.projectDir);
+ const projectDir = r.projectDir;
const config = await resolveConfigForCwd(projectDir);
const mcpUrl = await resolveMcpHttpUrl({
lockDir: getLocalDir(projectDir),
diff --git a/packages/cli/src/mcp/shim.test.ts b/packages/cli/src/mcp/shim.test.ts
index 010fecc18..2f938d8c3 100644
--- a/packages/cli/src/mcp/shim.test.ts
+++ b/packages/cli/src/mcp/shim.test.ts
@@ -4,7 +4,7 @@ import { tmpdir } from 'node:os';
import { resolve } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
import { LOCAL_DIR, OK_DIR } from '@inkeep/open-knowledge-core';
-import type { ServerLockMetadata } from '@inkeep/open-knowledge-server';
+import { AutoStartDisabledError, type ServerLockMetadata } from '@inkeep/open-knowledge-server';
import type { JSONRPCMessage } from '@modelcontextprotocol/sdk/types.js';
import {
bridgeStdioToHttpMcp,
@@ -135,15 +135,15 @@ describe('MCP stdio shim server resolution', () => {
});
test('auto-start opt-out turns missing server into a short diagnostic', async () => {
- await expect(
- resolveMcpHttpUrl({
- lockDir,
- contentDir: tmp,
- envAutoStart: '0',
- readLock: () => null,
- isAlive: () => false,
- }),
- ).rejects.toThrow('OK_MCP_AUTOSTART=0');
+ const err: unknown = await resolveMcpHttpUrl({
+ lockDir,
+ contentDir: tmp,
+ envAutoStart: '0',
+ readLock: () => null,
+ isAlive: () => false,
+ }).catch((e: unknown) => e);
+ expect(err).toBeInstanceOf(AutoStartDisabledError);
+ expect((err as Error).message).toContain('OK_MCP_AUTOSTART=0');
});
test('valid port override bypasses discovery and formats wildcard host as localhost', async () => {
diff --git a/packages/cli/src/mcp/shim.ts b/packages/cli/src/mcp/shim.ts
index e9b2037e6..98bd75efc 100644
--- a/packages/cli/src/mcp/shim.ts
+++ b/packages/cli/src/mcp/shim.ts
@@ -7,6 +7,7 @@ import { setTimeout as wait } from 'node:timers/promises';
import { clientVersionHeaders, SPAWN_ERROR_LOG } from '@inkeep/open-knowledge-core';
import { startKeepalive as defaultStartKeepalive } from '@inkeep/open-knowledge-core/keepalive';
import {
+ AutoStartDisabledError,
isProcessAlive as defaultIsProcessAlive,
MCP_CONNECTION_ID_HEADER,
RUNTIME_VERSION,
@@ -190,7 +191,7 @@ export async function resolveMcpHttpUrl(opts: ResolveMcpHttpUrlOptions): Promise
if (existingPort !== undefined) return mcpUrlForPort('localhost', existingPort);
if (opts.envAutoStart === '0') {
- throw new Error(
+ throw new AutoStartDisabledError(
'Open Knowledge server is not running and OK_MCP_AUTOSTART=0 disables auto-start.',
);
}
diff --git a/packages/server/assets/skills/project/SKILL.md b/packages/server/assets/skills/project/SKILL.md
index e2ce4fdf9..b9c9a8055 100644
--- a/packages/server/assets/skills/project/SKILL.md
+++ b/packages/server/assets/skills/project/SKILL.md
@@ -93,7 +93,7 @@ The user watches your edits land in a live browser preview. Open it once at sess
Warnings fire at most once per session in the fresh-start case.
-**`previewUrl: null` only means "no UI reachable" on the two attach-warning tools: `write` / `edit`.** Workflow tools return prose and don't carry `previewUrl`. `delete` / `move` emit `previousPreviewUrl` (different field, for closing stale tabs) and don't fire attach warnings. `preview_url` reports `running: false` + `url: null` when no UI is running.
+**`previewUrl: null` only means "no UI reachable" on the two attach-warning tools: `write` / `edit`.** Workflow tools return prose and don't carry `previewUrl`. `delete` / `move` emit `previousPreviewUrl` (different field, for closing stale tabs) and don't fire attach warnings. `preview_url` auto-starts the backend on demand (same `OK_MCP_AUTOSTART` gate as writes; a cold first call can take seconds) and reports `running: false` + `url: null` only when no UI could be reached — its hint names the right command.
If you see `"Hocuspocus server is not running"`, run `ok start` and retry.
@@ -468,3 +468,5 @@ Open Knowledge looks for documents under the resolved `content.dir` (discoverabl
Default mental model (no jargon): **every `.md` and `.mdx` under `content.dir`** not excluded by `.gitignore` or `.okignore` is an Open Knowledge document — including under `specs/`, `reports/`, `docs/`, etc. Read `.okignore` (and any nested `.okignore` files) once per turn to know what's excluded.
**First session in this project?** If substantial folders have no frontmatter of their own and no `templates_available`, the project isn't onboarded — invoke `workflow({ kind: 'discover' })` before writing.
+
+**Working in a git worktree?** Pass the worktree's absolute path as `cwd` on your OK tool calls once — it sticks for the rest of the session, so reads, writes, and the preview all target that worktree instead of the main checkout. If a tool warns that it routed to the main checkout while you're in a worktree, passing `cwd` once is the fix.
diff --git a/packages/server/scripts/generate-instructions.test.ts b/packages/server/scripts/generate-instructions.test.ts
index da1a3a03d..a154d47b2 100644
--- a/packages/server/scripts/generate-instructions.test.ts
+++ b/packages/server/scripts/generate-instructions.test.ts
@@ -123,7 +123,7 @@ describe('generateInstructions — byte budget', () => {
test('stays within the structural ceiling (truncation / cache-cost guard)', () => {
const skill = readFileSync(SKILL_PATH, 'utf8');
const result = generateInstructions(skill);
- expect(result.byteLength).toBeLessThan(11264);
+ expect(result.byteLength).toBeLessThan(11840);
});
test('reports per-section byte lengths so maintainers can spot the heaviest', () => {
diff --git a/packages/server/src/autostart.ts b/packages/server/src/autostart.ts
new file mode 100644
index 000000000..2c21196d9
--- /dev/null
+++ b/packages/server/src/autostart.ts
@@ -0,0 +1,6 @@
+export class AutoStartDisabledError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = 'AutoStartDisabledError';
+ }
+}
diff --git a/packages/server/src/index.ts b/packages/server/src/index.ts
index df8bb90ab..3a743d94c 100644
--- a/packages/server/src/index.ts
+++ b/packages/server/src/index.ts
@@ -45,6 +45,7 @@ export {
parseAuthRejectionWire,
parseHocuspocusAuthToken,
} from './auth-token-schema.ts';
+export { AutoStartDisabledError } from './autostart.ts';
export {
type BacklinkEntry,
BacklinkIndex,
diff --git a/packages/server/src/mcp/instructions.test.ts b/packages/server/src/mcp/instructions.test.ts
index 55522566c..b89826ade 100644
--- a/packages/server/src/mcp/instructions.test.ts
+++ b/packages/server/src/mcp/instructions.test.ts
@@ -83,5 +83,5 @@ test('buildInstructions exceeds the legacy 2 KB Claude Code cap (generator emits
const text = buildInstructions(defaultContent());
const bytes = Buffer.byteLength(text, 'utf8');
expect(bytes).toBeGreaterThan(2048);
- expect(bytes).toBeLessThan(11264);
+ expect(bytes).toBeLessThan(11840);
});
diff --git a/packages/server/src/mcp/instructions.ts b/packages/server/src/mcp/instructions.ts
index 628e2bb61..432297375 100644
--- a/packages/server/src/mcp/instructions.ts
+++ b/packages/server/src/mcp/instructions.ts
@@ -54,7 +54,7 @@ The user watches your edits land in a live browser preview. Open it once at sess
Warnings fire at most once per session in the fresh-start case.
-**\`previewUrl: null\` only means "no UI reachable" on the two attach-warning tools: \`write\` / \`edit\`.** Workflow tools return prose and don't carry \`previewUrl\`. \`delete\` / \`move\` emit \`previousPreviewUrl\` (different field, for closing stale tabs) and don't fire attach warnings. \`preview_url\` reports \`running: false\` + \`url: null\` when no UI is running.
+**\`previewUrl: null\` only means "no UI reachable" on the two attach-warning tools: \`write\` / \`edit\`.** Workflow tools return prose and don't carry \`previewUrl\`. \`delete\` / \`move\` emit \`previousPreviewUrl\` (different field, for closing stale tabs) and don't fire attach warnings. \`preview_url\` auto-starts the backend on demand (same \`OK_MCP_AUTOSTART\` gate as writes; a cold first call can take seconds) and reports \`running: false\` + \`url: null\` only when no UI could be reached — its hint names the right command.
If you see \`"Hocuspocus server is not running"\`, run \`ok start\` and retry.
@@ -72,6 +72,8 @@ Default mental model (no jargon): **every \`.md\` and \`.mdx\` under \`content.d
**First session in this project?** If substantial folders have no frontmatter of their own and no \`templates_available\`, the project isn't onboarded — invoke \`workflow({ kind: 'discover' })\` before writing.
+**Working in a git worktree?** Pass the worktree's absolute path as \`cwd\` on your OK tool calls once — it sticks for the rest of the session, so reads, writes, and the preview all target that worktree instead of the main checkout. If a tool warns that it routed to the main checkout while you're in a worktree, passing \`cwd\` once is the fix.
+
Full guidance lives in the bundled \`open-knowledge\` skill at \`~/.ok/skills/open-knowledge/SKILL.md\`.
`;
diff --git a/packages/server/src/mcp/tools/get-preview-url.test.ts b/packages/server/src/mcp/tools/get-preview-url.test.ts
index e93e4e43a..49eac39f2 100644
--- a/packages/server/src/mcp/tools/get-preview-url.test.ts
+++ b/packages/server/src/mcp/tools/get-preview-url.test.ts
@@ -2,11 +2,12 @@ import { describe, expect, test } from 'bun:test';
import { mkdtempSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { AutoStartDisabledError } from '../../autostart.ts';
import { resolveLockDir } from '../../config/paths.ts';
import { type Config, ConfigSchema } from '../../config/schema.ts';
import { readArmedPaneTarget } from '../../pane-target.ts';
import { register } from './get-preview-url.ts';
-import { bindTestUiLock } from './preview-url-test-helpers.ts';
+import { bindTestServerLock, bindTestUiLock } from './preview-url-test-helpers.ts';
import type { ServerInstance } from './shared.ts';
const BASE_CONFIG: Config = ConfigSchema.parse({});
@@ -21,13 +22,22 @@ interface ToolResult {
}
type ToolHandler = (args: {
- docName?: string;
+ document?: string;
folder?: string;
armPaneTarget?: boolean;
cwd?: string;
}) => Promise<ToolResult>;
-function captureRegistration(cwd: string, config: Config = BASE_CONFIG): ToolHandler {
+interface EnsureDeps {
+ serverUrl?: (cwd?: string) => Promise<string | undefined>;
+ uiBindWait?: { timeoutMs?: number; pollIntervalMs?: number };
+}
+
+function captureRegistration(
+ cwd: string,
+ config: Config = BASE_CONFIG,
+ ensure?: EnsureDeps,
+): ToolHandler {
let captured: ToolHandler | null = null;
const server = {
registerTool(_name: string, _config: unknown, handler: ToolHandler) {
@@ -40,13 +50,14 @@ function captureRegistration(cwd: string, config: Config = BASE_CONFIG): ToolHan
register(server, {
config,
resolveCwd: async () => cwd,
+ ...ensure,
});
if (!captured) throw new Error('tool not registered');
return captured;
}
describe('preview_url tool — UI running', () => {
- test('with docName: composes baseUrl + the doc route', async () => {
+ test('with document: composes baseUrl + the doc route', async () => {
const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));
const uiBase = bindTestUiLock(cwd);
const handler = captureRegistration(cwd);
@@ -140,7 +151,7 @@ describe('preview_url tool — UI running', () => {
});
describe('preview_url tool — no UI running', () => {
- test('returns running:false + null url when no ui.lock is present', async () => {
+ test('returns running:false + the ok-start hint when nothing is running', async () => {
const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));
const handler = captureRegistration(cwd);
const result = await handler({ document: 'specs/foo/SPEC' });
@@ -149,7 +160,9 @@ describe('preview_url tool — no UI running', () => {
expect(result.structuredContent?.url).toBeNull();
expect(result.structuredContent?.baseUrl).toBeNull();
expect(result.structuredContent?.autoOpen).toBe(true);
- expect(result.content[0]?.text).toContain('No UI is running');
+ expect(result.content[0]?.text).toContain('No Open Knowledge server is running');
+ expect(result.content[0]?.text).toContain('`ok start`');
+ expect(result.content[0]?.text).not.toContain('`ok ui`');
});
test('no-UI branch is the same regardless of docName', async () => {
@@ -160,6 +173,116 @@ describe('preview_url tool — no UI running', () => {
expect(result.structuredContent?.url).toBeNull();
expect(result.structuredContent?.autoOpen).toBe(true);
});
+
+ test('server alive but no UI: advises ok ui, not ok start', async () => {
+ const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));
+ bindTestServerLock(cwd);
+ const handler = captureRegistration(cwd);
+ const result = await handler({ document: 'specs/foo/SPEC' });
+ expect(result.structuredContent?.running).toBe(false);
+ expect(result.content[0]?.text).toContain('OK server is running');
+ expect(result.content[0]?.text).toContain('`ok ui`');
+ expect(result.content[0]?.text).not.toContain('`ok start`');
+ });
+});
+
+describe('preview_url tool — backend demand-ensure', () => {
+ test('cold project: ensure spawns the backend and the call returns a live URL once ui.lock binds', async () => {
+ const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));
+ let resolverCalls = 0;
+ let uiBase = '';
+ const handler = captureRegistration(cwd, BASE_CONFIG, {
+ serverUrl: async () => {
+ resolverCalls += 1;
+ bindTestServerLock(cwd);
+ setTimeout(() => {
+ uiBase = bindTestUiLock(cwd);
+ }, 30);
+ return 'http://localhost:4321';
+ },
+ uiBindWait: { timeoutMs: 1500, pollIntervalMs: 10 },
+ });
+ const result = await handler({ document: 'specs/foo/SPEC' });
+ expect(resolverCalls).toBe(1);
+ expect(result.isError).toBeUndefined();
+ expect(result.structuredContent?.running).toBe(true);
+ expect(result.structuredContent?.url).toBe(`${uiBase}/#/specs/foo/SPEC`);
+ });
+
+ test('resolver runs on every call, even with a live UI (orphan-heal contract)', async () => {
+ const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));
+ const uiBase = bindTestUiLock(cwd);
+ let resolverCalls = 0;
+ const handler = captureRegistration(cwd, BASE_CONFIG, {
+ serverUrl: async () => {
+ resolverCalls += 1;
+ return 'http://localhost:4321';
+ },
+ });
+ const result = await handler({});
+ expect(resolverCalls).toBe(1);
+ expect(result.structuredContent?.running).toBe(true);
+ expect(result.structuredContent?.url).toBe(uiBase);
+ });
+
+ test('auto-start opt-out: soft not-running payload naming the knob', async () => {
+ const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));
+ const handler = captureRegistration(cwd, BASE_CONFIG, {
+ serverUrl: async () => {
+ throw new AutoStartDisabledError(
+ 'Open Knowledge server is not running and OK_MCP_AUTOSTART=0 disables auto-start.',
+ );
+ },
+ });
+ const result = await handler({ document: 'specs/foo/SPEC' });
+ expect(result.isError).toBeUndefined();
+ expect(result.structuredContent?.running).toBe(false);
+ expect(result.structuredContent?.url).toBeNull();
+ expect(result.content[0]?.text).toContain('`ok start`');
+ expect(result.content[0]?.text).toContain('OK_MCP_AUTOSTART=0');
+ expect(result.content[0]?.text).not.toContain('`ok ui`');
+ });
+
+ test('spawn failure surfaces as a tool error carrying the resolver message', async () => {
+ const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));
+ const handler = captureRegistration(cwd, BASE_CONFIG, {
+ serverUrl: async () => {
+ throw new Error('server did not start within 5000ms stderr:\nboom');
+ },
+ });
+ const result = await handler({ document: 'specs/foo/SPEC' });
+ expect(result.isError).toBe(true);
+ expect(result.content[0]?.text).toContain('did not start within');
+ });
+
+ test('fresh spawn whose UI never binds: server-running hint after the bounded wait', async () => {
+ const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));
+ const handler = captureRegistration(cwd, BASE_CONFIG, {
+ serverUrl: async () => {
+ bindTestServerLock(cwd);
+ return 'http://localhost:4321';
+ },
+ uiBindWait: { timeoutMs: 60, pollIntervalMs: 10 },
+ });
+ const result = await handler({ document: 'specs/foo/SPEC' });
+ expect(result.isError).toBeUndefined();
+ expect(result.structuredContent?.running).toBe(false);
+ expect(result.content[0]?.text).toContain('OK server is running');
+ expect(result.content[0]?.text).toContain('`ok ui`');
+ expect(result.content[0]?.text).not.toContain('`ok start`');
+ });
+
+ test('ensure failure does not lose a requested pane-target arm', async () => {
+ const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));
+ const handler = captureRegistration(cwd, BASE_CONFIG, {
+ serverUrl: async () => {
+ throw new Error('spawn failed: ENOENT');
+ },
+ });
+ const result = await handler({ document: 'specs/foo/SPEC', armPaneTarget: true });
+ expect(result.isError).toBe(true);
+ expect(readArmedPaneTarget(resolveLockDir(cwd))).toBe('#/specs/foo/SPEC');
+ });
});
describe('preview_url tool — autoOpen field', () => {
diff --git a/packages/server/src/mcp/tools/get-preview-url.ts b/packages/server/src/mcp/tools/get-preview-url.ts
index 159b66b03..83066abcf 100644
--- a/packages/server/src/mcp/tools/get-preview-url.ts
+++ b/packages/server/src/mcp/tools/get-preview-url.ts
@@ -1,41 +1,51 @@
import { z } from 'zod';
+import { AutoStartDisabledError } from '../../autostart.ts';
import { resolveLockDir } from '../../config/paths.ts';
import { armPaneTarget } from '../../pane-target.ts';
+import { isProcessAlive } from '../../process-alive.ts';
+import { readServerLock } from '../../server-lock.ts';
import {
+ awaitUiBaseUrl,
encodeDocName,
encodeFolderRoute,
type PreviewUrlContext,
resolveUiInfo,
} from './preview-url.ts';
-import type { ConfigOrResolver, ServerInstance } from './shared.ts';
+import type { ConfigOrResolver, ServerInstance, ServerUrlOrResolver } from './shared.ts';
import {
outputSchemaWithText,
ROUTED_CWD_DESCRIPTION,
resolveProjectConfigContext,
+ resolveServerUrl,
textPlusStructured,
} from './shared.ts';
export const DESCRIPTION = [
- '[Operates on disk; no running OK server required] Resolve the browser-reachable preview URL for an Open Knowledge project (optionally for a specific doc).',
+ 'Resolve the browser-reachable preview URL for an Open Knowledge project (optionally for a specific doc). Opening a preview counts as demand: when no OK server is running for the project, this call auto-starts one (same `OK_MCP_AUTOSTART` gate and spawn timeout as the read/write tools) and waits briefly for the preview UI to bind — a cold first call can take a few seconds; calls against a running system answer immediately.',
'',
'Per-response `previewUrl` fields on read/write tools are ROUTE-ONLY (`/#/<doc>`, no host:port) — they identify which doc to preview, not a URL to open by itself. Call this tool to get the full, openable URL.',
'',
'Use this when YOUR host opens the URL itself: navigate your in-app browser to the returned `url`, or — only on a stdio host with no browser tool — `open` it in the system browser. Hosts with a preview pane (Claude Code Desktop) call `preview_start("open-knowledge-ui")` instead; the Claude Code CLI uses `ok open <doc>` to open in the OK Desktop app.',
'',
- 'Returns `{ url: null, baseUrl: null, running: false, autoOpen }` and a recovery hint when no UI is running for the project (start one with `ok ui`).',
+ 'Returns `{ url: null, baseUrl: null, running: false, autoOpen }` + a recovery hint only when no UI could be reached (auto-start disabled via `OK_MCP_AUTOSTART=0`, no spawn authority in this registration, or the UI did not bind in time) — the hint names the right command for the actual state.',
'',
'**Parameters:**',
'- `document` (optional) — Extension-less doc path (e.g. `specs/foo/SPEC`). Omit for the UI root URL.',
'- `folder` (optional) — Folder path (e.g. `specs/foo`); returns the `…/#/<folder>/` route. Mutually exclusive with `document`.',
- '- `armPaneTarget` (optional) — When true with a `document`/`folder`, writes a small TTL-bounded (~30s) state file under `.ok/local/` so a later Claude-pane base-open lands on that target. This is the tool’s ONLY side effect; omit it and the call is read-only.',
+ '- `armPaneTarget` (optional) — When true with a `document`/`folder`, writes a small TTL-bounded (~30s) state file under `.ok/local/` so a later Claude-pane base-open lands on that target. Independent of server state; omit it and the call writes nothing.',
'- `cwd` (optional) — Project root (see `cwd` description below).',
].join('\n');
interface GetPreviewUrlDeps {
config: ConfigOrResolver;
resolveCwd: (explicit?: string) => Promise<string>;
+ serverUrl?: ServerUrlOrResolver;
+ uiBindWait?: { timeoutMs?: number; pollIntervalMs?: number };
}
+const UI_BIND_WAIT_TIMEOUT_MS = 3000;
+const UI_BIND_WAIT_POLL_MS = 100;
+
const InputSchema = {
document: z
.string()
@@ -80,8 +90,23 @@ const OutputSchema = outputSchemaWithText({
),
});
-const NO_UI_MESSAGE =
- 'No UI is running for this project. Start one to see the preview: `ok ui` (terminal), `preview_start("open-knowledge-ui")` (Claude Code), or open the project in OK Electron.';
+const NO_UI_SERVER_RUNNING_MESSAGE =
+ 'The OK server is running but no UI has bound for this project yet. Retry in a few seconds, or start one: `ok ui` (terminal), `preview_start("open-knowledge-ui")` (Claude Code Desktop), or open the project in OK Electron.';
+const NO_SERVER_MESSAGE =
+ 'No Open Knowledge server is running for this project. Start it with `ok start` (also starts the preview UI), use `preview_start("open-knowledge-ui")` (Claude Code Desktop), or open the project in OK Electron.';
+const AUTOSTART_DISABLED_NOTE = ' Auto-start is disabled (OK_MCP_AUTOSTART=0).';
+
+function isServerLive(lockDir: string): boolean {
+ try {
+ const lock = readServerLock(lockDir);
+ return lock !== null && lock.port > 0 && isProcessAlive(lock.pid);
+ } catch (err) {
+ process.stderr.write(
+ `[preview-url] readServerLock failed at ${lockDir} while checking server liveness: ${err instanceof Error ? err.message : String(err)}\n`,
+ );
+ return false;
+ }
+}
export function register(server: ServerInstance, deps: GetPreviewUrlDeps): void {
server.registerTool(
@@ -116,7 +141,6 @@ export function register(server: ServerInstance, deps: GetPreviewUrlDeps): void
}
const lockDir = resolveLockDir(context.cwd);
const ctx: PreviewUrlContext = { lockDir };
- const { baseUrl } = resolveUiInfo(ctx);
const autoOpen = context.config.appearance.preview.autoOpen;
const routeFragment = args.document
@@ -136,8 +160,41 @@ export function register(server: ServerInstance, deps: GetPreviewUrlDeps): void
? ' (note: armPaneTarget was set but no document/folder was given, so nothing was armed)'
: '';
+ const serverWasLive = isServerLive(lockDir);
+ let autoStartDisabled = false;
+ if (deps.serverUrl !== undefined) {
+ try {
+ await resolveServerUrl(deps.serverUrl, context.cwd);
+ } catch (err) {
+ if (err instanceof AutoStartDisabledError) {
+ autoStartDisabled = true;
+ } else {
+ return {
+ isError: true,
+ content: [
+ {
+ type: 'text' as const,
+ text: `Error: ${err instanceof Error ? err.message : String(err)}`,
+ },
+ ],
+ };
+ }
+ }
+ }
+
+ let { baseUrl } = resolveUiInfo(ctx);
+ if (baseUrl === null && !serverWasLive && isServerLive(lockDir)) {
+ baseUrl = await awaitUiBaseUrl(ctx, {
+ timeoutMs: deps.uiBindWait?.timeoutMs ?? UI_BIND_WAIT_TIMEOUT_MS,
+ pollIntervalMs: deps.uiBindWait?.pollIntervalMs ?? UI_BIND_WAIT_POLL_MS,
+ });
+ }
+
if (baseUrl === null) {
- return textPlusStructured(`${NO_UI_MESSAGE}${armNote}`, {
+ const hint = isServerLive(lockDir)
+ ? NO_UI_SERVER_RUNNING_MESSAGE
+ : `${NO_SERVER_MESSAGE}${autoStartDisabled ? AUTOSTART_DISABLED_NOTE : ''}`;
+ return textPlusStructured(`${hint}${armNote}`, {
url: null,
baseUrl: null,
running: false,
diff --git a/packages/server/src/mcp/tools/index.ts b/packages/server/src/mcp/tools/index.ts
index b0c02b73a..346cd0445 100644
--- a/packages/server/src/mcp/tools/index.ts
+++ b/packages/server/src/mcp/tools/index.ts
@@ -165,6 +165,7 @@ export function registerAllTools(server: ServerInstance, opts: RegisterAllToolsO
registerPreviewUrl(registrationServer, {
config: opts.config,
resolveCwd: named('preview_url'),
+ serverUrl: opts.serverUrl,
});
registerConflicts(registrationServer, {
serverUrl: opts.serverUrl,
diff --git a/packages/server/src/mcp/tools/preview-url-test-helpers.ts b/packages/server/src/mcp/tools/preview-url-test-helpers.ts
index 46ed0bfee..3b4f1d243 100644
--- a/packages/server/src/mcp/tools/preview-url-test-helpers.ts
+++ b/packages/server/src/mcp/tools/preview-url-test-helpers.ts
@@ -1,5 +1,6 @@
import { resolve } from 'node:path';
import { LOCAL_DIR, OK_DIR } from '@inkeep/open-knowledge-core';
+import { acquireServerLock, updateServerLockPort } from '../../server-lock.ts';
import { acquireUiLock, updateUiLockPort } from '../../ui-lock.ts';
const TEST_UI_PORT = 5173;
@@ -10,3 +11,9 @@ export function bindTestUiLock(cwd: string, port = TEST_UI_PORT): string {
updateUiLockPort(lockDir, port);
return `http://localhost:${port}`;
}
+
+export function bindTestServerLock(cwd: string, port = 4321): void {
+ const lockDir = resolve(cwd, OK_DIR, LOCAL_DIR);
+ acquireServerLock(lockDir, { port: 0, worktreeRoot: cwd });
+ updateServerLockPort(lockDir, port);
+}
diff --git a/packages/server/src/mcp/tools/preview-url.ts b/packages/server/src/mcp/tools/preview-url.ts
index d0ade3cce..693440652 100644
--- a/packages/server/src/mcp/tools/preview-url.ts
+++ b/packages/server/src/mcp/tools/preview-url.ts
@@ -97,6 +97,19 @@ export function resolveUiInfo(ctx: PreviewUrlContext): UiInfo {
return { baseUrl: null };
}
+export async function awaitUiBaseUrl(
+ ctx: PreviewUrlContext,
+ opts: { timeoutMs: number; pollIntervalMs: number },
+): Promise<string | null> {
+ const deadline = Date.now() + opts.timeoutMs;
+ while (true) {
+ const { baseUrl } = resolveUiInfo(ctx);
+ if (baseUrl !== null) return baseUrl;
+ if (Date.now() >= deadline) return null;
+ await new Promise<void>((resolveSleep) => setTimeout(resolveSleep, opts.pollIntervalMs));
+ }
+}
+
export async function buildListResolver(
deps: PreviewUrlDeps,
cwd?: string,
diff --git a/packages/server/src/mcp/tools/shared.ts b/packages/server/src/mcp/tools/shared.ts
index acb5f76ba..8eabc9c0d 100644
--- a/packages/server/src/mcp/tools/shared.ts
+++ b/packages/server/src/mcp/tools/shared.ts
@@ -202,7 +202,10 @@ export type ServerUrlOrResolver =
| undefined
| ((cwd?: string) => Promise<string | undefined>);
-async function resolveServerUrl(x: ServerUrlOrResolver, cwd?: string): Promise<string | undefined> {
+export async function resolveServerUrl(
+ x: ServerUrlOrResolver,
+ cwd?: string,
+): Promise<string | undefined> {
return typeof x === 'function' ? await x(cwd) : x;
}