|
| 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 | +} |
0 commit comments