Skip to content

Commit 48a2889

Browse files
tim-inkeepinkeep-oss-sync[bot]
authored andcommitted
fix(ok): declare MCP tool schemas as JSON Schema 2020-12 (PRD-8060) (#3584)
The MCP SDK converts our Zod v4 tool schemas without passing a target dialect, so its internal mapMiniTarget falls through to draft-7 and every inputSchema and outputSchema ships stamped with the draft-07 $schema URI. Clients that validate structured output against the declared dialect reject the tool before it runs. A real Ajv 2020 instance fails to compile all 21 of our schemas with `no schema with key or ref "http://json-schema.org/draft-07/schema#"`, and because every OK tool declares an output schema, one strict client loses the entire tool surface rather than degrading a single tool. Only the declared label was wrong. Our schemas contain no construct where the two dialects diverge (no tuple-form items, no $defs or definitions, no $ref, and exclusiveMinimum/exclusiveMaximum are the numeric form both dialects share), so this re-stamps rather than converts. 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. Rather than patch the dependency, wrap the tools/list handler on the server instance, mirroring the existing installPrettyZodErrors: best effort, idempotent, and warning instead of throwing if SDK internals move. The installer must run after registerAllTools because the SDK registers its tools/list handler lazily on the first registerTool. A test pins that ordering contract so an install hoisted to construction time fails loudly rather than silently shipping draft-07. Upstream tracking: modelcontextprotocol/typescript-sdk#745 GitOrigin-RevId: f07db8bf88a00cb4d517439c86e426af831af3ed
1 parent 3e2d03e commit 48a2889

7 files changed

Lines changed: 232 additions & 0 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@inkeep/open-knowledge": patch
3+
---
4+
5+
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.

‎packages/cli/src/mcp/server.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ import {
3737
type AgentIdentity,
3838
type Config,
3939
getLocalDir,
40+
installJsonSchemaDialect,
4041
installPrettyZodErrors,
4142
isProjectRoot,
4243
MCP_SERVER_NAME,
@@ -442,6 +443,10 @@ export async function startGlobalMcpServer(
442443
isHostedAgent: resolveIsHostedAgent(process.env),
443444
});
444445

446+
// After `registerAllTools`, not before: the SDK installs its `tools/list`
447+
// handler lazily on the first `registerTool`.
448+
installJsonSchemaDialect(server);
449+
445450
const transport = new StdioServerTransport();
446451
let closed = false;
447452
let bundleWatcher: BundleIdentityWatcherHandle | undefined;

‎packages/server/src/console-discipline.test.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,10 @@ const FILE_ALLOWLIST: ReadonlyMap<string, string> = new Map([
5353
'mcp/logger.ts',
5454
'MCP stdio logger self-failure path — stdout is the JSON-RPC channel, so this surface writes to stderr/OK_LOG_FILE by design',
5555
],
56+
[
57+
'mcp/json-schema-dialect.ts',
58+
'runs inside the MCP server surface where stdout is the JSON-RPC channel; console.warn targets stderr',
59+
],
5660
[
5761
'mcp/pretty-zod-errors.ts',
5862
'runs inside the MCP server surface where stdout is the JSON-RPC channel; console.warn targets stderr',

‎packages/server/src/index.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -327,6 +327,10 @@ export {
327327
MCP_CONNECTION_ID_HEADER,
328328
sanitizeClientName,
329329
} from './mcp/agent-identity.ts';
330+
export {
331+
installJsonSchemaDialect,
332+
JSON_SCHEMA_DIALECT_2020_12,
333+
} from './mcp/json-schema-dialect.ts';
330334
export { getCurrentMcpLogger, McpLogger, runWithMcpLogger } from './mcp/logger.ts';
331335
export { installPrettyZodErrors } from './mcp/pretty-zod-errors.ts';
332336
export { buildExecResult, type ExecStructuredResult } from './mcp/tools/exec.ts';

‎packages/server/src/mcp-http.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import {
1313
MCP_HOSTED_AGENT_HEADER,
1414
sanitizeClientName,
1515
} from './mcp/agent-identity.ts';
16+
import { installJsonSchemaDialect } from './mcp/json-schema-dialect.ts';
1617
import { installPrettyZodErrors } from './mcp/pretty-zod-errors.ts';
1718
import { registerAllTools } from './mcp/tools/index.ts';
1819
import { resolveWithinRoot } from './mcp/tools/path-safety.ts';
@@ -145,6 +146,10 @@ function createSessionServer(
145146
isHostedAgent,
146147
});
147148

149+
// After `registerAllTools`, not before: the SDK installs its `tools/list`
150+
// handler lazily on the first `registerTool`.
151+
installJsonSchemaDialect(server);
152+
148153
return { server, transport };
149154
}
150155

Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
/**
2+
* Every MCP tool must advertise its `inputSchema` / `outputSchema` as JSON
3+
* Schema 2020-12.
4+
*
5+
* The SDK converts our Zod v4 schemas with no target, which lands on
6+
* draft-07. Clients that validate structured output against the declared
7+
* dialect then reject the tool before it ever runs, taking down the whole
8+
* tool surface rather than degrading one tool. An Ajv 2020 instance refuses
9+
* every draft-07-declaring schema with `no schema with key or ref
10+
* "http://json-schema.org/draft-07/schema#"`.
11+
*
12+
* Black-box: assertions read the `tools/list` result off a real client
13+
* connected over an in-memory transport, so they observe exactly the wire
14+
* bytes a Claude Code or Claude Desktop client would parse.
15+
*/
16+
17+
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
18+
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
19+
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
20+
import { describe, expect, test, vi } from 'vitest';
21+
import { z } from 'zod';
22+
import { installJsonSchemaDialect, JSON_SCHEMA_DIALECT_2020_12 } from './json-schema-dialect.ts';
23+
24+
const DRAFT_07 = 'http://json-schema.org/draft-07/schema#';
25+
26+
function buildServer(): McpServer {
27+
const server = new McpServer({ name: 'json-schema-dialect-test', version: '0.0.0' });
28+
server.registerTool(
29+
'exec_like',
30+
{
31+
description: 'Mirrors the shape every OK tool registers: both schemas present.',
32+
inputSchema: { command: z.string(), cwd: z.string().optional() },
33+
outputSchema: { text: z.string(), exitCode: z.number() },
34+
},
35+
async () => ({
36+
content: [{ type: 'text' as const, text: 'ok' }],
37+
structuredContent: { text: 'ok', exitCode: 0 },
38+
}),
39+
);
40+
return server;
41+
}
42+
43+
async function listToolsOverWire(server: McpServer) {
44+
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
45+
const client = new Client({ name: 'test-client', version: '0.0.0' });
46+
await Promise.all([server.connect(serverTransport), client.connect(clientTransport)]);
47+
const result = await client.listTools();
48+
await client.close();
49+
return result;
50+
}
51+
52+
describe('installJsonSchemaDialect', () => {
53+
test('the SDK default is draft-07, which is the bug this guards', async () => {
54+
const { tools } = await listToolsOverWire(buildServer());
55+
expect(tools).toHaveLength(1);
56+
expect(tools[0]?.inputSchema?.$schema).toBe(DRAFT_07);
57+
expect(tools[0]?.outputSchema?.$schema).toBe(DRAFT_07);
58+
});
59+
60+
test('re-declares both schema channels as 2020-12', async () => {
61+
const server = buildServer();
62+
installJsonSchemaDialect(server);
63+
64+
const { tools } = await listToolsOverWire(server);
65+
expect(tools[0]?.inputSchema?.$schema).toBe(JSON_SCHEMA_DIALECT_2020_12);
66+
expect(tools[0]?.outputSchema?.$schema).toBe(JSON_SCHEMA_DIALECT_2020_12);
67+
});
68+
69+
test('leaves the rest of the schema untouched', async () => {
70+
const before = (await listToolsOverWire(buildServer())).tools[0];
71+
const server = buildServer();
72+
installJsonSchemaDialect(server);
73+
const after = (await listToolsOverWire(server)).tools[0];
74+
75+
const strip = (s: unknown) => {
76+
const { $schema: _drop, ...rest } = (s ?? {}) as Record<string, unknown>;
77+
return rest;
78+
};
79+
expect(strip(after?.inputSchema)).toEqual(strip(before?.inputSchema));
80+
expect(strip(after?.outputSchema)).toEqual(strip(before?.outputSchema));
81+
});
82+
83+
test('is idempotent', async () => {
84+
const server = buildServer();
85+
installJsonSchemaDialect(server);
86+
installJsonSchemaDialect(server);
87+
88+
const { tools } = await listToolsOverWire(server);
89+
expect(tools[0]?.outputSchema?.$schema).toBe(JSON_SCHEMA_DIALECT_2020_12);
90+
});
91+
92+
test('warns instead of throwing when installed before any tool is registered', async () => {
93+
// The ordering contract: the SDK installs its `tools/list` handler lazily
94+
// on the first `registerTool`, so an install hoisted above tool
95+
// registration silently does nothing. Fail loud rather than ship draft-07.
96+
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
97+
const server = new McpServer({ name: 'json-schema-dialect-test', version: '0.0.0' });
98+
99+
expect(() => installJsonSchemaDialect(server)).not.toThrow();
100+
expect(warn).toHaveBeenCalledWith(expect.stringContaining('[json-schema-dialect]'));
101+
warn.mockRestore();
102+
});
103+
104+
test('a tool registered after install still gets re-declared', async () => {
105+
// The wrapper defers to the SDK handler, which reads the live tool
106+
// registry per request, so late registrations flow through it.
107+
const server = buildServer();
108+
installJsonSchemaDialect(server);
109+
server.registerTool(
110+
'late_tool',
111+
{ description: 'registered after install', outputSchema: { text: z.string() } },
112+
async () => ({
113+
content: [{ type: 'text' as const, text: 'ok' }],
114+
structuredContent: { text: 'ok' },
115+
}),
116+
);
117+
118+
const { tools } = await listToolsOverWire(server);
119+
const late = tools.find((t) => t.name === 'late_tool');
120+
expect(late?.outputSchema?.$schema).toBe(JSON_SCHEMA_DIALECT_2020_12);
121+
});
122+
});
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
/**
2+
* Re-declare tool schemas as JSON Schema 2020-12 in `tools/list` responses.
3+
*
4+
* The MCP SDK converts our Zod v4 tool schemas with no `target`, so its
5+
* internal `mapMiniTarget(undefined)` falls through to `'draft-7'` and every
6+
* `inputSchema` / `outputSchema` ships stamped
7+
* `"$schema": "http://json-schema.org/draft-07/schema#"`. Clients that
8+
* validate structured output against the declared dialect reject the tool
9+
* outright: an Ajv 2020 instance fails to compile every one of our schemas
10+
* with `no schema with key or ref "http://json-schema.org/draft-07/schema#"`,
11+
* so the whole tool surface disappears rather than one tool degrading.
12+
*
13+
* Only the label is wrong. Our schemas use no construct where the two
14+
* dialects diverge (no tuple-form `items`, no `$defs` / `definitions`, no
15+
* `$ref`, and `exclusiveMinimum` / `exclusiveMaximum` are the numeric form
16+
* both dialects share), so re-stamping is a relabel, not a conversion.
17+
*
18+
* The SDK exposes no way to pass a conversion target: neither `registerTool`
19+
* nor the server options accept one, and its `tools/list` handler hardcodes
20+
* the call. Upstream tracking: modelcontextprotocol/typescript-sdk#745.
21+
*
22+
* Best-effort, like the sibling `installPrettyZodErrors`: if the SDK's
23+
* internals move, warn and leave default behavior in place rather than
24+
* breaking the server.
25+
*/
26+
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
27+
import { ListToolsRequestSchema, type ServerResult } from '@modelcontextprotocol/sdk/types.js';
28+
29+
export const JSON_SCHEMA_DIALECT_2020_12 = 'https://json-schema.org/draft/2020-12/schema';
30+
31+
const LIST_TOOLS_METHOD = 'tools/list';
32+
33+
type RequestHandler = (request: unknown, extra: unknown) => ServerResult | Promise<ServerResult>;
34+
35+
/**
36+
* The narrow view we mutate. Deliberately NOT the handler's return type:
37+
* `ServerResult` is a union (it also covers task-shaped results), and
38+
* narrowing the return to a tools-only shape makes it unassignable.
39+
*/
40+
interface ListToolsShape {
41+
tools?: Array<{
42+
inputSchema?: { $schema?: string };
43+
outputSchema?: { $schema?: string };
44+
}>;
45+
}
46+
47+
/**
48+
* Install the dialect re-stamp on the given MCP server. Idempotent.
49+
*
50+
* MUST be called AFTER the server's tools are registered: the SDK installs
51+
* its `tools/list` handler lazily on the first `registerTool`, so calling
52+
* this at construction time finds nothing to wrap.
53+
*/
54+
export function installJsonSchemaDialect(server: McpServer): void {
55+
const target = server as unknown as { __jsonSchemaDialectInstalled?: true };
56+
if (target.__jsonSchemaDialectInstalled === true) {
57+
return;
58+
}
59+
60+
const inner = server.server as unknown as {
61+
_requestHandlers?: Map<string, RequestHandler>;
62+
};
63+
const original = inner._requestHandlers?.get(LIST_TOOLS_METHOD);
64+
if (typeof original !== 'function') {
65+
// Bracket-prefix matches the OK ops-warning convention. Without this the
66+
// regression looks identical to "we never installed it", and the symptom
67+
// (clients silently dropping the entire tool surface) points nowhere near
68+
// this file.
69+
console.warn(
70+
`[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.`,
71+
);
72+
return;
73+
}
74+
75+
server.server.setRequestHandler(ListToolsRequestSchema, async (request, extra) => {
76+
// The SDK rebuilds these schema objects on every `tools/list` call, so
77+
// mutating in place cannot leak across requests.
78+
const result = await original(request, extra);
79+
for (const tool of (result as ListToolsShape).tools ?? []) {
80+
if (tool.inputSchema) tool.inputSchema.$schema = JSON_SCHEMA_DIALECT_2020_12;
81+
if (tool.outputSchema) tool.outputSchema.$schema = JSON_SCHEMA_DIALECT_2020_12;
82+
}
83+
return result;
84+
});
85+
86+
target.__jsonSchemaDialectInstalled = true;
87+
}

0 commit comments

Comments
 (0)