/
githubmirror
/
Front-End-Checklist
Обзор
Документация
Войти
/
githubmirror
/
Front-End-Checklist
Код
Запросы
0
Пакеты
0
Релизы
0
Аналитика
Безопасность
main
packages/mcp/src/schema-utils.ts
88 строк
2 KB
David Dias
chore: new v2 version
30 май 2026, 00:54
30 май 2026, 00:54
7c05904
Код
Авторство
О чём код?
import * as z from 'zod' interface JsonLikeSchema { type?: string | string[] enum?: readonly string[] properties?: Record<string, JsonLikeSchema> items?: JsonLikeSchema required?: string[] [key: string]: unknown } /** * Mark a derived Zod schema nullable when JSON Schema includes `null`. * * @param schema - Base Zod schema. * @param type - Raw JSON Schema type field. * @returns Nullable or original schema depending on the input type. */ function applyNullable(schema: z.ZodTypeAny, type: JsonLikeSchema['type']): z.ZodTypeAny { if (!Array.isArray(type) || !type.includes('null')) { return schema } return schema.nullable() } /** * Convert a JSON Schema object shape into a Zod object schema. * * @param schema - JSON-like object schema. * @returns Zod object schema with optional fields handled from `required`. */ function buildObjectSchema(schema: JsonLikeSchema): z.ZodTypeAny { const required = new Set(schema.required || []) const shape = Object.fromEntries( Object.entries(schema.properties || {}).map(([key, value]) => { const propertySchema = required.has(key) ? jsonSchemaToZod(value) : jsonSchemaToZod(value).optional() return [key, propertySchema] }) ) return z.object(shape).catchall(z.any()) } /** * Convert a small subset of JSON Schema into a matching Zod schema. * * @param schema - JSON-like schema definition. * @returns Zod schema used by MCP tool registration. */ export function jsonSchemaToZod(schema: JsonLikeSchema | undefined): z.ZodTypeAny { if (!schema) { return z.any() } if (schema.enum && schema.enum.length > 0) { const values = [...schema.enum] const enumSchema = values.length === 1 ? z.literal(values[0]) : z.enum([values[0], ...values.slice(1)] as [string, ...string[]]) return applyNullable(enumSchema, schema.type) } const type = Array.isArray(schema.type) ? schema.type.filter(value => value !== 'null')[0] : schema.type switch (type) { case 'string': return applyNullable(z.string(), schema.type) case 'number': return applyNullable(z.number(), schema.type) case 'boolean': return applyNullable(z.boolean(), schema.type) case 'array': { const itemSchema = jsonSchemaToZod(schema.items) return applyNullable(z.array(itemSchema), schema.type) } default: { const objectSchema = buildObjectSchema(schema) return applyNullable(objectSchema, schema.type) } } }