Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

fix(ok): declare MCP tool schemas as JSON Schema 2020-12 (PRD-8060) (#3584)

tim-inkeep9184b4d3f3eb
diff --git a/.changeset/mcp-schema-dialect-2020-12.md b/.changeset/mcp-schema-dialect-2020-12.md
new file mode 100644
index 000000000..716b53718
--- /dev/null
+++ b/.changeset/mcp-schema-dialect-2020-12.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+MCP tools now declare their schemas as JSON Schema 2020-12, so clients that validate structured output no longer reject the entire tool surface. The MCP SDK converts our tool schemas without specifying a target dialect, which lands on draft-07, and a client validating against the declared dialect refuses to compile the schema and drops the tool before it can run. Because every OpenKnowledge tool declares an output schema, one strict client turned that into a total MCP outage: no reads, writes, or searches succeeded. Only the declared label was wrong, never the schemas themselves, so this is a relabel with no change to what any tool accepts or returns.
diff --git a/packages/cli/src/mcp/server.ts b/packages/cli/src/mcp/server.ts
index 71076993d..a7091ba67 100644
--- a/packages/cli/src/mcp/server.ts
+++ b/packages/cli/src/mcp/server.ts
@@ -37,6 +37,7 @@ import {
type AgentIdentity,
type Config,
getLocalDir,
+ installJsonSchemaDialect,
installPrettyZodErrors,
isProjectRoot,
MCP_SERVER_NAME,
@@ -442,6 +443,10 @@ export async function startGlobalMcpServer(
isHostedAgent: resolveIsHostedAgent(process.env),
});
+ // After `registerAllTools`, not before: the SDK installs its `tools/list`
+ // handler lazily on the first `registerTool`.
+ installJsonSchemaDialect(server);
+
const transport = new StdioServerTransport();
let closed = false;
let bundleWatcher: BundleIdentityWatcherHandle | undefined;
diff --git a/packages/server/src/console-discipline.test.ts b/packages/server/src/console-discipline.test.ts
index 8e07deacc..15d273be4 100644
--- a/packages/server/src/console-discipline.test.ts
+++ b/packages/server/src/console-discipline.test.ts
@@ -53,6 +53,10 @@ const FILE_ALLOWLIST: ReadonlyMap<string, string> = new Map([
'mcp/logger.ts',
'MCP stdio logger self-failure path — stdout is the JSON-RPC channel, so this surface writes to stderr/OK_LOG_FILE by design',
],
+ [
+ 'mcp/json-schema-dialect.ts',
+ 'runs inside the MCP server surface where stdout is the JSON-RPC channel; console.warn targets stderr',
+ ],
[
'mcp/pretty-zod-errors.ts',
'runs inside the MCP server surface where stdout is the JSON-RPC channel; console.warn targets stderr',
diff --git a/packages/server/src/index.ts b/packages/server/src/index.ts
index 4d71f800e..963dfeee2 100644
--- a/packages/server/src/index.ts
+++ b/packages/server/src/index.ts
@@ -327,6 +327,10 @@ export {
MCP_CONNECTION_ID_HEADER,
sanitizeClientName,
} from './mcp/agent-identity.ts';
+export {
+ installJsonSchemaDialect,
+ JSON_SCHEMA_DIALECT_2020_12,
+} from './mcp/json-schema-dialect.ts';
export { getCurrentMcpLogger, McpLogger, runWithMcpLogger } from './mcp/logger.ts';
export { installPrettyZodErrors } from './mcp/pretty-zod-errors.ts';
export { buildExecResult, type ExecStructuredResult } from './mcp/tools/exec.ts';
diff --git a/packages/server/src/mcp-http.ts b/packages/server/src/mcp-http.ts
index 646d05f3e..312440a9e 100644
--- a/packages/server/src/mcp-http.ts
+++ b/packages/server/src/mcp-http.ts
@@ -13,6 +13,7 @@ import {
MCP_HOSTED_AGENT_HEADER,
sanitizeClientName,
} from './mcp/agent-identity.ts';
+import { installJsonSchemaDialect } from './mcp/json-schema-dialect.ts';
import { installPrettyZodErrors } from './mcp/pretty-zod-errors.ts';
import { registerAllTools } from './mcp/tools/index.ts';
import { resolveWithinRoot } from './mcp/tools/path-safety.ts';
@@ -145,6 +146,10 @@ function createSessionServer(
isHostedAgent,
});
+ // After `registerAllTools`, not before: the SDK installs its `tools/list`
+ // handler lazily on the first `registerTool`.
+ installJsonSchemaDialect(server);
+
return { server, transport };
}
diff --git a/packages/server/src/mcp/json-schema-dialect.test.ts b/packages/server/src/mcp/json-schema-dialect.test.ts
new file mode 100644
index 000000000..65b8020ca
--- /dev/null
+++ b/packages/server/src/mcp/json-schema-dialect.test.ts
@@ -0,0 +1,122 @@
+/**
+ * Every MCP tool must advertise its `inputSchema` / `outputSchema` as JSON
+ * Schema 2020-12.
+ *
+ * The SDK converts our Zod v4 schemas with no target, which lands on
+ * draft-07. Clients that validate structured output against the declared
+ * dialect then reject the tool before it ever runs, taking down the whole
+ * tool surface rather than degrading one tool. An Ajv 2020 instance refuses
+ * every draft-07-declaring schema with `no schema with key or ref
+ * "http://json-schema.org/draft-07/schema#"`.
+ *
+ * Black-box: assertions read the `tools/list` result off a real client
+ * connected over an in-memory transport, so they observe exactly the wire
+ * bytes a Claude Code or Claude Desktop client would parse.
+ */
+
+import { Client } from '@modelcontextprotocol/sdk/client/index.js';
+import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
+import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
+import { describe, expect, test, vi } from 'vitest';
+import { z } from 'zod';
+import { installJsonSchemaDialect, JSON_SCHEMA_DIALECT_2020_12 } from './json-schema-dialect.ts';
+
+const DRAFT_07 = 'http://json-schema.org/draft-07/schema#';
+
+function buildServer(): McpServer {
+ const server = new McpServer({ name: 'json-schema-dialect-test', version: '0.0.0' });
+ server.registerTool(
+ 'exec_like',
+ {
+ description: 'Mirrors the shape every OK tool registers: both schemas present.',
+ inputSchema: { command: z.string(), cwd: z.string().optional() },
+ outputSchema: { text: z.string(), exitCode: z.number() },
+ },
+ async () => ({
+ content: [{ type: 'text' as const, text: 'ok' }],
+ structuredContent: { text: 'ok', exitCode: 0 },
+ }),
+ );
+ return server;
+}
+
+async function listToolsOverWire(server: McpServer) {
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
+ const client = new Client({ name: 'test-client', version: '0.0.0' });
+ await Promise.all([server.connect(serverTransport), client.connect(clientTransport)]);
+ const result = await client.listTools();
+ await client.close();
+ return result;
+}
+
+describe('installJsonSchemaDialect', () => {
+ test('the SDK default is draft-07, which is the bug this guards', async () => {
+ const { tools } = await listToolsOverWire(buildServer());
+ expect(tools).toHaveLength(1);
+ expect(tools[0]?.inputSchema?.$schema).toBe(DRAFT_07);
+ expect(tools[0]?.outputSchema?.$schema).toBe(DRAFT_07);
+ });
+
+ test('re-declares both schema channels as 2020-12', async () => {
+ const server = buildServer();
+ installJsonSchemaDialect(server);
+
+ const { tools } = await listToolsOverWire(server);
+ expect(tools[0]?.inputSchema?.$schema).toBe(JSON_SCHEMA_DIALECT_2020_12);
+ expect(tools[0]?.outputSchema?.$schema).toBe(JSON_SCHEMA_DIALECT_2020_12);
+ });
+
+ test('leaves the rest of the schema untouched', async () => {
+ const before = (await listToolsOverWire(buildServer())).tools[0];
+ const server = buildServer();
+ installJsonSchemaDialect(server);
+ const after = (await listToolsOverWire(server)).tools[0];
+
+ const strip = (s: unknown) => {
+ const { $schema: _drop, ...rest } = (s ?? {}) as Record<string, unknown>;
+ return rest;
+ };
+ expect(strip(after?.inputSchema)).toEqual(strip(before?.inputSchema));
+ expect(strip(after?.outputSchema)).toEqual(strip(before?.outputSchema));
+ });
+
+ test('is idempotent', async () => {
+ const server = buildServer();
+ installJsonSchemaDialect(server);
+ installJsonSchemaDialect(server);
+
+ const { tools } = await listToolsOverWire(server);
+ expect(tools[0]?.outputSchema?.$schema).toBe(JSON_SCHEMA_DIALECT_2020_12);
+ });
+
+ test('warns instead of throwing when installed before any tool is registered', async () => {
+ // The ordering contract: the SDK installs its `tools/list` handler lazily
+ // on the first `registerTool`, so an install hoisted above tool
+ // registration silently does nothing. Fail loud rather than ship draft-07.
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const server = new McpServer({ name: 'json-schema-dialect-test', version: '0.0.0' });
+
+ expect(() => installJsonSchemaDialect(server)).not.toThrow();
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('[json-schema-dialect]'));
+ warn.mockRestore();
+ });
+
+ test('a tool registered after install still gets re-declared', async () => {
+ // The wrapper defers to the SDK handler, which reads the live tool
+ // registry per request, so late registrations flow through it.
+ const server = buildServer();
+ installJsonSchemaDialect(server);
+ server.registerTool(
+ 'late_tool',
+ { description: 'registered after install', outputSchema: { text: z.string() } },
+ async () => ({
+ content: [{ type: 'text' as const, text: 'ok' }],
+ structuredContent: { text: 'ok' },
+ }),
+ );
+
+ const { tools } = await listToolsOverWire(server);
+ const late = tools.find((t) => t.name === 'late_tool');
+ expect(late?.outputSchema?.$schema).toBe(JSON_SCHEMA_DIALECT_2020_12);
+ });
+});
diff --git a/packages/server/src/mcp/json-schema-dialect.ts b/packages/server/src/mcp/json-schema-dialect.ts
new file mode 100644
index 000000000..96f517d46
--- /dev/null
+++ b/packages/server/src/mcp/json-schema-dialect.ts
@@ -0,0 +1,87 @@
+/**
+ * Re-declare tool schemas as JSON Schema 2020-12 in `tools/list` responses.
+ *
+ * The MCP SDK converts our Zod v4 tool schemas with no `target`, so its
+ * internal `mapMiniTarget(undefined)` falls through to `'draft-7'` and every
+ * `inputSchema` / `outputSchema` ships stamped
+ * `"$schema": "http://json-schema.org/draft-07/schema#"`. Clients that
+ * validate structured output against the declared dialect reject the tool
+ * outright: an Ajv 2020 instance fails to compile every one of our schemas
+ * with `no schema with key or ref "http://json-schema.org/draft-07/schema#"`,
+ * so the whole tool surface disappears rather than one tool degrading.
+ *
+ * Only the label is wrong. Our schemas use no construct where the two
+ * dialects diverge (no tuple-form `items`, no `$defs` / `definitions`, no
+ * `$ref`, and `exclusiveMinimum` / `exclusiveMaximum` are the numeric form
+ * both dialects share), so re-stamping is a relabel, not a conversion.
+ *
+ * The SDK exposes no way to pass a conversion target: neither `registerTool`
+ * nor the server options accept one, and its `tools/list` handler hardcodes
+ * the call. Upstream tracking: modelcontextprotocol/typescript-sdk#745.
+ *
+ * Best-effort, like the sibling `installPrettyZodErrors`: if the SDK's
+ * internals move, warn and leave default behavior in place rather than
+ * breaking the server.
+ */
+import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
+import { ListToolsRequestSchema, type ServerResult } from '@modelcontextprotocol/sdk/types.js';
+
+export const JSON_SCHEMA_DIALECT_2020_12 = 'https://json-schema.org/draft/2020-12/schema';
+
+const LIST_TOOLS_METHOD = 'tools/list';
+
+type RequestHandler = (request: unknown, extra: unknown) => ServerResult | Promise<ServerResult>;
+
+/**
+ * The narrow view we mutate. Deliberately NOT the handler's return type:
+ * `ServerResult` is a union (it also covers task-shaped results), and
+ * narrowing the return to a tools-only shape makes it unassignable.
+ */
+interface ListToolsShape {
+ tools?: Array<{
+ inputSchema?: { $schema?: string };
+ outputSchema?: { $schema?: string };
+ }>;
+}
+
+/**
+ * Install the dialect re-stamp on the given MCP server. Idempotent.
+ *
+ * MUST be called AFTER the server's tools are registered: the SDK installs
+ * its `tools/list` handler lazily on the first `registerTool`, so calling
+ * this at construction time finds nothing to wrap.
+ */
+export function installJsonSchemaDialect(server: McpServer): void {
+ const target = server as unknown as { __jsonSchemaDialectInstalled?: true };
+ if (target.__jsonSchemaDialectInstalled === true) {
+ return;
+ }
+
+ const inner = server.server as unknown as {
+ _requestHandlers?: Map<string, RequestHandler>;
+ };
+ const original = inner._requestHandlers?.get(LIST_TOOLS_METHOD);
+ if (typeof original !== 'function') {
+ // Bracket-prefix matches the OK ops-warning convention. Without this the
+ // regression looks identical to "we never installed it", and the symptom
+ // (clients silently dropping the entire tool surface) points nowhere near
+ // this file.
+ console.warn(
+ `[json-schema-dialect] No ${LIST_TOOLS_METHOD} handler found. Either the SDK internals changed, or this ran before tools were registered. Tool schemas will keep the SDK's draft-07 dialect.`,
+ );
+ return;
+ }
+
+ server.server.setRequestHandler(ListToolsRequestSchema, async (request, extra) => {
+ // The SDK rebuilds these schema objects on every `tools/list` call, so
+ // mutating in place cannot leak across requests.
+ const result = await original(request, extra);
+ for (const tool of (result as ListToolsShape).tools ?? []) {
+ if (tool.inputSchema) tool.inputSchema.$schema = JSON_SCHEMA_DIALECT_2020_12;
+ if (tool.outputSchema) tool.outputSchema.$schema = JSON_SCHEMA_DIALECT_2020_12;
+ }
+ return result;
+ });
+
+ target.__jsonSchemaDialectInstalled = true;
+}