Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

Fix OK MCP exec ignoring explicit subdirectory cwd (PRD-6973) (#1777)

tim-inkeep7550f5f81e24
diff --git a/.changeset/exec-honors-explicit-subdir-cwd.md b/.changeset/exec-honors-explicit-subdir-cwd.md
new file mode 100644
index 000000000..98b3a08f6
--- /dev/null
+++ b/.changeset/exec-honors-explicit-subdir-cwd.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge-server": patch
+---
+
+The MCP `exec` tool now runs commands in the explicit `cwd` you pass, even when it points at a subdirectory of an OK project. Previously the resolver walked `cwd` up to the enclosing `.ok/config.yml` and ran bash from the project root, so a subdir-relative command like `cat notes.md` (cwd `<project>/subdir`) failed with a spurious "No such file or directory" and `structuredContent.cwd` reported the root instead of the directory you asked for — agents had to work around it with project-root-relative paths. The walk-up still resolves which project owns the call (config, server URL, lock, and enrichment stay project-anchored), but the execution directory is now the literal path passed. `structuredContent.cwd` reports where the command actually ran, and referenced-file enrichment resolves correctly regardless of which subdirectory bash ran in.
diff --git a/packages/server/src/mcp/tools/exec.test.ts b/packages/server/src/mcp/tools/exec.test.ts
index 0c76bbb83..d0fa6bbe9 100644
--- a/packages/server/src/mcp/tools/exec.test.ts
+++ b/packages/server/src/mcp/tools/exec.test.ts
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
-import { mkdirSync, writeFileSync } from 'node:fs';
+import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { resolve } from 'node:path';
@@ -714,3 +714,118 @@ describe('exec — per-row route-only previewUrl (FR-2.2)', () => {
expect(paths.some((p) => p.includes('.ok/'))).toBe(false);
});
});
+
+describe('exec — explicit subdirectory cwd', () => {
+ function walkUpResolveCwd(start: string): string {
+ let dir = resolve(start);
+ for (;;) {
+ if (existsSync(resolve(dir, '.ok', 'config.yml'))) return dir;
+ const parent = resolve(dir, '..');
+ if (parent === dir) throw new Error(`no OK project at or above ${start}`);
+ dir = parent;
+ }
+ }
+
+ async function bootstrapWithMarker(): Promise<{ project: string; subdir: string }> {
+ const project = await bootstrap();
+ mkdirSync(resolve(project, '.ok'), { recursive: true });
+ writeFileSync(resolve(project, '.ok', 'config.yml'), 'content:\n dir: .\n');
+ const subdir = resolve(project, 'subdir');
+ mkdirSync(subdir, { recursive: true });
+ return { project, subdir };
+ }
+
+ test('runs in the passed subdir — bare subdir-relative path resolves', async () => {
+ const { subdir } = await bootstrapWithMarker();
+ writeFileSync(resolve(subdir, 'UNIQUE_MARKER.md'), 'marker contents\n');
+
+ const result = (await buildExecResult(
+ { command: 'cat UNIQUE_MARKER.md', cwd: subdir },
+ {
+ resolveCwd: async (explicit) => walkUpResolveCwd(explicit ?? subdir),
+ serverUrl: undefined,
+ config: DEFAULT_CONFIG,
+ },
+ )) as ExecResult;
+
+ expect(result.isError).toBeFalsy();
+ expect(structured(result).text).toContain('marker contents');
+ });
+
+ test('structuredContent.cwd reports the passed subdir, not the walked-up root', async () => {
+ const { project, subdir } = await bootstrapWithMarker();
+ writeFileSync(resolve(subdir, 'UNIQUE_MARKER.md'), 'marker contents\n');
+
+ const result = (await buildExecResult(
+ { command: 'cat UNIQUE_MARKER.md', cwd: subdir },
+ {
+ resolveCwd: async (explicit) => walkUpResolveCwd(explicit ?? subdir),
+ serverUrl: undefined,
+ config: DEFAULT_CONFIG,
+ },
+ )) as ExecResult;
+
+ expect(structured(result).cwd).toBe(subdir);
+ expect(structured(result).cwd).not.toBe(project);
+ });
+
+ test('enrichment addresses subdir files project-relative (docName under the root)', async () => {
+ const { subdir } = await bootstrapWithMarker();
+ writeFileSync(resolve(subdir, 'note.md'), '---\ntitle: Subdir Note\n---\n\nBody\n');
+
+ const result = (await buildExecResult(
+ { command: 'cat note.md', cwd: subdir },
+ {
+ resolveCwd: async (explicit) => walkUpResolveCwd(explicit ?? subdir),
+ serverUrl: undefined,
+ config: DEFAULT_CONFIG,
+ },
+ )) as ExecResult;
+
+ expect(result.isError).toBeFalsy();
+ const files = fileEntries(structured(result));
+ expect(files.length).toBe(1);
+ expect(files[0].path).toBe('subdir/note.md');
+ expect(files[0].title).toBe('Subdir Note');
+ expect(structured(result).text?.startsWith('==> subdir/note.md <==\n')).toBe(true);
+ });
+
+ test('ls provenance header is rebased to the project-relative dir from a subdir', async () => {
+ const { subdir } = await bootstrapWithMarker();
+ const inner = resolve(subdir, 'inner');
+ mkdirSync(inner, { recursive: true });
+ writeFileSync(resolve(inner, 'doc.md'), '---\ntitle: Inner\n---\nBody');
+
+ const result = (await buildExecResult(
+ { command: 'ls inner/', cwd: subdir },
+ {
+ resolveCwd: async (explicit) => walkUpResolveCwd(explicit ?? subdir),
+ serverUrl: undefined,
+ config: DEFAULT_CONFIG,
+ },
+ )) as ExecResult;
+
+ expect(result.isError).toBeFalsy();
+ expect(structured(result).text?.startsWith('subdir/inner/:\n')).toBe(true);
+ });
+
+ test('passing the project root still runs there (unchanged behavior)', async () => {
+ const { project } = await bootstrapWithMarker();
+ const articles = resolve(project, 'articles');
+ mkdirSync(articles, { recursive: true });
+ writeFileSync(resolve(articles, 'auth.md'), '---\ntitle: Auth\n---\nBody');
+
+ const result = (await buildExecResult(
+ { command: 'cat articles/auth.md', cwd: project },
+ {
+ resolveCwd: async (explicit) => walkUpResolveCwd(explicit ?? project),
+ serverUrl: undefined,
+ config: DEFAULT_CONFIG,
+ },
+ )) as ExecResult;
+
+ expect(result.isError).toBeFalsy();
+ expect(structured(result).cwd).toBe(project);
+ expect(fileEntries(structured(result))[0].path).toBe('articles/auth.md');
+ });
+});
diff --git a/packages/server/src/mcp/tools/exec.ts b/packages/server/src/mcp/tools/exec.ts
index d2486daa6..41d270e46 100644
--- a/packages/server/src/mcp/tools/exec.ts
+++ b/packages/server/src/mcp/tools/exec.ts
@@ -1,5 +1,5 @@
import { stat } from 'node:fs/promises';
-import { resolve } from 'node:path';
+import { relative, resolve } from 'node:path';
import { z } from 'zod';
import { argsOf, extractReferencedPaths, nonFlagArgs } from '../../bash/extract-paths.ts';
import { createBashInstance, execBash, StdoutOverflowError } from '../../bash/index.ts';
@@ -224,6 +224,7 @@ function buildStdoutProvenance(
stages: Stage[],
dirByPath: Map<string, DirectoryMeta>,
fileByPath: Map<string, EnrichedMeta>,
+ rebase: (p: string) => string,
): string {
let stage: Stage | null = null;
for (let i = stages.length - 1; i >= 0; i--) {
@@ -248,13 +249,15 @@ function buildStdoutProvenance(
let n = dirArg.replace(/\/+/g, '/');
if (n.startsWith('./')) n = n.slice(2);
if (n.endsWith('/')) n = n.slice(0, -1);
- if (!n || !dirByPath.has(n)) return '';
- return `${n}/:\n`;
+ if (!n) return '';
+ const key = rebase(n);
+ if (!dirByPath.has(key)) return '';
+ return `${key}/:\n`;
}
- const wikiFiles = pathArgs.filter((p) => /\.(md|mdx)$/.test(p) && fileByPath.has(p));
+ const wikiFiles = pathArgs.filter((p) => /\.(md|mdx)$/.test(p) && fileByPath.has(rebase(p)));
if (wikiFiles.length !== 1) return '';
- return `==> ${wikiFiles[0]} <==\n`;
+ return `==> ${rebase(wikiFiles[0])} <==\n`;
}
function formatEnrichedBlock(enriched: EnrichedEntry[]): string {
@@ -326,7 +329,12 @@ export async function buildExecResult(
if (!context.ok) {
return errorCategoryResult('shell_construct_blocked', `exec failed: ${context.error}`);
}
- const { cwd, config, url: resolvedServerUrl } = context;
+ const { cwd, executionCwd, config, url: resolvedServerUrl } = context;
+
+ const rebaseToProject =
+ executionCwd === cwd
+ ? (p: string) => p
+ : (p: string) => relative(cwd, resolve(executionCwd, p));
const parsed = parseCommand(args.command);
if ('error' in parsed) {
@@ -335,9 +343,9 @@ export async function buildExecResult(
const stages = augmentStagesWithExcludes(parsed.stages);
const effectiveCommand = serializeStages(stages);
- const pre = await snapshotMtimes(cwd);
+ const pre = await snapshotMtimes(executionCwd);
- const bash = createBashInstance(cwd);
+ const bash = createBashInstance(executionCwd);
let stdout = '';
let stderr = '';
try {
@@ -357,7 +365,7 @@ export async function buildExecResult(
);
}
- const post = await snapshotMtimes(cwd);
+ const post = await snapshotMtimes(executionCwd);
const mtimeDiff = diffMtimes(pre.snapshot, post.snapshot);
if (mtimeDiff.changed.length > 0) {
return errorCategoryResult(
@@ -369,7 +377,7 @@ export async function buildExecResult(
const capped = applySoftCap(stdout);
const rawPaths = extractReferencedPaths(stdout, stages);
- const paths = rawPaths.filter((p) => resolveWithinRoot(cwd, p).ok);
+ const paths = rawPaths.filter((p) => resolveWithinRoot(executionCwd, p).ok).map(rebaseToProject);
const { files, dirs } = await classifyPaths(cwd, paths);
const isSinglePathCat = stages.length === 1 && stages[0].command === 'cat' && files.length === 1;
const fileEnriched: EnrichedMeta[] = await Promise.all(
@@ -450,21 +458,21 @@ export async function buildExecResult(
}
const bannerText = banners.length > 0 ? `${banners.join('\n')}\n\n` : '';
- const provenance = buildStdoutProvenance(stages, dirByPath, fileByPath);
+ const provenance = buildStdoutProvenance(stages, dirByPath, fileByPath, rebaseToProject);
const stdoutText = provenance + capped.text;
const enrichmentBlock = formatEnrichedBlock(enriched);
const content = `${bannerText}${stdoutText}${enrichmentBlock}`;
- const { resolve } = await buildListResolver({
+ const { resolve: resolvePreviewUrl } = await buildListResolver({
config,
resolveCwd: async () => cwd,
});
- const enrichedWithPreview: ExecEnrichedEntry[] = withPreviewUrls(enriched, resolve);
+ const enrichedWithPreview: ExecEnrichedEntry[] = withPreviewUrls(enriched, resolvePreviewUrl);
const structured: ExecStructuredResult = {
enrichedPaths: enrichedWithPreview,
stdoutTruncated: capped.truncated,
- cwd,
+ cwd: executionCwd,
...(banners.length > 0 ? { warnings: banners } : {}),
};
return textPlusStructured(content, structured);
diff --git a/packages/server/src/mcp/tools/shared.test.ts b/packages/server/src/mcp/tools/shared.test.ts
index 0e277e864..40155e84a 100644
--- a/packages/server/src/mcp/tools/shared.test.ts
+++ b/packages/server/src/mcp/tools/shared.test.ts
@@ -222,6 +222,7 @@ describe('resolveProjectConfigContext', () => {
expect(result).toEqual({
ok: true,
cwd: '/workspace/project',
+ executionCwd: '/workspace/project',
config: {
...TEST_CONFIG,
content: { ...TEST_CONFIG.content, dir: '/workspace/project' },
@@ -229,6 +230,21 @@ describe('resolveProjectConfigContext', () => {
});
});
+ test('executionCwd is the literal explicit cwd; cwd is the walked-up root', async () => {
+ const result = await resolveProjectConfigContext(
+ async () => '/workspace/project',
+ TEST_CONFIG,
+ '/workspace/project/subdir/nested',
+ );
+
+ expect(result).toEqual({
+ ok: true,
+ cwd: '/workspace/project',
+ executionCwd: '/workspace/project/subdir/nested',
+ config: TEST_CONFIG,
+ });
+ });
+
test('returns an error when resolveCwd throws', async () => {
const result = await resolveProjectConfigContext(async () => {
throw new Error('No client roots');
@@ -260,6 +276,7 @@ describe('resolveProjectServerContext', () => {
expect(result).toEqual({
ok: true,
cwd: '/workspace/project',
+ executionCwd: '/workspace/project',
config: TEST_CONFIG,
url: 'ws://localhost/project',
});
diff --git a/packages/server/src/mcp/tools/shared.ts b/packages/server/src/mcp/tools/shared.ts
index 9cf198fbc..acb5f76ba 100644
--- a/packages/server/src/mcp/tools/shared.ts
+++ b/packages/server/src/mcp/tools/shared.ts
@@ -1,3 +1,4 @@
+import { resolve } from 'node:path';
import { validateDocName, WriteWarningSchema } from '@inkeep/open-knowledge-core';
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { z } from 'zod';
@@ -213,16 +214,19 @@ export async function resolveProjectConfigContext(
resolveCwd: (explicit?: string) => Promise<string>,
config: ConfigOrResolver,
explicitCwd?: string,
-): Promise<{ ok: true; cwd: string; config: Config } | { ok: false; error: string }> {
+): Promise<
+ { ok: true; cwd: string; executionCwd: string; config: Config } | { ok: false; error: string }
+> {
let cwd: string;
try {
cwd = await resolveCwd(explicitCwd);
} catch (err) {
return { ok: false, error: err instanceof Error ? err.message : String(err) };
}
+ const executionCwd = explicitCwd !== undefined ? resolve(explicitCwd) : cwd;
try {
const resolvedConfig = await resolveConfig(config, cwd);
- return { ok: true, cwd, config: resolvedConfig };
+ return { ok: true, cwd, executionCwd, config: resolvedConfig };
} catch (err) {
return { ok: false, error: err instanceof Error ? err.message : String(err) };
}
@@ -234,16 +238,17 @@ export async function resolveProjectServerContext(
serverUrl: ServerUrlOrResolver,
explicitCwd?: string,
): Promise<
- { ok: true; cwd: string; config: Config; url: string | undefined } | { ok: false; error: string }
+ | { ok: true; cwd: string; executionCwd: string; config: Config; url: string | undefined }
+ | { ok: false; error: string }
> {
const configContext = await resolveProjectConfigContext(resolveCwd, config, explicitCwd);
if (!configContext.ok) {
return configContext;
}
- const { cwd, config: resolvedConfig } = configContext;
+ const { cwd, executionCwd, config: resolvedConfig } = configContext;
try {
const url = await resolveServerUrl(serverUrl, cwd);
- return { ok: true, cwd, config: resolvedConfig, url };
+ return { ok: true, cwd, executionCwd, config: resolvedConfig, url };
} catch (err) {
return { ok: false, error: err instanceof Error ? err.message : String(err) };
}