Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(open-knowledge): dedup exec MCP body + recalibrate soft cap (PRD-6937) (#1657)
mike-inkeep25cf91a84b5c
diff --git a/.changeset/exec-stdout-dedup-cap.md b/.changeset/exec-stdout-dedup-cap.mdnew file mode 100644index 000000000..2a9b8a74d--- /dev/null+++ b/.changeset/exec-stdout-dedup-cap.md@@ -0,0 +1,7 @@+---+"@inkeep/open-knowledge-server": patch+---++Fix `exec` MCP results overflowing the client's per-result token limit on mid-size reads. The visible body was serialized up to 3× per result — `content[].text`, `structuredContent.text` (the load-bearing cross-client mirror that Claude-class clients read when they drop `content[].text`), and a redundant `structuredContent.stdout` raw copy — while the soft cap budgeted only one copy. A markdown file comfortably under the cap (so `exec` reported `stdoutTruncated: false`) could still produce a result large enough that the client rejected it and spilled to a file, silently degrading an in-budget read.++Two changes: (1) drop the `structuredContent.stdout` field. It was the original Claude-Desktop `content[].text`-drop workaround, fully superseded by the `structuredContent.text` mirror it predates; its bytes are a strict subset of `text` and nothing consumed it. (2) Recalibrate the soft cap to budget the realized 2× body duplication (`content[].text` + `structuredContent.text`) rather than a single copy — the per-string cap is now ~25 KB (`RESULT_BODY_BUDGET_BYTES / WIRE_BODY_COPIES`), so the doubled payload stays well under the client ceiling. Oversized reads now truncate with the existing `<truncated: … re-run with a more-specific query>` marker instead of silently overflowing. The cross-client `content[].text` + `structuredContent.text` mirror is unchanged.diff --git a/packages/server/src/mcp/tool-logging.ts b/packages/server/src/mcp/tool-logging.tsindex f63ddbbbb..705c07bc5 100644--- a/packages/server/src/mcp/tool-logging.ts+++ b/packages/server/src/mcp/tool-logging.ts@@ -115,9 +115,6 @@ function summarizeStructuredContentForLog(if ('previewUrlSource' in structured) {summary.previewUrlSource = structured.previewUrlSource;}- if (typeof structured.stdout === 'string') {- summary.stdoutChars = structured.stdout.length;- }if (Array.isArray(structured.warnings)) {summary.warningsCount = structured.warnings.length;}diff --git a/packages/server/src/mcp/tools/exec.test.ts b/packages/server/src/mcp/tools/exec.test.tsindex c33155740..0c76bbb83 100644--- a/packages/server/src/mcp/tools/exec.test.ts+++ b/packages/server/src/mcp/tools/exec.test.ts@@ -7,7 +7,13 @@ import { commitWip, initShadowRepo, type WriterIdentity } from '@inkeep/open-knoimport simpleGit from 'simple-git';import { type Config, ConfigSchema } from '../../config/schema.ts';import type { EnrichedMeta } from '../../content/enrichment.ts';-import { buildExecResult, DESCRIPTION, type ExecStructuredResult } from './exec.ts';+import {+ buildExecResult,+ DESCRIPTION,+ type ExecStructuredResult,+ RESULT_BODY_BUDGET_BYTES,+ WIRE_BODY_COPIES,+} from './exec.ts';import { bindTestUiLock } from './preview-url-test-helpers.ts';describe('exec DESCRIPTION — STOP-rule anchoring (SPEC 2026-04-22 FR4 / US-007 / QA-009)', () => {@@ -69,8 +75,8 @@ interface ExecResult {isError?: boolean;}-function structured(result: ExecResult): ExecStructuredResult {- return result.structuredContent as unknown as ExecStructuredResult;+function structured(result: ExecResult): ExecStructuredResult & { text?: string } {+ return result.structuredContent as unknown as ExecStructuredResult & { text?: string };}describe('exec — happy path', () => {@@ -260,7 +266,7 @@ describe('exec — stdout provenance headers', () => {)) as ExecResult;const s = structured(result);- expect(s.stdout?.startsWith('articles/:\n')).toBe(true);+ expect(s.text?.startsWith('articles/:\n')).toBe(true);expect(result.content[0].text).toContain('articles/:\n');});@@ -274,8 +280,8 @@ describe('exec — stdout provenance headers', () => {)) as ExecResult;const s = structured(result);- expect(s.stdout?.startsWith('./:')).toBe(false);- expect(s.stdout?.startsWith('.:')).toBe(false);+ expect(s.text?.startsWith('./:')).toBe(false);+ expect(s.text?.startsWith('.:')).toBe(false);});test('`cat <file.md>` prepends `==> <file> <==` header to stdout', async () => {@@ -290,7 +296,7 @@ describe('exec — stdout provenance headers', () => {)) as ExecResult;const s = structured(result);- expect(s.stdout?.startsWith('==> articles/auth.md <==\n')).toBe(true);+ expect(s.text?.startsWith('==> articles/auth.md <==\n')).toBe(true);});test('multi-file `cat a.md b.md` emits no header (would imply false boundaries)', async () => {@@ -306,7 +312,7 @@ describe('exec — stdout provenance headers', () => {)) as ExecResult;const s = structured(result);- expect(s.stdout).not.toContain('==>');+ expect(s.text).not.toContain('==>');const files = fileEntries(s);expect(files.map((f) => f.path).sort()).toEqual(['articles/a.md', 'articles/b.md']);});@@ -323,7 +329,7 @@ describe('exec — stdout provenance headers', () => {)) as ExecResult;const s = structured(result);- expect(s.stdout?.startsWith('==> articles/auth.md <==\n')).toBe(true);+ expect(s.text?.startsWith('==> articles/auth.md <==\n')).toBe(true);const files = fileEntries(s);expect(files.some((f) => f.path === 'articles/auth.md')).toBe(true);});@@ -340,7 +346,7 @@ describe('exec — stdout provenance headers', () => {)) as ExecResult;const s = structured(result);- expect(s.stdout?.startsWith('==> articles/auth.md <==\n')).toBe(true);+ expect(s.text).toContain('==> articles/auth.md <==\n');});});@@ -504,7 +510,7 @@ describe('exec — head/tail truncation banner', () => {});});-describe('exec — structuredContent mirrors stdout + warnings (Desktop fix)', () => {+describe('exec — structuredContent mirrors body text + warnings (Desktop fix)', () => {async function seed(project: string, nFiles: number, linesPerFile: number): Promise<void> {const content = resolve(project, 'content');mkdirSync(content, { recursive: true });@@ -514,7 +520,7 @@ describe('exec — structuredContent mirrors stdout + warnings (Desktop fix)', (}}- test('structuredContent.stdout contains the raw output', async () => {+ test('body rides structuredContent.text; raw stdout copy is dropped (PRD-6937)', async () => {const project = await bootstrap();const content = resolve(project, 'content');mkdirSync(content, { recursive: true });@@ -526,11 +532,52 @@ describe('exec — structuredContent mirrors stdout + warnings (Desktop fix)', ()) as ExecResult;const s = structured(result);- expect(typeof s.stdout).toBe('string');- expect(s.stdout).toContain('alpha body');+ expect(result.content[0].text).toContain('alpha body');+ expect(typeof s.text).toBe('string');+ expect(s.text).toContain('alpha body');+ expect('stdout' in (result.structuredContent ?? {})).toBe(false);expect(s.stdoutTruncated).toBe(false);});+ test('body is emitted exactly twice on the wire (content[].text + structuredContent.text)', async () => {+ const project = await bootstrap();+ const content = resolve(project, 'content');+ mkdirSync(content, { recursive: true });+ const token = 'WIRE_DEDUP_NEEDLE_3F9A';+ writeFileSync(resolve(content, 'one.md'), `# Doc\n\nfirst ${token} only\n`);++ const result = (await buildExecResult(+ { command: 'cat content/one.md' },+ { resolveCwd: async () => project, serverUrl: undefined, config: DEFAULT_CONFIG },+ )) as ExecResult;++ expect(structured(result).stdoutTruncated).toBe(false);+ const occurrences = JSON.stringify(result).split(token).length - 1;+ expect(occurrences).toBe(2);+ });++ test('mid-size cat stays within the realized per-copy + total wire budget (was 3× overflow)', async () => {+ const project = await bootstrap();+ const content = resolve(project, 'content');+ mkdirSync(content, { recursive: true });+ const line = `lorem ipsum dolor sit amet consectetur adipiscing elit ${'x'.repeat(40)}`;+ const body = Array.from({ length: 600 }, () => line).join('\n'); // ~60 KB raw+ const fm =+ '---\ntitle: Big Doc\ndescription: a mid-size doc with frontmatter\ntags: [alpha, beta, gamma]\n---\n';+ writeFileSync(resolve(content, 'big.md'), `${fm}# Big\n\n${body}\n`);++ const result = (await buildExecResult(+ { command: 'cat content/big.md' },+ { resolveCwd: async () => project, serverUrl: undefined, config: DEFAULT_CONFIG },+ )) as ExecResult;++ expect(structured(result).stdoutTruncated).toBe(true);+ expect(result.content[0].text).toContain('truncated');+ const perCopyBudget = Math.floor(RESULT_BODY_BUDGET_BYTES / WIRE_BODY_COPIES);+ expect(result.content[0].text.length).toBeLessThan(perCopyBudget);+ expect(JSON.stringify(result).length).toBeLessThan(RESULT_BODY_BUDGET_BYTES);+ });+test('structuredContent.warnings includes head-cap truncation banner', async () => {const project = await bootstrap();await seed(project, 5, 20);diff --git a/packages/server/src/mcp/tools/exec.ts b/packages/server/src/mcp/tools/exec.tsindex c908d7428..d2486daa6 100644--- a/packages/server/src/mcp/tools/exec.ts+++ b/packages/server/src/mcp/tools/exec.ts@@ -31,7 +31,11 @@ import {} from './shared.ts';const SOFT_CAP_LINES = 500;-const SOFT_CAP_BYTES = 50 * 1024;+export const WIRE_BODY_COPIES = 2;+export const RESULT_BODY_BUDGET_BYTES = 64 * 1024;+const PER_COPY_DECORATION_HEADROOM_BYTES = 8 * 1024;+const SOFT_CAP_BYTES =+ Math.floor(RESULT_BODY_BUDGET_BYTES / WIRE_BODY_COPIES) - PER_COPY_DECORATION_HEADROOM_BYTES;const BINARY_EXT_RE = /\.(png|jpe?g|gif|webp|svg|pdf|zip|tar|gz|tgz|mp4|mov|mp3|wav|ico|bmp)$/i;@@ -67,7 +71,6 @@ type ExecEnrichedEntry = EnrichedEntry & {export interface ExecStructuredResult {enrichedPaths: ExecEnrichedEntry[];cwd?: string;- stdout?: string;warnings?: string[];stdoutTruncated?: boolean;error?: { category: ErrorCategory; message: string };@@ -460,7 +463,6 @@ export async function buildExecResult(const structured: ExecStructuredResult = {enrichedPaths: enrichedWithPreview,- stdout: stdoutText,stdoutTruncated: capped.truncated,cwd,...(banners.length > 0 ? { warnings: banners } : {}),@@ -490,10 +492,6 @@ export function register(server: ServerInstance, deps: ExecDeps): void {enrichedPaths: looseObjectArray.describe('Per-referenced-file metadata: frontmatter, backlink/forward-link counts, recent shadow-repo activity, and a route-only previewUrl.',),- stdout: z- .string()- .optional()- .describe('Raw command stdout (soft-cap truncated), without banners or enrichment.'),stdoutTruncated: z.boolean().optional()