Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

feat(open-knowledge): LM Studio as an AI option + $ref-free tool schemas (#2582)

mike-inkeep57e997e67c95
diff --git a/.changeset/frontmatter-schema-ref-free.md b/.changeset/frontmatter-schema-ref-free.md
new file mode 100644
index 000000000..d811c97b5
--- /dev/null
+++ b/.changeset/frontmatter-schema-ref-free.md
@@ -0,0 +1,7 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Fix the `write` and `edit` MCP tools failing with a schema-conversion error on constrained-decoding hosts like LM Studio (`Error resolving ref #/definitions/__schema0`). Their `frontmatter` field advertised a recursive JSON Schema (`$ref: "#/definitions/__schema0"`); LM Studio — and some function-calling APIs like Gemini — can't resolve an intra-schema `$ref` in a tool definition and reject the whole tool. Claude and most MCP clients resolve it leniently, so this only surfaced on local-inference hosts.
+
+The `frontmatter` value now advertises a flat, `$ref`-free JSON Schema (scalar | array | object | null), while a runtime refinement re-applies the exact recursive validation — so accepted/rejected inputs are unchanged for every client and every write path (nested `null` is still rejected, deep nesting and heterogeneous arrays still accepted). Added a test that compiles every tool's input and output schema and fails if any emits a `$ref`, so this can't silently regress.
diff --git a/.changeset/lm-studio-mcp-editor.md b/.changeset/lm-studio-mcp-editor.md
new file mode 100644
index 000000000..f913cfcec
--- /dev/null
+++ b/.changeset/lm-studio-mcp-editor.md
@@ -0,0 +1,7 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Add LM Studio as a supported AI tool. `ok init` and the desktop consent dialog now register the OpenKnowledge MCP server into LM Studio's `mcp.json`, so a locally-hosted model in LM Studio's chat can read, search, and write your knowledge base through OK's tools — fully local inference, nothing leaves your machine.
+
+LM Studio is an MCP host that follows Cursor's `mcp.json` notation, so the entry is the same resilient stdio launcher every other editor gets. It's user-global only (no project-scoped config, like Claude Desktop). OpenKnowledge probes both the documented `~/.lmstudio/mcp.json` and the location LM Studio actually uses on macOS (`~/.cache/lm-studio/mcp.json`, per lmstudio-ai/lmstudio-bug-tracker#1371) and writes wherever LM Studio already keeps its config.
diff --git a/docs/content/integrations/lm-studio.mdx b/docs/content/integrations/lm-studio.mdx
new file mode 100644
index 000000000..591fe5204
--- /dev/null
+++ b/docs/content/integrations/lm-studio.mdx
@@ -0,0 +1,45 @@
+---
+title: LM Studio
+description: Use OpenKnowledge with local models in LM Studio over MCP.
+icon: LuCpu
+---
+
+[LM Studio](https://lmstudio.ai) is a desktop app for running open models locally. It's an [MCP](https://modelcontextprotocol.io) **host** — its chat connects to MCP servers — so once OpenKnowledge is registered, a locally-hosted model can read, search, and write your knowledge base through OK's tools, with full attribution, link-awareness, conflict-awareness, and a live browser preview. Nothing leaves your machine: both the model and the knowledge base run locally.
+
+## Install
+
+<McpInstall editor="LM Studio" />
+
+After `ok init` writes the config, open LM Studio's **Program** tab and enable the `open-knowledge` server (LM Studio spawns a process per MCP server on save). The model you chat with must support tool use — see [Pick a tool-capable model](#pick-a-tool-capable-model).
+
+`ok init` writes the OpenKnowledge server into LM Studio's `mcp.json`, using the same resilient launcher every other editor gets — it finds `ok` whether you installed the desktop app or the npm CLI, so there's no PATH to configure. LM Studio follows Cursor's `mcp.json` notation, so the entry lands under a top-level `mcpServers` map.
+
+<Callout type="info">
+ **The config is user-global — one registration serves every project.** LM Studio has no
+ project-local MCP config, so OpenKnowledge registers once and each OK tool call takes a `cwd`
+ argument to target a specific knowledge base (pass it once and it sticks for that session).
+</Callout>
+
+## Pick a tool-capable model
+
+MCP tools only work when the chat model can call functions, and small local models vary a lot in how reliably they do. For the best results, load a model with strong tool-use / function-calling support and enough context to hold OK's tool descriptions. If the model answers in prose instead of calling `exec` / `search` / `write`, it either doesn't support tools or the server isn't enabled — check both before assuming OpenKnowledge is misconfigured.
+
+## Verify
+
+Load a tool-capable model, open a knowledge base, and ask:
+
+<VerifyExec subject="LM Studio" />
+
+If the model doesn't call the tool, confirm the `open-knowledge` server is toggled on in the **Program** tab and that the loaded model supports tool use.
+
+## Troubleshooting
+
+| Symptom | Cause | Fix |
+| --- | --- | --- |
+| `ok init` showed LM Studio as `config root missing; skipped` | LM Studio's config dir doesn't exist yet, so it wasn't detected | Launch LM Studio once (it creates its config dir), then re-run `ok init` |
+| `ok init` reported the config was `left unchanged` | OpenKnowledge declined to edit `mcp.json` for the reason shown in parentheses | Fix what the reason names (invalid JSON, a duplicated server block, an oversize config), then re-run `ok init` |
+| Model answers in prose, never calls a tool | the loaded model doesn't support tool use, or the server is disabled | Load a tool-capable model and enable `open-knowledge` in the **Program** tab |
+| MCP call fails with `... exceeds the available context size ...` (400) | OpenKnowledge's MCP tools + skill are larger than a small local model's context window (e.g. 8K tokens), so the request can't fit | Load the model with the largest context window it supports (or pick a bigger model). If that still isn't enough, [open an issue](https://github.com/inkeep/open-knowledge/issues) or reach out — trimming the tool surface for small local models is on our radar. |
+| `write` / `edit` -> "Hocuspocus server is not running" | OK server not started | Run `ok start` (or leave the desktop app running) and retry |
+
+New to OpenKnowledge itself? Start with the [quickstart](/docs/get-started/quickstart) for `ok init` and `ok start`.
diff --git a/docs/content/integrations/meta.json b/docs/content/integrations/meta.json
index 169216ec3..645170460 100644
--- a/docs/content/integrations/meta.json
+++ b/docs/content/integrations/meta.json
@@ -1,5 +1,14 @@
{
"title": "Integrations",
"icon": "LuPlug",
- "pages": ["claude-code", "cursor", "codex", "opencode", "pi", "openclaw", "antigravity"]
+ "pages": [
+ "claude-code",
+ "cursor",
+ "codex",
+ "opencode",
+ "pi",
+ "openclaw",
+ "antigravity",
+ "lm-studio"
+ ]
}
diff --git a/packages/cli/src/commands/editors.test.ts b/packages/cli/src/commands/editors.test.ts
index 4b6379663..dbee35dcd 100644
--- a/packages/cli/src/commands/editors.test.ts
+++ b/packages/cli/src/commands/editors.test.ts
@@ -1,4 +1,7 @@
import { afterEach, beforeEach, describe, expect, it } from 'bun:test';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
import {
buildManagedServerEntry,
CHAIN_V1,
@@ -16,6 +19,7 @@ import {
resolveCodexConfigPath,
resolveCursorConfigPath,
resolveEditorTargets,
+ resolveLmStudioConfigPath,
resolveOpenClawConfigPath,
resolveOpenCodeConfigPath,
resolvePiAgentDirPath,
@@ -232,6 +236,55 @@ describe('resolvePiAgentDirPath', () => {
});
});
+describe('resolveLmStudioConfigPath', () => {
+ it('defaults macOS to the observed cache path when no config exists yet', () => {
+ // The documented `~/.lmstudio/mcp.json` is a silent no-op on macOS (LM
+ // Studio reads `~/.cache/lm-studio/mcp.json`; bug-tracker#1371), so a fresh
+ // install resolves to the cache path we know it actually reads.
+ expect(resolveLmStudioConfigPath({ home: '/Users/alice', platformName: 'darwin' })).toBe(
+ '/Users/alice/.cache/lm-studio/mcp.json',
+ );
+ });
+
+ it('defaults Linux and Windows to the documented ~/.lmstudio path', () => {
+ expect(resolveLmStudioConfigPath({ home: '/home/alice', platformName: 'linux' })).toBe(
+ '/home/alice/.lmstudio/mcp.json',
+ );
+ expect(resolveLmStudioConfigPath({ home: 'C:\\Users\\alice', platformName: 'win32' })).toBe(
+ 'C:\\Users\\alice\\.lmstudio\\mcp.json',
+ );
+ });
+
+ it('prefers an existing candidate dir over the platform default', () => {
+ const home = mkdtempSync(join(tmpdir(), 'lmstudio-home-'));
+ try {
+ // Only the documented dir exists; macOS would otherwise default to cache.
+ mkdirSync(join(home, '.lmstudio'), { recursive: true });
+ expect(resolveLmStudioConfigPath({ home, platformName: 'darwin' })).toBe(
+ join(home, '.lmstudio', 'mcp.json'),
+ );
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+
+ it('prefers an existing mcp.json over any candidate dir', () => {
+ const home = mkdtempSync(join(tmpdir(), 'lmstudio-home-'));
+ try {
+ // Cache dir exists (macOS default location) but holds no file; the real
+ // mcp.json lives in the documented dir and must win.
+ mkdirSync(join(home, '.cache', 'lm-studio'), { recursive: true });
+ mkdirSync(join(home, '.lmstudio'), { recursive: true });
+ writeFileSync(join(home, '.lmstudio', 'mcp.json'), '{}');
+ expect(resolveLmStudioConfigPath({ home, platformName: 'darwin' })).toBe(
+ join(home, '.lmstudio', 'mcp.json'),
+ );
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+});
+
describe('EDITOR_TARGETS.pi', () => {
const t = EDITOR_TARGETS.pi;
diff --git a/packages/cli/src/commands/editors.ts b/packages/cli/src/commands/editors.ts
index 0423afcf1..ba8fa6b4c 100644
--- a/packages/cli/src/commands/editors.ts
+++ b/packages/cli/src/commands/editors.ts
@@ -5,6 +5,7 @@
* configuration. This module encodes those differences declaratively so that
* `init.ts` can loop over targets without per-editor branching.
*/
+import { existsSync } from 'node:fs';
import { homedir } from 'node:os';
import { basename, dirname, join, posix, resolve, sep, win32 } from 'node:path';
import {
@@ -639,6 +640,41 @@ export function resolveAntigravityConfigPath(options: AppSupportOptions = {}): s
return pathApiForPlatform(platformName).join(home, '.gemini', 'config', 'mcp_config.json');
}
+/**
+ * Candidate `mcp.json` locations for LM Studio, ordered so the first element is
+ * the platform default when none exist yet. LM Studio's own docs say
+ * `~/.lmstudio/mcp.json`, but on macOS the file actually lives at
+ * `~/.cache/lm-studio/mcp.json` — a documented-vs-real mismatch that is still
+ * open upstream (lmstudio-ai/lmstudio-bug-tracker#1371, seen through v0.3.33).
+ * So we probe both rather than trust either, and default macOS to the observed
+ * cache path (writing the documented path there would be a silent no-op LM
+ * Studio never reads).
+ */
+function lmStudioConfigCandidates(home: string, platformName: NodeJS.Platform): string[] {
+ const pathApi = pathApiForPlatform(platformName);
+ const dotDir = pathApi.join(home, '.lmstudio', 'mcp.json');
+ const cacheDir = pathApi.join(home, '.cache', 'lm-studio', 'mcp.json');
+ return platformName === 'darwin' ? [cacheDir, dotDir] : [dotDir, cacheDir];
+}
+
+/**
+ * Resolve LM Studio's user-global `mcp.json`. LM Studio is an MCP *host* that
+ * follows Cursor's `mcp.json` notation, so OK's entry shape is identical to
+ * Cursor's — only the (unstable, see {@link lmStudioConfigCandidates}) location
+ * differs. Prefers an existing `mcp.json`, then an existing candidate dir, then
+ * the platform default, so we write where LM Studio will actually read.
+ */
+export function resolveLmStudioConfigPath(options: AppSupportOptions = {}): string {
+ const platformName = options.platformName ?? process.platform;
+ const home = options.home ?? homedir();
+ const candidates = lmStudioConfigCandidates(home, platformName);
+ const existingFile = candidates.find((candidate) => existsSync(candidate));
+ if (existingFile) return existingFile;
+ const existingDir = candidates.find((candidate) => existsSync(dirname(candidate)));
+ if (existingDir) return existingDir;
+ return candidates[0];
+}
+
export interface EditorMcpTarget {
id: EditorId;
/** Human-friendly name for CLI output. */
@@ -850,6 +886,26 @@ export const EDITOR_TARGETS: Record<EditorId, EditorMcpTarget> = {
// skipAvailabilityCheck, exactly like OpenClaw.
offerOnlyWhenDetected: true,
},
+ 'lm-studio': {
+ id: 'lm-studio',
+ label: EDITOR_LABELS['lm-studio'],
+ configPath: (_cwd, home) => resolveLmStudioConfigPath({ home }),
+ format: 'json',
+ // LM Studio follows Cursor's `mcp.json` notation (a top-level `mcpServers`
+ // map of stdio `{command,args}` entries), so a resolved OK server is
+ // byte-identical to Cursor's — same resilient launcher, only the config
+ // location differs. Global-only: LM Studio has no project-local MCP config,
+ // like Claude Desktop, so no project skill/config paths.
+ topLevelKey: 'mcpServers',
+ serverName: () => MCP_SERVER_NAME,
+ buildEntry: (_cwd, options) => buildManagedServerEntry(options),
+ scope: 'global',
+ detectPath: (_cwd, home) => dirname(resolveLmStudioConfigPath({ home })),
+ // Never write LM Studio's `mcp.json` unless it's actually installed —
+ // gated on detection even under the consent flow's skipAvailabilityCheck,
+ // like OpenClaw. Writing a config for an absent app is a pointless no-op.
+ offerOnlyWhenDetected: true,
+ },
};
/**
diff --git a/packages/cli/src/commands/init.test.ts b/packages/cli/src/commands/init.test.ts
index 03a96b9a9..2def10918 100644
--- a/packages/cli/src/commands/init.test.ts
+++ b/packages/cli/src/commands/init.test.ts
@@ -26,6 +26,7 @@ import {
resolveClaudeDesktopConfigPath,
resolveCodexConfigPath,
resolveCursorConfigPath,
+ resolveLmStudioConfigPath,
resolveOpenCodeConfigPath,
} from './editors.ts';
@@ -158,6 +159,7 @@ describe('runInit', () => {
const cursorConfigPath = () => resolveCursorConfigPath({ home: fakeHome });
const codexConfigPath = () => resolveCodexConfigPath({ home: fakeHome, env: {} });
const opencodeConfigPath = () => resolveOpenCodeConfigPath({ home: fakeHome, env: {} });
+ const lmStudioConfigPath = () => resolveLmStudioConfigPath({ home: fakeHome });
const devRepoRoot = () => join(testDir, 'local-open-knowledge');
// `--dev-mcp` resolves the worktree's `dist/cli.mjs` from `process.argv[1]`.
// Tests stub argv[1] via `enableDevMcp()` so resolution lands at a
@@ -805,6 +807,8 @@ describe('runInit', () => {
// Antigravity is `offerOnlyWhenDetected`, so its user-global write is
// gated on the `~/.gemini` home existing even under the consent flow.
mkdirSync(join(fakeHome, '.gemini'), { recursive: true });
+ // LM Studio is likewise `offerOnlyWhenDetected` — create its config dir.
+ mkdirSync(dirname(lmStudioConfigPath()), { recursive: true });
const result = await runInitForTest({ editors: [...ALL_EDITOR_IDS] });
@@ -822,6 +826,7 @@ describe('runInit', () => {
expect(existsSync(cursorConfigPath())).toBe(true);
expect(existsSync(codexConfigPath())).toBe(true);
expect(existsSync(opencodeConfigPath())).toBe(true);
+ expect(existsSync(lmStudioConfigPath())).toBe(true);
// OpenClaw nests under `mcp.servers` — verify the entry landed there.
const openclawConfig = JSON.parse(
readFileSync(join(fakeHome, '.openclaw', 'openclaw.json'), 'utf-8'),
@@ -2334,6 +2339,7 @@ describe('detectInstalledEditors', () => {
const cursorConfigPath = () => resolveCursorConfigPath({ home: fakeHome });
const codexConfigPath = () => resolveCodexConfigPath({ home: fakeHome, env: {} });
const opencodeConfigPath = () => resolveOpenCodeConfigPath({ home: fakeHome, env: {} });
+ const lmStudioConfigPath = () => resolveLmStudioConfigPath({ home: fakeHome });
beforeEach(() => {
testDir = resolve(
@@ -2427,6 +2433,7 @@ describe('detectInstalledEditors', () => {
mkdirSync(join(fakeHome, '.openclaw'), { recursive: true });
mkdirSync(join(fakeHome, '.pi', 'agent'), { recursive: true });
mkdirSync(join(fakeHome, '.gemini'), { recursive: true });
+ mkdirSync(dirname(lmStudioConfigPath()), { recursive: true });
const detected = detectInstalledEditors(testDir, fakeHome);
expect(detected).toEqual(expect.arrayContaining([...ALL_EDITOR_IDS]));
expect(detected).toHaveLength(ALL_EDITOR_IDS.length);
diff --git a/packages/core/src/constants/editors.ts b/packages/core/src/constants/editors.ts
index 551f39952..765376518 100644
--- a/packages/core/src/constants/editors.ts
+++ b/packages/core/src/constants/editors.ts
@@ -14,7 +14,8 @@ export type EditorId =
| 'opencode'
| 'openclaw'
| 'pi'
- | 'antigravity';
+ | 'antigravity'
+ | 'lm-studio';
export const ALL_EDITOR_IDS = [
'claude',
@@ -25,6 +26,7 @@ export const ALL_EDITOR_IDS = [
'openclaw',
'pi',
'antigravity',
+ 'lm-studio',
] as const satisfies readonly EditorId[];
/**
@@ -42,6 +44,7 @@ export const EDITOR_LABELS = {
openclaw: 'OpenClaw',
pi: 'Pi',
antigravity: 'Antigravity',
+ 'lm-studio': 'LM Studio',
} as const satisfies Record<EditorId, string>;
/**
@@ -103,6 +106,9 @@ export const EDITOR_PROJECT_SKILL_ROOT = {
// Like OpenClaw, its integration is the user-global MCP config; OK ships no
// per-project skill for it.
antigravity: null,
+ // LM Studio is an MCP host (its chat connects to MCP servers) with no Agent
+ // Skills surface at all — OK's only integration is the user-global MCP config.
+ 'lm-studio': null,
} as const satisfies Record<EditorId, string | null>;
/** Editor ids that have a project skill surface (valid install-projection targets). */
@@ -151,6 +157,7 @@ export const EDITOR_SETUP_DOC_SLUG = {
openclaw: 'openclaw',
pi: 'pi',
antigravity: 'antigravity',
+ 'lm-studio': 'lm-studio',
} as const satisfies Record<EditorId, string>;
/**
@@ -183,4 +190,8 @@ export const EDITOR_PROJECT_CONFIG_PATH = {
// is never detected as "project-configured"; like Claude Desktop / OpenClaw,
// OK writes only the user-global config.
antigravity: null,
+ // LM Studio's MCP config is a single user-global `mcp.json` (it follows
+ // Cursor's notation but has no project-local variant), so it is never
+ // detected as "project-configured".
+ 'lm-studio': null,
} as const satisfies Record<EditorId, string | null>;
diff --git a/packages/desktop/tests/integration/m1-smoke.test.ts b/packages/desktop/tests/integration/m1-smoke.test.ts
index ab0d5a8a3..55496a71b 100644
--- a/packages/desktop/tests/integration/m1-smoke.test.ts
+++ b/packages/desktop/tests/integration/m1-smoke.test.ts
@@ -400,7 +400,7 @@ describe('M1 smoke', () => {
typeName: 'EditorId',
canonicalPath: editorsConstantPath,
canonicalRe: /type\s+EditorId\s*=([^;]+);/,
- expectedLiteralCount: 8,
+ expectedLiteralCount: 9,
inlineRe:
/'claude'\s*\|\s*'claude-desktop'\s*\|\s*'cursor'\s*\|\s*'codex'\s*\|\s*'opencode'\s*\|\s*'openclaw'/,
mirrors: [
diff --git a/packages/server/src/mcp/tools/tool-schema-ref-free.test.ts b/packages/server/src/mcp/tools/tool-schema-ref-free.test.ts
new file mode 100644
index 000000000..0f937d2ad
--- /dev/null
+++ b/packages/server/src/mcp/tools/tool-schema-ref-free.test.ts
@@ -0,0 +1,89 @@
+/**
+ * Portability guard: no MCP tool schema may advertise an intra-schema `$ref`.
+ *
+ * `zod-to-json-schema` (and Zod v4's native emitter) hoist a reused/recursive
+ * schema into a top-level `definitions`/`$defs` block and reference it with
+ * `"$ref": "#/definitions/__schemaN"`. Lenient clients (Claude) resolve that;
+ * constrained-decoding hosts (LM Studio) and some function-calling APIs (Gemini)
+ * do NOT — they reject the whole tool with a schema-conversion error. The
+ * regression that motivated this: `write`/`edit` advertised a recursive
+ * `frontmatter` value → `$ref: "#/definitions/__schema0"` → LM Studio 400.
+ *
+ * This sweep compiles EVERY registered tool's input AND output schema through
+ * the SDK's exact `tools/list` pipeline and fails if any emits a `$ref` or a
+ * `definitions`/`$defs` block — so a future recursive/reused schema can't
+ * silently re-break local-inference and function-calling clients.
+ */
+
+import { describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+// Internal SDK compat modules — the exact conversion `mcp.js` runs on
+// `tools/list`. Reachable only via the SDK's wildcard `./*` export; the SDK is
+// pinned to an exact version so a minor bump can't silently rename them.
+import { normalizeObjectSchema } from '@modelcontextprotocol/sdk/server/zod-compat.js';
+import { toJsonSchemaCompat } from '@modelcontextprotocol/sdk/server/zod-json-schema-compat.js';
+import { type Config, ConfigSchema } from '../../config/schema.ts';
+import { registerAllTools } from './index.ts';
+import type { ServerInstance } from './shared.ts';
+
+const BASE_CONFIG: Config = ConfigSchema.parse({});
+
+interface Registration {
+ name: string;
+ inputSchema?: unknown;
+ outputSchema?: unknown;
+}
+
+function captureAllRegistrations(cwd: string): Registration[] {
+ const captured: Registration[] = [];
+ const server = {
+ registerTool(name: string, cfg: { inputSchema?: unknown; outputSchema?: unknown }) {
+ captured.push({ name, inputSchema: cfg.inputSchema, outputSchema: cfg.outputSchema });
+ },
+ // Legacy `server.tool()` API bypasses schema compilation; not relevant here.
+ tool() {},
+ } as unknown as ServerInstance;
+ registerAllTools(server, {
+ config: BASE_CONFIG,
+ resolveCwd: async () => cwd,
+ serverUrl: undefined,
+ });
+ return captured;
+}
+
+/** Every `$ref` pointer + whether a definitions/$defs block is present. */
+function refOffenders(rawShape: unknown, pipeStrategy: 'input' | 'output'): string[] {
+ const normalized = normalizeObjectSchema(rawShape);
+ if (!normalized) return [];
+ const json = toJsonSchemaCompat(normalized, { strictUnions: true, pipeStrategy }) as Record<
+ string,
+ unknown
+ >;
+ const serialized = JSON.stringify(json);
+ const refs = [...serialized.matchAll(/#\/(?:definitions|\$defs)\/[A-Za-z0-9_]+/g)].map(
+ (m) => m[0],
+ );
+ const offenders = [...new Set(refs)];
+ if ('definitions' in json) offenders.push('<top-level definitions block>');
+ if ('$defs' in json) offenders.push('<top-level $defs block>');
+ return offenders;
+}
+
+describe('MCP tool schema portability — no intra-schema $ref (LM Studio / Gemini compat)', () => {
+ const cwd = mkdtempSync(join(tmpdir(), 'ok-reffree-'));
+ mkdirSync(join(cwd, '.ok'), { recursive: true });
+ const registrations = captureAllRegistrations(cwd);
+
+ test('registration sweep is non-empty (guards against a broken capture)', () => {
+ expect(registrations.length).toBeGreaterThan(10);
+ });
+
+ for (const { name, inputSchema, outputSchema } of registrations) {
+ test(`${name}: input + output schemas are $ref-free`, () => {
+ expect({ input: refOffenders(inputSchema, 'input') }).toEqual({ input: [] });
+ expect({ output: refOffenders(outputSchema, 'output') }).toEqual({ output: [] });
+ });
+ }
+});
diff --git a/packages/server/src/mcp/tools/verb-schemas.ts b/packages/server/src/mcp/tools/verb-schemas.ts
index 9160affba..2ee6c6e2b 100644
--- a/packages/server/src/mcp/tools/verb-schemas.ts
+++ b/packages/server/src/mcp/tools/verb-schemas.ts
@@ -18,6 +18,7 @@
*/
import {
+ type FrontmatterValue,
FrontmatterValueSchema,
MANAGED_ARTIFACT_SCOPES,
SKILL_NAME_REGEX,
@@ -38,11 +39,53 @@ import { SUPPORTED_DOC_EXTENSIONS } from '../../doc-extensions.ts';
* is rejected; to delete a single nested leaf, send the full subtree without
* that leaf, or null out the whole top-level key to drop the subtree.
*/
+/** The real per-value contract: a recursive frontmatter value, or top-level `null` (RFC 7396 delete). */
const FrontmatterPatchValue = z.union([FrontmatterValueSchema, z.null()]);
+/**
+ * Flat, ref-free ADVERTISED shape for the frontmatter value. Superset of what
+ * {@link FrontmatterPatchValue} admits at the top level (array/object leaves are
+ * open), so the `.superRefine` below narrows it to the exact recursive contract
+ * without the base union ever pre-rejecting a valid value.
+ *
+ * Why not just advertise the recursive schema: a self-referential Zod schema
+ * serializes to `$ref: "#/definitions/__schema0"` in the tool's JSON Schema.
+ * Constrained-decoding MCP hosts (LM Studio) and some function-calling APIs
+ * (Gemini) can't resolve a `$ref` inside a tool schema and reject the whole
+ * tool. This flat union carries no `$ref`, and refinements don't appear in JSON
+ * Schema — so the wire schema stays portable while runtime validation is
+ * unchanged for every client and every write path (write-with-inline-content
+ * and folder frontmatter have no downstream value gate, so this IS the gate).
+ */
+// The runtime union is the real schema the SDK serializes (flat, ref-free) and
+// the `.superRefine` validates against the recursive contract — so pinning the
+// INFERRED output type to the recursive `FrontmatterValue | null` is sound and
+// keeps every consuming handler typed against the canonical frontmatter value.
+const FrontmatterAdvertisedValue = z.union([
+ z.string(),
+ z.number(),
+ z.boolean(),
+ z.array(z.unknown()),
+ z.record(z.string(), z.unknown()),
+ z.null(),
+]) as unknown as z.ZodType<FrontmatterValue | null>;
+
/** A frontmatter merge-patch map with an instructive description + example. */
export const FrontmatterArg = z
- .record(z.string(), FrontmatterPatchValue)
+ .record(z.string(), FrontmatterAdvertisedValue)
+ .superRefine((patch, ctx) => {
+ for (const [key, value] of Object.entries(patch)) {
+ if (!FrontmatterPatchValue.safeParse(value).success) {
+ ctx.addIssue({
+ code: 'custom',
+ path: [key],
+ message:
+ 'invalid frontmatter value — allowed: a scalar (string | number | boolean), a scalar array, ' +
+ 'a nested object, or an array of objects; a top-level key may be null to delete it, but nested null is not allowed',
+ });
+ }
+ }
+ })
.describe(
'Metadata as a key→value map. Values may be a scalar (string | number | boolean), a scalar array, ' +
'a nested object, or an array of objects. Merge-patch: include a top-level key to set it, set a ' +