Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
| 1 | import * as z from 'zod/v3'; |
| 2 | |
| 3 | import type { Decorations, IssueSink, StringFormat, WholeSchemaGuard, ZodBackend } from './types'; |
| 4 | import { applyObjectPolicy, buildTuple, composeGuards, run, withPath } from './shared'; |
| 5 | |
| 6 | type S = z.ZodTypeAny; |
| 7 | |
| 8 | type GuardedDef = z.ZodTypeDef & { wholeSchemaGuard?: WholeSchemaGuard }; |
| 9 | type ZodSchemaClass = { |
| 10 | new (def: z.ZodTypeDef): z.ZodTypeAny; |
| 11 | prototype: z.ZodTypeAny; |
| 12 | }; |
| 13 | |
| 14 | const guardedSchemaClasses = new WeakMap<ZodSchemaClass, ZodSchemaClass>(); |
| 15 | |
| 16 | /** |
| 17 | * A subclass of the parsed schema's own class that checks the source value |
| 18 | * against the guard before parsing it. Keeping the class, rather than wrapping |
| 19 | * it in a pipeline, keeps the schema's kind: a guarded object is still a |
| 20 | * `ZodObject` with a `shape`, which is what zod-to-json-schema and the MCP SDK |
| 21 | * need to emit a root `type: "object"` for LLM tool parameters. The guard lives |
| 22 | * on `_def`, so copies such as `.describe()` keep it. |
| 23 | */ |
| 24 | const guardedSchemaClass = (Base: ZodSchemaClass): ZodSchemaClass => { |
| 25 | const cached = guardedSchemaClasses.get(Base); |
| 26 | if (cached) { |
| 27 | return cached; |
| 28 | } |
| 29 | |
| 30 | const parseAsBase = Base.prototype._parse; |
| 31 | class Guarded extends Base { |
| 32 | override _parse(input: z.ParseInput): z.ParseReturnType<unknown> { |
| 33 | const failure = (this._def as GuardedDef).wholeSchemaGuard?.(input.data); |
| 34 | if (failure === undefined) { |
| 35 | return parseAsBase.call(this, input); |
| 36 | } |
| 37 | z.addIssueToContext(this._getOrReturnCtx(input), { |
| 38 | code: z.ZodIssueCode.custom, |
| 39 | message: failure, |
| 40 | }); |
| 41 | return z.DIRTY(input.data); |
| 42 | } |
| 43 | } |
| 44 | guardedSchemaClasses.set(Base, Guarded); |
| 45 | // Guarding an already guarded schema reuses its class and composes guards. |
| 46 | guardedSchemaClasses.set(Guarded, Guarded); |
| 47 | return Guarded; |
| 48 | }; |
| 49 | |
| 50 | const attachGuard = (schema: S, guard: WholeSchemaGuard): S => { |
| 51 | // Validate the source value before defaults and other Zod transforms run. |
| 52 | // Otherwise a missing required field can be synthesized and incorrectly |
| 53 | // appear valid to the JSON Schema interpreter. |
| 54 | const wholeSchemaGuard = composeGuards(guard, (schema._def as GuardedDef).wholeSchemaGuard); |
| 55 | |
| 56 | const Guarded = guardedSchemaClass(schema.constructor as ZodSchemaClass); |
| 57 | return new Guarded({ ...schema._def, wholeSchemaGuard } as GuardedDef); |
| 58 | }; |
| 59 | |
| 60 | /** Issues raised through the refinement context; Zod prefixes the context path itself. */ |
| 61 | const sink = (ctx: z.RefinementCtx): IssueSink => ({ |
| 62 | custom(message, options) { |
| 63 | ctx.addIssue({ |
| 64 | ...withPath(options?.path), |
| 65 | code: z.ZodIssueCode.custom, |
| 66 | message, |
| 67 | ...(options?.params === undefined ? {} : { params: options.params }), |
| 68 | }); |
| 69 | }, |
| 70 | unrecognizedKeys(keys, message, options) { |
| 71 | ctx.addIssue({ |
| 72 | ...withPath(options?.path), |
| 73 | code: z.ZodIssueCode.unrecognized_keys, |
| 74 | keys: [...keys], |
| 75 | message, |
| 76 | }); |
| 77 | }, |
| 78 | invalidUnion(message, failures, options) { |
| 79 | ctx.addIssue({ |
| 80 | ...withPath(options?.path), |
| 81 | code: z.ZodIssueCode.invalid_union, |
| 82 | unionErrors: failures as z.ZodError[], |
| 83 | message, |
| 84 | }); |
| 85 | }, |
| 86 | forward(failure) { |
| 87 | for (const issue of failure.issues) { |
| 88 | ctx.addIssue(issue as z.ZodIssue); |
| 89 | } |
| 90 | }, |
| 91 | }); |
| 92 | |
| 93 | const stringFormat = (schema: S, format: StringFormat, message?: string): S => { |
| 94 | const string = schema as z.ZodString; |
| 95 | switch (format) { |
| 96 | case 'email': |
| 97 | return string.email(message); |
| 98 | case 'ip': |
| 99 | return string.ip(message); |
| 100 | case 'ipv4': |
| 101 | return string.ip({ version: 'v4', message }); |
| 102 | case 'ipv6': |
| 103 | return string.ip({ version: 'v6', message }); |
| 104 | case 'uri': |
| 105 | return string.url(message); |
| 106 | case 'uuid': |
| 107 | return string.uuid(message); |
| 108 | case 'date-time': |
| 109 | return string.datetime({ offset: true, message }); |
| 110 | case 'time': |
| 111 | return string.time(message); |
| 112 | case 'date': |
| 113 | return string.date(message); |
| 114 | case 'duration': |
| 115 | return string.duration(message); |
| 116 | } |
| 117 | }; |
| 118 | |
| 119 | /** Zod v3 output: descriptions on `_def`, refinements as `ZodEffects`, the guard as a subclass. */ |
| 120 | export const zodV3Backend: ZodBackend<S> = { |
| 121 | isSchema: (value): value is S => value instanceof z.ZodType, |
| 122 | isNever: schema => schema instanceof z.ZodNever, |
| 123 | |
| 124 | any: () => z.any(), |
| 125 | never: () => z.never(), |
| 126 | boolean: () => z.boolean(), |
| 127 | null: () => z.null(), |
| 128 | string: () => z.string(), |
| 129 | number: () => z.number(), |
| 130 | literal: value => z.literal(value), |
| 131 | enum: values => z.enum(values as [string, ...string[]]), |
| 132 | predicate: test => z.custom(test), |
| 133 | |
| 134 | stringFormat, |
| 135 | base64: (schema, message) => (schema as z.ZodString).base64(message), |
| 136 | regex: (schema, pattern, message) => (schema as z.ZodString).regex(pattern, message), |
| 137 | |
| 138 | integer: (schema, message) => (schema as z.ZodNumber).int(message), |
| 139 | bound: (schema, kind, value, message) => (schema as z.ZodNumber)[kind](value, message), |
| 140 | |
| 141 | array: item => z.array(item), |
| 142 | minItems: (schema, count, message) => (schema as z.ZodArray<S>).min(count, message), |
| 143 | maxItems: (schema, count, message) => (schema as z.ZodArray<S>).max(count, message), |
| 144 | tuple: (items, rest) => buildTuple<S>(z.tuple(items as unknown as [S]), rest), |
| 145 | |
| 146 | object: (shape, policy) => applyObjectPolicy<S>(z.object(shape), policy), |
| 147 | record: value => z.record(value), |
| 148 | |
| 149 | union: options => z.union(options as unknown as [S, S]), |
| 150 | intersection: (left, right) => z.intersection(left, right), |
| 151 | |
| 152 | optional: schema => schema.optional(), |
| 153 | nullable: schema => schema.nullable(), |
| 154 | withDefault: (schema, value) => schema.default(value), |
| 155 | readonly: schema => schema.readonly(), |
| 156 | decorate: (schema, decorations: Decorations) => |
| 157 | decorations.description === undefined ? schema : schema.describe(decorations.description), |
| 158 | |
| 159 | refine: (schema, test, message) => schema.refine(test, { message }), |
| 160 | superRefine: (schema, check) => schema.superRefine((value, ctx) => check(value, sink(ctx))), |
| 161 | rewrite: (schema, fn) => schema.transform((value, ctx) => fn(value, sink(ctx))), |
| 162 | |
| 163 | run, |
| 164 | attachGuard, |
| 165 | }; |