Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
feat(open-knowledge): expose explicit extension field on MCP write tool (#1977)
tim-inkeep1b22fc3504a7
diff --git a/.changeset/mcp-write-extension-field.md b/.changeset/mcp-write-extension-field.mdnew file mode 100644index 000000000..6daa2cfc1--- /dev/null+++ b/.changeset/mcp-write-extension-field.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++Expose an explicit `extension` field on the MCP `write` tool's document target, so agents can reliably author `.mdx` (Markdown + JSX) docs instead of relying on an undocumented path suffix. The tool's `path` description previously said "no extension," contradicting the skill guidance and hiding a capability that already worked end to end. Precedence is `extension` field > `.md`/`.mdx` suffix in `path` > default `.md`; an existing doc keeps its on-disk extension. The supported-extension list is now single-sourced from one canonical constant shared by the HTTP schema, the MCP tool schema, and the on-disk path probes, so the accepted set can no longer drift between layers.diff --git a/packages/app/tests/integration/mcp-write-extension.test.ts b/packages/app/tests/integration/mcp-write-extension.test.tsnew file mode 100644index 000000000..506f80ae8--- /dev/null+++ b/packages/app/tests/integration/mcp-write-extension.test.ts@@ -0,0 +1,150 @@+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { existsSync } from 'node:fs';+import { join } from 'node:path';+import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';+import { createTestServer, pollUntil, type TestServer } from './test-harness.ts';++const MCP_PROTOCOL_VERSION = '2025-06-18';++interface InitializedSession {+ sessionId: string;+ protocolVersion: string;+}++async function openMcpSession(port: number): Promise<InitializedSession> {+ const init = await fetch(`http://127.0.0.1:${port}/mcp`, {+ method: 'POST',+ headers: { accept: 'application/json, text/event-stream', 'content-type': 'application/json' },+ body: JSON.stringify({+ jsonrpc: '2.0',+ id: 1,+ method: 'initialize',+ params: {+ protocolVersion: MCP_PROTOCOL_VERSION,+ capabilities: {},+ clientInfo: { name: 'Claude', version: '1.0.0' },+ },+ }),+ });+ expect(init.status).toBe(200);+ const sessionId = init.headers.get('mcp-session-id');+ expect(sessionId).toBeTruthy();+ const initBody = (await init.json()) as { result?: { protocolVersion?: string } };+ const protocolVersion = initBody.result?.protocolVersion ?? MCP_PROTOCOL_VERSION;++ const initialized = await fetch(`http://127.0.0.1:${port}/mcp`, {+ method: 'POST',+ headers: {+ accept: 'application/json, text/event-stream',+ 'content-type': 'application/json',+ 'mcp-session-id': sessionId as string,+ 'mcp-protocol-version': protocolVersion,+ },+ body: JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' }),+ });+ expect(initialized.status).toBe(202);+ return { sessionId: sessionId as string, protocolVersion };+}++async function callWrite(+ port: number,+ session: InitializedSession,+ args: Record<string, unknown>,+ cwd: string,+): Promise<{ isError?: boolean }> {+ const res = await fetch(`http://127.0.0.1:${port}/mcp`, {+ method: 'POST',+ headers: {+ accept: 'application/json, text/event-stream',+ 'content-type': 'application/json',+ 'mcp-session-id': session.sessionId,+ 'mcp-protocol-version': session.protocolVersion,+ },+ body: JSON.stringify({+ jsonrpc: '2.0',+ id: 2,+ method: 'tools/call',+ params: { name: 'write', arguments: { ...args, cwd } },+ }),+ });+ expect(res.status).toBe(200);+ const body = (await res.json()) as { result?: { isError?: boolean }; error?: unknown };+ if (body.error) throw new Error(`tools/call error: ${JSON.stringify(body.error)}`);+ return body.result ?? {};+}++let server: TestServer;++beforeAll(async () => {+ server = await createTestServer({ debounce: 50, maxDebounce: 200 });+}, HARNESS_BOOT_TIMEOUT_MS);++afterAll(async () => {+ await server.cleanup();+});++test('explicit `extension: ".mdx"` on a suffix-less path creates a .mdx file', async () => {+ const session = await openMcpSession(server.port);+ const docName = `mdx-field-${randomUUID().slice(0, 8)}`;++ const result = await callWrite(+ server.port,+ session,+ {+ document: {+ path: docName,+ content: '# Hello MDX\n\nFrom the extension field.\n',+ extension: '.mdx',+ },+ },+ server.contentDir,+ );+ expect(result.isError ?? false).toBe(false);++ await pollUntil(() => existsSync(join(server.contentDir, `${docName}.mdx`)));+ expect(existsSync(join(server.contentDir, `${docName}.md`))).toBe(false);+});++test('the `extension` field wins over an extension typed into `path`', async () => {+ const session = await openMcpSession(server.port);+ const docName = `mdx-precedence-${randomUUID().slice(0, 8)}`;++ const result = await callWrite(+ server.port,+ session,+ { document: { path: `${docName}.md`, content: '# Precedence\n', extension: '.mdx' } },+ server.contentDir,+ );+ expect(result.isError ?? false).toBe(false);++ await pollUntil(() => existsSync(join(server.contentDir, `${docName}.mdx`)));+ expect(existsSync(join(server.contentDir, `${docName}.md`))).toBe(false);+});++test('batch `documents` write honors a per-entry `extension`', async () => {+ const session = await openMcpSession(server.port);+ const a = `mdx-batch-a-${randomUUID().slice(0, 8)}`;+ const b = `mdx-batch-b-${randomUUID().slice(0, 8)}`;++ const result = await callWrite(+ server.port,+ session,+ {+ documents: [+ { path: a, content: '# Batch A\n', extension: '.mdx' },+ { path: b, content: '# Batch B\n', extension: '.mdx' },+ ],+ },+ server.contentDir,+ );+ expect(result.isError ?? false).toBe(false);++ await pollUntil(+ () =>+ existsSync(join(server.contentDir, `${a}.mdx`)) &&+ existsSync(join(server.contentDir, `${b}.mdx`)),+ );+ expect(existsSync(join(server.contentDir, `${a}.md`))).toBe(false);+ expect(existsSync(join(server.contentDir, `${b}.md`))).toBe(false);+});diff --git a/packages/core/src/constants/doc-extensions.ts b/packages/core/src/constants/doc-extensions.tsnew file mode 100644index 000000000..e9634d215--- /dev/null+++ b/packages/core/src/constants/doc-extensions.ts@@ -0,0 +1,5 @@+export const SUPPORTED_DOC_EXTENSIONS = ['.mdx', '.md'] as const;++export type DocExtension = (typeof SUPPORTED_DOC_EXTENSIONS)[number];++export const DEFAULT_DOC_EXTENSION: DocExtension = '.md';diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 548e25fc9..196a81979 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -185,6 +185,11 @@ export {CREATE_NEW_PROJECT_FAILURE_REASONS,type CreateNewProjectFailureReason,} from './constants/create-new-project-reason.ts';+export {+ DEFAULT_DOC_EXTENSION,+ type DocExtension,+ SUPPORTED_DOC_EXTENSIONS,+} from './constants/doc-extensions.ts';export { LINEAGE_EPOCH_KEY } from './constants/doc-lifecycle.ts';export {DOCUMENT_OPEN_BYTE_LIMIT,diff --git a/packages/core/src/schemas/api/agent-write.ts b/packages/core/src/schemas/api/agent-write.tsindex db32c5080..67b4ed5e2 100644--- a/packages/core/src/schemas/api/agent-write.ts+++ b/packages/core/src/schemas/api/agent-write.ts@@ -1,5 +1,6 @@import type { StandardSchemaV1 } from '@standard-schema/spec';import { z } from 'zod';+import { SUPPORTED_DOC_EXTENSIONS } from '../../constants/doc-extensions.ts';import { FRONTMATTER_TYPES, FrontmatterValueSchema } from '../../frontmatter/schema.ts';import { agentIdentityFields, safeDocNameField, summaryField } from './_shared.ts';@@ -20,7 +21,7 @@ export const AgentWriteMdRequestSchema = zsummary: summaryField,markdown: z.string(),position: z.enum(['append', 'prepend', 'replace']).optional(),- extension: z.enum(['.md', '.mdx']).optional(),+ extension: z.enum(SUPPORTED_DOC_EXTENSIONS).optional(),...agentIdentityFields,}).loose() satisfies StandardSchemaV1;diff --git a/packages/server/assets/skills/project/SKILL.md b/packages/server/assets/skills/project/SKILL.mdindex 337036175..3169d3c4a 100644--- a/packages/server/assets/skills/project/SKILL.md+++ b/packages/server/assets/skills/project/SKILL.md@@ -137,7 +137,7 @@ Call `write` / `edit` as soon as you have content. Native `Edit` / `sed` / direc**Advisory warnings on writes.** `write` and `edit` responses may include `structuredContent.document.warnings` (batch: per-doc `structuredContent.documents[].warnings`) — advisory entries discriminated by `kind`, each also summarized as a `⚠` line in the response text. The write always landed; the entries tell you what to do next. Write-integrity kinds mean re-read the doc (`exec("cat <path>")`) before continuing: `content-divergence` (`{ kind, intendedBytes, actualBytes, byteDelta, hint }` — the converged Y.Text doesn't match what the payload composed to: concurrent peer residue, or — rare — a primitive regression) and `disk-edit-reconciled` (an out-of-band disk edit was folded in before your write landed on top). The renderability kind `mermaid-parse-error` (`{ kind, fenceIndex, fenceFirstLine, message, line? }`) means that mermaid fence will not render — fix the fence and re-edit. (A deprecated single-valued `warning` field on the HTTP body mirrors the highest-precedence integrity entry for older consumers.) Distinct from the preview-attach `warning` field (`action: "attach-preview-once" | "start-ui"`), which stays at the top level — separate keys, can coexist.-To author an MDX doc (the KB renders MDX/JSX components), pass a `.mdx` path on the create: `write({ document: { path: "guides/widget.mdx", content, position: "replace" } })` lands `guides/widget.mdx`. A `.md` or extension-less path lands `.md`. An existing doc keeps its on-disk extension regardless of the suffix you pass — changing it in place isn't available via the MCP today.+To author an MDX doc (the KB renders MDX/JSX components), set `extension: ".mdx"` on the create: `write({ document: { path: "guides/widget", content, extension: ".mdx", position: "replace" } })` lands `guides/widget.mdx`. A `.mdx` suffix typed into `path` works too (the `extension` field wins if you pass both); omit both and it lands `.md`. An existing doc keeps its on-disk extension regardless — changing it in place isn't available via the MCP today.To delete a doc, call `delete({ document })` — never `rm` / `unlink` / native `Bash` removal on in-scope markdown. The MCP path closes open agent sessions and unloads the doc from Hocuspocus before unlinking; native `rm` desynchronizes those. Deletion is irreversible — call `checkpoint()` first if you may need to roll back (it snapshots the whole project; afterwards restore the doc via `restore_version({ document, version })`, finding the `version` in `history`), and `links({ kind: "backlinks", document })` first if you want to fix referrers that will become redlinks. To move or rename a doc instead of delete + rewrite, use `move({ from, to })` — it auto-detects document vs folder vs asset and rewrites incoming references atomically.diff --git a/packages/server/src/doc-extensions.ts b/packages/server/src/doc-extensions.tsindex a2e691693..99e011acc 100644--- a/packages/server/src/doc-extensions.ts+++ b/packages/server/src/doc-extensions.ts@@ -1,9 +1,13 @@import { extname } from 'node:path';+import {+ DEFAULT_DOC_EXTENSION,+ type DocExtension,+ SUPPORTED_DOC_EXTENSIONS,+} from '@inkeep/open-knowledge-core';-export const SUPPORTED_DOC_EXTENSIONS = ['.mdx', '.md'] as const;-type DocExtension = (typeof SUPPORTED_DOC_EXTENSIONS)[number];+export { SUPPORTED_DOC_EXTENSIONS };-const DEFAULT_EXTENSION: DocExtension = '.md';+const DEFAULT_EXTENSION: DocExtension = DEFAULT_DOC_EXTENSION;export function isSupportedDocFile(path: string): boolean {const ext = extname(path).toLowerCase();diff --git a/packages/server/src/mcp/tools/move.ts b/packages/server/src/mcp/tools/move.tsindex 09cad3d35..ff00c86b7 100644--- a/packages/server/src/mcp/tools/move.ts+++ b/packages/server/src/mcp/tools/move.ts@@ -1,6 +1,7 @@import { existsSync, statSync } from 'node:fs';import { join } from 'node:path';import { z } from 'zod';+import { SUPPORTED_DOC_EXTENSIONS } from '../../doc-extensions.ts';import type { AgentIdentity } from '../agent-identity.ts';import { resolveWithinRoot } from './path-safety.ts';import { type PreviewUrlSource, resolvePreviewUrlForTool } from './preview-url.ts';@@ -123,7 +124,7 @@ function resolveMoveKind(contentDir: string, from: string): 'file' | 'folder' |if (code === 'EACCES' || code === 'EPERM') return 'file';}}- for (const ext of ['.md', '.mdx']) {+ for (const ext of SUPPORTED_DOC_EXTENSIONS) {if (existsSync(`${absBase}${ext}`)) return 'file';}return null;diff --git a/packages/server/src/mcp/tools/share-link.ts b/packages/server/src/mcp/tools/share-link.tsindex db13626b7..ba998772e 100644--- a/packages/server/src/mcp/tools/share-link.ts+++ b/packages/server/src/mcp/tools/share-link.ts@@ -5,6 +5,7 @@ import {ShareConstructUrlResponseSchema,} from '@inkeep/open-knowledge-core';import { z } from 'zod';+import { SUPPORTED_DOC_EXTENSIONS } from '../../doc-extensions.ts';import { resolveWithinRoot } from './path-safety.ts';import { encodeDocName, resolvePreviewUrlForTool } from './preview-url.ts';import type { ConfigOrResolver, ServerInstance, ServerUrlOrResolver } from './shared.ts';@@ -94,7 +95,7 @@ function isExistingDirectory(abs: string): boolean {}function resolveExistingDocPath(projectDir: string, absBase: string): string | null {- for (const ext of ['.mdx', '.md'] as const) {+ for (const ext of SUPPORTED_DOC_EXTENSIONS) {const absWithExt = `${absBase}${ext}`;if (existsSync(absWithExt)) {const projectContained = resolveWithinRoot(projectDir, absWithExt);diff --git a/packages/server/src/mcp/tools/verb-schemas.test.ts b/packages/server/src/mcp/tools/verb-schemas.test.tsindex 955873769..74c17255d 100644--- a/packages/server/src/mcp/tools/verb-schemas.test.ts+++ b/packages/server/src/mcp/tools/verb-schemas.test.ts@@ -1,5 +1,6 @@import { describe, expect, test } from 'bun:test';-import { FrontmatterArg } from './verb-schemas.ts';+import { SUPPORTED_DOC_EXTENSIONS } from '../../doc-extensions.ts';+import { DocExtensionArg, FrontmatterArg } from './verb-schemas.ts';describe('FrontmatterArg — recursive value contract (PRD-6947)', () => {test('flat scalar values still parse (regression guard for the pre-PRD-6947 contract)', () => {@@ -65,3 +66,27 @@ describe('FrontmatterArg — recursive value contract (PRD-6947)', () => {expect(description).not.toContain('flat key→value');});});++describe('DocExtensionArg — explicit on-create file format', () => {+ test('accepts every supported extension', () => {+ for (const ext of SUPPORTED_DOC_EXTENSIONS) {+ expect(DocExtensionArg.safeParse(ext).success).toBe(true);+ }+ });++ test('rejects unsupported extensions', () => {+ for (const bad of ['.markdown', '.txt', 'mdx', '.MDX', '']) {+ expect(DocExtensionArg.safeParse(bad).success).toBe(false);+ }+ });++ test('enum is single-sourced from SUPPORTED_DOC_EXTENSIONS (no drift)', () => {+ expect(DocExtensionArg.options).toEqual([...SUPPORTED_DOC_EXTENSIONS]);+ });++ test('description names .mdx + default and is part of the agent-facing wire contract', () => {+ const description = DocExtensionArg.description ?? '';+ expect(description).toContain('.mdx');+ expect(description).toContain('default');+ });+});diff --git a/packages/server/src/mcp/tools/verb-schemas.ts b/packages/server/src/mcp/tools/verb-schemas.tsindex 4fcec9287..a62b02766 100644--- a/packages/server/src/mcp/tools/verb-schemas.ts+++ b/packages/server/src/mcp/tools/verb-schemas.ts@@ -1,5 +1,6 @@import { FrontmatterValueSchema } from '@inkeep/open-knowledge-core';import { z } from 'zod';+import { SUPPORTED_DOC_EXTENSIONS } from '../../doc-extensions.ts';const FrontmatterPatchValue = z.union([FrontmatterValueSchema, z.null()]);@@ -21,6 +22,14 @@ export const PositionArg = z'append / prepend = add to the end / start.',);+export const DocExtensionArg = z+ .enum(SUPPORTED_DOC_EXTENSIONS)+ .describe(+ 'File format for a NEW doc: `.md` (default) or `.mdx` (Markdown + JSX components). ' ++ 'Honored only on create — an existing doc keeps its on-disk extension. ' ++ 'Takes precedence over an extension typed into `path`.',+ );+export function splitTargetPath(path: string): { folder: string; name: string } {const clean = path.replace(/^\/+/, '').replace(/\/+$/, '');const idx = clean.lastIndexOf('/');diff --git a/packages/server/src/mcp/tools/write.ts b/packages/server/src/mcp/tools/write.tsindex 5d2bb32a4..23ea6c7d3 100644--- a/packages/server/src/mcp/tools/write.ts+++ b/packages/server/src/mcp/tools/write.ts@@ -1,6 +1,7 @@import { existsSync, readFileSync } from 'node:fs';import { resolve as resolvePath } from 'node:path';import {+ type DocExtension,type FrontmatterMap,type FrontmatterPatch,normalizeBridge,@@ -47,6 +48,7 @@ import {textResult,} from './shared.ts';import {+ DocExtensionArg,exactlyOneTargetError,FrontmatterArg,PositionArg,@@ -85,6 +87,7 @@ interface DocSpec {frontmatter?: FrontmatterPatch;position?: string;summary?: string;+ extension?: DocExtension;}type WriteApiResult = Awaited<ReturnType<typeof httpPost>>;@@ -194,7 +197,7 @@ async function writeOneDoc(const existingExt = docExtensionOnDisk(contentDir, docName);const docExists = existingExt !== null;- const requestedExt = requestedDocExtension(spec.path);+ const requestedExt = spec.extension ?? requestedDocExtension(spec.path);let effectivePosition: string;if (spec.position !== undefined) {@@ -592,12 +595,15 @@ export function register(server: ServerInstance, deps: WriteDeps): void {path: z.string().describe(- 'Document path, no extension. The slashes are the folder it lands in; missing parent folders are created. Example: "meetings/2026-06-03-standup".',+ 'Document path. The slashes are the folder it lands in; missing parent folders are created. ' ++ 'Example: "meetings/2026-06-03-standup". An optional `.md`/`.mdx` suffix selects the file format ' ++ '(default `.md`); prefer the `extension` field for that. The docName itself is always extension-less.',),content: z.string().optional().describe('The full Markdown body. Mutually exclusive with `template`.'),+ extension: DocExtensionArg.optional(),template: z.string().min(1)