@devries-cameron20 / composio Mirror · read-only / commits / 4ddfafcad
Fork 0

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 23, 01:45 UTC

Fix JSON schema transformation issues with jsonSchemaToZodSchema (#28)

* Fix transformation issues * Add changeset * Fix types * Fix types * Add changeset

Musthaq Ahamad committed Jun 5, 2025 at 15:11 UTC 4ddfafcadb6baf255fd3cfa123e665ba839c747f
43 files changed +1702 -404
.changeset/thirty-rockets-pay.md new
+13
@@ -0,0 +1,13 @@
1 +---
2 +'@composio/langchain': patch
3 +'@composio/json-schema-to-zod': patch
4 +'@composio/core': patch
5 +'@composio/anthropic': patch
6 +'@composio/cloudflare': patch
7 +'@composio/google': patch
8 +'@composio/mastra': patch
9 +'@composio/openai': patch
10 +'@composio/vercel': patch
11 +---
12 +
13 +Add json schema to zod schema
examples/mastra/src/index.ts
+8 -2
@@ -27,11 +27,17 @@ const composio = new Composio({
27 * Attach beforeExecute and afterExecute hooks to the tools for logging
28 */
29 const tools = await composio.tools.get('default', 'HACKERNEWS_GET_USER', {
30 - beforeExecute: (toolkitSlug, toolSlug, input) => {
30 + modifySchema: (toolSlug, toolkitSlug, schema) => {
31 + console.log(
32 + `🔄 Modifying schema for tool ${toolSlug}/${toolkitSlug} with schema ${JSON.stringify(schema)}`
33 + );
34 + return schema;
35 + },
36 + beforeExecute: (toolSlug, toolkitSlug, input) => {
37 console.log(`🔄 Executing tool ${toolSlug}/${toolkitSlug} with input ${JSON.stringify(input)}`);
38 return input;
39 },
34 - afterExecute: (toolkitSlug, toolSlug, output) => {
40 + afterExecute: (toolSlug, toolkitSlug, output) => {
41 console.log(
42 `✅ Tool ${toolSlug}/${toolkitSlug} executed successfully with output ${JSON.stringify(output)}`
43 );
examples/openai/package.json
+2 -1
@@ -18,7 +18,8 @@
18 "dependencies": {
19 "@composio/core": "workspace:*",
20 "dotenv": "^16.4.1",
21 - "openai": "^4.94.0"
21 + "openai": "^4.94.0",
22 + "zod": "^3.24.2"
23 },
24 "devDependencies": {
25 "@types/bun": "^1.2.9",
package.json
+1
@@ -5,6 +5,7 @@
5 "description": "",
6 "workspaces": [
7 "packages/core",
8 + "packages/json-schema-to-zod",
9 "packages/providers/*"
10 ],
11 "scripts": {
packages/core/package.json
+1
@@ -37,6 +37,7 @@
37 },
38 "dependencies": {
39 "@composio/client": "0.1.0-alpha.16",
40 + "@composio/json-schema-to-zod": "workspace:^",
41 "chalk": "^5.4.1",
42 "openai": "^4.94.0",
43 "pusher-js": "^8.4.0",
packages/core/src/errors/ValidationErrors.ts
+13 -1
@@ -8,6 +8,7 @@ import { ComposioError, ComposioErrorOptions } from './ComposioError';
8 */
9 export const ValidationErrorCodes = {
10 VALIDATION_ERROR: 'VALIDATION_ERROR',
11 + JSON_SCHEMA_TO_ZOD_ERROR: 'JSON_SCHEMA_TO_ZOD_ERROR',
12 } as const;
13
14 export class ValidationError extends ComposioError {
@@ -46,7 +47,6 @@ export class ValidationError extends ComposioError {
47 // Create a friendly error message for users
48 const userFriendlyMessage = this.generateUserFriendlyMessage();
49 this.message = `${message}: ${userFriendlyMessage}`;
49 -
50 }
51
52 private generateUserFriendlyMessage(): string {
@@ -67,3 +67,15 @@ export class ValidationError extends ComposioError {
67 return 'Please check your input parameters';
68 }
69 }
70 +
71 +export class JsonSchemaToZodError extends ComposioError {
72 + constructor(
73 + message: string = 'Failed to convert JSON schema to Zod schema',
74 + options: ComposioErrorOptions = {}
75 + ) {
76 + super(message, {
77 + ...options,
78 + code: options.code || ValidationErrorCodes.JSON_SCHEMA_TO_ZOD_ERROR,
79 + });
80 + }
81 +}
packages/core/src/types/modifiers.types.ts
+8 -4
@@ -52,7 +52,7 @@ export type beforeExecuteModifier = (
52 toolSlug: string,
53 toolkitSlug: string,
54 toolExecuteParams: ToolExecuteParams
55 -) => Promise<ToolExecuteParams>;
55 +) => Promise<ToolExecuteParams> | ToolExecuteParams;
56
57 /**
58 * Modifier for altering the tool execution response after execution completes.
@@ -108,7 +108,7 @@ export type afterExecuteModifier = (
108 toolSlug: string,
109 toolkitSlug: string,
110 toolExecuteResponse: ToolExecuteResponse
111 -) => Promise<ToolExecuteResponse>;
111 +) => Promise<ToolExecuteResponse> | ToolExecuteResponse;
112
113 /**
114 * Modifier for altering the tool schema before it's exposed to consumers.
@@ -309,5 +309,9 @@ export type AgenticToolOptions = ToolOptions & ExecuteToolModifiers;
309 * });
310 * ```
311 */
312 -export type ProviderOptions<T extends BaseComposioProvider<unknown, unknown>> =
313 - T extends BaseAgenticProvider<unknown, unknown> ? AgenticToolOptions : ToolOptions;
312 +export type ProviderOptions<TProvider> =
313 + TProvider extends BaseComposioProvider<infer TToolCollection, infer TTool>
314 + ? TProvider extends BaseAgenticProvider<TToolCollection, TTool>
315 + ? AgenticToolOptions
316 + : ToolOptions
317 + : never;
packages/core/src/types/tool.types.ts
+1 -1
@@ -42,7 +42,7 @@ const ParametersSchema = z.object({
42 required: z.array(z.string()).optional(),
43 title: z.string().optional(),
44 description: z.string().optional(),
45 - additionalProperties: z.boolean().optional(),
45 + additionalProperties: z.boolean().default(false).optional(),
46 });
47
48 /**
packages/core/src/utils/jsonSchema.ts
+11 -214
@@ -1,150 +1,14 @@
1 import { z } from 'zod';
2 -
3 -type SchemaTypeToTsType = {
4 - [key: string]: unknown;
5 -};
6 -
7 -const PYDANTIC_TYPE_TO_TS_TYPE: SchemaTypeToTsType = {
8 - string: String,
9 - integer: Number,
10 - number: Number,
11 - boolean: Boolean,
12 - null: null,
13 -};
14 -
15 -export function jsonSchemaToTsType(jsonSchema: Record<string, unknown>): unknown {
16 - if (!jsonSchema.type) {
17 - jsonSchema.type = 'string';
18 - }
19 - const type = jsonSchema.type as string;
20 -
21 - if (type === 'array') {
22 - const itemsSchema = jsonSchema.items;
23 - if (itemsSchema) {
24 - const ItemType = jsonSchemaToTsType(itemsSchema as Record<string, unknown>);
25 - return ItemType;
26 - }
27 - return Array;
28 - }
29 -
30 - if (type === 'object') {
31 - const properties = jsonSchema.properties;
32 - if (properties) {
33 - const nestedModel = jsonSchemaToZodSchema(jsonSchema);
34 - return nestedModel;
35 - }
36 - return Object;
37 - }
38 -
39 - const tsType = PYDANTIC_TYPE_TO_TS_TYPE[type];
40 - if (tsType !== undefined) {
41 - return tsType;
42 - }
43 -
44 - throw new Error(`Unsupported JSON schema type: ${type}`);
45 -}
46 -
47 -export function jsonSchemaToTsField(
48 - name: string,
49 - jsonSchema: Record<string, unknown>,
50 - required: string[]
51 -): [unknown, Record<string, unknown>] {
52 - const description = jsonSchema.description;
53 - const examples = jsonSchema.examples || [];
54 - return [
55 - jsonSchemaToTsType(jsonSchema),
56 - {
57 - description: description,
58 - examples: examples,
59 - required: required.includes(name),
60 - default: required.includes(name) ? undefined : null,
61 - },
62 - ];
63 -}
64 -
65 -function jsonSchemaPropertiesToTSTypes(value: {
66 - type: string;
67 - description?: string;
68 - examples?: string[];
69 - items?: Record<string, unknown>;
70 -}): z.ZodTypeAny {
71 - if (!value.type) {
72 - return z.object({});
73 - }
74 -
75 - let zodType;
76 - switch (value.type) {
77 - case 'string':
78 - zodType = z
79 - .string()
80 - .describe(
81 - (value.description || '') +
82 - (value.examples ? `\nExamples: ${value.examples.join(', ')}` : '')
83 - );
84 - break;
85 - case 'number':
86 - zodType = z
87 - .number()
88 - .describe(
89 - (value.description || '') +
90 - (value.examples ? `\nExamples: ${value.examples.join(', ')}` : '')
91 - );
92 - break;
93 - case 'integer':
94 - zodType = z
95 - .number()
96 - .int()
97 - .describe(
98 - (value.description || '') +
99 - (value.examples ? `\nExamples: ${value.examples.join(', ')}` : '')
100 - );
101 - break;
102 - case 'boolean':
103 - zodType = z
104 - .boolean()
105 - .describe(
106 - (value.description || '') +
107 - (value.examples ? `\nExamples: ${value.examples.join(', ')}` : '')
108 - );
109 - break;
110 - case 'array':
111 - zodType = z
112 - .array(
113 - jsonSchemaPropertiesToTSTypes(
114 - value.items as {
115 - type: string;
116 - description?: string;
117 - examples?: string[];
118 - items?: Record<string, unknown>;
119 - }
120 - )
121 - )
122 - .describe(
123 - (value.description || '') +
124 - (value.examples ? `\nExamples: ${value.examples.join(', ')}` : '')
125 - );
126 - break;
127 - case 'object':
128 - zodType = jsonSchemaToZodSchema(value).describe(
129 - (value.description || '') +
130 - (value.examples ? `\nExamples: ${value.examples.join(', ')}` : '')
131 - );
132 - break;
133 - case 'null':
134 - zodType = z.null().describe(value.description || '');
135 - break;
136 - default:
137 - throw new Error(`Unsupported JSON schema type: ${value.type}`);
138 - }
139 -
140 - return zodType;
141 -}
2 +import { JsonSchemaToZodError } from '../errors';
3 +import { jsonSchemaToZod } from '@composio/json-schema-to-zod';
4
5 /**
6 * Convert a JSON schema to a Zod schema
7 * @param jsonSchema - The JSON schema to convert
8 * @returns The Zod schema
9 *
10 + * @throws {JsonSchemaToZodError} If the JSON schema is invalid
11 + *
12 * @example
13 * ```ts
14 * const zodSchema = jsonSchemaToZodSchema({
@@ -160,79 +24,12 @@ function jsonSchemaPropertiesToTSTypes(value: {
24 export function jsonSchemaToZodSchema(
25 jsonSchema: Record<string, unknown>
26 ): z.ZodObject<Record<string, z.ZodTypeAny>> {
163 - const properties = jsonSchema.properties as Record<string, unknown>;
164 - const requiredFields = (jsonSchema.required as string[]) || [];
165 - if (!properties) {
166 - return z.object({});
167 - }
168 -
169 - const zodSchema: Record<string, z.ZodTypeAny> = {};
170 - for (const [key, _] of Object.entries(properties)) {
171 - const value = _ as Record<string, unknown>;
172 - let zodType;
173 - if (value.anyOf) {
174 - const anyOfTypes = (value.anyOf as Record<string, unknown>[]).map(schema =>
175 - jsonSchemaPropertiesToTSTypes(
176 - schema as {
177 - type: string;
178 - description?: string;
179 - examples?: string[];
180 - items?: Record<string, unknown>;
181 - }
182 - )
183 - );
184 - zodType = z
185 - .union(anyOfTypes as [z.ZodTypeAny, z.ZodTypeAny, ...z.ZodTypeAny[]])
186 - .describe(
187 - ((value.description as string) || '') +
188 - (value.examples ? `\nExamples: ${(value.examples as string[]).join(', ')}` : '')
189 - );
190 - } else if (value.allOf) {
191 - const allOfTypes = (value.allOf as Record<string, unknown>[]).map(schema =>
192 - jsonSchemaPropertiesToTSTypes(
193 - schema as {
194 - type: string;
195 - description?: string;
196 - examples?: string[];
197 - items?: Record<string, unknown>;
198 - }
199 - )
200 - );
201 - zodType = z
202 - .intersection(
203 - allOfTypes[0],
204 - allOfTypes
205 - .slice(1)
206 - .reduce((acc: z.ZodTypeAny, schema: z.ZodTypeAny) => acc.and(schema), allOfTypes[0])
207 - )
208 - .describe(
209 - ((value.description as string) || '') +
210 - (value.examples ? `\nExamples: ${(value.examples as string[]).join(', ')}` : '')
211 - );
212 - } else {
213 - if (!value.type) {
214 - value.type = 'string';
215 - }
216 - zodType = jsonSchemaPropertiesToTSTypes(
217 - value as {
218 - type: string;
219 - description?: string;
220 - examples?: string[];
221 - items?: Record<string, unknown>;
222 - }
223 - );
224 - }
225 -
226 - if (value.description) {
227 - zodType = zodType.describe(value.description as string);
228 - }
229 -
230 - if (requiredFields.includes(key)) {
231 - zodSchema[key] = zodType;
232 - } else {
233 - zodSchema[key] = zodType.optional();
234 - }
27 + try {
28 + // Convert the JSON schema properties to Zod schema
29 + return jsonSchemaToZod(jsonSchema);
30 + } catch (error) {
31 + throw new JsonSchemaToZodError('Failed to convert JSON Schema to Zod Schema', {
32 + cause: error,
33 + });
34 }
236 -
237 - return z.object(zodSchema);
35 }
packages/core/test/utils/mocks/data.mock.ts
+4
@@ -13,6 +13,7 @@ export const toolMocks = {
13 description: 'The search query',
14 },
15 },
16 + additionalProperties: false,
17 },
18 output_parameters: {
19 type: 'object',
@@ -24,6 +25,7 @@ export const toolMocks = {
25 },
26 },
27 },
28 + additionalProperties: false,
29 },
30 toolkit: {
31 logo: 'https://example.com/logo.png',
@@ -75,6 +77,7 @@ export const toolMocks = {
77 description: 'The search query',
78 },
79 },
80 + additionalProperties: false,
81 },
82 outputParameters: {
83 type: 'object',
@@ -86,6 +89,7 @@ export const toolMocks = {
89 },
90 },
91 },
92 + additionalProperties: false,
93 },
94 },
95 // transformed response from the sdk
packages/json-schema-to-zod/README.md new
+34
@@ -0,0 +1,34 @@
1 +# Json-Schema-to-Zod
2 +
3 +A package to convert JSON schema (draft 4+) objects into Zod schemas in the form of Zod objects at runtime.
4 +
5 +## Installation
6 +
7 +```sh
8 +npm install @composio/json-schema-to-zod
9 +```
10 +
11 +### Simple example
12 +
13 +```typescript
14 +import { jsonSchemaToZod } from 'json-schema-to-zod';
15 +
16 +const jsonSchema = {
17 + type: 'object',
18 + properties: {
19 + hello: {
20 + type: 'string',
21 + },
22 + },
23 +};
24 +
25 +const zodSchema = jsonSchemaToZod(myObject);
26 +```
27 +
28 +### Overriding a parser
29 +
30 +You can pass a function to the `overrideParser` option, which represents a function that receives the current schema node and the reference object, and should return a zod object when it wants to replace a default output. If the default output should be used for the node just return undefined.
31 +
32 +## Acknowledgements
33 +
34 +This is a fork of [`json-schema-to-zod`](https://github.com/StefanTerdell/json-schema-to-zod).
packages/json-schema-to-zod/eslint.config.mjs new
+6
@@ -0,0 +1,6 @@
1 +module.exports = {
2 + extends: ['../../.eslintrc.cjs'],
3 + // parserOptions: {
4 + // project: ['./tsconfig.json'],
5 + // },
6 +}
packages/json-schema-to-zod/package.json new
+39
@@ -0,0 +1,39 @@
1 +{
2 + "name": "@composio/json-schema-to-zod",
3 + "version": "0.1.0",
4 + "description": "",
5 + "main": "src/index.ts",
6 + "type": "module",
7 + "publishConfig": {
8 + "access": "public",
9 + "main": "dist/index.js",
10 + "types": "dist/index.d.ts"
11 + },
12 + "exports": {
13 + ".": {
14 + "import": "./dist/index.js",
15 + "types": "./dist/index.d.ts",
16 + "require": "./dist/index.cjs"
17 + }
18 + },
19 + "files": [
20 + "README.md",
21 + "dist"
22 + ],
23 + "scripts": {
24 + "build": "tsup",
25 + "test": "vitest run"
26 + },
27 + "keywords": [],
28 + "author": "",
29 + "license": "ISC",
30 + "packageManager": "pnpm@10.8.0",
31 + "devDependencies": {
32 + "tsup": "^8.4.0",
33 + "typescript": "^5.8.3",
34 + "vitest": "^3.1.4"
35 + },
36 + "dependencies": {
37 + "zod": "^3.24.2"
38 + }
39 +}
packages/json-schema-to-zod/src/index.ts new
+2
@@ -0,0 +1,2 @@
1 +export type * from './types';
2 +export { jsonSchemaToZod } from './json-schema-to-zod';
packages/json-schema-to-zod/src/json-schema-to-zod.ts new
+15
@@ -0,0 +1,15 @@
1 +import type { z } from 'zod';
2 +
3 +import { parseSchema } from './parsers/parse-schema';
4 +import type { JsonSchemaToZodOptions, JsonSchema } from './types';
5 +
6 +export const jsonSchemaToZod = <T extends z.ZodTypeAny = z.ZodTypeAny>(
7 + schema: JsonSchema,
8 + options: JsonSchemaToZodOptions = {},
9 +): T => {
10 + return parseSchema(schema, {
11 + path: [],
12 + seen: new Map(),
13 + ...options,
14 + }) as T;
15 +};
packages/json-schema-to-zod/src/parsers/parse-all-of.ts new
+46
@@ -0,0 +1,46 @@
1 +import { z } from 'zod';
2 +
3 +import { parseSchema } from './parse-schema';
4 +import type { JsonSchemaObject, JsonSchema, Refs } from '../types';
5 +import { half } from '../utils/half';
6 +
7 +const originalIndex = Symbol('Original index');
8 +
9 +const ensureOriginalIndex = (arr: JsonSchema[]) => {
10 + const newArr = [];
11 +
12 + for (let i = 0; i < arr.length; i++) {
13 + const item = arr[i];
14 + if (typeof item === 'boolean') {
15 + newArr.push(item ? { [originalIndex]: i } : { [originalIndex]: i, not: {} });
16 + } else if (originalIndex in item) {
17 + return arr;
18 + } else {
19 + newArr.push({ ...item, [originalIndex]: i });
20 + }
21 + }
22 +
23 + return newArr;
24 +};
25 +
26 +export function parseAllOf(
27 + jsonSchema: JsonSchemaObject & { allOf: JsonSchema[] },
28 + refs: Refs,
29 +): z.ZodTypeAny {
30 + if (jsonSchema.allOf.length === 0) {
31 + return z.never();
32 + }
33 +
34 + if (jsonSchema.allOf.length === 1) {
35 + const item = jsonSchema.allOf[0];
36 +
37 + return parseSchema(item, {
38 + ...refs,
39 + path: [...refs.path, 'allOf', (item as never)[originalIndex]],
40 + });
41 + }
42 +
43 + const [left, right] = half(ensureOriginalIndex(jsonSchema.allOf));
44 +
45 + return z.intersection(parseAllOf({ allOf: left }, refs), parseAllOf({ allOf: right }, refs));
46 +}
packages/json-schema-to-zod/src/parsers/parse-any-of.ts new
+19
@@ -0,0 +1,19 @@
1 +import { z } from 'zod';
2 +
3 +import { parseSchema } from './parse-schema';
4 +import type { JsonSchemaObject, JsonSchema, Refs } from '../types';
5 +
6 +export const parseAnyOf = (jsonSchema: JsonSchemaObject & { anyOf: JsonSchema[] }, refs: Refs) => {
7 + return jsonSchema.anyOf.length
8 + ? jsonSchema.anyOf.length === 1
9 + ? parseSchema(jsonSchema.anyOf[0], {
10 + ...refs,
11 + path: [...refs.path, 'anyOf', 0],
12 + })
13 + : z.union(
14 + jsonSchema.anyOf.map((schema, i) =>
15 + parseSchema(schema, { ...refs, path: [...refs.path, 'anyOf', i] }),
16 + ) as [z.ZodTypeAny, z.ZodTypeAny],
17 + )
18 + : z.any();
19 +};
packages/json-schema-to-zod/src/parsers/parse-array.ts new
+34
@@ -0,0 +1,34 @@
1 +import { z } from 'zod';
2 +
3 +import { parseSchema } from './parse-schema';
4 +import type { JsonSchemaObject, Refs } from '../types';
5 +import { extendSchemaWithMessage } from '../utils/extend-schema';
6 +
7 +export const parseArray = (jsonSchema: JsonSchemaObject & { type: 'array' }, refs: Refs) => {
8 + if (Array.isArray(jsonSchema.items)) {
9 + return z.tuple(
10 + jsonSchema.items.map((v, i) =>
11 + parseSchema(v, { ...refs, path: [...refs.path, 'items', i] }),
12 + ) as [z.ZodTypeAny],
13 + );
14 + }
15 +
16 + let zodSchema = !jsonSchema.items
17 + ? z.array(z.any())
18 + : z.array(parseSchema(jsonSchema.items, { ...refs, path: [...refs.path, 'items'] }));
19 +
20 + zodSchema = extendSchemaWithMessage(
21 + zodSchema,
22 + jsonSchema,
23 + 'minItems',
24 + (zs, minItems, errorMessage) => zs.min(minItems, errorMessage),
25 + );
26 + zodSchema = extendSchemaWithMessage(
27 + zodSchema,
28 + jsonSchema,
29 + 'maxItems',
30 + (zs, maxItems, errorMessage) => zs.max(maxItems, errorMessage),
31 + );
32 +
33 + return zodSchema;
34 +};
packages/json-schema-to-zod/src/parsers/parse-boolean.ts new
+7
@@ -0,0 +1,7 @@
1 +import { z } from 'zod';
2 +
3 +import type { JsonSchemaObject } from '../types';
4 +
5 +export const parseBoolean = (_jsonSchema: JsonSchemaObject & { type: 'boolean' }) => {
6 + return z.boolean();
7 +};
packages/json-schema-to-zod/src/parsers/parse-const.ts new
+7
@@ -0,0 +1,7 @@
1 +import { z } from 'zod';
2 +
3 +import type { JsonSchemaObject, Serializable } from '../types';
4 +
5 +export const parseConst = (jsonSchema: JsonSchemaObject & { const: Serializable }) => {
6 + return z.literal(jsonSchema.const as z.Primitive);
7 +};
packages/json-schema-to-zod/src/parsers/parse-default.ts new
+7
@@ -0,0 +1,7 @@
1 +import { z } from 'zod';
2 +
3 +import type { JsonSchemaObject } from '../types';
4 +
5 +export const parseDefault = (_jsonSchema: JsonSchemaObject) => {
6 + return z.any();
7 +};
packages/json-schema-to-zod/src/parsers/parse-enum.ts new
+25
@@ -0,0 +1,25 @@
1 +import { z } from 'zod';
2 +
3 +import type { JsonSchemaObject, Serializable } from '../types';
4 +
5 +export const parseEnum = (jsonSchema: JsonSchemaObject & { enum: Serializable[] }) => {
6 + if (jsonSchema.enum.length === 0) {
7 + return z.never();
8 + }
9 +
10 + if (jsonSchema.enum.length === 1) {
11 + // union does not work when there is only one element
12 + return z.literal(jsonSchema.enum[0] as z.Primitive);
13 + }
14 +
15 + if (jsonSchema.enum.every((x) => typeof x === 'string')) {
16 + return z.enum(jsonSchema.enum as [string]);
17 + }
18 +
19 + return z.union(
20 + jsonSchema.enum.map((x) => z.literal(x as z.Primitive)) as unknown as [
21 + z.ZodTypeAny,
22 + z.ZodTypeAny,
23 + ],
24 + );
25 +};
packages/json-schema-to-zod/src/parsers/parse-if-then-else.ts new
+31
@@ -0,0 +1,31 @@
1 +import { z } from 'zod';
2 +
3 +import { parseSchema } from './parse-schema';
4 +import type { JsonSchemaObject, JsonSchema, Refs } from '../types';
5 +
6 +export const parseIfThenElse = (
7 + jsonSchema: JsonSchemaObject & {
8 + if: JsonSchema;
9 + then: JsonSchema;
10 + else: JsonSchema;
11 + },
12 + refs: Refs
13 +) => {
14 + const $if = parseSchema(jsonSchema.if, { ...refs, path: [...refs.path, 'if'] });
15 + const $then = parseSchema(jsonSchema.then, {
16 + ...refs,
17 + path: [...refs.path, 'then'],
18 + });
19 + const $else = parseSchema(jsonSchema.else, {
20 + ...refs,
21 + path: [...refs.path, 'else'],
22 + });
23 +
24 + return z.union([$then, $else]).superRefine((value, ctx) => {
25 + const result = $if.safeParse(value).success ? $then.safeParse(value) : $else.safeParse(value);
26 +
27 + if (!result.success) {
28 + result.error.errors.forEach(error => ctx.addIssue(error));
29 + }
30 + });
31 +};
packages/json-schema-to-zod/src/parsers/parse-multiple-type.ts new
+16
@@ -0,0 +1,16 @@
1 +import { z } from 'zod';
2 +
3 +import { parseSchema } from './parse-schema';
4 +import type { JsonSchema, JsonSchemaObject, Refs } from '../types';
5 +
6 +export const parseMultipleType = (
7 + jsonSchema: JsonSchemaObject & { type: string[] },
8 + refs: Refs,
9 +) => {
10 + return z.union(
11 + jsonSchema.type.map((type) => parseSchema({ ...jsonSchema, type } as JsonSchema, refs)) as [
12 + z.ZodTypeAny,
13 + z.ZodTypeAny,
14 + ],
15 + );
16 +};
packages/json-schema-to-zod/src/parsers/parse-not.ts new
+15
@@ -0,0 +1,15 @@
1 +import { z } from 'zod';
2 +
3 +import { parseSchema } from './parse-schema';
4 +import type { JsonSchemaObject, JsonSchema, Refs } from '../types';
5 +
6 +export const parseNot = (jsonSchema: JsonSchemaObject & { not: JsonSchema }, refs: Refs) => {
7 + return z.any().refine(
8 + (value) =>
9 + !parseSchema(jsonSchema.not, {
10 + ...refs,
11 + path: [...refs.path, 'not'],
12 + }).safeParse(value).success,
13 + 'Invalid input: Should NOT be valid against schema',
14 + );
15 +};
packages/json-schema-to-zod/src/parsers/parse-null.ts new
+7
@@ -0,0 +1,7 @@
1 +import { z } from 'zod';
2 +
3 +import type { JsonSchemaObject } from '../types';
4 +
5 +export const parseNull = (_jsonSchema: JsonSchemaObject & { type: 'null' }) => {
6 + return z.null();
7 +};
packages/json-schema-to-zod/src/parsers/parse-nullable.ts new
+10
@@ -0,0 +1,10 @@
1 +import { parseSchema } from './parse-schema';
2 +import type { JsonSchemaObject, Refs } from '../types';
3 +import { omit } from '../utils/omit';
4 +
5 +/**
6 + * For compatibility with open api 3.0 nullable
7 + */
8 +export const parseNullable = (jsonSchema: JsonSchemaObject & { nullable: true }, refs: Refs) => {
9 + return parseSchema(omit(jsonSchema, 'nullable'), refs, true).nullable();
10 +};
packages/json-schema-to-zod/src/parsers/parse-number.ts new
+88
@@ -0,0 +1,88 @@
1 +import { z } from 'zod';
2 +
3 +import type { JsonSchemaObject } from '../types';
4 +import { extendSchemaWithMessage } from '../utils/extend-schema';
5 +
6 +export const parseNumber = (jsonSchema: JsonSchemaObject & { type: 'number' | 'integer' }) => {
7 + let zodSchema = z.number();
8 +
9 + let isInteger = false;
10 + if (jsonSchema.type === 'integer') {
11 + isInteger = true;
12 + zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, 'type', (zs, _, errorMsg) =>
13 + zs.int(errorMsg),
14 + );
15 + } else if (jsonSchema.format === 'int64') {
16 + isInteger = true;
17 + zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, 'format', (zs, _, errorMsg) =>
18 + zs.int(errorMsg),
19 + );
20 + }
21 +
22 + zodSchema = extendSchemaWithMessage(
23 + zodSchema,
24 + jsonSchema,
25 + 'multipleOf',
26 + (zs, multipleOf, errorMsg) => {
27 + if (multipleOf === 1) {
28 + if (isInteger) return zs;
29 +
30 + return zs.int(errorMsg);
31 + }
32 +
33 + return zs.multipleOf(multipleOf, errorMsg);
34 + },
35 + );
36 +
37 + if (typeof jsonSchema.minimum === 'number') {
38 + if (jsonSchema.exclusiveMinimum === true) {
39 + zodSchema = extendSchemaWithMessage(
40 + zodSchema,
41 + jsonSchema,
42 + 'minimum',
43 + (zs, minimum, errorMsg) => zs.gt(minimum, errorMsg),
44 + );
45 + } else {
46 + zodSchema = extendSchemaWithMessage(
47 + zodSchema,
48 + jsonSchema,
49 + 'minimum',
50 + (zs, minimum, errorMsg) => zs.gte(minimum, errorMsg),
51 + );
52 + }
53 + } else if (typeof jsonSchema.exclusiveMinimum === 'number') {
54 + zodSchema = extendSchemaWithMessage(
55 + zodSchema,
56 + jsonSchema,
57 + 'exclusiveMinimum',
58 + (zs, exclusiveMinimum, errorMsg) => zs.gt(exclusiveMinimum as number, errorMsg),
59 + );
60 + }
61 +
62 + if (typeof jsonSchema.maximum === 'number') {
63 + if (jsonSchema.exclusiveMaximum === true) {
64 + zodSchema = extendSchemaWithMessage(
65 + zodSchema,
66 + jsonSchema,
67 + 'maximum',
68 + (zs, maximum, errorMsg) => zs.lt(maximum, errorMsg),
69 + );
70 + } else {
71 + zodSchema = extendSchemaWithMessage(
72 + zodSchema,
73 + jsonSchema,
74 + 'maximum',
75 + (zs, maximum, errorMsg) => zs.lte(maximum, errorMsg),
76 + );
77 + }
78 + } else if (typeof jsonSchema.exclusiveMaximum === 'number') {
79 + zodSchema = extendSchemaWithMessage(
80 + zodSchema,
81 + jsonSchema,
82 + 'exclusiveMaximum',
83 + (zs, exclusiveMaximum, errorMsg) => zs.lt(exclusiveMaximum as number, errorMsg),
84 + );
85 + }
86 +
87 + return zodSchema;
88 +};
packages/json-schema-to-zod/src/parsers/parse-object.ts new
+227
@@ -0,0 +1,227 @@
1 +import * as z from 'zod';
2 +
3 +import { parseAllOf } from './parse-all-of';
4 +import { parseAnyOf } from './parse-any-of';
5 +import { parseOneOf } from './parse-one-of';
6 +import { parseSchema } from './parse-schema';
7 +import type { JsonSchemaObject, Refs } from '../types';
8 +import { its } from '../utils/its';
9 +
10 +function parseObjectProperties(objectSchema: JsonSchemaObject & { type: 'object' }, refs: Refs) {
11 + if (!objectSchema.properties) {
12 + return undefined;
13 + }
14 +
15 + const propertyKeys = Object.keys(objectSchema.properties);
16 + if (propertyKeys.length === 0) {
17 + return z.object({});
18 + }
19 +
20 + const properties: Record<string, z.ZodTypeAny> = {};
21 +
22 + for (const key of propertyKeys) {
23 + const propJsonSchema = objectSchema.properties[key];
24 +
25 + const propZodSchema = parseSchema(propJsonSchema, {
26 + ...refs,
27 + path: [...refs.path, 'properties', key],
28 + });
29 +
30 + const hasDefault = typeof propJsonSchema === 'object' && propJsonSchema.default !== undefined;
31 + const required = Array.isArray(objectSchema.required)
32 + ? objectSchema.required.includes(key)
33 + : typeof propJsonSchema === 'object' && propJsonSchema.required === true;
34 +
35 + // If property has a default value or is an object with nested defaults,
36 + // we should include it in the schema even if it's not required
37 + const isOptional =
38 + !hasDefault &&
39 + !required &&
40 + !(
41 + typeof propJsonSchema === 'object' &&
42 + propJsonSchema.type === 'object' &&
43 + propJsonSchema.properties
44 + );
45 +
46 + properties[key] = isOptional ? propZodSchema.optional() : propZodSchema;
47 + }
48 +
49 + return z.object(properties);
50 +}
51 +
52 +export function parseObject(
53 + objectSchema: JsonSchemaObject & { type: 'object' },
54 + refs: Refs
55 +): z.ZodTypeAny {
56 + const hasPatternProperties = Object.keys(objectSchema.patternProperties ?? {}).length > 0;
57 +
58 + const propertiesSchema:
59 + | z.ZodObject<Record<string, z.ZodTypeAny>, 'strip', z.ZodTypeAny>
60 + | undefined = parseObjectProperties(objectSchema, refs);
61 + let zodSchema: z.ZodTypeAny | undefined = propertiesSchema;
62 +
63 + const additionalProperties =
64 + objectSchema.additionalProperties !== undefined
65 + ? parseSchema(objectSchema.additionalProperties, {
66 + ...refs,
67 + path: [...refs.path, 'additionalProperties'],
68 + })
69 + : undefined;
70 +
71 + if (objectSchema.patternProperties) {
72 + const parsedPatternProperties = Object.fromEntries(
73 + Object.entries(objectSchema.patternProperties).map(([key, value]) => {
74 + return [
75 + key,
76 + parseSchema(value, {
77 + ...refs,
78 + path: [...refs.path, 'patternProperties', key],
79 + }),
80 + ];
81 + })
82 + );
83 + const patternPropertyValues = Object.values(parsedPatternProperties);
84 +
85 + if (propertiesSchema) {
86 + if (additionalProperties) {
87 + zodSchema = propertiesSchema.catchall(
88 + z.union([...patternPropertyValues, additionalProperties] as [z.ZodTypeAny, z.ZodTypeAny])
89 + );
90 + } else if (Object.keys(parsedPatternProperties).length > 1) {
91 + zodSchema = propertiesSchema.catchall(
92 + z.union(patternPropertyValues as [z.ZodTypeAny, z.ZodTypeAny])
93 + );
94 + } else {
95 + zodSchema = propertiesSchema.catchall(patternPropertyValues[0]);
96 + }
97 + } else {
98 + if (additionalProperties) {
99 + zodSchema = z.record(
100 + z.union([...patternPropertyValues, additionalProperties] as [z.ZodTypeAny, z.ZodTypeAny])
101 + );
102 + } else if (patternPropertyValues.length > 1) {
103 + zodSchema = z.record(z.union(patternPropertyValues as [z.ZodTypeAny, z.ZodTypeAny]));
104 + } else {
105 + zodSchema = z.record(patternPropertyValues[0]);
106 + }
107 + }
108 +
109 + const objectPropertyKeys = new Set(Object.keys(objectSchema.properties ?? {}));
110 + zodSchema = zodSchema.superRefine((value: Record<string, unknown>, ctx) => {
111 + for (const key in value) {
112 + let wasMatched = objectPropertyKeys.has(key);
113 +
114 + for (const patternPropertyKey in objectSchema.patternProperties) {
115 + const regex = new RegExp(patternPropertyKey);
116 + if (key.match(regex)) {
117 + wasMatched = true;
118 + const result = parsedPatternProperties[patternPropertyKey].safeParse(value[key]);
119 + if (!result.success) {
120 + ctx.addIssue({
121 + path: [...ctx.path, key],
122 + code: 'custom',
123 + message: `Invalid input: Key matching regex /${key}/ must match schema`,
124 + params: {
125 + issues: result.error.issues,
126 + },
127 + });
128 + }
129 + }
130 + }
131 +
132 + if (!wasMatched && additionalProperties) {
133 + const result = additionalProperties.safeParse(value[key]);
134 + if (!result.success) {
135 + ctx.addIssue({
136 + path: [...ctx.path, key],
137 + code: 'custom',
138 + message: 'Invalid input: must match catchall schema',
139 + params: {
140 + issues: result.error.issues,
141 + },
142 + });
143 + }
144 + }
145 + }
146 + });
147 + }
148 +
149 + let output: z.ZodTypeAny;
150 + if (propertiesSchema) {
151 + if (hasPatternProperties) {
152 + output = zodSchema!;
153 + } else if (additionalProperties) {
154 + if (additionalProperties instanceof z.ZodNever) {
155 + output = propertiesSchema.strict();
156 + } else {
157 + output = propertiesSchema.catchall(additionalProperties);
158 + }
159 + } else {
160 + output = zodSchema!;
161 + }
162 + } else {
163 + if (hasPatternProperties) {
164 + output = zodSchema!;
165 + } else if (additionalProperties) {
166 + output = z.record(additionalProperties);
167 + } else {
168 + output = z.record(z.any());
169 + }
170 + }
171 +
172 + if (its.an.anyOf(objectSchema)) {
173 + output = output.and(
174 + parseAnyOf(
175 + {
176 + ...objectSchema,
177 + anyOf: objectSchema.anyOf.map(x =>
178 + typeof x === 'object' &&
179 + !x.type &&
180 + (x.properties ?? x.additionalProperties ?? x.patternProperties)
181 + ? { ...x, type: 'object' }
182 + : x
183 + ),
184 + },
185 + refs
186 + )
187 + );
188 + }
189 +
190 + if (its.a.oneOf(objectSchema)) {
191 + output = output.and(
192 + parseOneOf(
193 + {
194 + ...objectSchema,
195 + oneOf: objectSchema.oneOf.map(x =>
196 + typeof x === 'object' &&
197 + !x.type &&
198 + (x.properties ?? x.additionalProperties ?? x.patternProperties)
199 + ? { ...x, type: 'object' }
200 + : x
201 + ),
202 + },
203 + refs
204 + )
205 + );
206 + }
207 +
208 + if (its.an.allOf(objectSchema)) {
209 + output = output.and(
210 + parseAllOf(
211 + {
212 + ...objectSchema,
213 + allOf: objectSchema.allOf.map(x =>
214 + typeof x === 'object' &&
215 + !x.type &&
216 + (x.properties ?? x.additionalProperties ?? x.patternProperties)
217 + ? { ...x, type: 'object' }
218 + : x
219 + ),
220 + },
221 + refs
222 + )
223 + );
224 + }
225 +
226 + return output;
227 +}
packages/json-schema-to-zod/src/parsers/parse-one-of.ts new
+41
@@ -0,0 +1,41 @@
1 +import { z } from 'zod';
2 +
3 +import { parseSchema } from './parse-schema';
4 +import type { JsonSchemaObject, JsonSchema, Refs } from '../types';
5 +
6 +export const parseOneOf = (jsonSchema: JsonSchemaObject & { oneOf: JsonSchema[] }, refs: Refs) => {
7 + if (!jsonSchema.oneOf.length) {
8 + return z.any();
9 + }
10 +
11 + if (jsonSchema.oneOf.length === 1) {
12 + return parseSchema(jsonSchema.oneOf[0], {
13 + ...refs,
14 + path: [...refs.path, 'oneOf', 0],
15 + });
16 + }
17 +
18 + return z.any().superRefine((x, ctx) => {
19 + const schemas = jsonSchema.oneOf.map((schema, i) =>
20 + parseSchema(schema, {
21 + ...refs,
22 + path: [...refs.path, 'oneOf', i],
23 + }),
24 + );
25 +
26 + const unionErrors = schemas.reduce<z.ZodError[]>(
27 + (errors, schema) =>
28 + ((result) => (result.error ? [...errors, result.error] : errors))(schema.safeParse(x)),
29 + [],
30 + );
31 +
32 + if (schemas.length - unionErrors.length !== 1) {
33 + ctx.addIssue({
34 + path: ctx.path,
35 + code: 'invalid_union',
36 + unionErrors,
37 + message: 'Invalid input: Should pass single schema',
38 + });
39 + }
40 + });
41 +};
packages/json-schema-to-zod/src/parsers/parse-schema.ts new
+132
@@ -0,0 +1,132 @@
1 +import * as z from 'zod';
2 +
3 +import { parseAllOf } from './parse-all-of';
4 +import { parseAnyOf } from './parse-any-of';
5 +import { parseArray } from './parse-array';
6 +import { parseBoolean } from './parse-boolean';
7 +import { parseConst } from './parse-const';
8 +import { parseDefault } from './parse-default';
9 +import { parseEnum } from './parse-enum';
10 +import { parseIfThenElse } from './parse-if-then-else';
11 +import { parseMultipleType } from './parse-multiple-type';
12 +import { parseNot } from './parse-not';
13 +import { parseNull } from './parse-null';
14 +import { parseNullable } from './parse-nullable';
15 +import { parseNumber } from './parse-number';
16 +import { parseObject } from './parse-object';
17 +import { parseOneOf } from './parse-one-of';
18 +import { parseString } from './parse-string';
19 +import type { ParserSelector, Refs, JsonSchemaObject, JsonSchema } from '../types';
20 +import { its } from '../utils/its';
21 +
22 +const addDescribes = (jsonSchema: JsonSchemaObject, zodSchema: z.ZodTypeAny): z.ZodTypeAny => {
23 + if (jsonSchema.description) {
24 + zodSchema = zodSchema.describe(jsonSchema.description);
25 + } else if (jsonSchema.title) {
26 + zodSchema = zodSchema.describe(jsonSchema.title);
27 + }
28 +
29 + return zodSchema;
30 +};
31 +
32 +const addDefaults = (jsonSchema: JsonSchemaObject, zodSchema: z.ZodTypeAny): z.ZodTypeAny => {
33 + if (jsonSchema.default !== undefined) {
34 + zodSchema = zodSchema.default(jsonSchema.default);
35 + }
36 +
37 + return zodSchema;
38 +};
39 +
40 +const addAnnotations = (jsonSchema: JsonSchemaObject, zodSchema: z.ZodTypeAny): z.ZodTypeAny => {
41 + if (jsonSchema.readOnly) {
42 + zodSchema = zodSchema.readonly();
43 + }
44 +
45 + return zodSchema;
46 +};
47 +
48 +const selectParser: ParserSelector = (schema, refs) => {
49 + if (its.a.nullable(schema)) {
50 + return parseNullable(schema, refs);
51 + } else if (its.an.object(schema)) {
52 + return parseObject(schema, refs);
53 + } else if (its.an.array(schema)) {
54 + return parseArray(schema, refs);
55 + } else if (its.an.anyOf(schema)) {
56 + return parseAnyOf(schema, refs);
57 + } else if (its.an.allOf(schema)) {
58 + return parseAllOf(schema, refs);
59 + } else if (its.a.oneOf(schema)) {
60 + return parseOneOf(schema, refs);
61 + } else if (its.a.not(schema)) {
62 + return parseNot(schema, refs);
63 + } else if (its.an.enum(schema)) {
64 + return parseEnum(schema); //<-- needs to come before primitives
65 + } else if (its.a.const(schema)) {
66 + return parseConst(schema);
67 + } else if (its.a.multipleType(schema)) {
68 + return parseMultipleType(schema, refs);
69 + } else if (its.a.primitive(schema, 'string')) {
70 + return parseString(schema);
71 + } else if (its.a.primitive(schema, 'number') || its.a.primitive(schema, 'integer')) {
72 + return parseNumber(schema);
73 + } else if (its.a.primitive(schema, 'boolean')) {
74 + return parseBoolean(schema);
75 + } else if (its.a.primitive(schema, 'null')) {
76 + return parseNull(schema);
77 + } else if (its.a.conditional(schema)) {
78 + return parseIfThenElse(schema, refs);
79 + } else {
80 + return parseDefault(schema);
81 + }
82 +};
83 +
84 +export const parseSchema = (
85 + jsonSchema: JsonSchema,
86 + refs: Refs = { seen: new Map(), path: [] },
87 + blockMeta?: boolean
88 +): z.ZodTypeAny => {
89 + if (typeof jsonSchema !== 'object') return jsonSchema ? z.any() : z.never();
90 +
91 + if (refs.parserOverride) {
92 + const custom = refs.parserOverride(jsonSchema, refs);
93 +
94 + if (custom instanceof z.ZodType) {
95 + return custom;
96 + }
97 + }
98 +
99 + let seen = refs.seen.get(jsonSchema);
100 +
101 + if (seen) {
102 + if (seen.r !== undefined) {
103 + return seen.r;
104 + }
105 +
106 + if (refs.depth === undefined || seen.n >= refs.depth) {
107 + return z.any();
108 + }
109 +
110 + seen.n += 1;
111 + } else {
112 + seen = { r: undefined, n: 0 };
113 + refs.seen.set(jsonSchema, seen);
114 + }
115 +
116 + let parsedZodSchema = selectParser(jsonSchema, refs);
117 + if (!blockMeta) {
118 + if (!refs.withoutDescribes) {
119 + parsedZodSchema = addDescribes(jsonSchema, parsedZodSchema);
120 + }
121 +
122 + if (!refs.withoutDefaults) {
123 + parsedZodSchema = addDefaults(jsonSchema, parsedZodSchema);
124 + }
125 +
126 + parsedZodSchema = addAnnotations(jsonSchema, parsedZodSchema);
127 + }
128 +
129 + seen.r = parsedZodSchema;
130 +
131 + return parsedZodSchema;
132 +};
packages/json-schema-to-zod/src/parsers/parse-string.ts new
+58
@@ -0,0 +1,58 @@
1 +import { z } from 'zod';
2 +
3 +import type { JsonSchemaObject } from '../types';
4 +import { extendSchemaWithMessage } from '../utils/extend-schema';
5 +
6 +export const parseString = (jsonSchema: JsonSchemaObject & { type: 'string' }) => {
7 + let zodSchema = z.string();
8 +
9 + zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, 'format', (zs, format, errorMsg) => {
10 + switch (format) {
11 + case 'email':
12 + return zs.email(errorMsg);
13 + case 'ip':
14 + return zs.ip(errorMsg);
15 + case 'ipv4':
16 + return zs.ip({ version: 'v4', message: errorMsg });
17 + case 'ipv6':
18 + return zs.ip({ version: 'v6', message: errorMsg });
19 + case 'uri':
20 + return zs.url(errorMsg);
21 + case 'uuid':
22 + return zs.uuid(errorMsg);
23 + case 'date-time':
24 + return zs.datetime({ offset: true, message: errorMsg });
25 + case 'time':
26 + return zs.time(errorMsg);
27 + case 'date':
28 + return zs.date(errorMsg);
29 + case 'binary':
30 + return zs.base64(errorMsg);
31 + case 'duration':
32 + return zs.duration(errorMsg);
33 + default:
34 + return zs;
35 + }
36 + });
37 +
38 + zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, 'contentEncoding', (zs, _, errorMsg) =>
39 + zs.base64(errorMsg)
40 + );
41 + zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, 'pattern', (zs, pattern, errorMsg) =>
42 + zs.regex(new RegExp(pattern), errorMsg)
43 + );
44 + zodSchema = extendSchemaWithMessage(
45 + zodSchema,
46 + jsonSchema,
47 + 'minLength',
48 + (zs, minLength, errorMsg) => zs.min(minLength, errorMsg)
49 + );
50 + zodSchema = extendSchemaWithMessage(
51 + zodSchema,
52 + jsonSchema,
53 + 'maxLength',
54 + (zs, maxLength, errorMsg) => zs.max(maxLength, errorMsg)
55 + );
56 +
57 + return zodSchema;
58 +};
packages/json-schema-to-zod/src/types.ts new
+83
@@ -0,0 +1,83 @@
1 +import type { ZodTypeAny } from 'zod';
2 +
3 +export type Serializable =
4 + | { [key: string]: Serializable }
5 + | Serializable[]
6 + | string
7 + | number
8 + | boolean
9 + | null;
10 +
11 +export type JsonSchema = JsonSchemaObject | boolean;
12 +export type JsonSchemaObject = {
13 + // left permissive by design
14 + type?: string | string[];
15 +
16 + // object
17 + properties?: { [key: string]: JsonSchema };
18 + additionalProperties?: JsonSchema;
19 + unevaluatedProperties?: JsonSchema;
20 + patternProperties?: { [key: string]: JsonSchema };
21 + minProperties?: number;
22 + maxProperties?: number;
23 + required?: string[] | boolean;
24 + propertyNames?: JsonSchema;
25 +
26 + // array
27 + items?: JsonSchema | JsonSchema[];
28 + additionalItems?: JsonSchema;
29 + minItems?: number;
30 + maxItems?: number;
31 + uniqueItems?: boolean;
32 +
33 + // string
34 + minLength?: number;
35 + maxLength?: number;
36 + pattern?: string;
37 + format?: string;
38 +
39 + // number
40 + minimum?: number;
41 + maximum?: number;
42 + exclusiveMinimum?: number | boolean;
43 + exclusiveMaximum?: number | boolean;
44 + multipleOf?: number;
45 +
46 + // unions
47 + anyOf?: JsonSchema[];
48 + allOf?: JsonSchema[];
49 + oneOf?: JsonSchema[];
50 +
51 + if?: JsonSchema;
52 + then?: JsonSchema;
53 + else?: JsonSchema;
54 +
55 + // shared
56 + const?: Serializable;
57 + enum?: Serializable[];
58 +
59 + errorMessage?: { [key: string]: string | undefined };
60 +
61 + description?: string;
62 + title?: string;
63 + default?: Serializable;
64 + readOnly?: boolean;
65 + not?: JsonSchema;
66 + contentEncoding?: string;
67 + nullable?: boolean;
68 +};
69 +
70 +export type ParserSelector = (schema: JsonSchemaObject, refs: Refs) => ZodTypeAny;
71 +export type ParserOverride = (schema: JsonSchemaObject, refs: Refs) => ZodTypeAny | undefined;
72 +
73 +export type JsonSchemaToZodOptions = {
74 + withoutDefaults?: boolean;
75 + withoutDescribes?: boolean;
76 + parserOverride?: ParserOverride;
77 + depth?: number;
78 +};
79 +
80 +export type Refs = JsonSchemaToZodOptions & {
81 + path: Array<string | number>;
82 + seen: Map<object | boolean, { n: number; r: ZodTypeAny | undefined }>;
83 +};
packages/json-schema-to-zod/src/utils/extend-schema.ts new
+23
@@ -0,0 +1,23 @@
1 +import type { z } from 'zod';
2 +
3 +import type { JsonSchemaObject } from '../types';
4 +
5 +export function extendSchemaWithMessage<
6 + TZod extends z.ZodTypeAny,
7 + TJson extends JsonSchemaObject,
8 + TKey extends keyof TJson,
9 +>(
10 + zodSchema: TZod,
11 + jsonSchema: TJson,
12 + key: TKey,
13 + extend: (zodSchema: TZod, value: NonNullable<TJson[TKey]>, errorMessage?: string) => TZod,
14 +) {
15 + const value = jsonSchema[key];
16 +
17 + if (value !== undefined) {
18 + const errorMessage = jsonSchema.errorMessage?.[key as string];
19 + return extend(zodSchema, value as NonNullable<TJson[TKey]>, errorMessage);
20 + }
21 +
22 + return zodSchema;
23 +}
packages/json-schema-to-zod/src/utils/half.ts new
+3
@@ -0,0 +1,3 @@
1 +export const half = <T>(arr: T[]): [T[], T[]] => {
2 + return [arr.slice(0, arr.length / 2), arr.slice(arr.length / 2)];
3 +};
packages/json-schema-to-zod/src/utils/its.ts new
+56
@@ -0,0 +1,56 @@
1 +import type { JsonSchema, JsonSchemaObject, Serializable } from '../types';
2 +
3 +export const its = {
4 + an: {
5 + object: (x: JsonSchemaObject): x is JsonSchemaObject & { type: 'object' } =>
6 + x.type === 'object',
7 + array: (x: JsonSchemaObject): x is JsonSchemaObject & { type: 'array' } => x.type === 'array',
8 + anyOf: (
9 + x: JsonSchemaObject
10 + ): x is JsonSchemaObject & {
11 + anyOf: JsonSchema[];
12 + } => x.anyOf !== undefined,
13 + allOf: (
14 + x: JsonSchemaObject
15 + ): x is JsonSchemaObject & {
16 + allOf: JsonSchema[];
17 + } => x.allOf !== undefined,
18 + enum: (
19 + x: JsonSchemaObject
20 + ): x is JsonSchemaObject & {
21 + enum: Serializable | Serializable[];
22 + } => x.enum !== undefined,
23 + },
24 + a: {
25 + nullable: (x: JsonSchemaObject): x is JsonSchemaObject & { nullable: true } =>
26 + (x as unknown as { nullable: boolean }).nullable === true,
27 + multipleType: (x: JsonSchemaObject): x is JsonSchemaObject & { type: string[] } =>
28 + Array.isArray(x.type),
29 + not: (
30 + x: JsonSchemaObject
31 + ): x is JsonSchemaObject & {
32 + not: JsonSchema;
33 + } => x.not !== undefined,
34 + const: (
35 + x: JsonSchemaObject
36 + ): x is JsonSchemaObject & {
37 + const: Serializable;
38 + } => x.const !== undefined,
39 + primitive: <T extends 'string' | 'number' | 'integer' | 'boolean' | 'null'>(
40 + x: JsonSchemaObject,
41 + p: T
42 + ): x is JsonSchemaObject & { type: T } => x.type === p,
43 + conditional: (
44 + x: JsonSchemaObject
45 + ): x is JsonSchemaObject & {
46 + if: JsonSchema;
47 + then: JsonSchema;
48 + else: JsonSchema;
49 + } => Boolean('if' in x && x.if && 'then' in x && 'else' in x && x.then && x.else),
50 + oneOf: (
51 + x: JsonSchemaObject
52 + ): x is JsonSchemaObject & {
53 + oneOf: JsonSchema[];
54 + } => x.oneOf !== undefined,
55 + },
56 +};
packages/json-schema-to-zod/src/utils/omit.ts new
+8
@@ -0,0 +1,8 @@
1 +export const omit = <T extends object, K extends keyof T>(obj: T, ...keys: K[]): Omit<T, K> =>
2 + Object.keys(obj).reduce((acc: Record<string, unknown>, key) => {
3 + if (!keys.includes(key as K)) {
4 + acc[key] = obj[key as K];
5 + }
6 +
7 + return acc;
8 + }, {}) as Omit<T, K>;
packages/json-schema-to-zod/test/json-to-zod.test.ts new
+453
@@ -0,0 +1,453 @@
1 +import { describe, it, expect } from 'vitest';
2 +import { z } from 'zod';
3 +import { jsonSchemaToZod } from '../src/json-schema-to-zod';
4 +import type { JsonSchema } from '../src/types';
5 +
6 +describe('jsonSchemaToZod', () => {
7 + describe('Basic Types', () => {
8 + it('should convert string schema', () => {
9 + const schema: JsonSchema = {
10 + type: 'string',
11 + };
12 + const zodSchema = jsonSchemaToZod(schema);
13 + expect(zodSchema).toBeInstanceOf(z.ZodString);
14 + expect(zodSchema.parse('test')).toBe('test');
15 + expect(() => zodSchema.parse(123)).toThrow();
16 + });
17 +
18 + it('should convert number schema', () => {
19 + const schema: JsonSchema = {
20 + type: 'number',
21 + };
22 + const zodSchema = jsonSchemaToZod(schema);
23 + expect(zodSchema).toBeInstanceOf(z.ZodNumber);
24 + expect(zodSchema.parse(123)).toBe(123);
25 + expect(() => zodSchema.parse('123')).toThrow();
26 + });
27 +
28 + it('should convert integer schema', () => {
29 + const schema: JsonSchema = {
30 + type: 'integer',
31 + };
32 + const zodSchema = jsonSchemaToZod(schema);
33 + expect(zodSchema.parse(123)).toBe(123);
34 + expect(() => zodSchema.parse(123.45)).toThrow();
35 + });
36 +
37 + it('should convert boolean schema', () => {
38 + const schema: JsonSchema = {
39 + type: 'boolean',
40 + };
41 + const zodSchema = jsonSchemaToZod(schema);
42 + expect(zodSchema).toBeInstanceOf(z.ZodBoolean);
43 + expect(zodSchema.parse(true)).toBe(true);
44 + expect(() => zodSchema.parse('true')).toThrow();
45 + });
46 +
47 + it('should convert null schema', () => {
48 + const schema: JsonSchema = {
49 + type: 'null',
50 + };
51 + const zodSchema = jsonSchemaToZod(schema);
52 + expect(zodSchema).toBeInstanceOf(z.ZodNull);
53 + expect(zodSchema.parse(null)).toBe(null);
54 + expect(() => zodSchema.parse(undefined)).toThrow();
55 + });
56 + });
57 +
58 + describe('String Formats', () => {
59 + it('should validate email format', () => {
60 + const schema: JsonSchema = {
61 + type: 'string',
62 + format: 'email',
63 + };
64 + const zodSchema = jsonSchemaToZod(schema);
65 + expect(zodSchema.parse('test@example.com')).toBe('test@example.com');
66 + expect(() => zodSchema.parse('invalid-email')).toThrow();
67 + });
68 +
69 + it('should validate date-time format', () => {
70 + const schema: JsonSchema = {
71 + type: 'string',
72 + format: 'date-time',
73 + };
74 + const zodSchema = jsonSchemaToZod(schema);
75 + expect(zodSchema.parse('2024-03-20T12:00:00Z')).toBe('2024-03-20T12:00:00Z');
76 + expect(() => zodSchema.parse('invalid-date')).toThrow();
77 + });
78 +
79 + it('should validate uuid format', () => {
80 + const schema: JsonSchema = {
81 + type: 'string',
82 + format: 'uuid',
83 + };
84 + const zodSchema = jsonSchemaToZod(schema);
85 + expect(zodSchema.parse('123e4567-e89b-12d3-a456-426614174000')).toBe(
86 + '123e4567-e89b-12d3-a456-426614174000'
87 + );
88 + expect(() => zodSchema.parse('invalid-uuid')).toThrow();
89 + });
90 + });
91 +
92 + describe('Number Validations', () => {
93 + it('should validate minimum and maximum', () => {
94 + const schema: JsonSchema = {
95 + type: 'number',
96 + minimum: 0,
97 + maximum: 100,
98 + };
99 + const zodSchema = jsonSchemaToZod(schema);
100 + expect(zodSchema.parse(50)).toBe(50);
101 + expect(() => zodSchema.parse(-1)).toThrow();
102 + expect(() => zodSchema.parse(101)).toThrow();
103 + });
104 +
105 + it('should validate exclusive minimum and maximum', () => {
106 + const schema: JsonSchema = {
107 + type: 'number',
108 + exclusiveMinimum: 0,
109 + exclusiveMaximum: 100,
110 + };
111 + const zodSchema = jsonSchemaToZod(schema);
112 + expect(zodSchema.parse(50)).toBe(50);
113 + expect(() => zodSchema.parse(0)).toThrow();
114 + expect(() => zodSchema.parse(100)).toThrow();
115 + });
116 +
117 + it('should validate multipleOf', () => {
118 + const schema: JsonSchema = {
119 + type: 'number',
120 + multipleOf: 5,
121 + };
122 + const zodSchema = jsonSchemaToZod(schema);
123 + expect(zodSchema.parse(15)).toBe(15);
124 + expect(() => zodSchema.parse(17)).toThrow();
125 + });
126 + });
127 +
128 + describe('Object Schemas', () => {
129 + it('should validate required properties', () => {
130 + const schema: JsonSchema = {
131 + type: 'object',
132 + properties: {
133 + name: { type: 'string' },
134 + age: { type: 'number' },
135 + },
136 + required: ['name'],
137 + };
138 + const zodSchema = jsonSchemaToZod(schema);
139 + expect(zodSchema.parse({ name: 'John', age: 30 })).toEqual({ name: 'John', age: 30 });
140 + expect(zodSchema.parse({ name: 'John' })).toEqual({ name: 'John' });
141 + expect(() => zodSchema.parse({ age: 30 })).toThrow();
142 + });
143 +
144 + it('should validate additional properties', () => {
145 + const schema: JsonSchema = {
146 + type: 'object',
147 + properties: {
148 + name: { type: 'string' },
149 + },
150 + additionalProperties: false,
151 + };
152 + const zodSchema = jsonSchemaToZod(schema);
153 + expect(zodSchema.parse({ name: 'John' })).toEqual({ name: 'John' });
154 + expect(() => zodSchema.parse({ name: 'John', extra: 'field' })).toThrow();
155 + });
156 +
157 + it('should validate pattern properties', () => {
158 + const schema: JsonSchema = {
159 + type: 'object',
160 + patternProperties: {
161 + '^prefix_': { type: 'string' },
162 + },
163 + };
164 + const zodSchema = jsonSchemaToZod(schema);
165 + expect(zodSchema.parse({ prefix_one: 'value1', prefix_two: 'value2' })).toEqual({
166 + prefix_one: 'value1',
167 + prefix_two: 'value2',
168 + });
169 + expect(() => zodSchema.parse({ prefix_one: 123 })).toThrow();
170 + });
171 + });
172 +
173 + describe('Array Schemas', () => {
174 + it('should validate array items', () => {
175 + const schema: JsonSchema = {
176 + type: 'array',
177 + items: { type: 'string' },
178 + };
179 + const zodSchema = jsonSchemaToZod(schema);
180 + expect(zodSchema.parse(['one', 'two'])).toEqual(['one', 'two']);
181 + expect(() => zodSchema.parse(['one', 2])).toThrow();
182 + });
183 +
184 + it('should validate tuple items', () => {
185 + const schema: JsonSchema = {
186 + type: 'array',
187 + items: [{ type: 'string' }, { type: 'number' }],
188 + };
189 + const zodSchema = jsonSchemaToZod(schema);
190 + expect(zodSchema.parse(['test', 123])).toEqual(['test', 123]);
191 + expect(() => zodSchema.parse(['test', 'wrong'])).toThrow();
192 + });
193 +
194 + it('should validate array length', () => {
195 + const schema: JsonSchema = {
196 + type: 'array',
197 + items: { type: 'string' },
198 + minItems: 1,
199 + maxItems: 3,
200 + };
201 + const zodSchema = jsonSchemaToZod(schema);
202 + expect(zodSchema.parse(['one'])).toEqual(['one']);
203 + expect(zodSchema.parse(['one', 'two', 'three'])).toEqual(['one', 'two', 'three']);
204 + expect(() => zodSchema.parse([])).toThrow();
205 + expect(() => zodSchema.parse(['one', 'two', 'three', 'four'])).toThrow();
206 + });
207 + });
208 +
209 + describe('Enum Schemas', () => {
210 + it('should validate string enums', () => {
211 + const schema: JsonSchema = {
212 + type: 'string',
213 + enum: ['one', 'two', 'three'],
214 + };
215 + const zodSchema = jsonSchemaToZod(schema);
216 + expect(zodSchema.parse('one')).toBe('one');
217 + expect(() => zodSchema.parse('four')).toThrow();
218 + });
219 +
220 + it('should validate mixed type enums', () => {
221 + const schema: JsonSchema = {
222 + enum: ['string', 123, true],
223 + };
224 + const zodSchema = jsonSchemaToZod(schema);
225 + expect(zodSchema.parse('string')).toBe('string');
226 + expect(zodSchema.parse(123)).toBe(123);
227 + expect(zodSchema.parse(true)).toBe(true);
228 + expect(() => zodSchema.parse('invalid')).toThrow();
229 + });
230 + });
231 +
232 + describe('Combining Schemas', () => {
233 + it('should validate anyOf', () => {
234 + const schema: JsonSchema = {
235 + anyOf: [{ type: 'string' }, { type: 'number' }],
236 + };
237 + const zodSchema = jsonSchemaToZod(schema);
238 + expect(zodSchema.parse('test')).toBe('test');
239 + expect(zodSchema.parse(123)).toBe(123);
240 + expect(() => zodSchema.parse(true)).toThrow();
241 + });
242 +
243 + it('should validate oneOf', () => {
244 + const schema: JsonSchema = {
245 + oneOf: [
246 + { type: 'number', minimum: 0 },
247 + { type: 'number', maximum: 0 },
248 + ],
249 + };
250 + const zodSchema = jsonSchemaToZod(schema);
251 + expect(zodSchema.parse(1)).toBe(1);
252 + expect(zodSchema.parse(-1)).toBe(-1);
253 + expect(() => zodSchema.parse(0)).toThrow(); // Should fail as 0 matches both schemas
254 + });
255 +
256 + it('should validate allOf', () => {
257 + const schema: JsonSchema = {
258 + allOf: [
259 + { type: 'number', minimum: 0 },
260 + { type: 'number', maximum: 100 },
261 + ],
262 + };
263 + const zodSchema = jsonSchemaToZod(schema);
264 + expect(zodSchema.parse(50)).toBe(50);
265 + expect(() => zodSchema.parse(-1)).toThrow();
266 + expect(() => zodSchema.parse(101)).toThrow();
267 + });
268 + });
269 +
270 + describe('Complex Nested Schemas', () => {
271 + it('should validate deeply nested objects', () => {
272 + const schema: JsonSchema = {
273 + type: 'object',
274 + properties: {
275 + user: {
276 + type: 'object',
277 + properties: {
278 + name: { type: 'string' },
279 + contacts: {
280 + type: 'array',
281 + items: {
282 + type: 'object',
283 + properties: {
284 + type: { type: 'string', enum: ['email', 'phone'] },
285 + value: { type: 'string' },
286 + },
287 + required: ['type', 'value'],
288 + },
289 + },
290 + },
291 + required: ['name'],
292 + },
293 + },
294 + required: ['user'],
295 + };
296 + const zodSchema = jsonSchemaToZod(schema);
297 +
298 + const validData = {
299 + user: {
300 + name: 'John Doe',
301 + contacts: [
302 + { type: 'email', value: 'john@example.com' },
303 + { type: 'phone', value: '1234567890' },
304 + ],
305 + },
306 + };
307 +
308 + expect(zodSchema.parse(validData)).toEqual(validData);
309 + expect(() =>
310 + zodSchema.parse({
311 + user: {
312 + name: 'John Doe',
313 + contacts: [{ type: 'invalid', value: 'test' }],
314 + },
315 + })
316 + ).toThrow();
317 + });
318 + });
319 +
320 + describe('Schema Metadata and Constraints', () => {
321 + it('should handle required fields and descriptions', () => {
322 + const schema: JsonSchema = {
323 + type: 'object',
324 + description: 'A user profile object',
325 + properties: {
326 + username: {
327 + type: 'string',
328 + description: "The user's display name",
329 + },
330 + email: {
331 + type: 'string',
332 + description: "The user's email address",
333 + format: 'email',
334 + },
335 + age: {
336 + type: 'number',
337 + description: "User's age in years",
338 + },
339 + },
340 + required: ['username', 'email'],
341 + };
342 +
343 + const zodSchema = jsonSchemaToZod(schema);
344 +
345 + // Test description
346 + expect(zodSchema.description).toBe('A user profile object');
347 +
348 + // Test required fields
349 + expect(() => zodSchema.parse({})).toThrow();
350 + expect(() => zodSchema.parse({ username: 'test' })).toThrow();
351 + expect(() => zodSchema.parse({ email: 'test@example.com' })).toThrow();
352 +
353 + // Valid data should pass
354 + expect(
355 + zodSchema.parse({
356 + username: 'testuser',
357 + email: 'test@example.com',
358 + })
359 + ).toEqual({
360 + username: 'testuser',
361 + email: 'test@example.com',
362 + });
363 +
364 + // Optional field should be allowed to be missing
365 + expect(
366 + zodSchema.parse({
367 + username: 'testuser',
368 + email: 'test@example.com',
369 + })
370 + ).toEqual({
371 + username: 'testuser',
372 + email: 'test@example.com',
373 + });
374 + });
375 +
376 + it('should handle default values', () => {
377 + const schema: JsonSchema = {
378 + type: 'object',
379 + properties: {
380 + name: {
381 + type: 'string',
382 + default: 'Anonymous',
383 + },
384 + settings: {
385 + type: 'object',
386 + default: { theme: 'light' },
387 + properties: {
388 + theme: {
389 + type: 'string',
390 + },
391 + },
392 + },
393 + },
394 + };
395 +
396 + const zodSchema = jsonSchemaToZod(schema);
397 +
398 + // Test default values for top-level property
399 + expect(zodSchema.parse({})).toEqual({
400 + name: 'Anonymous',
401 + settings: { theme: 'light' },
402 + });
403 +
404 + // Test that defaults don't override provided values
405 + expect(
406 + zodSchema.parse({
407 + name: 'John',
408 + settings: {
409 + theme: 'dark',
410 + },
411 + })
412 + ).toEqual({
413 + name: 'John',
414 + settings: {
415 + theme: 'dark',
416 + },
417 + });
418 + });
419 +
420 + it('should transform GetUserRequest schema correctly', () => {
421 + const schema: JsonSchema = {
422 + type: 'object',
423 + properties: {
424 + username: {
425 + type: 'string',
426 + description: 'The username of the Hacker News user to retrieve.',
427 + title: 'Username',
428 + },
429 + },
430 + required: ['username'],
431 + title: 'GetUserRequest',
432 + };
433 +
434 + const zodSchema = jsonSchemaToZod(schema);
435 +
436 + // Test schema description/title
437 + expect(zodSchema.description).toBe('GetUserRequest');
438 +
439 + // Test required field validation
440 + expect(() => zodSchema.parse({})).toThrow();
441 + expect(() => zodSchema.parse({ username: 123 })).toThrow();
442 +
443 + // Test valid data
444 + expect(zodSchema.parse({ username: 'testuser' })).toEqual({
445 + username: 'testuser',
446 + });
447 +
448 + // Test property description
449 + const shape = zodSchema._def.shape();
450 + expect(shape.username.description).toBe('The username of the Hacker News user to retrieve.');
451 + });
452 + });
453 +});
packages/json-schema-to-zod/tsconfig.json new
+15
@@ -0,0 +1,15 @@
1 +{
2 + "compilerOptions": {
3 + "target": "ESNext",
4 + "module": "ESNext",
5 + "declaration": true,
6 + "outDir": "./dist",
7 + "rootDir": "./src",
8 + "strict": true,
9 + "esModuleInterop": true,
10 + "moduleResolution": "node",
11 + "skipLibCheck": true,
12 + "resolveJsonModule": true
13 + },
14 + "include": ["src"]
15 +}
packages/json-schema-to-zod/tsup.config.ts new
+10
@@ -0,0 +1,10 @@
1 +import { defineConfig } from 'tsup';
2 +
3 +export default defineConfig({
4 + entry: ['src/index.ts'],
5 + format: ['esm', 'cjs'],
6 + dts: true,
7 + clean: true,
8 + minify: false,
9 + outDir: 'dist',
10 +});
packages/providers/langchain/test/langchain.test.ts
+100 -181
@@ -1,239 +1,158 @@
1 -import { describe, it, expect, vi, beforeEach } from 'vitest';
1 +import { describe, it, expect, beforeEach } from 'vitest';
2 import { LangchainProvider } from '../src';
3 import { Tool } from '@composio/core';
4 import { DynamicStructuredTool } from '@langchain/core/tools';
5
6 -// Define an interface for our mocked LangChain tool
7 -interface MockedLangChainTool extends DynamicStructuredTool {
8 - _isMockedLangChainTool: boolean;
9 -}
10 -
11 -// Mock the @langchain/core/tools module
12 -vi.mock('@langchain/core/tools', () => {
13 - return {
14 - DynamicStructuredTool: vi.fn().mockImplementation(config => {
15 - return {
16 - name: config.name,
17 - description: config.description,
18 - schema: config.schema,
19 - func: config.func,
20 - _isMockedLangChainTool: true,
21 - } as MockedLangChainTool;
22 - }),
23 - };
24 -});
25 -
26 -// Mock the jsonSchemaToZodSchema function from @composio/core
27 -vi.mock('@composio/core', async () => {
28 - const actual = await vi.importActual('@composio/core');
29 - return {
30 - ...(actual as object),
31 - jsonSchemaToZodSchema: vi.fn().mockImplementation(schema => {
32 - return { type: 'mock-schema', originalSchema: schema };
33 - }),
34 - };
35 -});
36 -
6 describe('LangchainProvider', () => {
7 let provider: LangchainProvider;
39 - let mockTool: Tool;
40 - let mockExecuteToolFn: any;
8 + let sampleTool: Tool;
9 + let executeToolFn: (
10 + toolSlug: string,
11 + params: Record<string, unknown>,
12 + modifiers?: any
13 + ) => Promise<any>;
14
15 beforeEach(() => {
16 provider = new LangchainProvider();
17
45 - // Mock the global execute tool function
46 - mockExecuteToolFn = vi.fn().mockResolvedValue({
47 - data: { result: 'success' },
48 - error: null,
49 - successful: true,
50 - });
51 - provider._setExecuteToolFn(mockExecuteToolFn);
18 + // Create a real execute function that simulates tool execution
19 + executeToolFn = async (toolSlug: string, params: Record<string, unknown>) => {
20 + // Simulate actual tool execution with realistic response
21 + return {
22 + data: { toolSlug, params },
23 + error: null,
24 + successful: true,
25 + };
26 + };
27
53 - // Create a mock Composio tool
54 - mockTool = {
55 - slug: 'test-tool',
56 - name: 'Test Tool',
57 - description: 'A tool for testing',
28 + // Create a real sample tool that matches actual tool structure
29 + sampleTool = {
30 + slug: 'SEARCH_TOOL',
31 + name: 'Search Tool',
32 + description: 'Search for information in the knowledge base',
33 inputParameters: {
34 type: 'object',
35 properties: {
61 - input: {
36 + query: {
37 type: 'string',
63 - description: 'Test input',
38 + description: 'The search query',
39 },
40 },
66 - required: ['input'],
41 + required: ['query'],
42 + additionalProperties: false,
43 },
44 toolkit: {
69 - slug: 'test-toolkit',
70 - name: 'Test Toolkit',
45 + slug: 'search_toolkit',
46 + name: 'Search Toolkit',
47 },
72 - tags: [],
48 + tags: ['search', 'knowledge'],
49 };
74 -
75 - // Reset mocks before each test
76 - vi.clearAllMocks();
50 });
51
79 - describe('name property', () => {
80 - it('should have the correct name', () => {
52 + describe('Provider Configuration', () => {
53 + it('should be properly initialized with correct name', () => {
54 expect(provider.name).toBe('langchain');
55 });
83 - });
56
85 - describe('_isAgentic property', () => {
86 - it('should be agentic', () => {
57 + it('should be marked as agentic', () => {
58 expect(provider._isAgentic).toBe(true);
59 });
60 });
61
91 - describe('wrapTool', () => {
92 - it('should wrap a tool in LangChain DynamicStructuredTool format', () => {
93 - const wrapped = provider.wrapTool(mockTool, mockExecuteToolFn) as MockedLangChainTool;
94 -
95 - expect(DynamicStructuredTool).toHaveBeenCalledWith({
96 - name: mockTool.slug,
97 - description: mockTool.description,
98 - schema: expect.objectContaining({
99 - type: 'mock-schema',
100 - originalSchema: mockTool.inputParameters,
101 - }),
102 - func: expect.any(Function),
103 - });
62 + describe('Tool Wrapping', () => {
63 + it('should successfully wrap a valid tool into LangChain format', () => {
64 + const wrappedTool = provider.wrapTool(sampleTool, executeToolFn);
65
105 - expect(wrapped._isMockedLangChainTool).toBe(true);
66 + // Verify the wrapped tool has the correct structure
67 + expect(wrappedTool).toBeInstanceOf(DynamicStructuredTool);
68 + expect(wrappedTool.name).toBe(sampleTool.slug);
69 + expect(wrappedTool.description).toBe(sampleTool.description);
70 + expect(typeof wrappedTool.func).toBe('function');
71 });
72
108 - it('should throw an error if toolkit name is not defined', () => {
109 - const toolWithoutToolkit: Tool = {
110 - ...mockTool,
111 - toolkit: undefined,
112 - };
73 + it('should wrap a tool that can be executed with parameters', async () => {
74 + const wrappedTool = provider.wrapTool(sampleTool, executeToolFn);
75 + const searchParams = { query: 'test search' };
76
114 - expect(() => {
115 - provider.wrapTool(toolWithoutToolkit, mockExecuteToolFn);
116 - }).toThrow('App name is not defined');
77 + const result = await wrappedTool.func(searchParams);
78 + const parsedResult = JSON.parse(result as string);
79 +
80 + expect(parsedResult).toEqual({
81 + data: {
82 + toolSlug: sampleTool.slug,
83 + params: searchParams,
84 + },
85 + error: null,
86 + successful: true,
87 + });
88 });
89
119 - it('should throw an error if inputParameters are not defined', () => {
120 - const toolWithoutParams: Tool = {
121 - ...mockTool,
122 - inputParameters: undefined,
123 - };
90 + it('should fail to wrap a tool without toolkit', () => {
91 + const invalidTool = { ...sampleTool, toolkit: undefined };
92
93 expect(() => {
126 - provider.wrapTool(toolWithoutParams, mockExecuteToolFn);
127 - }).toThrow('Tool input parameters are not defined');
94 + provider.wrapTool(invalidTool, executeToolFn);
95 + }).toThrow('App name is not defined');
96 });
97
130 - it('should create a function that executes the tool with the right parameters', async () => {
131 - const wrapped = provider.wrapTool(mockTool, mockExecuteToolFn);
132 -
133 - // Extract the function from the constructor call
134 - const executeFunction = (DynamicStructuredTool as any).mock.calls[0][0].func;
98 + it('should fail to wrap a tool without input parameters', () => {
99 + const invalidTool = { ...sampleTool, inputParameters: undefined };
100
136 - // Test the execute function
137 - const params = { input: 'test-value' };
138 - const result = await executeFunction(params);
139 -
140 - // Check that executeToolFn was called with the right parameters
141 - expect(mockExecuteToolFn).toHaveBeenCalledWith(mockTool.slug, params);
142 -
143 - // Check that the result was stringified
144 - expect(result).toBe(
145 - JSON.stringify({
146 - data: { result: 'success' },
147 - error: null,
148 - successful: true,
149 - })
150 - );
101 + expect(() => {
102 + provider.wrapTool(invalidTool, executeToolFn);
103 + }).toThrow('Tool input parameters are not defined');
104 });
105 });
106
154 - describe('wrapTools', () => {
155 - it('should wrap multiple tools', () => {
107 + describe('Multiple Tools Wrapping', () => {
108 + it('should wrap multiple tools correctly', () => {
109 const anotherTool: Tool = {
157 - ...mockTool,
158 - slug: 'another-tool',
159 - name: 'Another Tool',
160 - };
161 - const tools = [mockTool, anotherTool];
162 -
163 - const wrapped = provider.wrapTools(tools, mockExecuteToolFn);
164 -
165 - // Verify the result is an array of the right length
166 - expect(wrapped).toHaveLength(2);
167 -
168 - // Verify the DynamicStructuredTool constructor was called with the right parameters for each tool
169 - expect(DynamicStructuredTool).toHaveBeenCalledTimes(2);
170 - expect(DynamicStructuredTool).toHaveBeenCalledWith(
171 - expect.objectContaining({
172 - name: mockTool.slug,
173 - })
174 - );
175 - expect(DynamicStructuredTool).toHaveBeenCalledWith(
176 - expect.objectContaining({
177 - name: anotherTool.slug,
178 - })
179 - );
180 - });
181 -
182 - it('should return an empty array for empty tools array', () => {
183 - const wrapped = provider.wrapTools([], mockExecuteToolFn);
184 - expect(wrapped).toEqual([]);
185 - expect(DynamicStructuredTool).not.toHaveBeenCalled();
186 - });
187 - });
188 -
189 - describe('executeTool', () => {
190 - it('should execute a tool using the global execute function', async () => {
191 - const toolSlug = 'test-tool';
192 - const toolParams = {
193 - userId: 'test-user',
194 - arguments: { input: 'test-value' },
110 + ...sampleTool,
111 + slug: 'WEATHER_TOOL',
112 + name: 'Weather Tool',
113 + description: 'Get weather information',
114 + inputParameters: {
115 + type: 'object',
116 + properties: {
117 + location: {
118 + type: 'string',
119 + description: 'Location to get weather for',
120 + },
121 + },
122 + required: ['location'],
123 + additionalProperties: false,
124 + },
125 };
126
197 - const result = await provider.executeTool(toolSlug, toolParams);
127 + const tools = [sampleTool, anotherTool];
128 + const wrappedTools = provider.wrapTools(tools, executeToolFn);
129
199 - expect(mockExecuteToolFn).toHaveBeenCalledWith(toolSlug, toolParams, undefined);
200 - expect(result).toEqual({
201 - data: { result: 'success' },
202 - error: null,
203 - successful: true,
204 - });
130 + expect(wrappedTools).toHaveLength(2);
131 + expect(wrappedTools[0].name).toBe('SEARCH_TOOL');
132 + expect(wrappedTools[1].name).toBe('WEATHER_TOOL');
133 + expect(wrappedTools.every(tool => tool instanceof DynamicStructuredTool)).toBe(true);
134 });
135
207 - it('should pass modifiers to the global execute function', async () => {
208 - const toolSlug = 'test-tool';
209 - const toolParams = {
210 - userId: 'test-user',
211 - arguments: { input: 'test-value' },
212 - };
213 -
214 - const modifiers = {
215 - beforeExecute: vi.fn(params => params),
216 - afterExecute: vi.fn(response => response),
217 - };
218 -
219 - await provider.executeTool(toolSlug, toolParams, modifiers);
220 -
221 - expect(mockExecuteToolFn).toHaveBeenCalledWith(toolSlug, toolParams, modifiers);
136 + it('should handle empty tools array', () => {
137 + const wrappedTools = provider.wrapTools([], executeToolFn);
138 + expect(wrappedTools).toEqual([]);
139 });
140 });
141
225 - describe('integration with LangChain', () => {
226 - it('should produce tools compatible with LangChain', () => {
227 - const wrapped = provider.wrapTool(mockTool, mockExecuteToolFn) as MockedLangChainTool;
142 + describe('LangChain Integration', () => {
143 + it('should produce tools that can be used with LangChain', async () => {
144 + const wrappedTool = provider.wrapTool(sampleTool, executeToolFn);
145
229 - // Verify the wrapped tool has the expected structure
230 - expect(wrapped).toHaveProperty('name');
231 - expect(wrapped).toHaveProperty('description');
232 - expect(wrapped).toHaveProperty('schema');
233 - expect(wrapped).toHaveProperty('func');
146 + // Verify the tool has all required LangChain properties
147 + expect(wrappedTool).toHaveProperty('name');
148 + expect(wrappedTool).toHaveProperty('description');
149 + expect(wrappedTool).toHaveProperty('schema');
150 + expect(wrappedTool).toHaveProperty('func');
151
235 - // The func property should be a function
236 - expect(typeof wrapped.func).toBe('function');
152 + // Test actual execution through LangChain interface
153 + const result = await wrappedTool.func({ query: 'test query' });
154 + expect(typeof result).toBe('string');
155 + expect(() => JSON.parse(result as string)).not.toThrow();
156 });
157 });
158 });
pnpm-lock.yaml
+22
@@ -235,6 +235,9 @@ importers:
235 openai:
236 specifier: ^4.94.0
237 version: 4.98.0(encoding@0.1.13)(ws@8.18.2)(zod@3.24.4)
238 + zod:
239 + specifier: ^3.24.2
240 + version: 3.24.4
241 devDependencies:
242 '@types/bun':
243 specifier: ^1.2.9
@@ -349,6 +352,9 @@ importers:
352 '@composio/client':
353 specifier: 0.1.0-alpha.16
354 version: 0.1.0-alpha.16
355 + '@composio/json-schema-to-zod':
356 + specifier: workspace:^
357 + version: link:../json-schema-to-zod
358 chalk:
359 specifier: ^5.4.1
360 version: 5.4.1
@@ -387,6 +393,22 @@ importers:
393 specifier: ^3.1.4
394 version: 3.1.4(@types/node@22.15.18)(@vitest/ui@3.1.4)(tsx@4.19.4)(yaml@2.8.0)
395
396 + packages/json-schema-to-zod:
397 + dependencies:
398 + zod:
399 + specifier: ^3.24.2
400 + version: 3.24.4
401 + devDependencies:
402 + tsup:
403 + specifier: ^8.4.0
404 + version: 8.4.0(postcss@8.5.3)(tsx@4.19.4)(typescript@5.8.3)(yaml@2.8.0)
405 + typescript:
406 + specifier: ^5.8.3
407 + version: 5.8.3
408 + vitest:
409 + specifier: ^3.1.4
410 + version: 3.1.4(@types/node@22.15.18)(@vitest/ui@3.1.4)(tsx@4.19.4)(yaml@2.8.0)
411 +
412 packages/providers/anthropic:
413 dependencies:
414 '@anthropic-ai/sdk':
pnpm-workspace.yaml
+1
@@ -1,5 +1,6 @@
1 packages:
2 - 'packages/core'
3 + - 'packages/json-schema-to-zod'
4 - 'packages/providers/*'
5 - 'packages/wrappers/*'
6 - 'examples/*'