|
| 1 | +/** |
| 2 | + * MCP 工具 inputSchema 的 JSON Schema 预处理 |
| 3 | + * |
| 4 | + * 移植自 @langchain/mcp-adapters 的 tools.ts(MIT License): |
| 5 | + * - dereferenceJsonSchema:把 $defs/$definitions 里的 $ref 内联展开 |
| 6 | + * (部分 JSON Schema 校验器与 LLM API 不解析 $ref) |
| 7 | + * - simplifyJsonSchemaForLLM:摊平 allOf/anyOf/oneOf、剥离 if/then/else/not |
| 8 | + * 等顶层组合关键字,生成 OpenAI 等工具调用 API 可接受的 schema |
| 9 | + */ |
| 10 | + |
| 11 | +/** |
| 12 | + * 将 JSON Schema 中的 $ref 指针内联为 $defs/definitions 中的定义 |
| 13 | + */ |
| 14 | +function dereferenceJsonSchema(schema: Record<string, any>): Record<string, any> { |
| 15 | + const definitions = schema.$defs ?? schema.definitions ?? {}; |
| 16 | + |
| 17 | + function resolveRefs(obj: any, visitedRefs: Set<string> = new Set()): any { |
| 18 | + if (typeof obj !== "object" || obj === null) return obj; |
| 19 | + if (obj.$ref && typeof obj.$ref === "string") { |
| 20 | + const refPath: string = obj.$ref; |
| 21 | + const match = refPath.match(/^#\/\$defs\/(.+)$/) ?? refPath.match(/^#\/definitions\/(.+)$/); |
| 22 | + if (match) { |
| 23 | + const definition = definitions[match[1]]; |
| 24 | + if (definition) { |
| 25 | + // 循环引用防御:退化为空对象,避免无限递归 |
| 26 | + if (visitedRefs.has(refPath)) return { type: "object" }; |
| 27 | + const newVisited = new Set(visitedRefs); |
| 28 | + newVisited.add(refPath); |
| 29 | + const { $ref: _ref, ...restOfObj } = obj; |
| 30 | + return { ...resolveRefs(definition, newVisited), ...restOfObj }; |
| 31 | + } |
| 32 | + } |
| 33 | + return obj; |
| 34 | + } |
| 35 | + const result: Record<string, any> = {}; |
| 36 | + for (const [key, value] of Object.entries(obj)) { |
| 37 | + if (key === "$defs" || key === "definitions") continue; |
| 38 | + if (Array.isArray(value)) result[key] = value.map(item => (typeof item === "object" && item !== null ? resolveRefs(item, visitedRefs) : item)); |
| 39 | + else if (typeof value === "object" && value !== null) result[key] = resolveRefs(value, visitedRefs); |
| 40 | + else result[key] = value; |
| 41 | + } |
| 42 | + return result; |
| 43 | + } |
| 44 | + |
| 45 | + return resolveRefs(schema); |
| 46 | +} |
| 47 | + |
| 48 | +/** |
| 49 | + * 深合并两个 JSON Schema 对象: |
| 50 | + * 数组拼接(enum 去重)、对象递归合并、基本类型覆盖 |
| 51 | + */ |
| 52 | +function deepMergeSchemas(target: Record<string, any>, source: Record<string, any>): Record<string, any> { |
| 53 | + const result: Record<string, any> = { ...target }; |
| 54 | + for (const [key, sourceValue] of Object.entries(source)) { |
| 55 | + const targetValue = result[key]; |
| 56 | + if (key === "required" && Array.isArray(targetValue)) { |
| 57 | + result[key] = [...new Set([...targetValue, ...(Array.isArray(sourceValue) ? sourceValue : [])])]; |
| 58 | + } else if (key === "const") { |
| 59 | + const values = new Set<any>(); |
| 60 | + if (Array.isArray(result.enum)) result.enum.forEach(v => values.add(v)); |
| 61 | + if (result.const !== undefined) values.add(result.const); |
| 62 | + values.add(sourceValue); |
| 63 | + delete result.const; |
| 64 | + result.enum = [...values]; |
| 65 | + } else if (key === "enum" && Array.isArray(sourceValue)) { |
| 66 | + const values = new Set<any>(); |
| 67 | + if (Array.isArray(targetValue)) targetValue.forEach(v => values.add(v)); |
| 68 | + if (result.const !== undefined) { |
| 69 | + values.add(result.const); |
| 70 | + delete result.const; |
| 71 | + } |
| 72 | + sourceValue.forEach(v => values.add(v)); |
| 73 | + result[key] = [...values]; |
| 74 | + } else if (key === "properties" && typeof targetValue === "object" && targetValue !== null && typeof sourceValue === "object" && sourceValue !== null) { |
| 75 | + const mergedProps = { ...targetValue }; |
| 76 | + for (const [propKey, propValue] of Object.entries(sourceValue)) { |
| 77 | + const existing = mergedProps[propKey]; |
| 78 | + mergedProps[propKey] = (existing && typeof existing === "object" && propValue && typeof propValue === "object") |
| 79 | + ? deepMergeSchemas(existing as Record<string, any>, propValue as Record<string, any>) |
| 80 | + : propValue; |
| 81 | + } |
| 82 | + result[key] = mergedProps; |
| 83 | + } else if (Array.isArray(sourceValue) && Array.isArray(targetValue)) { |
| 84 | + result[key] = [...targetValue, ...sourceValue]; |
| 85 | + } else if (typeof sourceValue === "object" && sourceValue !== null && !Array.isArray(sourceValue) |
| 86 | + && typeof targetValue === "object" && targetValue !== null && !Array.isArray(targetValue)) { |
| 87 | + result[key] = deepMergeSchemas(targetValue, sourceValue); |
| 88 | + } else { |
| 89 | + result[key] = sourceValue; |
| 90 | + } |
| 91 | + } |
| 92 | + return result; |
| 93 | +} |
| 94 | + |
| 95 | +/** |
| 96 | + * 从 if/then/else 条件 schema 中提取并合并 properties / required |
| 97 | + */ |
| 98 | +function extractPropertiesFromConditional(schema: Record<string, any>): Record<string, any> { |
| 99 | + let result: Record<string, any> = {}; |
| 100 | + for (const branch of [schema.then, schema.else]) { |
| 101 | + const b = branch as Record<string, any> | undefined; |
| 102 | + if (b && typeof b === "object") { |
| 103 | + if (b.properties) result = deepMergeSchemas(result, { properties: b.properties }); |
| 104 | + if (b.required) result.required = [...new Set([...(result.required || []), ...b.required])]; |
| 105 | + } |
| 106 | + } |
| 107 | + return result; |
| 108 | +} |
| 109 | + |
| 110 | +/** |
| 111 | + * 为 LLM 工具调用 API 简化 JSON Schema: |
| 112 | + * - allOf 合并进主 schema;anyOf/oneOf 摊平为对象属性合并 |
| 113 | + * - if/then/else / not / $schema / unevaluatedProperties 剥离(提取其中的属性) |
| 114 | + * 递归应用到嵌套 schema |
| 115 | + */ |
| 116 | +export function simplifyJsonSchemaForLLM(schema: Record<string, any>): Record<string, any> { |
| 117 | + if (typeof schema !== "object" || schema === null) return schema; |
| 118 | + const { |
| 119 | + allOf, anyOf, oneOf, not: _not, if: schemaIf, then: schemaThen, else: schemaElse, |
| 120 | + $schema: _$schema, unevaluatedProperties: _unevaluatedProperties, ...baseSchema |
| 121 | + } = schema; |
| 122 | + let result: Record<string, any> = { ...baseSchema }; |
| 123 | + |
| 124 | + if (schemaIf || schemaThen || schemaElse) { |
| 125 | + const conditionalProps = extractPropertiesFromConditional({ if: schemaIf, then: schemaThen, else: schemaElse }); |
| 126 | + result = deepMergeSchemas(result, conditionalProps); |
| 127 | + } |
| 128 | + |
| 129 | + if (Array.isArray(allOf)) { |
| 130 | + for (const subSchema of allOf) { |
| 131 | + if (subSchema?.if || subSchema?.then || subSchema?.else) { |
| 132 | + result = deepMergeSchemas(result, extractPropertiesFromConditional(subSchema)); |
| 133 | + } |
| 134 | + result = deepMergeSchemas(result, simplifyJsonSchemaForLLM(subSchema)); |
| 135 | + } |
| 136 | + } |
| 137 | + |
| 138 | + const unionSchemas = anyOf || oneOf; |
| 139 | + if (Array.isArray(unionSchemas) && unionSchemas.length > 0) { |
| 140 | + const schemasToMerge = unionSchemas.filter((s: any) => typeof s === "object" && s !== null && (s.type === "object" || s.properties)); |
| 141 | + const mergedProperties: Record<string, any> = {}; |
| 142 | + const requiredSets: Set<string>[] = []; |
| 143 | + for (const subSchema of schemasToMerge) { |
| 144 | + const simplified = simplifyJsonSchemaForLLM(subSchema); |
| 145 | + if (simplified.properties) Object.assign(mergedProperties, simplified.properties); |
| 146 | + if (Array.isArray(simplified.required)) requiredSets.push(new Set(simplified.required)); |
| 147 | + if (simplified.type && !result.type) result.type = simplified.type; |
| 148 | + } |
| 149 | + if (Object.keys(mergedProperties).length > 0) { |
| 150 | + result.properties = { ...result.properties, ...mergedProperties }; |
| 151 | + } |
| 152 | + if (requiredSets.length > 0) { |
| 153 | + // 各分支 required 的交集:所有分支都要求的字段才是必填 |
| 154 | + const commonRequired = requiredSets.reduce((acc, set) => new Set([...acc].filter(x => set.has(x)))); |
| 155 | + if (commonRequired.size > 0) result.required = [...new Set([...(result.required || []), ...commonRequired])]; |
| 156 | + } |
| 157 | + } |
| 158 | + |
| 159 | + if (result.properties && !result.type) result.type = "object"; |
| 160 | + if (result.properties) { |
| 161 | + const simplifiedProperties: Record<string, any> = {}; |
| 162 | + for (const [propName, propSchema] of Object.entries(result.properties)) { |
| 163 | + simplifiedProperties[propName] = (typeof propSchema === "object" && propSchema !== null) |
| 164 | + ? simplifyJsonSchemaForLLM(propSchema) |
| 165 | + : propSchema; |
| 166 | + } |
| 167 | + result.properties = simplifiedProperties; |
| 168 | + } |
| 169 | + if (result.items) { |
| 170 | + if (Array.isArray(result.items)) result.items = result.items.map(item => (typeof item === "object" && item !== null ? simplifyJsonSchemaForLLM(item) : item)); |
| 171 | + else if (typeof result.items === "object" && result.items !== null) result.items = simplifyJsonSchemaForLLM(result.items); |
| 172 | + } |
| 173 | + if (typeof result.additionalProperties === "object" && result.additionalProperties !== null) { |
| 174 | + result.additionalProperties = simplifyJsonSchemaForLLM(result.additionalProperties); |
| 175 | + } |
| 176 | + return result; |
| 177 | +} |
| 178 | + |
| 179 | +/** |
| 180 | + * 工具 inputSchema 的完整预处理入口:解引用 + LLM 兼容简化 |
| 181 | + */ |
| 182 | +export function prepareToolSchema(inputSchema: Record<string, any>): Record<string, any> { |
| 183 | + const schema = { ...inputSchema }; |
| 184 | + if (!schema.properties) schema.properties = {}; |
| 185 | + return simplifyJsonSchemaForLLM(dereferenceJsonSchema(schema)); |
| 186 | +} |
0 commit comments