Skip to content

Commit adafe15

Browse files
authored
Merge pull request #395 from asyncsquadlabs/fix/mcp-input-schema-defs-refs
fix(core): resolve and preserve MCP tool inputSchema $defs/$ref definitions
2 parents a66979d + 70e8740 commit adafe15

8 files changed

Lines changed: 618 additions & 31 deletions

File tree

‎package-lock.json‎

Lines changed: 63 additions & 3 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎packages/core/package.json‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,8 @@
6464
"test": "node src/tests/run-tests.mjs"
6565
},
6666
"dependencies": {
67+
"ajv": "^8.20.0",
68+
"ajv-formats": "^3.0.1",
6769
"chalk": "^5.6.2",
6870
"ejs": "^5.0.2",
6971
"gray-matter": "^4.0.3",

‎packages/core/src/mcp/mcp-client.ts‎

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { spawn, type ChildProcess } from "child_process";
22
import { createInterface, type Interface } from "readline";
33
import * as path from "path";
44
import { killProcessTree } from "../common/process-tree";
5+
import type { McpInputSchema } from "./mcp-schema";
56

67
type JsonRpcRequest = {
78
jsonrpc: "2.0";
@@ -26,12 +27,7 @@ type JsonRpcNotification = {
2627
export type McpToolDefinition = {
2728
name: string;
2829
description?: string;
29-
inputSchema: {
30-
type: "object";
31-
properties: Record<string, unknown>;
32-
required?: string[];
33-
additionalProperties?: boolean;
34-
};
30+
inputSchema: McpInputSchema;
3531
};
3632

3733
type ListToolsResult = {

‎packages/core/src/mcp/mcp-manager.ts‎

Lines changed: 16 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import { createHash } from "crypto";
22
import { McpClient, type McpToolDefinition, type McpPromptDefinition, type McpResourceDefinition } from "./mcp-client";
33
import type { McpServerConfig } from "../settings";
4+
import type { ToolDefinition } from "../prompt";
5+
import { prepareMcpInputSchema, type PreparedMcpInputSchema } from "./mcp-schema";
46

57
const MCP_STARTUP_TIMEOUT_MS = process.env.DEEPCODE_MCP_TIMEOUT
68
? parseInt(process.env.DEEPCODE_MCP_TIMEOUT, 10)
@@ -59,6 +61,7 @@ function buildMcpNamespacedName(
5961
export class McpManager {
6062
private clients: McpClient[] = [];
6163
private tools: McpToolEntry[] = [];
64+
private toolSchemas = new WeakMap<McpToolDefinition, PreparedMcpInputSchema>();
6265
private prompts: Array<{
6366
serverName: string;
6467
namespacedName: string;
@@ -303,32 +306,22 @@ export class McpManager {
303306
return result;
304307
}
305308

306-
getMcpToolDefinitions(): Array<{
307-
type: "function";
308-
function: {
309-
name: string;
310-
description: string;
311-
parameters: {
312-
type: "object";
313-
properties: Record<string, unknown>;
314-
required?: string[];
315-
additionalProperties?: boolean;
316-
};
317-
};
318-
}> {
309+
private getToolSchema(tool: McpToolDefinition): PreparedMcpInputSchema {
310+
let schema = this.toolSchemas.get(tool);
311+
if (!schema) {
312+
schema = prepareMcpInputSchema(tool.inputSchema);
313+
this.toolSchemas.set(tool, schema);
314+
}
315+
return schema;
316+
}
317+
318+
getMcpToolDefinitions(): ToolDefinition[] {
319319
return this.tools.map((t) => ({
320320
type: "function" as const,
321321
function: {
322322
name: t.namespacedName,
323323
description: this.buildMcpToolDescription(t),
324-
parameters: {
325-
type: "object" as const,
326-
properties: t.definition.inputSchema.properties,
327-
required: t.definition.inputSchema.required,
328-
...(t.definition.inputSchema.additionalProperties !== undefined
329-
? { additionalProperties: t.definition.inputSchema.additionalProperties }
330-
: {}),
331-
},
324+
parameters: this.getToolSchema(t.definition).parameters,
332325
},
333326
}));
334327
}
@@ -348,6 +341,8 @@ export class McpManager {
348341
}
349342

350343
try {
344+
const validationError = this.getToolSchema(tool.definition).validateArguments?.(args);
345+
if (validationError) return { ok: false, name, error: validationError };
351346
const result = await tool.client.callTool(tool.originalName, args, timeoutMs);
352347
const text = result.content
353348
.filter((c) => c.type === "text" && c.text)
Lines changed: 167 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,167 @@
1+
import Ajv, { type AnySchema, type ValidateFunction } from "ajv";
2+
import Ajv2019 from "ajv/dist/2019.js";
3+
import Ajv2020 from "ajv/dist/2020.js";
4+
import addFormats from "ajv-formats";
5+
6+
export type McpInputSchema = {
7+
type: "object";
8+
properties?: Record<string, unknown>;
9+
required?: string[];
10+
additionalProperties?: boolean | Record<string, unknown>;
11+
$defs?: Record<string, unknown>;
12+
definitions?: Record<string, unknown>;
13+
[keyword: string]: unknown;
14+
};
15+
16+
export type PreparedMcpInputSchema = {
17+
parameters: McpInputSchema & { properties: Record<string, unknown> };
18+
validateArguments?: (args: Record<string, unknown>) => string | undefined;
19+
};
20+
21+
const SCHEMA_MAPS = new Set(["properties", "patternProperties", "$defs", "definitions", "dependentSchemas"]);
22+
const SCHEMA_ARRAYS = new Set(["allOf", "anyOf", "oneOf", "prefixItems"]);
23+
const SCHEMAS = new Set([
24+
"items",
25+
"additionalItems",
26+
"additionalProperties",
27+
"unevaluatedItems",
28+
"unevaluatedProperties",
29+
"contains",
30+
"propertyNames",
31+
"not",
32+
"if",
33+
"then",
34+
"else",
35+
"contentSchema",
36+
]);
37+
38+
/** Keep references and composition intact; only adapt tuples for the model API. */
39+
export function prepareMcpInputSchema(inputSchema?: McpInputSchema): PreparedMcpInputSchema {
40+
const original: McpInputSchema = structuredClone(
41+
isObject(inputSchema) ? inputSchema : { type: "object", properties: {} }
42+
);
43+
let hasTuples = false;
44+
let hasPrefixItems = false;
45+
46+
const locations = new Map<string, string>();
47+
const references: Array<{ node: Record<string, unknown>; sourceRoot: string; targetRoot: string }> = [];
48+
49+
const visit = (node: unknown, source = "", target = "", sourceRoot = "", targetRoot = ""): unknown => {
50+
locations.set(source, target);
51+
if (!isObject(node)) return node;
52+
if (typeof node.$id === "string" && !node.$id.startsWith("#")) {
53+
sourceRoot = source;
54+
targetRoot = target;
55+
}
56+
const child = (schema: unknown, from: string[], to = from) =>
57+
visit(schema, pointer(source, ...from), pointer(target, ...to), sourceRoot, targetRoot);
58+
const modern = Array.isArray(node.prefixItems);
59+
const tuple = modern ? node.prefixItems : node.items;
60+
const out: Record<string, unknown> = Object.fromEntries(
61+
Object.entries(node).map(([key, value]) => {
62+
if (Array.isArray(tuple) && ["items", "prefixItems", "additionalItems"].includes(key)) {
63+
return [key, value]; // Converted below, with reference locations recorded.
64+
}
65+
if ((SCHEMA_MAPS.has(key) || key === "dependencies") && isObject(value)) {
66+
return [
67+
key,
68+
Object.fromEntries(Object.entries(value).map(([name, schema]) => [name, child(schema, [key, name])])),
69+
];
70+
}
71+
if (SCHEMA_ARRAYS.has(key) && Array.isArray(value)) {
72+
return [key, value.map((schema, index) => child(schema, [key, String(index)]))];
73+
}
74+
return [key, SCHEMAS.has(key) ? child(value, [key]) : value];
75+
})
76+
);
77+
78+
if (Array.isArray(tuple)) {
79+
hasTuples = true;
80+
hasPrefixItems ||= modern;
81+
const tupleKey = modern ? "prefixItems" : "items";
82+
const tailKey = modern ? "items" : "additionalItems";
83+
const tail = node[tailKey];
84+
const alternatives = tuple.map((schema, index) =>
85+
child(schema, [tupleKey, String(index)], ["items", "anyOf", String(index)])
86+
);
87+
// An omitted tail is unconstrained. Keep every branch, including an open
88+
// tail, so valid server arguments and references into tuple items survive.
89+
alternatives.push(child(tail ?? {}, [tailKey], ["items", "anyOf", String(tuple.length)]));
90+
out.items = { anyOf: alternatives };
91+
if (tail === false) {
92+
out.maxItems = typeof out.maxItems === "number" ? Math.min(out.maxItems, tuple.length) : tuple.length;
93+
}
94+
delete out.prefixItems;
95+
delete out.additionalItems;
96+
}
97+
references.push({ node: out, sourceRoot, targetRoot });
98+
return out;
99+
};
100+
101+
const parameters = visit(structuredClone(original)) as PreparedMcpInputSchema["parameters"];
102+
// Tuple conversion relocates schemas such as /items/0. Rewrite only local
103+
// schema references, never strings in defaults, enums or examples.
104+
for (const { node, sourceRoot, targetRoot } of references) {
105+
for (const keyword of ["$ref", "$dynamicRef", "$recursiveRef"]) {
106+
const ref = node[keyword];
107+
if (typeof ref !== "string" || (ref !== "#" && !ref.startsWith("#/"))) continue;
108+
let fragment: string;
109+
try {
110+
fragment = decodeURIComponent(ref.slice(1));
111+
} catch {
112+
continue;
113+
}
114+
const relocated = locations.get(sourceRoot + fragment);
115+
if (relocated !== undefined && relocated !== sourceRoot + fragment) {
116+
node[keyword] = "#" + encodeURI(relocated.slice(targetRoot.length)).replace(/#/g, "%23");
117+
}
118+
}
119+
}
120+
parameters.properties ??= {};
121+
if (!hasTuples) return { parameters };
122+
123+
// Compile lazily so one unsupported server schema cannot prevent discovery
124+
// of other tools. Compilation failures still block this tool's execution.
125+
let validate: ValidateFunction | undefined;
126+
let compilationError: string | undefined;
127+
return {
128+
parameters,
129+
validateArguments(args) {
130+
if (!validate && !compilationError) {
131+
try {
132+
const dialect = original.$schema;
133+
const Validator =
134+
dialect === "https://json-schema.org/draft/2020-12/schema" || (!dialect && hasPrefixItems)
135+
? Ajv2020
136+
: dialect === "https://json-schema.org/draft/2019-09/schema"
137+
? Ajv2019
138+
: Ajv;
139+
const ajv = new Validator({
140+
strict: false,
141+
coerceTypes: false,
142+
useDefaults: false,
143+
removeAdditional: false,
144+
});
145+
addFormats(ajv);
146+
validate = ajv.compile(original as AnySchema);
147+
if ("$async" in validate && validate.$async) throw new Error("Asynchronous schemas are not supported.");
148+
} catch (error) {
149+
validate = undefined;
150+
compilationError = `Cannot validate MCP tool arguments: ${error instanceof Error ? error.message : String(error)}`;
151+
}
152+
}
153+
if (compilationError) return compilationError;
154+
if (validate!(args)) return undefined;
155+
const error = validate!.errors?.[0];
156+
return `Invalid MCP tool arguments at ${error?.instancePath || "/"}: ${error?.message ?? "schema validation failed"}.`;
157+
},
158+
};
159+
}
160+
161+
function isObject(value: unknown): value is Record<string, unknown> {
162+
return value !== null && typeof value === "object" && !Array.isArray(value);
163+
}
164+
165+
function pointer(base: string, ...parts: string[]): string {
166+
return base + parts.map((part) => "/" + part.replace(/~/g, "~0").replace(/\//g, "~1")).join("");
167+
}

‎packages/core/src/prompt.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -393,7 +393,9 @@ export type ToolDefinition = {
393393
type: "object";
394394
properties: Record<string, unknown>;
395395
required?: string[];
396-
additionalProperties?: boolean;
396+
additionalProperties?: boolean | Record<string, unknown>;
397+
$defs?: Record<string, unknown>;
398+
definitions?: Record<string, unknown>;
397399
};
398400
};
399401
};

0 commit comments

Comments
 (0)