Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

Honor the folder in an MCP asset write's path and report where it landed (PRD-9122) (#6136)

serafin-garciadebeb6a312f6
diff --git a/.changeset/mcp-asset-path-folder.md b/.changeset/mcp-asset-path-folder.md
new file mode 100644
index 000000000..037ba7890
--- /dev/null
+++ b/.changeset/mcp-asset-path-folder.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+The MCP `write` tool now saves an `asset` into the folder its path names, even when the project sets an attachment folder. A bare file name still goes to the attachment folder.
diff --git a/.changeset/mcp-asset-reply-path.md b/.changeset/mcp-asset-reply-path.md
new file mode 100644
index 000000000..56f65987e
--- /dev/null
+++ b/.changeset/mcp-asset-reply-path.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+The MCP `write` reply for an `asset` now names the path where the file was saved, including when the file was renamed or placed in the attachment folder.
diff --git a/docs/content/reference/configuration.mdx b/docs/content/reference/configuration.mdx
index f14eaaecf..ad02cc48b 100644
--- a/docs/content/reference/configuration.mdx
+++ b/docs/content/reference/configuration.mdx
@@ -34,7 +34,7 @@ A key set in a file more specific than its scope (a user-scope key in `.ok/confi
| Field | Type | Default | Scope | Description |
| --- | --- | --- | --- | --- |
| `content.dir` | string | `"."` | project | Content directory, relative to project root. Defaults to `.` (the project root) even when `.ok/` is scaffolded at the git working-tree root from a sub-folder, so opened folder and content scope align by default. To narrow scope to a sub-folder, pass `--content-dir <dir>` to `ok init`, or uncomment `content.dir` in `.ok/config.yml` post-init. Excluded paths live in `.okignore`; see [Ignore patterns](/docs/features/ignore-patterns). |
-| `content.attachmentFolderPath` | string | `"./"` | project | Where pasted and dropped assets are stored. `"./"` colocates beside the current document; `"/"` targets the content root; `"./subdir"` targets a subfolder under the current folder; `"folder"` targets a fixed folder under the content root. A configured folder also widens what counts as content: linkable files inside it (images, PDFs, media) are treated as project content without needing a Markdown document beside them, so in shared projects they auto-sync to teammates. The default `"./"` keeps the historical rule (assets sync only beside a document). |
+| `content.attachmentFolderPath` | string | `"./"` | project | Where pasted and dropped assets, and MCP `write` assets given a bare file name, are stored. `"./"` colocates beside the current document; `"/"` targets the content root; `"./subdir"` targets a subfolder under the current folder; `"folder"` targets a fixed folder under the content root. A configured folder also widens what counts as content: linkable files inside it (images, PDFs, media) are treated as project content without needing a Markdown document beside them, so in shared projects they auto-sync to teammates. The default `"./"` keeps the historical rule (assets sync only beside a document). |
| `contentRules.markdownlint.enabled` | boolean | `false` | project | Enable the [markdownlint](/docs/advanced/content-rules/markdownlint) content-rules plugin for this project (shared via git). Off by default — turn it on in **Settings → This project → Plugins**. The rules themselves live in your native `.markdownlint.*` file, not here. |
| `contentRules.frontmatter.enabled` | boolean | `false` | project | Enable the [Frontmatter schemas](/docs/advanced/content-rules/frontmatter) content-rules plugin for this project (shared via git). Off by default — turn it on in **Settings → This project → Plugins**. |
| `contentRules.frontmatter.schemas` | array | `[]` | project | Frontmatter schema mappings: each entry scopes one JSON Schema file to a set of docs — `file` (project-root-relative path), optional `appliesTo` (glob or list; leading `!` excludes; absent means every doc), optional `enabled: false` to park a mapping. Schema content lives in the mapped files, not here. See [Frontmatter schemas](/docs/advanced/content-rules/frontmatter). |
diff --git a/docs/content/reference/mcp.mdx b/docs/content/reference/mcp.mdx
index 38e0651f1..42d1b6b3d 100644
--- a/docs/content/reference/mcp.mdx
+++ b/docs/content/reference/mcp.mdx
@@ -27,7 +27,7 @@ To point an MCP client at this server, locally or over a tunnel from another mac
| `palette` | Markdown-native authoring forms, themed `html preview` embed starters, and theme tokens. Pass `components` for the canonical components' full JSX prop schemas |
| `preview_url` | Resolve the browser-reachable preview URL. Targets a `document`, `folder`, or `skill` in the current project, or — via `file`, an absolute path — a markdown file outside it (resolved through the session serving that file). Per-response `previewUrl` fields elsewhere are route-only (`/#/<doc>`); call this when you need the full openable URL |
| `share_link` | Build a GitHub-substrate share URL for a doc or folder to send to a teammate (`kind` disambiguates; `path: ""` with `kind: "folder"` shares the content root). Responses carry a `freshness` verdict — `current`, `stale` (unpushed changes), or `absent` (never pushed), omitted when the probe can't run — and prepend a matching warning to relay with the link. Read-only against `.git/`; never publishes |
-| `write` | Create or overwrite a `document`, `folder`, `template`, `skill`, or `asset`. For a document: `{ path, content }`, or `{ path, template }` to instantiate from a folder template. `position` selects `replace` (full rewrite; the only mode that touches frontmatter), `append`, or `prepend`. An `append` or `prepend` to a path with no document creates it, and the response opens with `Created new document`. A replace is refused if another writer changed the document in the last few seconds: wait and retry, or use `append`, `prepend`, or `edit`, which bypass concurrent-overwrite protection but still require valid input. `extension` selects `.md` (default) or `.mdx` for a new document; an existing doc keeps its extension (the MCP cannot change it). An `asset` takes exactly one of `content` (base64, for small files) or `source` (a local path the server reads, for large files) |
+| `write` | Create or overwrite a `document`, `folder`, `template`, `skill`, or `asset`. For a document: `{ path, content }`, or `{ path, template }` to instantiate from a folder template. `position` selects `replace` (full rewrite; the only mode that touches frontmatter), `append`, or `prepend`. An `append` or `prepend` to a path with no document creates it, and the response opens with `Created new document`. A replace is refused if another writer changed the document in the last few seconds: wait and retry, or use `append`, `prepend`, or `edit`, which bypass concurrent-overwrite protection but still require valid input. `extension` selects `.md` (default) or `.mdx` for a new document; an existing doc keeps its extension (the MCP cannot change it). An `asset` takes exactly one of `content` (base64, for small files) or `source` (a local path the server reads, for large files). An asset `path` with a folder lands in that folder; a bare file name goes to the attachment folder ([`content.attachmentFolderPath`](/docs/reference/configuration), by default the content root) |
| `edit` | Modify a `document` (body find/replace **or** a frontmatter merge-patch), a `folder` (frontmatter merge-patch), a `template`, or a `skill`. Body edits take `{ path, find, replace, occurrence? }`; `occurrence` selects which match (1 = first). A document `edit` changes only an existing document; a path with no document is refused and nothing is created |
| `delete` | Delete a `document` (one path or an array), `folder`, `template`, `skill`, or `asset` |
| `move` | Move or rename a `document`, `folder`, `asset`, `template`, or `skill`. Links to the moved document keep pointing to it. The old path stops existing; no redirect or stub is left behind. The move can also edit referring documents to preserve their existing link targets, including links to documents that did not move when the new path would otherwise take precedence. Correctly resolving shorthand stays unchanged; necessary wiki rewrites preserve displayed text, aliases and headings. Renaming or moving a page in the app's sidebar rewrites links the same way, so the old name stays visible as link text. A skill also moves between Project and Global scope via `scope` + `toScope`: history does not transfer; the editor locations the destination level can host are re-projected there, while everything else (the `agents` hub, custom roots, and any editor with no skills root at that level) is removed at the source and not re-created at the destination. The removed locations come back as `droppedLocations`; re-add the ones that level can place with `install`. That only holds on a success: on a failed move the same field lists source-side placements the call had already removed, so installing them at the destination would spread a retained copy instead of restoring anything |
diff --git a/packages/core/src/config/schema.ts b/packages/core/src/config/schema.ts
index a3d879cf8..5a4849c67 100644
--- a/packages/core/src/config/schema.ts
+++ b/packages/core/src/config/schema.ts
@@ -142,7 +142,7 @@ export const ConfigSchema = z.looseObject({
reload: 'live',
defaultScope: 'project',
description:
- "Where pasted and dropped assets are stored, relative to the content root. './' colocates beside the current document (default); '/' targets the content root; './subdir' targets a subfolder under the current document folder; 'folder' targets a fixed folder under the content root. Whitespace-only values are treated as './'.",
+ "Where pasted and dropped assets, and MCP write assets given a bare file name, are stored, relative to the content root. './' colocates beside the current document (default); '/' targets the content root; './subdir' targets a subfolder under the current document folder; 'folder' targets a fixed folder under the content root. Whitespace-only values are treated as './'.",
})
.refine(isValidAttachmentFolderPath, {
message:
diff --git a/packages/server/assets/skills/project/references/media-and-assets.md b/packages/server/assets/skills/project/references/media-and-assets.md
index cf76dc9a7..27d1d9633 100644
--- a/packages/server/assets/skills/project/references/media-and-assets.md
+++ b/packages/server/assets/skills/project/references/media-and-assets.md
@@ -3,7 +3,7 @@
- **Markdown syntax only:** `![alt text](./path/to/image.png)`. Do NOT emit HTML `<img>` tags — they don't participate in OK's content graph and don't render consistently across Fumadocs / preview surfaces. Paths resolve relative to the doc.
- **Always a doc-relative path — never a server URL.** Reference an asset by its path relative to the doc (`./image.png`, `../assets/foo.png`), never an absolute `http://localhost:<port>/…`, `127.0.0.1`, or other server URL. `preview_url`'s `url` navigates the *preview* — it is NOT an asset path; never paste it (or any `localhost` base) into an `![]()`. An asset already in the tree is the same rule: find its path with `exec("ls -A <dir>")` and write the relative link. (Upload via `write({ asset })` hands you the exact relative `![alt](ref)` to copy.)
- **Save locally, don't hot-link.** Hot-linked external image URLs rot when the source disappears. Fetch it through the ingest procedure in `references/ingest-and-sources.md` (SSRF-safe fetch flags, size + executable-extension gates, wrapper frontmatter) — never an ad-hoc `WebFetch` / `curl` into the tree — then reference the local file via a relative markdown link and cite the ingested wrapper below.
-- **Placement model.** Free-form image embeds → co-located alongside the referencing doc (sha256 same-directory dedup). Raw sources via `ingest` → `external-sources/<slug>.<ext>` + `external-sources/<slug>.md` (the wrapper-binary pair). Check via `exec("ls -A")` if the project uses a different convention.
+- **Placement model.** Free-form image embeds → co-located alongside the referencing doc (sha256 same-directory dedup): give `write({ asset })` a `path` in that doc's folder, because a bare file name goes to the attachment folder (`content.attachmentFolderPath`, by default the content root). Raw sources via `ingest` → `external-sources/<slug>.<ext>` + `external-sources/<slug>.md` (the wrapper-binary pair). Check via `exec("ls -A")` if the project uses a different convention.
- **Cannot fetch** (no network, paywall) → don't invent a local path. Omit, or mark inline `(TODO: image needs sourcing from <URL>)`.
- **Meaningful alt text required** — describes WHAT the image shows, not what it is. `![]()` / `![image]()` / `![filename.png]()` all fail. OK indexes alt text — it's both accessibility AND searchability.
- **Cite web image sources** below the image (Grounding rule):
diff --git a/packages/server/src/mcp-dual-transport-rig.test-helper.ts b/packages/server/src/mcp-dual-transport-rig.test-helper.ts
new file mode 100644
index 000000000..3b9b73069
--- /dev/null
+++ b/packages/server/src/mcp-dual-transport-rig.test-helper.ts
@@ -0,0 +1,96 @@
+import { mkdirSync } from 'node:fs';
+import { mkdtemp, rm } from 'node:fs/promises';
+import { createServer, type Server } from 'node:http';
+import type { AddressInfo } from 'node:net';
+import { tmpdir } from 'node:os';
+import { resolve } from 'node:path';
+import type { Client } from '@modelcontextprotocol/sdk/client/index.js';
+import { type BootedServer, bootServer } from './boot.ts';
+import { ConfigSchema } from './config/schema.ts';
+import { connectMcpTestClient } from './mcp/client.test-helper.ts';
+import { createMcpHttpHandler, type McpHttpHandler } from './mcp-http.ts';
+
+export interface DualTransportMcpRig {
+ readonly booted: BootedServer;
+ readonly contentDir: string;
+ readonly localClient: Client;
+ readonly httpClient: Client;
+ readonly close: () => Promise<void>;
+}
+
+export async function startDualTransportMcpRig(options: {
+ readonly tmpPrefix: string;
+ readonly clientName: string;
+ readonly seed: (contentDir: string) => void;
+}): Promise<DualTransportMcpRig> {
+ const config = ConfigSchema.parse({});
+ const tmpDir = await mkdtemp(resolve(tmpdir(), options.tmpPrefix));
+ const contentDir = resolve(tmpDir, 'project');
+ let booted: BootedServer | undefined;
+ let httpOnlyMcp: McpHttpHandler | undefined;
+ let sideServer: Server | undefined;
+ let localClient: Client | undefined;
+ let httpClient: Client | undefined;
+
+ const close = async (): Promise<void> => {
+ await localClient?.close().catch(() => {});
+ await httpClient?.close().catch(() => {});
+ await httpOnlyMcp?.close();
+ sideServer?.closeAllConnections();
+ sideServer?.close();
+ await booted?.destroy();
+ await rm(tmpDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
+ };
+
+ try {
+ mkdirSync(contentDir, { recursive: true });
+ options.seed(contentDir);
+
+ const server = await bootServer({
+ host: '127.0.0.1',
+ config,
+ contentDir,
+ port: 0,
+ quiet: true,
+ gitEnabled: false,
+ idleShutdownMs: null,
+ });
+ booted = server;
+ await server.ready;
+
+ const handler = createMcpHttpHandler({
+ contentDir: server.contentDir,
+ projectDir: server.contentDir,
+ config,
+ getServerUrl: () => `http://127.0.0.1:${server.port}`,
+ });
+ httpOnlyMcp = handler;
+ const side = createServer((req, res) => {
+ void handler.handle(req, res);
+ });
+ sideServer = side;
+ const sidePort = await new Promise<number>((resolvePort) => {
+ side.listen(0, '127.0.0.1', () => {
+ resolvePort((side.address() as AddressInfo).port);
+ });
+ });
+
+ const identity = { name: options.clientName, version: '0.0.0-test' };
+ const local = await connectMcpTestClient(`http://127.0.0.1:${server.port}/mcp`, identity);
+ localClient = local;
+ const http = await connectMcpTestClient(`http://127.0.0.1:${sidePort}/mcp`, identity);
+ httpClient = http;
+
+ return { booted: server, contentDir, localClient: local, httpClient: http, close };
+ } catch (err) {
+ try {
+ await close();
+ } catch (cleanupErr) {
+ throw new AggregateError(
+ [err, cleanupErr],
+ 'dual-transport MCP rig startup and cleanup failed',
+ );
+ }
+ throw err;
+ }
+}
diff --git a/packages/server/src/mcp-local-dispatch-parity.test.ts b/packages/server/src/mcp-local-dispatch-parity.test.ts
index bf50f26b9..0a20eb6fa 100644
--- a/packages/server/src/mcp-local-dispatch-parity.test.ts
+++ b/packages/server/src/mcp-local-dispatch-parity.test.ts
@@ -1,23 +1,16 @@
import { mkdirSync, writeFileSync } from 'node:fs';
-import { mkdtemp, rm } from 'node:fs/promises';
-import { createServer, type Server } from 'node:http';
-import type { AddressInfo } from 'node:net';
-import { tmpdir } from 'node:os';
import { resolve } from 'node:path';
import { OK_DIR } from '@inkeep/open-knowledge-core';
import type { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
-import { type BootedServer, bootServer } from './boot.ts';
-import { ConfigSchema } from './config/schema.ts';
-import { connectMcpTestClient } from './mcp/client.test-helper.ts';
-import { createMcpHttpHandler, type McpHttpHandler } from './mcp-http.ts';
+import type { BootedServer } from './boot.ts';
+import {
+ type DualTransportMcpRig,
+ startDualTransportMcpRig,
+} from './mcp-dual-transport-rig.test-helper.ts';
-const TEST_CONFIG = ConfigSchema.parse({});
-
-let tmpDir: string;
+let rig: DualTransportMcpRig | undefined;
let booted: BootedServer;
-let httpOnlyMcp: McpHttpHandler;
-let sideServer: Server;
let localClient: Client;
let httpClient: Client;
@@ -34,9 +27,6 @@ function seedOkScaffold(projectDir: string): void {
writeFileSync(resolve(okDir, '.gitignore'), '', 'utf-8');
}
-const connectClient = (url: string, name: string): Promise<Client> =>
- connectMcpTestClient(url, { name, version: '0.0.0-test' });
-
function maskVolatile(result: ToolResult): unknown {
return JSON.parse(
JSON.stringify({
@@ -55,47 +45,26 @@ async function callBoth(name: string, args: Record<string, unknown>): Promise<[u
}
beforeAll(async () => {
- tmpDir = await mkdtemp(resolve(tmpdir(), 'ok-mcp-parity-'));
- const contentDir = resolve(tmpDir, 'project');
- mkdirSync(contentDir, { recursive: true });
- seedOkScaffold(contentDir);
- writeFileSync(resolve(contentDir, 'alpha.md'), '# Alpha\n\nThe alpha reference doc.\n', 'utf-8');
- writeFileSync(
- resolve(contentDir, 'beta.md'),
- '# Beta\n\nSee [[alpha]] and the missing [[gamma-nowhere]].\n',
- 'utf-8',
- );
- writeFileSync(resolve(contentDir, 'del-local.md'), '# Doomed\n\nSame body.\n', 'utf-8');
- writeFileSync(resolve(contentDir, 'del-http.md'), '# Doomed\n\nSame body.\n', 'utf-8');
-
- booted = await bootServer({
- host: '127.0.0.1',
- config: TEST_CONFIG,
- contentDir,
- port: 0,
- quiet: true,
- gitEnabled: false,
- idleShutdownMs: null,
- });
- await booted.ready;
-
- httpOnlyMcp = createMcpHttpHandler({
- contentDir: booted.contentDir,
- projectDir: booted.contentDir,
- config: TEST_CONFIG,
- getServerUrl: () => `http://127.0.0.1:${booted.port}`,
- });
- sideServer = createServer((req, res) => {
- void httpOnlyMcp.handle(req, res);
- });
- const sidePort = await new Promise<number>((resolvePort) => {
- sideServer.listen(0, '127.0.0.1', () => {
- resolvePort((sideServer.address() as AddressInfo).port);
- });
- });
-
- localClient = await connectClient(`http://127.0.0.1:${booted.port}/mcp`, 'parity-suite');
- httpClient = await connectClient(`http://127.0.0.1:${sidePort}/mcp`, 'parity-suite');
+ rig = await startDualTransportMcpRig({
+ tmpPrefix: 'ok-mcp-parity-',
+ clientName: 'parity-suite',
+ seed: (contentDir) => {
+ seedOkScaffold(contentDir);
+ writeFileSync(
+ resolve(contentDir, 'alpha.md'),
+ '# Alpha\n\nThe alpha reference doc.\n',
+ 'utf-8',
+ );
+ writeFileSync(
+ resolve(contentDir, 'beta.md'),
+ '# Beta\n\nSee [[alpha]] and the missing [[gamma-nowhere]].\n',
+ 'utf-8',
+ );
+ writeFileSync(resolve(contentDir, 'del-local.md'), '# Doomed\n\nSame body.\n', 'utf-8');
+ writeFileSync(resolve(contentDir, 'del-http.md'), '# Doomed\n\nSame body.\n', 'utf-8');
+ },
+ });
+ ({ booted, localClient, httpClient } = rig);
const deadline = Date.now() + 15_000;
for (;;) {
@@ -112,13 +81,7 @@ beforeAll(async () => {
}, 60_000);
afterAll(async () => {
- await localClient?.close().catch(() => {});
- await httpClient?.close().catch(() => {});
- await httpOnlyMcp?.close();
- sideServer?.closeAllConnections();
- sideServer?.close();
- await booted?.destroy();
- await rm(tmpDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
+ await rig?.close();
});
describe('MCP local-dispatch transport parity (same server, two sessions)', () => {
diff --git a/packages/server/src/mcp-write-asset-placement.test.ts b/packages/server/src/mcp-write-asset-placement.test.ts
new file mode 100644
index 000000000..8dad9df5b
--- /dev/null
+++ b/packages/server/src/mcp-write-asset-placement.test.ts
@@ -0,0 +1,149 @@
+import { mkdirSync, readdirSync, writeFileSync } from 'node:fs';
+import { posix, relative, resolve, sep } from 'node:path';
+import { OK_DIR } from '@inkeep/open-knowledge-core';
+import type { Client } from '@modelcontextprotocol/sdk/client/index.js';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
+import {
+ type DualTransportMcpRig,
+ startDualTransportMcpRig,
+} from './mcp-dual-transport-rig.test-helper.ts';
+
+const ATTACHMENT_FOLDER = 'attachments';
+
+const PNG_1X1 = Buffer.from(
+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==',
+ 'base64',
+);
+
+const TRANSPORTS = [
+ { arm: 'in-process localApi', transport: 'local' },
+ { arm: 'HTTP fetch', transport: 'http' },
+] as const;
+
+type Transport = (typeof TRANSPORTS)[number]['transport'];
+
+type ToolResult = {
+ content?: Array<{ type: string; text?: string }>;
+ structuredContent?: { asset?: { path?: string } };
+ isError?: boolean;
+};
+
+interface AssetWrite {
+ readonly reply: string;
+ readonly structuredPath: string | undefined;
+ readonly written: readonly string[];
+}
+
+let rig: DualTransportMcpRig;
+
+beforeAll(async () => {
+ rig = await startDualTransportMcpRig({
+ tmpPrefix: 'ok-mcp-asset-placement-',
+ clientName: 'asset-placement-suite',
+ seed: (contentDir) => {
+ const okDir = resolve(contentDir, OK_DIR);
+ mkdirSync(okDir, { recursive: true });
+ writeFileSync(
+ resolve(okDir, 'config.yml'),
+ `content:\n attachmentFolderPath: ${ATTACHMENT_FOLDER}\n`,
+ 'utf-8',
+ );
+ writeFileSync(resolve(okDir, '.gitignore'), '', 'utf-8');
+ mkdirSync(resolve(contentDir, 'docs'), { recursive: true });
+ writeFileSync(resolve(contentDir, 'docs', 'readme.md'), '# Docs\n', 'utf-8');
+ },
+ });
+}, 60_000);
+
+afterAll(async () => {
+ await rig?.close();
+});
+
+const clientFor = (transport: Transport): Client =>
+ transport === 'local' ? rig.localClient : rig.httpClient;
+
+function listContentFiles(dir: string = rig.contentDir, out: string[] = []): string[] {
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
+ if (entry.name === OK_DIR || entry.name === '.git') continue;
+ const abs = resolve(dir, entry.name);
+ if (entry.isDirectory()) listContentFiles(abs, out);
+ else out.push(relative(rig.contentDir, abs).split(sep).join('/'));
+ }
+ return out;
+}
+
+async function writeAsset(transport: Transport, path: string, tag: string): Promise<AssetWrite> {
+ const stem = posix.basename(path, posix.extname(path));
+ const before = new Set(listContentFiles());
+ const result = (await clientFor(transport).callTool({
+ name: 'write',
+ arguments: {
+ asset: { path, content: Buffer.concat([PNG_1X1, Buffer.from(tag)]).toString('base64') },
+ },
+ })) as ToolResult;
+ const reply = result.content?.map((c) => c.text ?? '').join('\n') ?? '';
+ expect(result.isError ?? false, reply).toBe(false);
+ return {
+ reply,
+ structuredPath: result.structuredContent?.asset?.path,
+ written: listContentFiles().filter((p) => !before.has(p) && posix.basename(p).startsWith(stem)),
+ };
+}
+
+const pathToken = (path: string): RegExp =>
+ new RegExp(`(?:^|[\\s\`'"])/?${path.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?![\\w/-])`, 'm');
+
+describe(`MCP write({ asset }) with content.attachmentFolderPath: ${ATTACHMENT_FOLDER}`, () => {
+ describe('an explicit folder in asset.path decides where the bytes land', () => {
+ test.each(TRANSPORTS)('$arm: docs/<name> lands in docs/', async ({ transport }) => {
+ const requested = `docs/${transport}-placed.png`;
+ const { written } = await writeAsset(transport, requested, `${transport}-placed`);
+ expect(written).toEqual([requested]);
+ });
+ });
+
+ describe('a bare name follows the configured attachment folder', () => {
+ test.each(TRANSPORTS)('$arm: <name> lands in the attachment folder', async ({ transport }) => {
+ const { written } = await writeAsset(transport, `${transport}-bare.png`, `${transport}-bare`);
+ expect(written).toEqual([`${ATTACHMENT_FOLDER}/${transport}-bare.png`]);
+ });
+ });
+
+ describe('the reply names the path actually written', () => {
+ test.each(TRANSPORTS)(
+ '$arm: a bare name redirected into the attachment folder',
+ async ({ transport }) => {
+ const requested = `${transport}-redirected.png`;
+ const { reply, structuredPath, written } = await writeAsset(
+ transport,
+ requested,
+ `${transport}-redirected`,
+ );
+ expect(written).toHaveLength(1);
+ const [writtenPath = ''] = written;
+ expect(writtenPath).not.toBe(requested);
+ expect(structuredPath).toBe(writtenPath);
+ expect(reply).toMatch(pathToken(writtenPath));
+ },
+ );
+
+ test.each(TRANSPORTS)(
+ '$arm: a same-name collision the server renamed',
+ async ({ transport }) => {
+ const requested = `docs/${transport}-dup.png`;
+ const first = await writeAsset(transport, requested, `${transport}-dup-first`);
+ expect(first.written).toHaveLength(1);
+ const { reply, structuredPath, written } = await writeAsset(
+ transport,
+ requested,
+ `${transport}-dup-second`,
+ );
+ expect(written).toHaveLength(1);
+ const [writtenPath = ''] = written;
+ expect(posix.basename(writtenPath)).not.toBe(posix.basename(requested));
+ expect(structuredPath).toBe(writtenPath);
+ expect(reply).toMatch(pathToken(writtenPath));
+ },
+ );
+ });
+});
diff --git a/packages/server/src/mcp/tools/write.test.ts b/packages/server/src/mcp/tools/write.test.ts
index b12d16840..0cfd022c4 100644
--- a/packages/server/src/mcp/tools/write.test.ts
+++ b/packages/server/src/mcp/tools/write.test.ts
@@ -434,3 +434,55 @@ describe('write — an asset upload whose request to the server fails', () => {
expect(result.content[0]?.text).toBe('Error: Server unreachable: fetch failed');
});
});
+
+describe('write — the reply to an asset upload the server accepted', () => {
+ type AssetHandler = (args: Record<string, unknown>) => Promise<{
+ isError?: boolean;
+ content: Array<{ type: string; text?: string }>;
+ structuredContent?: { asset?: unknown };
+ }>;
+ const asset = { path: 'assets/photo.bin', content: Buffer.from('bytes').toString('base64') };
+ let cwd: string;
+
+ beforeAll(() => {
+ cwd = mkdtempSync(join(tmpdir(), 'ok-write-asset-reply-'));
+ mkdirSync(join(cwd, '.ok'), { recursive: true });
+ });
+
+ afterAll(() => {
+ rmSync(cwd, { recursive: true, force: true });
+ });
+
+ function uploadAnswering(bodyText: string): AssetHandler {
+ let captured: AssetHandler | null = null;
+ const server = {
+ registerTool(_name: string, _cfg: unknown, toolHandler: AssetHandler) {
+ captured = toolHandler;
+ },
+ } as unknown as ServerInstance;
+ registerWrite(server, {
+ serverUrl: 'http://127.0.0.1:1',
+ localApi: async () => ({ status: 200, bodyText }),
+ config: ConfigSchema.parse({}),
+ resolveCwd: async () => cwd,
+ });
+ if (captured === null) throw new Error('write tool did not register');
+ return captured as AssetHandler;
+ }
+
+ it('claims no location rather than the requested path when the response names none', async () => {
+ const result = await uploadAnswering('{"src":"photo.bin"}')({ asset });
+ expect(result.isError ?? false).toBe(false);
+ expect(result.structuredContent?.asset).toStrictEqual({ ok: true, src: 'photo.bin' });
+ expect(result.content[0]?.text).not.toContain(asset.path);
+ });
+
+ it('reports an error, not an upload, when the response breaks the upload contract', async () => {
+ const result = await uploadAnswering('{"src":"photo.bin","path":12345}')({ asset });
+ expect(result.isError).toBe(true);
+ expect(result.structuredContent?.asset).toBeUndefined();
+ expect(result.content[0]?.text).toMatch(
+ /^Error: Server returned 2xx response with malformed upload body: .*path/s,
+ );
+ });
+});
diff --git a/packages/server/src/mcp/tools/write.ts b/packages/server/src/mcp/tools/write.ts
index cf04764be..4435d2502 100644
--- a/packages/server/src/mcp/tools/write.ts
+++ b/packages/server/src/mcp/tools/write.ts
@@ -11,6 +11,8 @@ import {
SKILL_AUTHORING_WARNING_CODES,
serializeFrontmatterMap,
stripFrontmatter,
+ UploadAssetSuccessSchema,
+ type UploadRequest,
unwrapFrontmatterFences,
withFences,
} from '@inkeep/open-knowledge-core';
@@ -509,6 +511,7 @@ async function handleAsset(
const form = new FormData();
form.append('parentDocName', parentDocName);
+ if (folder) form.append('placement', 'parent-dir' satisfies UploadRequest['placement']);
form.append('file', new Blob([new Uint8Array(bytes)]), fileName);
const uploadPath = `/api/upload${qs ? `?${qs}` : ''}`;
@@ -568,18 +571,22 @@ async function handleAsset(
};
if (!resBody.ok) return textResult(`Error: ${resBody.error}`, true);
- const src = typeof resBody.data?.src === 'string' ? resBody.data.src : undefined;
- const path = typeof resBody.data?.path === 'string' ? resBody.data.path : undefined;
- const deduped = resBody.data?.deduped === true;
- const ref = src ?? path ?? fileName;
+ const success = UploadAssetSuccessSchema.safeParse(resBody.data);
+ if (!success.success) {
+ return textResult(
+ `Error: Server returned 2xx response with malformed upload body: ${z.prettifyError(success.error)}`,
+ true,
+ );
+ }
+ const { src, path, deduped } = success.data;
const text = [
- `Uploaded asset to ${parentDocName}${deduped ? ' (deduplicated — identical bytes already present)' : ''}.`,
- `Reference it in a doc with: ![${fileName}](${ref})`,
+ `Uploaded asset${path ? ` to ${path}` : ''}${deduped ? ' (deduplicated — identical bytes already present)' : ''}.`,
+ `Reference it in a doc with: ![${fileName}](${src})`,
].join('\n');
return textPlusStructured(text, {
asset: {
ok: true,
- ...(src ? { src } : {}),
+ src,
...(path ? { path } : {}),
...(deduped ? { deduped } : {}),
},
@@ -957,7 +964,7 @@ export function register(server: ServerInstance, deps: WriteDeps): void {
path: z
.string()
.describe(
- 'Asset path incl. extension — the slashes are the folder. Example: "images/diagram.png".',
+ 'Asset path incl. extension — the slashes are the folder. Example: "images/diagram.png". A bare file name (no folder) goes to the attachment folder (`content.attachmentFolderPath`; by default the content root).',
),
content: z.string().optional().describe('Base64 of the binary. Use for small files.'),
source: z
@@ -1039,8 +1046,13 @@ export function register(server: ServerInstance, deps: WriteDeps): void {
asset: z
.object({
ok: z.boolean(),
- src: z.string().optional().describe('The reference src to embed in a doc.'),
- path: z.string().optional(),
+ src: z.string().describe('The reference src to embed in a doc.'),
+ path: z
+ .string()
+ .optional()
+ .describe(
+ 'Content-root-relative path the server reports holding the asset (the existing file when `deduped`). Absent when the server reports none.',
+ ),
deduped: z
.boolean()
.optional()