Skip to content

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

Fix JSON schema transformation issues with jsonSchemaToZodSchema (#28)

Musthaq Ahamad4ddfafcadb6b
diff --git a/.changeset/thirty-rockets-pay.md b/.changeset/thirty-rockets-pay.md
new file mode 100644
index 000000000..b84ed55fc
--- /dev/null
+++ b/.changeset/thirty-rockets-pay.md
@@ -0,0 +1,13 @@
+---
+'@composio/langchain': patch
+'@composio/json-schema-to-zod': patch
+'@composio/core': patch
+'@composio/anthropic': patch
+'@composio/cloudflare': patch
+'@composio/google': patch
+'@composio/mastra': patch
+'@composio/openai': patch
+'@composio/vercel': patch
+---
+
+Add json schema to zod schema
diff --git a/examples/mastra/src/index.ts b/examples/mastra/src/index.ts
index b4a28aeea..fbc19ed67 100644
--- a/examples/mastra/src/index.ts
+++ b/examples/mastra/src/index.ts
@@ -27,11 +27,17 @@ const composio = new Composio({
* Attach beforeExecute and afterExecute hooks to the tools for logging
*/
const tools = await composio.tools.get('default', 'HACKERNEWS_GET_USER', {
- beforeExecute: (toolkitSlug, toolSlug, input) => {
+ modifySchema: (toolSlug, toolkitSlug, schema) => {
+ console.log(
+ `🔄 Modifying schema for tool ${toolSlug}/${toolkitSlug} with schema ${JSON.stringify(schema)}`
+ );
+ return schema;
+ },
+ beforeExecute: (toolSlug, toolkitSlug, input) => {
console.log(`🔄 Executing tool ${toolSlug}/${toolkitSlug} with input ${JSON.stringify(input)}`);
return input;
},
- afterExecute: (toolkitSlug, toolSlug, output) => {
+ afterExecute: (toolSlug, toolkitSlug, output) => {
console.log(
`✅ Tool ${toolSlug}/${toolkitSlug} executed successfully with output ${JSON.stringify(output)}`
);
diff --git a/examples/openai/package.json b/examples/openai/package.json
index e140e5eb4..a1df95a29 100644
--- a/examples/openai/package.json
+++ b/examples/openai/package.json
@@ -18,7 +18,8 @@
"dependencies": {
"@composio/core": "workspace:*",
"dotenv": "^16.4.1",
- "openai": "^4.94.0"
+ "openai": "^4.94.0",
+ "zod": "^3.24.2"
},
"devDependencies": {
"@types/bun": "^1.2.9",
diff --git a/package.json b/package.json
index 6e22c70bd..c95f76ebb 100644
--- a/package.json
+++ b/package.json
@@ -5,6 +5,7 @@
"description": "",
"workspaces": [
"packages/core",
+ "packages/json-schema-to-zod",
"packages/providers/*"
],
"scripts": {
diff --git a/packages/core/package.json b/packages/core/package.json
index 54ebf3765..a82093130 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -37,6 +37,7 @@
},
"dependencies": {
"@composio/client": "0.1.0-alpha.16",
+ "@composio/json-schema-to-zod": "workspace:^",
"chalk": "^5.4.1",
"openai": "^4.94.0",
"pusher-js": "^8.4.0",
diff --git a/packages/core/src/errors/ValidationErrors.ts b/packages/core/src/errors/ValidationErrors.ts
index dcab5f100..a5225b821 100644
--- a/packages/core/src/errors/ValidationErrors.ts
+++ b/packages/core/src/errors/ValidationErrors.ts
@@ -8,6 +8,7 @@ import { ComposioError, ComposioErrorOptions } from './ComposioError';
*/
export const ValidationErrorCodes = {
VALIDATION_ERROR: 'VALIDATION_ERROR',
+ JSON_SCHEMA_TO_ZOD_ERROR: 'JSON_SCHEMA_TO_ZOD_ERROR',
} as const;
export class ValidationError extends ComposioError {
@@ -46,7 +47,6 @@ export class ValidationError extends ComposioError {
// Create a friendly error message for users
const userFriendlyMessage = this.generateUserFriendlyMessage();
this.message = `${message}: ${userFriendlyMessage}`;
-
}
private generateUserFriendlyMessage(): string {
@@ -67,3 +67,15 @@ export class ValidationError extends ComposioError {
return 'Please check your input parameters';
}
}
+
+export class JsonSchemaToZodError extends ComposioError {
+ constructor(
+ message: string = 'Failed to convert JSON schema to Zod schema',
+ options: ComposioErrorOptions = {}
+ ) {
+ super(message, {
+ ...options,
+ code: options.code || ValidationErrorCodes.JSON_SCHEMA_TO_ZOD_ERROR,
+ });
+ }
+}
diff --git a/packages/core/src/types/modifiers.types.ts b/packages/core/src/types/modifiers.types.ts
index c128e94da..0ce28afd1 100644
--- a/packages/core/src/types/modifiers.types.ts
+++ b/packages/core/src/types/modifiers.types.ts
@@ -52,7 +52,7 @@ export type beforeExecuteModifier = (
toolSlug: string,
toolkitSlug: string,
toolExecuteParams: ToolExecuteParams
-) => Promise<ToolExecuteParams>;
+) => Promise<ToolExecuteParams> | ToolExecuteParams;
/**
* Modifier for altering the tool execution response after execution completes.
@@ -108,7 +108,7 @@ export type afterExecuteModifier = (
toolSlug: string,
toolkitSlug: string,
toolExecuteResponse: ToolExecuteResponse
-) => Promise<ToolExecuteResponse>;
+) => Promise<ToolExecuteResponse> | ToolExecuteResponse;
/**
* Modifier for altering the tool schema before it's exposed to consumers.
@@ -309,5 +309,9 @@ export type AgenticToolOptions = ToolOptions & ExecuteToolModifiers;
* });
* ```
*/
-export type ProviderOptions<T extends BaseComposioProvider<unknown, unknown>> =
- T extends BaseAgenticProvider<unknown, unknown> ? AgenticToolOptions : ToolOptions;
+export type ProviderOptions<TProvider> =
+ TProvider extends BaseComposioProvider<infer TToolCollection, infer TTool>
+ ? TProvider extends BaseAgenticProvider<TToolCollection, TTool>
+ ? AgenticToolOptions
+ : ToolOptions
+ : never;
diff --git a/packages/core/src/types/tool.types.ts b/packages/core/src/types/tool.types.ts
index e305b6d29..6c0356bb0 100644
--- a/packages/core/src/types/tool.types.ts
+++ b/packages/core/src/types/tool.types.ts
@@ -42,7 +42,7 @@ const ParametersSchema = z.object({
required: z.array(z.string()).optional(),
title: z.string().optional(),
description: z.string().optional(),
- additionalProperties: z.boolean().optional(),
+ additionalProperties: z.boolean().default(false).optional(),
});
/**
diff --git a/packages/core/src/utils/jsonSchema.ts b/packages/core/src/utils/jsonSchema.ts
index 91ec300ce..75ac4476a 100644
--- a/packages/core/src/utils/jsonSchema.ts
+++ b/packages/core/src/utils/jsonSchema.ts
@@ -1,150 +1,14 @@
import { z } from 'zod';
-
-type SchemaTypeToTsType = {
- [key: string]: unknown;
-};
-
-const PYDANTIC_TYPE_TO_TS_TYPE: SchemaTypeToTsType = {
- string: String,
- integer: Number,
- number: Number,
- boolean: Boolean,
- null: null,
-};
-
-export function jsonSchemaToTsType(jsonSchema: Record<string, unknown>): unknown {
- if (!jsonSchema.type) {
- jsonSchema.type = 'string';
- }
- const type = jsonSchema.type as string;
-
- if (type === 'array') {
- const itemsSchema = jsonSchema.items;
- if (itemsSchema) {
- const ItemType = jsonSchemaToTsType(itemsSchema as Record<string, unknown>);
- return ItemType;
- }
- return Array;
- }
-
- if (type === 'object') {
- const properties = jsonSchema.properties;
- if (properties) {
- const nestedModel = jsonSchemaToZodSchema(jsonSchema);
- return nestedModel;
- }
- return Object;
- }
-
- const tsType = PYDANTIC_TYPE_TO_TS_TYPE[type];
- if (tsType !== undefined) {
- return tsType;
- }
-
- throw new Error(`Unsupported JSON schema type: ${type}`);
-}
-
-export function jsonSchemaToTsField(
- name: string,
- jsonSchema: Record<string, unknown>,
- required: string[]
-): [unknown, Record<string, unknown>] {
- const description = jsonSchema.description;
- const examples = jsonSchema.examples || [];
- return [
- jsonSchemaToTsType(jsonSchema),
- {
- description: description,
- examples: examples,
- required: required.includes(name),
- default: required.includes(name) ? undefined : null,
- },
- ];
-}
-
-function jsonSchemaPropertiesToTSTypes(value: {
- type: string;
- description?: string;
- examples?: string[];
- items?: Record<string, unknown>;
-}): z.ZodTypeAny {
- if (!value.type) {
- return z.object({});
- }
-
- let zodType;
- switch (value.type) {
- case 'string':
- zodType = z
- .string()
- .describe(
- (value.description || '') +
- (value.examples ? `\nExamples: ${value.examples.join(', ')}` : '')
- );
- break;
- case 'number':
- zodType = z
- .number()
- .describe(
- (value.description || '') +
- (value.examples ? `\nExamples: ${value.examples.join(', ')}` : '')
- );
- break;
- case 'integer':
- zodType = z
- .number()
- .int()
- .describe(
- (value.description || '') +
- (value.examples ? `\nExamples: ${value.examples.join(', ')}` : '')
- );
- break;
- case 'boolean':
- zodType = z
- .boolean()
- .describe(
- (value.description || '') +
- (value.examples ? `\nExamples: ${value.examples.join(', ')}` : '')
- );
- break;
- case 'array':
- zodType = z
- .array(
- jsonSchemaPropertiesToTSTypes(
- value.items as {
- type: string;
- description?: string;
- examples?: string[];
- items?: Record<string, unknown>;
- }
- )
- )
- .describe(
- (value.description || '') +
- (value.examples ? `\nExamples: ${value.examples.join(', ')}` : '')
- );
- break;
- case 'object':
- zodType = jsonSchemaToZodSchema(value).describe(
- (value.description || '') +
- (value.examples ? `\nExamples: ${value.examples.join(', ')}` : '')
- );
- break;
- case 'null':
- zodType = z.null().describe(value.description || '');
- break;
- default:
- throw new Error(`Unsupported JSON schema type: ${value.type}`);
- }
-
- return zodType;
-}
+import { JsonSchemaToZodError } from '../errors';
+import { jsonSchemaToZod } from '@composio/json-schema-to-zod';
/**
* Convert a JSON schema to a Zod schema
* @param jsonSchema - The JSON schema to convert
* @returns The Zod schema
*
+ * @throws {JsonSchemaToZodError} If the JSON schema is invalid
+ *
* @example
* ```ts
* const zodSchema = jsonSchemaToZodSchema({
@@ -160,79 +24,12 @@ function jsonSchemaPropertiesToTSTypes(value: {
export function jsonSchemaToZodSchema(
jsonSchema: Record<string, unknown>
): z.ZodObject<Record<string, z.ZodTypeAny>> {
- const properties = jsonSchema.properties as Record<string, unknown>;
- const requiredFields = (jsonSchema.required as string[]) || [];
- if (!properties) {
- return z.object({});
- }
-
- const zodSchema: Record<string, z.ZodTypeAny> = {};
- for (const [key, _] of Object.entries(properties)) {
- const value = _ as Record<string, unknown>;
- let zodType;
- if (value.anyOf) {
- const anyOfTypes = (value.anyOf as Record<string, unknown>[]).map(schema =>
- jsonSchemaPropertiesToTSTypes(
- schema as {
- type: string;
- description?: string;
- examples?: string[];
- items?: Record<string, unknown>;
- }
- )
- );
- zodType = z
- .union(anyOfTypes as [z.ZodTypeAny, z.ZodTypeAny, ...z.ZodTypeAny[]])
- .describe(
- ((value.description as string) || '') +
- (value.examples ? `\nExamples: ${(value.examples as string[]).join(', ')}` : '')
- );
- } else if (value.allOf) {
- const allOfTypes = (value.allOf as Record<string, unknown>[]).map(schema =>
- jsonSchemaPropertiesToTSTypes(
- schema as {
- type: string;
- description?: string;
- examples?: string[];
- items?: Record<string, unknown>;
- }
- )
- );
- zodType = z
- .intersection(
- allOfTypes[0],
- allOfTypes
- .slice(1)
- .reduce((acc: z.ZodTypeAny, schema: z.ZodTypeAny) => acc.and(schema), allOfTypes[0])
- )
- .describe(
- ((value.description as string) || '') +
- (value.examples ? `\nExamples: ${(value.examples as string[]).join(', ')}` : '')
- );
- } else {
- if (!value.type) {
- value.type = 'string';
- }
- zodType = jsonSchemaPropertiesToTSTypes(
- value as {
- type: string;
- description?: string;
- examples?: string[];
- items?: Record<string, unknown>;
- }
- );
- }
-
- if (value.description) {
- zodType = zodType.describe(value.description as string);
- }
-
- if (requiredFields.includes(key)) {
- zodSchema[key] = zodType;
- } else {
- zodSchema[key] = zodType.optional();
- }
+ try {
+ // Convert the JSON schema properties to Zod schema
+ return jsonSchemaToZod(jsonSchema);
+ } catch (error) {
+ throw new JsonSchemaToZodError('Failed to convert JSON Schema to Zod Schema', {
+ cause: error,
+ });
}
-
- return z.object(zodSchema);
}
diff --git a/packages/core/test/utils/mocks/data.mock.ts b/packages/core/test/utils/mocks/data.mock.ts
index c62cb0e54..d3fc8ad01 100644
--- a/packages/core/test/utils/mocks/data.mock.ts
+++ b/packages/core/test/utils/mocks/data.mock.ts
@@ -13,6 +13,7 @@ export const toolMocks = {
description: 'The search query',
},
},
+ additionalProperties: false,
},
output_parameters: {
type: 'object',
@@ -24,6 +25,7 @@ export const toolMocks = {
},
},
},
+ additionalProperties: false,
},
toolkit: {
logo: 'https://example.com/logo.png',
@@ -75,6 +77,7 @@ export const toolMocks = {
description: 'The search query',
},
},
+ additionalProperties: false,
},
outputParameters: {
type: 'object',
@@ -86,6 +89,7 @@ export const toolMocks = {
},
},
},
+ additionalProperties: false,
},
},
// transformed response from the sdk
diff --git a/packages/json-schema-to-zod/README.md b/packages/json-schema-to-zod/README.md
new file mode 100644
index 000000000..497abf18c
--- /dev/null
+++ b/packages/json-schema-to-zod/README.md
@@ -0,0 +1,34 @@
+# Json-Schema-to-Zod
+
+A package to convert JSON schema (draft 4+) objects into Zod schemas in the form of Zod objects at runtime.
+
+## Installation
+
+```sh
+npm install @composio/json-schema-to-zod
+```
+
+### Simple example
+
+```typescript
+import { jsonSchemaToZod } from 'json-schema-to-zod';
+
+const jsonSchema = {
+ type: 'object',
+ properties: {
+ hello: {
+ type: 'string',
+ },
+ },
+};
+
+const zodSchema = jsonSchemaToZod(myObject);
+```
+
+### Overriding a parser
+
+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.
+
+## Acknowledgements
+
+This is a fork of [`json-schema-to-zod`](https://github.com/StefanTerdell/json-schema-to-zod).
diff --git a/packages/json-schema-to-zod/eslint.config.mjs b/packages/json-schema-to-zod/eslint.config.mjs
new file mode 100644
index 000000000..6af0ee0ef
--- /dev/null
+++ b/packages/json-schema-to-zod/eslint.config.mjs
@@ -0,0 +1,6 @@
+module.exports = {
+ extends: ['../../.eslintrc.cjs'],
+ // parserOptions: {
+ // project: ['./tsconfig.json'],
+ // },
+}
diff --git a/packages/json-schema-to-zod/package.json b/packages/json-schema-to-zod/package.json
new file mode 100644
index 000000000..51897532d
--- /dev/null
+++ b/packages/json-schema-to-zod/package.json
@@ -0,0 +1,39 @@
+{
+ "name": "@composio/json-schema-to-zod",
+ "version": "0.1.0",
+ "description": "",
+ "main": "src/index.ts",
+ "type": "module",
+ "publishConfig": {
+ "access": "public",
+ "main": "dist/index.js",
+ "types": "dist/index.d.ts"
+ },
+ "exports": {
+ ".": {
+ "import": "./dist/index.js",
+ "types": "./dist/index.d.ts",
+ "require": "./dist/index.cjs"
+ }
+ },
+ "files": [
+ "README.md",
+ "dist"
+ ],
+ "scripts": {
+ "build": "tsup",
+ "test": "vitest run"
+ },
+ "keywords": [],
+ "author": "",
+ "license": "ISC",
+ "packageManager": "[email protected]",
+ "devDependencies": {
+ "tsup": "^8.4.0",
+ "typescript": "^5.8.3",
+ "vitest": "^3.1.4"
+ },
+ "dependencies": {
+ "zod": "^3.24.2"
+ }
+}
diff --git a/packages/json-schema-to-zod/src/index.ts b/packages/json-schema-to-zod/src/index.ts
new file mode 100644
index 000000000..8de0516a2
--- /dev/null
+++ b/packages/json-schema-to-zod/src/index.ts
@@ -0,0 +1,2 @@
+export type * from './types';
+export { jsonSchemaToZod } from './json-schema-to-zod';
diff --git a/packages/json-schema-to-zod/src/json-schema-to-zod.ts b/packages/json-schema-to-zod/src/json-schema-to-zod.ts
new file mode 100644
index 000000000..6f1c6a131
--- /dev/null
+++ b/packages/json-schema-to-zod/src/json-schema-to-zod.ts
@@ -0,0 +1,15 @@
+import type { z } from 'zod';
+
+import { parseSchema } from './parsers/parse-schema';
+import type { JsonSchemaToZodOptions, JsonSchema } from './types';
+
+export const jsonSchemaToZod = <T extends z.ZodTypeAny = z.ZodTypeAny>(
+ schema: JsonSchema,
+ options: JsonSchemaToZodOptions = {},
+): T => {
+ return parseSchema(schema, {
+ path: [],
+ seen: new Map(),
+ ...options,
+ }) as T;
+};
diff --git a/packages/json-schema-to-zod/src/parsers/parse-all-of.ts b/packages/json-schema-to-zod/src/parsers/parse-all-of.ts
new file mode 100644
index 000000000..be8fd2c7e
--- /dev/null
+++ b/packages/json-schema-to-zod/src/parsers/parse-all-of.ts
@@ -0,0 +1,46 @@
+import { z } from 'zod';
+
+import { parseSchema } from './parse-schema';
+import type { JsonSchemaObject, JsonSchema, Refs } from '../types';
+import { half } from '../utils/half';
+
+const originalIndex = Symbol('Original index');
+
+const ensureOriginalIndex = (arr: JsonSchema[]) => {
+ const newArr = [];
+
+ for (let i = 0; i < arr.length; i++) {
+ const item = arr[i];
+ if (typeof item === 'boolean') {
+ newArr.push(item ? { [originalIndex]: i } : { [originalIndex]: i, not: {} });
+ } else if (originalIndex in item) {
+ return arr;
+ } else {
+ newArr.push({ ...item, [originalIndex]: i });
+ }
+ }
+
+ return newArr;
+};
+
+export function parseAllOf(
+ jsonSchema: JsonSchemaObject & { allOf: JsonSchema[] },
+ refs: Refs,
+): z.ZodTypeAny {
+ if (jsonSchema.allOf.length === 0) {
+ return z.never();
+ }
+
+ if (jsonSchema.allOf.length === 1) {
+ const item = jsonSchema.allOf[0];
+
+ return parseSchema(item, {
+ ...refs,
+ path: [...refs.path, 'allOf', (item as never)[originalIndex]],
+ });
+ }
+
+ const [left, right] = half(ensureOriginalIndex(jsonSchema.allOf));
+
+ return z.intersection(parseAllOf({ allOf: left }, refs), parseAllOf({ allOf: right }, refs));
+}
diff --git a/packages/json-schema-to-zod/src/parsers/parse-any-of.ts b/packages/json-schema-to-zod/src/parsers/parse-any-of.ts
new file mode 100644
index 000000000..73b19b173
--- /dev/null
+++ b/packages/json-schema-to-zod/src/parsers/parse-any-of.ts
@@ -0,0 +1,19 @@
+import { z } from 'zod';
+
+import { parseSchema } from './parse-schema';
+import type { JsonSchemaObject, JsonSchema, Refs } from '../types';
+
+export const parseAnyOf = (jsonSchema: JsonSchemaObject & { anyOf: JsonSchema[] }, refs: Refs) => {
+ return jsonSchema.anyOf.length
+ ? jsonSchema.anyOf.length === 1
+ ? parseSchema(jsonSchema.anyOf[0], {
+ ...refs,
+ path: [...refs.path, 'anyOf', 0],
+ })
+ : z.union(
+ jsonSchema.anyOf.map((schema, i) =>
+ parseSchema(schema, { ...refs, path: [...refs.path, 'anyOf', i] }),
+ ) as [z.ZodTypeAny, z.ZodTypeAny],
+ )
+ : z.any();
+};
diff --git a/packages/json-schema-to-zod/src/parsers/parse-array.ts b/packages/json-schema-to-zod/src/parsers/parse-array.ts
new file mode 100644
index 000000000..5e01473fd
--- /dev/null
+++ b/packages/json-schema-to-zod/src/parsers/parse-array.ts
@@ -0,0 +1,34 @@
+import { z } from 'zod';
+
+import { parseSchema } from './parse-schema';
+import type { JsonSchemaObject, Refs } from '../types';
+import { extendSchemaWithMessage } from '../utils/extend-schema';
+
+export const parseArray = (jsonSchema: JsonSchemaObject & { type: 'array' }, refs: Refs) => {
+ if (Array.isArray(jsonSchema.items)) {
+ return z.tuple(
+ jsonSchema.items.map((v, i) =>
+ parseSchema(v, { ...refs, path: [...refs.path, 'items', i] }),
+ ) as [z.ZodTypeAny],
+ );
+ }
+
+ let zodSchema = !jsonSchema.items
+ ? z.array(z.any())
+ : z.array(parseSchema(jsonSchema.items, { ...refs, path: [...refs.path, 'items'] }));
+
+ zodSchema = extendSchemaWithMessage(
+ zodSchema,
+ jsonSchema,
+ 'minItems',
+ (zs, minItems, errorMessage) => zs.min(minItems, errorMessage),
+ );
+ zodSchema = extendSchemaWithMessage(
+ zodSchema,
+ jsonSchema,
+ 'maxItems',
+ (zs, maxItems, errorMessage) => zs.max(maxItems, errorMessage),
+ );
+
+ return zodSchema;
+};
diff --git a/packages/json-schema-to-zod/src/parsers/parse-boolean.ts b/packages/json-schema-to-zod/src/parsers/parse-boolean.ts
new file mode 100644
index 000000000..be8e309e4
--- /dev/null
+++ b/packages/json-schema-to-zod/src/parsers/parse-boolean.ts
@@ -0,0 +1,7 @@
+import { z } from 'zod';
+
+import type { JsonSchemaObject } from '../types';
+
+export const parseBoolean = (_jsonSchema: JsonSchemaObject & { type: 'boolean' }) => {
+ return z.boolean();
+};
diff --git a/packages/json-schema-to-zod/src/parsers/parse-const.ts b/packages/json-schema-to-zod/src/parsers/parse-const.ts
new file mode 100644
index 000000000..445523652
--- /dev/null
+++ b/packages/json-schema-to-zod/src/parsers/parse-const.ts
@@ -0,0 +1,7 @@
+import { z } from 'zod';
+
+import type { JsonSchemaObject, Serializable } from '../types';
+
+export const parseConst = (jsonSchema: JsonSchemaObject & { const: Serializable }) => {
+ return z.literal(jsonSchema.const as z.Primitive);
+};
diff --git a/packages/json-schema-to-zod/src/parsers/parse-default.ts b/packages/json-schema-to-zod/src/parsers/parse-default.ts
new file mode 100644
index 000000000..d64bcf85c
--- /dev/null
+++ b/packages/json-schema-to-zod/src/parsers/parse-default.ts
@@ -0,0 +1,7 @@
+import { z } from 'zod';
+
+import type { JsonSchemaObject } from '../types';
+
+export const parseDefault = (_jsonSchema: JsonSchemaObject) => {
+ return z.any();
+};
diff --git a/packages/json-schema-to-zod/src/parsers/parse-enum.ts b/packages/json-schema-to-zod/src/parsers/parse-enum.ts
new file mode 100644
index 000000000..26385472c
--- /dev/null
+++ b/packages/json-schema-to-zod/src/parsers/parse-enum.ts
@@ -0,0 +1,25 @@
+import { z } from 'zod';
+
+import type { JsonSchemaObject, Serializable } from '../types';
+
+export const parseEnum = (jsonSchema: JsonSchemaObject & { enum: Serializable[] }) => {
+ if (jsonSchema.enum.length === 0) {
+ return z.never();
+ }
+
+ if (jsonSchema.enum.length === 1) {
+ // union does not work when there is only one element
+ return z.literal(jsonSchema.enum[0] as z.Primitive);
+ }
+
+ if (jsonSchema.enum.every((x) => typeof x === 'string')) {
+ return z.enum(jsonSchema.enum as [string]);
+ }
+
+ return z.union(
+ jsonSchema.enum.map((x) => z.literal(x as z.Primitive)) as unknown as [
+ z.ZodTypeAny,
+ z.ZodTypeAny,
+ ],
+ );
+};
diff --git a/packages/json-schema-to-zod/src/parsers/parse-if-then-else.ts b/packages/json-schema-to-zod/src/parsers/parse-if-then-else.ts
new file mode 100644
index 000000000..96542f3d7
--- /dev/null
+++ b/packages/json-schema-to-zod/src/parsers/parse-if-then-else.ts
@@ -0,0 +1,31 @@
+import { z } from 'zod';
+
+import { parseSchema } from './parse-schema';
+import type { JsonSchemaObject, JsonSchema, Refs } from '../types';
+
+export const parseIfThenElse = (
+ jsonSchema: JsonSchemaObject & {
+ if: JsonSchema;
+ then: JsonSchema;
+ else: JsonSchema;
+ },
+ refs: Refs
+) => {
+ const $if = parseSchema(jsonSchema.if, { ...refs, path: [...refs.path, 'if'] });
+ const $then = parseSchema(jsonSchema.then, {
+ ...refs,
+ path: [...refs.path, 'then'],
+ });
+ const $else = parseSchema(jsonSchema.else, {
+ ...refs,
+ path: [...refs.path, 'else'],
+ });
+
+ return z.union([$then, $else]).superRefine((value, ctx) => {
+ const result = $if.safeParse(value).success ? $then.safeParse(value) : $else.safeParse(value);
+
+ if (!result.success) {
+ result.error.errors.forEach(error => ctx.addIssue(error));
+ }
+ });
+};
diff --git a/packages/json-schema-to-zod/src/parsers/parse-multiple-type.ts b/packages/json-schema-to-zod/src/parsers/parse-multiple-type.ts
new file mode 100644
index 000000000..65ff3c35b
--- /dev/null
+++ b/packages/json-schema-to-zod/src/parsers/parse-multiple-type.ts
@@ -0,0 +1,16 @@
+import { z } from 'zod';
+
+import { parseSchema } from './parse-schema';
+import type { JsonSchema, JsonSchemaObject, Refs } from '../types';
+
+export const parseMultipleType = (
+ jsonSchema: JsonSchemaObject & { type: string[] },
+ refs: Refs,
+) => {
+ return z.union(
+ jsonSchema.type.map((type) => parseSchema({ ...jsonSchema, type } as JsonSchema, refs)) as [
+ z.ZodTypeAny,
+ z.ZodTypeAny,
+ ],
+ );
+};
diff --git a/packages/json-schema-to-zod/src/parsers/parse-not.ts b/packages/json-schema-to-zod/src/parsers/parse-not.ts
new file mode 100644
index 000000000..219d32c8d
--- /dev/null
+++ b/packages/json-schema-to-zod/src/parsers/parse-not.ts
@@ -0,0 +1,15 @@
+import { z } from 'zod';
+
+import { parseSchema } from './parse-schema';
+import type { JsonSchemaObject, JsonSchema, Refs } from '../types';
+
+export const parseNot = (jsonSchema: JsonSchemaObject & { not: JsonSchema }, refs: Refs) => {
+ return z.any().refine(
+ (value) =>
+ !parseSchema(jsonSchema.not, {
+ ...refs,
+ path: [...refs.path, 'not'],
+ }).safeParse(value).success,
+ 'Invalid input: Should NOT be valid against schema',
+ );
+};
diff --git a/packages/json-schema-to-zod/src/parsers/parse-null.ts b/packages/json-schema-to-zod/src/parsers/parse-null.ts
new file mode 100644
index 000000000..86dbfea43
--- /dev/null
+++ b/packages/json-schema-to-zod/src/parsers/parse-null.ts
@@ -0,0 +1,7 @@
+import { z } from 'zod';
+
+import type { JsonSchemaObject } from '../types';
+
+export const parseNull = (_jsonSchema: JsonSchemaObject & { type: 'null' }) => {
+ return z.null();
+};
diff --git a/packages/json-schema-to-zod/src/parsers/parse-nullable.ts b/packages/json-schema-to-zod/src/parsers/parse-nullable.ts
new file mode 100644
index 000000000..cfc575e9c
--- /dev/null
+++ b/packages/json-schema-to-zod/src/parsers/parse-nullable.ts
@@ -0,0 +1,10 @@
+import { parseSchema } from './parse-schema';
+import type { JsonSchemaObject, Refs } from '../types';
+import { omit } from '../utils/omit';
+
+/**
+ * For compatibility with open api 3.0 nullable
+ */
+export const parseNullable = (jsonSchema: JsonSchemaObject & { nullable: true }, refs: Refs) => {
+ return parseSchema(omit(jsonSchema, 'nullable'), refs, true).nullable();
+};
diff --git a/packages/json-schema-to-zod/src/parsers/parse-number.ts b/packages/json-schema-to-zod/src/parsers/parse-number.ts
new file mode 100644
index 000000000..504a453fa
--- /dev/null
+++ b/packages/json-schema-to-zod/src/parsers/parse-number.ts
@@ -0,0 +1,88 @@
+import { z } from 'zod';
+
+import type { JsonSchemaObject } from '../types';
+import { extendSchemaWithMessage } from '../utils/extend-schema';
+
+export const parseNumber = (jsonSchema: JsonSchemaObject & { type: 'number' | 'integer' }) => {
+ let zodSchema = z.number();
+
+ let isInteger = false;
+ if (jsonSchema.type === 'integer') {
+ isInteger = true;
+ zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, 'type', (zs, _, errorMsg) =>
+ zs.int(errorMsg),
+ );
+ } else if (jsonSchema.format === 'int64') {
+ isInteger = true;
+ zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, 'format', (zs, _, errorMsg) =>
+ zs.int(errorMsg),
+ );
+ }
+
+ zodSchema = extendSchemaWithMessage(
+ zodSchema,
+ jsonSchema,
+ 'multipleOf',
+ (zs, multipleOf, errorMsg) => {
+ if (multipleOf === 1) {
+ if (isInteger) return zs;
+
+ return zs.int(errorMsg);
+ }
+
+ return zs.multipleOf(multipleOf, errorMsg);
+ },
+ );
+
+ if (typeof jsonSchema.minimum === 'number') {
+ if (jsonSchema.exclusiveMinimum === true) {
+ zodSchema = extendSchemaWithMessage(
+ zodSchema,
+ jsonSchema,
+ 'minimum',
+ (zs, minimum, errorMsg) => zs.gt(minimum, errorMsg),
+ );
+ } else {
+ zodSchema = extendSchemaWithMessage(
+ zodSchema,
+ jsonSchema,
+ 'minimum',
+ (zs, minimum, errorMsg) => zs.gte(minimum, errorMsg),
+ );
+ }
+ } else if (typeof jsonSchema.exclusiveMinimum === 'number') {
+ zodSchema = extendSchemaWithMessage(
+ zodSchema,
+ jsonSchema,
+ 'exclusiveMinimum',
+ (zs, exclusiveMinimum, errorMsg) => zs.gt(exclusiveMinimum as number, errorMsg),
+ );
+ }
+
+ if (typeof jsonSchema.maximum === 'number') {
+ if (jsonSchema.exclusiveMaximum === true) {
+ zodSchema = extendSchemaWithMessage(
+ zodSchema,
+ jsonSchema,
+ 'maximum',
+ (zs, maximum, errorMsg) => zs.lt(maximum, errorMsg),
+ );
+ } else {
+ zodSchema = extendSchemaWithMessage(
+ zodSchema,
+ jsonSchema,
+ 'maximum',
+ (zs, maximum, errorMsg) => zs.lte(maximum, errorMsg),
+ );
+ }
+ } else if (typeof jsonSchema.exclusiveMaximum === 'number') {
+ zodSchema = extendSchemaWithMessage(
+ zodSchema,
+ jsonSchema,
+ 'exclusiveMaximum',
+ (zs, exclusiveMaximum, errorMsg) => zs.lt(exclusiveMaximum as number, errorMsg),
+ );
+ }
+
+ return zodSchema;
+};
diff --git a/packages/json-schema-to-zod/src/parsers/parse-object.ts b/packages/json-schema-to-zod/src/parsers/parse-object.ts
new file mode 100644
index 000000000..7aecf7ba7
--- /dev/null
+++ b/packages/json-schema-to-zod/src/parsers/parse-object.ts
@@ -0,0 +1,227 @@
+import * as z from 'zod';
+
+import { parseAllOf } from './parse-all-of';
+import { parseAnyOf } from './parse-any-of';
+import { parseOneOf } from './parse-one-of';
+import { parseSchema } from './parse-schema';
+import type { JsonSchemaObject, Refs } from '../types';
+import { its } from '../utils/its';
+
+function parseObjectProperties(objectSchema: JsonSchemaObject & { type: 'object' }, refs: Refs) {
+ if (!objectSchema.properties) {
+ return undefined;
+ }
+
+ const propertyKeys = Object.keys(objectSchema.properties);
+ if (propertyKeys.length === 0) {
+ return z.object({});
+ }
+
+ const properties: Record<string, z.ZodTypeAny> = {};
+
+ for (const key of propertyKeys) {
+ const propJsonSchema = objectSchema.properties[key];
+
+ const propZodSchema = parseSchema(propJsonSchema, {
+ ...refs,
+ path: [...refs.path, 'properties', key],
+ });
+
+ const hasDefault = typeof propJsonSchema === 'object' && propJsonSchema.default !== undefined;
+ const required = Array.isArray(objectSchema.required)
+ ? objectSchema.required.includes(key)
+ : typeof propJsonSchema === 'object' && propJsonSchema.required === true;
+
+ // If property has a default value or is an object with nested defaults,
+ // we should include it in the schema even if it's not required
+ const isOptional =
+ !hasDefault &&
+ !required &&
+ !(
+ typeof propJsonSchema === 'object' &&
+ propJsonSchema.type === 'object' &&
+ propJsonSchema.properties
+ );
+
+ properties[key] = isOptional ? propZodSchema.optional() : propZodSchema;
+ }
+
+ return z.object(properties);
+}
+
+export function parseObject(
+ objectSchema: JsonSchemaObject & { type: 'object' },
+ refs: Refs
+): z.ZodTypeAny {
+ const hasPatternProperties = Object.keys(objectSchema.patternProperties ?? {}).length > 0;
+
+ const propertiesSchema:
+ | z.ZodObject<Record<string, z.ZodTypeAny>, 'strip', z.ZodTypeAny>
+ | undefined = parseObjectProperties(objectSchema, refs);
+ let zodSchema: z.ZodTypeAny | undefined = propertiesSchema;
+
+ const additionalProperties =
+ objectSchema.additionalProperties !== undefined
+ ? parseSchema(objectSchema.additionalProperties, {
+ ...refs,
+ path: [...refs.path, 'additionalProperties'],
+ })
+ : undefined;
+
+ if (objectSchema.patternProperties) {
+ const parsedPatternProperties = Object.fromEntries(
+ Object.entries(objectSchema.patternProperties).map(([key, value]) => {
+ return [
+ key,
+ parseSchema(value, {
+ ...refs,
+ path: [...refs.path, 'patternProperties', key],
+ }),
+ ];
+ })
+ );
+ const patternPropertyValues = Object.values(parsedPatternProperties);
+
+ if (propertiesSchema) {
+ if (additionalProperties) {
+ zodSchema = propertiesSchema.catchall(
+ z.union([...patternPropertyValues, additionalProperties] as [z.ZodTypeAny, z.ZodTypeAny])
+ );
+ } else if (Object.keys(parsedPatternProperties).length > 1) {
+ zodSchema = propertiesSchema.catchall(
+ z.union(patternPropertyValues as [z.ZodTypeAny, z.ZodTypeAny])
+ );
+ } else {
+ zodSchema = propertiesSchema.catchall(patternPropertyValues[0]);
+ }
+ } else {
+ if (additionalProperties) {
+ zodSchema = z.record(
+ z.union([...patternPropertyValues, additionalProperties] as [z.ZodTypeAny, z.ZodTypeAny])
+ );
+ } else if (patternPropertyValues.length > 1) {
+ zodSchema = z.record(z.union(patternPropertyValues as [z.ZodTypeAny, z.ZodTypeAny]));
+ } else {
+ zodSchema = z.record(patternPropertyValues[0]);
+ }
+ }
+
+ const objectPropertyKeys = new Set(Object.keys(objectSchema.properties ?? {}));
+ zodSchema = zodSchema.superRefine((value: Record<string, unknown>, ctx) => {
+ for (const key in value) {
+ let wasMatched = objectPropertyKeys.has(key);
+
+ for (const patternPropertyKey in objectSchema.patternProperties) {
+ const regex = new RegExp(patternPropertyKey);
+ if (key.match(regex)) {
+ wasMatched = true;
+ const result = parsedPatternProperties[patternPropertyKey].safeParse(value[key]);
+ if (!result.success) {
+ ctx.addIssue({
+ path: [...ctx.path, key],
+ code: 'custom',
+ message: `Invalid input: Key matching regex /${key}/ must match schema`,
+ params: {
+ issues: result.error.issues,
+ },
+ });
+ }
+ }
+ }
+
+ if (!wasMatched && additionalProperties) {
+ const result = additionalProperties.safeParse(value[key]);
+ if (!result.success) {
+ ctx.addIssue({
+ path: [...ctx.path, key],
+ code: 'custom',
+ message: 'Invalid input: must match catchall schema',
+ params: {
+ issues: result.error.issues,
+ },
+ });
+ }
+ }
+ }
+ });
+ }
+
+ let output: z.ZodTypeAny;
+ if (propertiesSchema) {
+ if (hasPatternProperties) {
+ output = zodSchema!;
+ } else if (additionalProperties) {
+ if (additionalProperties instanceof z.ZodNever) {
+ output = propertiesSchema.strict();
+ } else {
+ output = propertiesSchema.catchall(additionalProperties);
+ }
+ } else {
+ output = zodSchema!;
+ }
+ } else {
+ if (hasPatternProperties) {
+ output = zodSchema!;
+ } else if (additionalProperties) {
+ output = z.record(additionalProperties);
+ } else {
+ output = z.record(z.any());
+ }
+ }
+
+ if (its.an.anyOf(objectSchema)) {
+ output = output.and(
+ parseAnyOf(
+ {
+ ...objectSchema,
+ anyOf: objectSchema.anyOf.map(x =>
+ typeof x === 'object' &&
+ !x.type &&
+ (x.properties ?? x.additionalProperties ?? x.patternProperties)
+ ? { ...x, type: 'object' }
+ : x
+ ),
+ },
+ refs
+ )
+ );
+ }
+
+ if (its.a.oneOf(objectSchema)) {
+ output = output.and(
+ parseOneOf(
+ {
+ ...objectSchema,
+ oneOf: objectSchema.oneOf.map(x =>
+ typeof x === 'object' &&
+ !x.type &&
+ (x.properties ?? x.additionalProperties ?? x.patternProperties)
+ ? { ...x, type: 'object' }
+ : x
+ ),
+ },
+ refs
+ )
+ );
+ }
+
+ if (its.an.allOf(objectSchema)) {
+ output = output.and(
+ parseAllOf(
+ {
+ ...objectSchema,
+ allOf: objectSchema.allOf.map(x =>
+ typeof x === 'object' &&
+ !x.type &&
+ (x.properties ?? x.additionalProperties ?? x.patternProperties)
+ ? { ...x, type: 'object' }
+ : x
+ ),
+ },
+ refs
+ )
+ );
+ }
+
+ return output;
+}
diff --git a/packages/json-schema-to-zod/src/parsers/parse-one-of.ts b/packages/json-schema-to-zod/src/parsers/parse-one-of.ts
new file mode 100644
index 000000000..10931a967
--- /dev/null
+++ b/packages/json-schema-to-zod/src/parsers/parse-one-of.ts
@@ -0,0 +1,41 @@
+import { z } from 'zod';
+
+import { parseSchema } from './parse-schema';
+import type { JsonSchemaObject, JsonSchema, Refs } from '../types';
+
+export const parseOneOf = (jsonSchema: JsonSchemaObject & { oneOf: JsonSchema[] }, refs: Refs) => {
+ if (!jsonSchema.oneOf.length) {
+ return z.any();
+ }
+
+ if (jsonSchema.oneOf.length === 1) {
+ return parseSchema(jsonSchema.oneOf[0], {
+ ...refs,
+ path: [...refs.path, 'oneOf', 0],
+ });
+ }
+
+ return z.any().superRefine((x, ctx) => {
+ const schemas = jsonSchema.oneOf.map((schema, i) =>
+ parseSchema(schema, {
+ ...refs,
+ path: [...refs.path, 'oneOf', i],
+ }),
+ );
+
+ const unionErrors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) => (result.error ? [...errors, result.error] : errors))(schema.safeParse(x)),
+ [],
+ );
+
+ if (schemas.length - unionErrors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors,
+ message: 'Invalid input: Should pass single schema',
+ });
+ }
+ });
+};
diff --git a/packages/json-schema-to-zod/src/parsers/parse-schema.ts b/packages/json-schema-to-zod/src/parsers/parse-schema.ts
new file mode 100644
index 000000000..ed50dbd2f
--- /dev/null
+++ b/packages/json-schema-to-zod/src/parsers/parse-schema.ts
@@ -0,0 +1,132 @@
+import * as z from 'zod';
+
+import { parseAllOf } from './parse-all-of';
+import { parseAnyOf } from './parse-any-of';
+import { parseArray } from './parse-array';
+import { parseBoolean } from './parse-boolean';
+import { parseConst } from './parse-const';
+import { parseDefault } from './parse-default';
+import { parseEnum } from './parse-enum';
+import { parseIfThenElse } from './parse-if-then-else';
+import { parseMultipleType } from './parse-multiple-type';
+import { parseNot } from './parse-not';
+import { parseNull } from './parse-null';
+import { parseNullable } from './parse-nullable';
+import { parseNumber } from './parse-number';
+import { parseObject } from './parse-object';
+import { parseOneOf } from './parse-one-of';
+import { parseString } from './parse-string';
+import type { ParserSelector, Refs, JsonSchemaObject, JsonSchema } from '../types';
+import { its } from '../utils/its';
+
+const addDescribes = (jsonSchema: JsonSchemaObject, zodSchema: z.ZodTypeAny): z.ZodTypeAny => {
+ if (jsonSchema.description) {
+ zodSchema = zodSchema.describe(jsonSchema.description);
+ } else if (jsonSchema.title) {
+ zodSchema = zodSchema.describe(jsonSchema.title);
+ }
+
+ return zodSchema;
+};
+
+const addDefaults = (jsonSchema: JsonSchemaObject, zodSchema: z.ZodTypeAny): z.ZodTypeAny => {
+ if (jsonSchema.default !== undefined) {
+ zodSchema = zodSchema.default(jsonSchema.default);
+ }
+
+ return zodSchema;
+};
+
+const addAnnotations = (jsonSchema: JsonSchemaObject, zodSchema: z.ZodTypeAny): z.ZodTypeAny => {
+ if (jsonSchema.readOnly) {
+ zodSchema = zodSchema.readonly();
+ }
+
+ return zodSchema;
+};
+
+const selectParser: ParserSelector = (schema, refs) => {
+ if (its.a.nullable(schema)) {
+ return parseNullable(schema, refs);
+ } else if (its.an.object(schema)) {
+ return parseObject(schema, refs);
+ } else if (its.an.array(schema)) {
+ return parseArray(schema, refs);
+ } else if (its.an.anyOf(schema)) {
+ return parseAnyOf(schema, refs);
+ } else if (its.an.allOf(schema)) {
+ return parseAllOf(schema, refs);
+ } else if (its.a.oneOf(schema)) {
+ return parseOneOf(schema, refs);
+ } else if (its.a.not(schema)) {
+ return parseNot(schema, refs);
+ } else if (its.an.enum(schema)) {
+ return parseEnum(schema); //<-- needs to come before primitives
+ } else if (its.a.const(schema)) {
+ return parseConst(schema);
+ } else if (its.a.multipleType(schema)) {
+ return parseMultipleType(schema, refs);
+ } else if (its.a.primitive(schema, 'string')) {
+ return parseString(schema);
+ } else if (its.a.primitive(schema, 'number') || its.a.primitive(schema, 'integer')) {
+ return parseNumber(schema);
+ } else if (its.a.primitive(schema, 'boolean')) {
+ return parseBoolean(schema);
+ } else if (its.a.primitive(schema, 'null')) {
+ return parseNull(schema);
+ } else if (its.a.conditional(schema)) {
+ return parseIfThenElse(schema, refs);
+ } else {
+ return parseDefault(schema);
+ }
+};
+
+export const parseSchema = (
+ jsonSchema: JsonSchema,
+ refs: Refs = { seen: new Map(), path: [] },
+ blockMeta?: boolean
+): z.ZodTypeAny => {
+ if (typeof jsonSchema !== 'object') return jsonSchema ? z.any() : z.never();
+
+ if (refs.parserOverride) {
+ const custom = refs.parserOverride(jsonSchema, refs);
+
+ if (custom instanceof z.ZodType) {
+ return custom;
+ }
+ }
+
+ let seen = refs.seen.get(jsonSchema);
+
+ if (seen) {
+ if (seen.r !== undefined) {
+ return seen.r;
+ }
+
+ if (refs.depth === undefined || seen.n >= refs.depth) {
+ return z.any();
+ }
+
+ seen.n += 1;
+ } else {
+ seen = { r: undefined, n: 0 };
+ refs.seen.set(jsonSchema, seen);
+ }
+
+ let parsedZodSchema = selectParser(jsonSchema, refs);
+ if (!blockMeta) {
+ if (!refs.withoutDescribes) {
+ parsedZodSchema = addDescribes(jsonSchema, parsedZodSchema);
+ }
+
+ if (!refs.withoutDefaults) {
+ parsedZodSchema = addDefaults(jsonSchema, parsedZodSchema);
+ }
+
+ parsedZodSchema = addAnnotations(jsonSchema, parsedZodSchema);
+ }
+
+ seen.r = parsedZodSchema;
+
+ return parsedZodSchema;
+};
diff --git a/packages/json-schema-to-zod/src/parsers/parse-string.ts b/packages/json-schema-to-zod/src/parsers/parse-string.ts
new file mode 100644
index 000000000..c8e587112
--- /dev/null
+++ b/packages/json-schema-to-zod/src/parsers/parse-string.ts
@@ -0,0 +1,58 @@
+import { z } from 'zod';
+
+import type { JsonSchemaObject } from '../types';
+import { extendSchemaWithMessage } from '../utils/extend-schema';
+
+export const parseString = (jsonSchema: JsonSchemaObject & { type: 'string' }) => {
+ let zodSchema = z.string();
+
+ zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, 'format', (zs, format, errorMsg) => {
+ switch (format) {
+ case 'email':
+ return zs.email(errorMsg);
+ case 'ip':
+ return zs.ip(errorMsg);
+ case 'ipv4':
+ return zs.ip({ version: 'v4', message: errorMsg });
+ case 'ipv6':
+ return zs.ip({ version: 'v6', message: errorMsg });
+ case 'uri':
+ return zs.url(errorMsg);
+ case 'uuid':
+ return zs.uuid(errorMsg);
+ case 'date-time':
+ return zs.datetime({ offset: true, message: errorMsg });
+ case 'time':
+ return zs.time(errorMsg);
+ case 'date':
+ return zs.date(errorMsg);
+ case 'binary':
+ return zs.base64(errorMsg);
+ case 'duration':
+ return zs.duration(errorMsg);
+ default:
+ return zs;
+ }
+ });
+
+ zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, 'contentEncoding', (zs, _, errorMsg) =>
+ zs.base64(errorMsg)
+ );
+ zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, 'pattern', (zs, pattern, errorMsg) =>
+ zs.regex(new RegExp(pattern), errorMsg)
+ );
+ zodSchema = extendSchemaWithMessage(
+ zodSchema,
+ jsonSchema,
+ 'minLength',
+ (zs, minLength, errorMsg) => zs.min(minLength, errorMsg)
+ );
+ zodSchema = extendSchemaWithMessage(
+ zodSchema,
+ jsonSchema,
+ 'maxLength',
+ (zs, maxLength, errorMsg) => zs.max(maxLength, errorMsg)
+ );
+
+ return zodSchema;
+};
diff --git a/packages/json-schema-to-zod/src/types.ts b/packages/json-schema-to-zod/src/types.ts
new file mode 100644
index 000000000..ec0c4f311
--- /dev/null
+++ b/packages/json-schema-to-zod/src/types.ts
@@ -0,0 +1,83 @@
+import type { ZodTypeAny } from 'zod';
+
+export type Serializable =
+ | { [key: string]: Serializable }
+ | Serializable[]
+ | string
+ | number
+ | boolean
+ | null;
+
+export type JsonSchema = JsonSchemaObject | boolean;
+export type JsonSchemaObject = {
+ // left permissive by design
+ type?: string | string[];
+
+ // object
+ properties?: { [key: string]: JsonSchema };
+ additionalProperties?: JsonSchema;
+ unevaluatedProperties?: JsonSchema;
+ patternProperties?: { [key: string]: JsonSchema };
+ minProperties?: number;
+ maxProperties?: number;
+ required?: string[] | boolean;
+ propertyNames?: JsonSchema;
+
+ // array
+ items?: JsonSchema | JsonSchema[];
+ additionalItems?: JsonSchema;
+ minItems?: number;
+ maxItems?: number;
+ uniqueItems?: boolean;
+
+ // string
+ minLength?: number;
+ maxLength?: number;
+ pattern?: string;
+ format?: string;
+
+ // number
+ minimum?: number;
+ maximum?: number;
+ exclusiveMinimum?: number | boolean;
+ exclusiveMaximum?: number | boolean;
+ multipleOf?: number;
+
+ // unions
+ anyOf?: JsonSchema[];
+ allOf?: JsonSchema[];
+ oneOf?: JsonSchema[];
+
+ if?: JsonSchema;
+ then?: JsonSchema;
+ else?: JsonSchema;
+
+ // shared
+ const?: Serializable;
+ enum?: Serializable[];
+
+ errorMessage?: { [key: string]: string | undefined };
+
+ description?: string;
+ title?: string;
+ default?: Serializable;
+ readOnly?: boolean;
+ not?: JsonSchema;
+ contentEncoding?: string;
+ nullable?: boolean;
+};
+
+export type ParserSelector = (schema: JsonSchemaObject, refs: Refs) => ZodTypeAny;
+export type ParserOverride = (schema: JsonSchemaObject, refs: Refs) => ZodTypeAny | undefined;
+
+export type JsonSchemaToZodOptions = {
+ withoutDefaults?: boolean;
+ withoutDescribes?: boolean;
+ parserOverride?: ParserOverride;
+ depth?: number;
+};
+
+export type Refs = JsonSchemaToZodOptions & {
+ path: Array<string | number>;
+ seen: Map<object | boolean, { n: number; r: ZodTypeAny | undefined }>;
+};
diff --git a/packages/json-schema-to-zod/src/utils/extend-schema.ts b/packages/json-schema-to-zod/src/utils/extend-schema.ts
new file mode 100644
index 000000000..1fd0ed720
--- /dev/null
+++ b/packages/json-schema-to-zod/src/utils/extend-schema.ts
@@ -0,0 +1,23 @@
+import type { z } from 'zod';
+
+import type { JsonSchemaObject } from '../types';
+
+export function extendSchemaWithMessage<
+ TZod extends z.ZodTypeAny,
+ TJson extends JsonSchemaObject,
+ TKey extends keyof TJson,
+>(
+ zodSchema: TZod,
+ jsonSchema: TJson,
+ key: TKey,
+ extend: (zodSchema: TZod, value: NonNullable<TJson[TKey]>, errorMessage?: string) => TZod,
+) {
+ const value = jsonSchema[key];
+
+ if (value !== undefined) {
+ const errorMessage = jsonSchema.errorMessage?.[key as string];
+ return extend(zodSchema, value as NonNullable<TJson[TKey]>, errorMessage);
+ }
+
+ return zodSchema;
+}
diff --git a/packages/json-schema-to-zod/src/utils/half.ts b/packages/json-schema-to-zod/src/utils/half.ts
new file mode 100644
index 000000000..810776e6c
--- /dev/null
+++ b/packages/json-schema-to-zod/src/utils/half.ts
@@ -0,0 +1,3 @@
+export const half = <T>(arr: T[]): [T[], T[]] => {
+ return [arr.slice(0, arr.length / 2), arr.slice(arr.length / 2)];
+};
diff --git a/packages/json-schema-to-zod/src/utils/its.ts b/packages/json-schema-to-zod/src/utils/its.ts
new file mode 100644
index 000000000..64db6675c
--- /dev/null
+++ b/packages/json-schema-to-zod/src/utils/its.ts
@@ -0,0 +1,56 @@
+import type { JsonSchema, JsonSchemaObject, Serializable } from '../types';
+
+export const its = {
+ an: {
+ object: (x: JsonSchemaObject): x is JsonSchemaObject & { type: 'object' } =>
+ x.type === 'object',
+ array: (x: JsonSchemaObject): x is JsonSchemaObject & { type: 'array' } => x.type === 'array',
+ anyOf: (
+ x: JsonSchemaObject
+ ): x is JsonSchemaObject & {
+ anyOf: JsonSchema[];
+ } => x.anyOf !== undefined,
+ allOf: (
+ x: JsonSchemaObject
+ ): x is JsonSchemaObject & {
+ allOf: JsonSchema[];
+ } => x.allOf !== undefined,
+ enum: (
+ x: JsonSchemaObject
+ ): x is JsonSchemaObject & {
+ enum: Serializable | Serializable[];
+ } => x.enum !== undefined,
+ },
+ a: {
+ nullable: (x: JsonSchemaObject): x is JsonSchemaObject & { nullable: true } =>
+ (x as unknown as { nullable: boolean }).nullable === true,
+ multipleType: (x: JsonSchemaObject): x is JsonSchemaObject & { type: string[] } =>
+ Array.isArray(x.type),
+ not: (
+ x: JsonSchemaObject
+ ): x is JsonSchemaObject & {
+ not: JsonSchema;
+ } => x.not !== undefined,
+ const: (
+ x: JsonSchemaObject
+ ): x is JsonSchemaObject & {
+ const: Serializable;
+ } => x.const !== undefined,
+ primitive: <T extends 'string' | 'number' | 'integer' | 'boolean' | 'null'>(
+ x: JsonSchemaObject,
+ p: T
+ ): x is JsonSchemaObject & { type: T } => x.type === p,
+ conditional: (
+ x: JsonSchemaObject
+ ): x is JsonSchemaObject & {
+ if: JsonSchema;
+ then: JsonSchema;
+ else: JsonSchema;
+ } => Boolean('if' in x && x.if && 'then' in x && 'else' in x && x.then && x.else),
+ oneOf: (
+ x: JsonSchemaObject
+ ): x is JsonSchemaObject & {
+ oneOf: JsonSchema[];
+ } => x.oneOf !== undefined,
+ },
+};
diff --git a/packages/json-schema-to-zod/src/utils/omit.ts b/packages/json-schema-to-zod/src/utils/omit.ts
new file mode 100644
index 000000000..af9d579fb
--- /dev/null
+++ b/packages/json-schema-to-zod/src/utils/omit.ts
@@ -0,0 +1,8 @@
+export const omit = <T extends object, K extends keyof T>(obj: T, ...keys: K[]): Omit<T, K> =>
+ Object.keys(obj).reduce((acc: Record<string, unknown>, key) => {
+ if (!keys.includes(key as K)) {
+ acc[key] = obj[key as K];
+ }
+
+ return acc;
+ }, {}) as Omit<T, K>;
diff --git a/packages/json-schema-to-zod/test/json-to-zod.test.ts b/packages/json-schema-to-zod/test/json-to-zod.test.ts
new file mode 100644
index 000000000..6137f1e1c
--- /dev/null
+++ b/packages/json-schema-to-zod/test/json-to-zod.test.ts
@@ -0,0 +1,453 @@
+import { describe, it, expect } from 'vitest';
+import { z } from 'zod';
+import { jsonSchemaToZod } from '../src/json-schema-to-zod';
+import type { JsonSchema } from '../src/types';
+
+describe('jsonSchemaToZod', () => {
+ describe('Basic Types', () => {
+ it('should convert string schema', () => {
+ const schema: JsonSchema = {
+ type: 'string',
+ };
+ const zodSchema = jsonSchemaToZod(schema);
+ expect(zodSchema).toBeInstanceOf(z.ZodString);
+ expect(zodSchema.parse('test')).toBe('test');
+ expect(() => zodSchema.parse(123)).toThrow();
+ });
+
+ it('should convert number schema', () => {
+ const schema: JsonSchema = {
+ type: 'number',
+ };
+ const zodSchema = jsonSchemaToZod(schema);
+ expect(zodSchema).toBeInstanceOf(z.ZodNumber);
+ expect(zodSchema.parse(123)).toBe(123);
+ expect(() => zodSchema.parse('123')).toThrow();
+ });
+
+ it('should convert integer schema', () => {
+ const schema: JsonSchema = {
+ type: 'integer',
+ };
+ const zodSchema = jsonSchemaToZod(schema);
+ expect(zodSchema.parse(123)).toBe(123);
+ expect(() => zodSchema.parse(123.45)).toThrow();
+ });
+
+ it('should convert boolean schema', () => {
+ const schema: JsonSchema = {
+ type: 'boolean',
+ };
+ const zodSchema = jsonSchemaToZod(schema);
+ expect(zodSchema).toBeInstanceOf(z.ZodBoolean);
+ expect(zodSchema.parse(true)).toBe(true);
+ expect(() => zodSchema.parse('true')).toThrow();
+ });
+
+ it('should convert null schema', () => {
+ const schema: JsonSchema = {
+ type: 'null',
+ };
+ const zodSchema = jsonSchemaToZod(schema);
+ expect(zodSchema).toBeInstanceOf(z.ZodNull);
+ expect(zodSchema.parse(null)).toBe(null);
+ expect(() => zodSchema.parse(undefined)).toThrow();
+ });
+ });
+
+ describe('String Formats', () => {
+ it('should validate email format', () => {
+ const schema: JsonSchema = {
+ type: 'string',
+ format: 'email',
+ };
+ const zodSchema = jsonSchemaToZod(schema);
+ expect(zodSchema.parse('[email protected]')).toBe('[email protected]');
+ expect(() => zodSchema.parse('invalid-email')).toThrow();
+ });
+
+ it('should validate date-time format', () => {
+ const schema: JsonSchema = {
+ type: 'string',
+ format: 'date-time',
+ };
+ const zodSchema = jsonSchemaToZod(schema);
+ expect(zodSchema.parse('2024-03-20T12:00:00Z')).toBe('2024-03-20T12:00:00Z');
+ expect(() => zodSchema.parse('invalid-date')).toThrow();
+ });
+
+ it('should validate uuid format', () => {
+ const schema: JsonSchema = {
+ type: 'string',
+ format: 'uuid',
+ };
+ const zodSchema = jsonSchemaToZod(schema);
+ expect(zodSchema.parse('123e4567-e89b-12d3-a456-426614174000')).toBe(
+ '123e4567-e89b-12d3-a456-426614174000'
+ );
+ expect(() => zodSchema.parse('invalid-uuid')).toThrow();
+ });
+ });
+
+ describe('Number Validations', () => {
+ it('should validate minimum and maximum', () => {
+ const schema: JsonSchema = {
+ type: 'number',
+ minimum: 0,
+ maximum: 100,
+ };
+ const zodSchema = jsonSchemaToZod(schema);
+ expect(zodSchema.parse(50)).toBe(50);
+ expect(() => zodSchema.parse(-1)).toThrow();
+ expect(() => zodSchema.parse(101)).toThrow();
+ });
+
+ it('should validate exclusive minimum and maximum', () => {
+ const schema: JsonSchema = {
+ type: 'number',
+ exclusiveMinimum: 0,
+ exclusiveMaximum: 100,
+ };
+ const zodSchema = jsonSchemaToZod(schema);
+ expect(zodSchema.parse(50)).toBe(50);
+ expect(() => zodSchema.parse(0)).toThrow();
+ expect(() => zodSchema.parse(100)).toThrow();
+ });
+
+ it('should validate multipleOf', () => {
+ const schema: JsonSchema = {
+ type: 'number',
+ multipleOf: 5,
+ };
+ const zodSchema = jsonSchemaToZod(schema);
+ expect(zodSchema.parse(15)).toBe(15);
+ expect(() => zodSchema.parse(17)).toThrow();
+ });
+ });
+
+ describe('Object Schemas', () => {
+ it('should validate required properties', () => {
+ const schema: JsonSchema = {
+ type: 'object',
+ properties: {
+ name: { type: 'string' },
+ age: { type: 'number' },
+ },
+ required: ['name'],
+ };
+ const zodSchema = jsonSchemaToZod(schema);
+ expect(zodSchema.parse({ name: 'John', age: 30 })).toEqual({ name: 'John', age: 30 });
+ expect(zodSchema.parse({ name: 'John' })).toEqual({ name: 'John' });
+ expect(() => zodSchema.parse({ age: 30 })).toThrow();
+ });
+
+ it('should validate additional properties', () => {
+ const schema: JsonSchema = {
+ type: 'object',
+ properties: {
+ name: { type: 'string' },
+ },
+ additionalProperties: false,
+ };
+ const zodSchema = jsonSchemaToZod(schema);
+ expect(zodSchema.parse({ name: 'John' })).toEqual({ name: 'John' });
+ expect(() => zodSchema.parse({ name: 'John', extra: 'field' })).toThrow();
+ });
+
+ it('should validate pattern properties', () => {
+ const schema: JsonSchema = {
+ type: 'object',
+ patternProperties: {
+ '^prefix_': { type: 'string' },
+ },
+ };
+ const zodSchema = jsonSchemaToZod(schema);
+ expect(zodSchema.parse({ prefix_one: 'value1', prefix_two: 'value2' })).toEqual({
+ prefix_one: 'value1',
+ prefix_two: 'value2',
+ });
+ expect(() => zodSchema.parse({ prefix_one: 123 })).toThrow();
+ });
+ });
+
+ describe('Array Schemas', () => {
+ it('should validate array items', () => {
+ const schema: JsonSchema = {
+ type: 'array',
+ items: { type: 'string' },
+ };
+ const zodSchema = jsonSchemaToZod(schema);
+ expect(zodSchema.parse(['one', 'two'])).toEqual(['one', 'two']);
+ expect(() => zodSchema.parse(['one', 2])).toThrow();
+ });
+
+ it('should validate tuple items', () => {
+ const schema: JsonSchema = {
+ type: 'array',
+ items: [{ type: 'string' }, { type: 'number' }],
+ };
+ const zodSchema = jsonSchemaToZod(schema);
+ expect(zodSchema.parse(['test', 123])).toEqual(['test', 123]);
+ expect(() => zodSchema.parse(['test', 'wrong'])).toThrow();
+ });
+
+ it('should validate array length', () => {
+ const schema: JsonSchema = {
+ type: 'array',
+ items: { type: 'string' },
+ minItems: 1,
+ maxItems: 3,
+ };
+ const zodSchema = jsonSchemaToZod(schema);
+ expect(zodSchema.parse(['one'])).toEqual(['one']);
+ expect(zodSchema.parse(['one', 'two', 'three'])).toEqual(['one', 'two', 'three']);
+ expect(() => zodSchema.parse([])).toThrow();
+ expect(() => zodSchema.parse(['one', 'two', 'three', 'four'])).toThrow();
+ });
+ });
+
+ describe('Enum Schemas', () => {
+ it('should validate string enums', () => {
+ const schema: JsonSchema = {
+ type: 'string',
+ enum: ['one', 'two', 'three'],
+ };
+ const zodSchema = jsonSchemaToZod(schema);
+ expect(zodSchema.parse('one')).toBe('one');
+ expect(() => zodSchema.parse('four')).toThrow();
+ });
+
+ it('should validate mixed type enums', () => {
+ const schema: JsonSchema = {
+ enum: ['string', 123, true],
+ };
+ const zodSchema = jsonSchemaToZod(schema);
+ expect(zodSchema.parse('string')).toBe('string');
+ expect(zodSchema.parse(123)).toBe(123);
+ expect(zodSchema.parse(true)).toBe(true);
+ expect(() => zodSchema.parse('invalid')).toThrow();
+ });
+ });
+
+ describe('Combining Schemas', () => {
+ it('should validate anyOf', () => {
+ const schema: JsonSchema = {
+ anyOf: [{ type: 'string' }, { type: 'number' }],
+ };
+ const zodSchema = jsonSchemaToZod(schema);
+ expect(zodSchema.parse('test')).toBe('test');
+ expect(zodSchema.parse(123)).toBe(123);
+ expect(() => zodSchema.parse(true)).toThrow();
+ });
+
+ it('should validate oneOf', () => {
+ const schema: JsonSchema = {
+ oneOf: [
+ { type: 'number', minimum: 0 },
+ { type: 'number', maximum: 0 },
+ ],
+ };
+ const zodSchema = jsonSchemaToZod(schema);
+ expect(zodSchema.parse(1)).toBe(1);
+ expect(zodSchema.parse(-1)).toBe(-1);
+ expect(() => zodSchema.parse(0)).toThrow(); // Should fail as 0 matches both schemas
+ });
+
+ it('should validate allOf', () => {
+ const schema: JsonSchema = {
+ allOf: [
+ { type: 'number', minimum: 0 },
+ { type: 'number', maximum: 100 },
+ ],
+ };
+ const zodSchema = jsonSchemaToZod(schema);
+ expect(zodSchema.parse(50)).toBe(50);
+ expect(() => zodSchema.parse(-1)).toThrow();
+ expect(() => zodSchema.parse(101)).toThrow();
+ });
+ });
+
+ describe('Complex Nested Schemas', () => {
+ it('should validate deeply nested objects', () => {
+ const schema: JsonSchema = {
+ type: 'object',
+ properties: {
+ user: {
+ type: 'object',
+ properties: {
+ name: { type: 'string' },
+ contacts: {
+ type: 'array',
+ items: {
+ type: 'object',
+ properties: {
+ type: { type: 'string', enum: ['email', 'phone'] },
+ value: { type: 'string' },
+ },
+ required: ['type', 'value'],
+ },
+ },
+ },
+ required: ['name'],
+ },
+ },
+ required: ['user'],
+ };
+ const zodSchema = jsonSchemaToZod(schema);
+
+ const validData = {
+ user: {
+ name: 'John Doe',
+ contacts: [
+ { type: 'email', value: '[email protected]' },
+ { type: 'phone', value: '1234567890' },
+ ],
+ },
+ };
+
+ expect(zodSchema.parse(validData)).toEqual(validData);
+ expect(() =>
+ zodSchema.parse({
+ user: {
+ name: 'John Doe',
+ contacts: [{ type: 'invalid', value: 'test' }],
+ },
+ })
+ ).toThrow();
+ });
+ });
+
+ describe('Schema Metadata and Constraints', () => {
+ it('should handle required fields and descriptions', () => {
+ const schema: JsonSchema = {
+ type: 'object',
+ description: 'A user profile object',
+ properties: {
+ username: {
+ type: 'string',
+ description: "The user's display name",
+ },
+ email: {
+ type: 'string',
+ description: "The user's email address",
+ format: 'email',
+ },
+ age: {
+ type: 'number',
+ description: "User's age in years",
+ },
+ },
+ required: ['username', 'email'],
+ };
+
+ const zodSchema = jsonSchemaToZod(schema);
+
+ // Test description
+ expect(zodSchema.description).toBe('A user profile object');
+
+ // Test required fields
+ expect(() => zodSchema.parse({})).toThrow();
+ expect(() => zodSchema.parse({ username: 'test' })).toThrow();
+ expect(() => zodSchema.parse({ email: '[email protected]' })).toThrow();
+
+ // Valid data should pass
+ expect(
+ zodSchema.parse({
+ username: 'testuser',
+ email: '[email protected]',
+ })
+ ).toEqual({
+ username: 'testuser',
+ email: '[email protected]',
+ });
+
+ // Optional field should be allowed to be missing
+ expect(
+ zodSchema.parse({
+ username: 'testuser',
+ email: '[email protected]',
+ })
+ ).toEqual({
+ username: 'testuser',
+ email: '[email protected]',
+ });
+ });
+
+ it('should handle default values', () => {
+ const schema: JsonSchema = {
+ type: 'object',
+ properties: {
+ name: {
+ type: 'string',
+ default: 'Anonymous',
+ },
+ settings: {
+ type: 'object',
+ default: { theme: 'light' },
+ properties: {
+ theme: {
+ type: 'string',
+ },
+ },
+ },
+ },
+ };
+
+ const zodSchema = jsonSchemaToZod(schema);
+
+ // Test default values for top-level property
+ expect(zodSchema.parse({})).toEqual({
+ name: 'Anonymous',
+ settings: { theme: 'light' },
+ });
+
+ // Test that defaults don't override provided values
+ expect(
+ zodSchema.parse({
+ name: 'John',
+ settings: {
+ theme: 'dark',
+ },
+ })
+ ).toEqual({
+ name: 'John',
+ settings: {
+ theme: 'dark',
+ },
+ });
+ });
+
+ it('should transform GetUserRequest schema correctly', () => {
+ const schema: JsonSchema = {
+ type: 'object',
+ properties: {
+ username: {
+ type: 'string',
+ description: 'The username of the Hacker News user to retrieve.',
+ title: 'Username',
+ },
+ },
+ required: ['username'],
+ title: 'GetUserRequest',
+ };
+
+ const zodSchema = jsonSchemaToZod(schema);
+
+ // Test schema description/title
+ expect(zodSchema.description).toBe('GetUserRequest');
+
+ // Test required field validation
+ expect(() => zodSchema.parse({})).toThrow();
+ expect(() => zodSchema.parse({ username: 123 })).toThrow();
+
+ // Test valid data
+ expect(zodSchema.parse({ username: 'testuser' })).toEqual({
+ username: 'testuser',
+ });
+
+ // Test property description
+ const shape = zodSchema._def.shape();
+ expect(shape.username.description).toBe('The username of the Hacker News user to retrieve.');
+ });
+ });
+});
diff --git a/packages/json-schema-to-zod/tsconfig.json b/packages/json-schema-to-zod/tsconfig.json
new file mode 100644
index 000000000..cf32bdd82
--- /dev/null
+++ b/packages/json-schema-to-zod/tsconfig.json
@@ -0,0 +1,15 @@
+{
+ "compilerOptions": {
+ "target": "ESNext",
+ "module": "ESNext",
+ "declaration": true,
+ "outDir": "./dist",
+ "rootDir": "./src",
+ "strict": true,
+ "esModuleInterop": true,
+ "moduleResolution": "node",
+ "skipLibCheck": true,
+ "resolveJsonModule": true
+ },
+ "include": ["src"]
+}
diff --git a/packages/json-schema-to-zod/tsup.config.ts b/packages/json-schema-to-zod/tsup.config.ts
new file mode 100644
index 000000000..f9cdf4040
--- /dev/null
+++ b/packages/json-schema-to-zod/tsup.config.ts
@@ -0,0 +1,10 @@
+import { defineConfig } from 'tsup';
+
+export default defineConfig({
+ entry: ['src/index.ts'],
+ format: ['esm', 'cjs'],
+ dts: true,
+ clean: true,
+ minify: false,
+ outDir: 'dist',
+});
diff --git a/packages/providers/langchain/test/langchain.test.ts b/packages/providers/langchain/test/langchain.test.ts
index 670e81250..0838e3455 100644
--- a/packages/providers/langchain/test/langchain.test.ts
+++ b/packages/providers/langchain/test/langchain.test.ts
@@ -1,239 +1,158 @@
-import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { describe, it, expect, beforeEach } from 'vitest';
import { LangchainProvider } from '../src';
import { Tool } from '@composio/core';
import { DynamicStructuredTool } from '@langchain/core/tools';
-// Define an interface for our mocked LangChain tool
-interface MockedLangChainTool extends DynamicStructuredTool {
- _isMockedLangChainTool: boolean;
-}
-
-// Mock the @langchain/core/tools module
-vi.mock('@langchain/core/tools', () => {
- return {
- DynamicStructuredTool: vi.fn().mockImplementation(config => {
- return {
- name: config.name,
- description: config.description,
- schema: config.schema,
- func: config.func,
- _isMockedLangChainTool: true,
- } as MockedLangChainTool;
- }),
- };
-});
-
-// Mock the jsonSchemaToZodSchema function from @composio/core
-vi.mock('@composio/core', async () => {
- const actual = await vi.importActual('@composio/core');
- return {
- ...(actual as object),
- jsonSchemaToZodSchema: vi.fn().mockImplementation(schema => {
- return { type: 'mock-schema', originalSchema: schema };
- }),
- };
-});
-
describe('LangchainProvider', () => {
let provider: LangchainProvider;
- let mockTool: Tool;
- let mockExecuteToolFn: any;
+ let sampleTool: Tool;
+ let executeToolFn: (
+ toolSlug: string,
+ params: Record<string, unknown>,
+ modifiers?: any
+ ) => Promise<any>;
beforeEach(() => {
provider = new LangchainProvider();
- // Mock the global execute tool function
- mockExecuteToolFn = vi.fn().mockResolvedValue({
- data: { result: 'success' },
- error: null,
- successful: true,
- });
- provider._setExecuteToolFn(mockExecuteToolFn);
+ // Create a real execute function that simulates tool execution
+ executeToolFn = async (toolSlug: string, params: Record<string, unknown>) => {
+ // Simulate actual tool execution with realistic response
+ return {
+ data: { toolSlug, params },
+ error: null,
+ successful: true,
+ };
+ };
- // Create a mock Composio tool
- mockTool = {
- slug: 'test-tool',
- name: 'Test Tool',
- description: 'A tool for testing',
+ // Create a real sample tool that matches actual tool structure
+ sampleTool = {
+ slug: 'SEARCH_TOOL',
+ name: 'Search Tool',
+ description: 'Search for information in the knowledge base',
inputParameters: {
type: 'object',
properties: {
- input: {
+ query: {
type: 'string',
- description: 'Test input',
+ description: 'The search query',
},
},
- required: ['input'],
+ required: ['query'],
+ additionalProperties: false,
},
toolkit: {
- slug: 'test-toolkit',
- name: 'Test Toolkit',
+ slug: 'search_toolkit',
+ name: 'Search Toolkit',
},
- tags: [],
+ tags: ['search', 'knowledge'],
};
-
- // Reset mocks before each test
- vi.clearAllMocks();
});
- describe('name property', () => {
- it('should have the correct name', () => {
+ describe('Provider Configuration', () => {
+ it('should be properly initialized with correct name', () => {
expect(provider.name).toBe('langchain');
});
- });
- describe('_isAgentic property', () => {
- it('should be agentic', () => {
+ it('should be marked as agentic', () => {
expect(provider._isAgentic).toBe(true);
});
});
- describe('wrapTool', () => {
- it('should wrap a tool in LangChain DynamicStructuredTool format', () => {
- const wrapped = provider.wrapTool(mockTool, mockExecuteToolFn) as MockedLangChainTool;
-
- expect(DynamicStructuredTool).toHaveBeenCalledWith({
- name: mockTool.slug,
- description: mockTool.description,
- schema: expect.objectContaining({
- type: 'mock-schema',
- originalSchema: mockTool.inputParameters,
- }),
- func: expect.any(Function),
- });
+ describe('Tool Wrapping', () => {
+ it('should successfully wrap a valid tool into LangChain format', () => {
+ const wrappedTool = provider.wrapTool(sampleTool, executeToolFn);
- expect(wrapped._isMockedLangChainTool).toBe(true);
+ // Verify the wrapped tool has the correct structure
+ expect(wrappedTool).toBeInstanceOf(DynamicStructuredTool);
+ expect(wrappedTool.name).toBe(sampleTool.slug);
+ expect(wrappedTool.description).toBe(sampleTool.description);
+ expect(typeof wrappedTool.func).toBe('function');
});
- it('should throw an error if toolkit name is not defined', () => {
- const toolWithoutToolkit: Tool = {
- ...mockTool,
- toolkit: undefined,
- };
+ it('should wrap a tool that can be executed with parameters', async () => {
+ const wrappedTool = provider.wrapTool(sampleTool, executeToolFn);
+ const searchParams = { query: 'test search' };
- expect(() => {
- provider.wrapTool(toolWithoutToolkit, mockExecuteToolFn);
- }).toThrow('App name is not defined');
+ const result = await wrappedTool.func(searchParams);
+ const parsedResult = JSON.parse(result as string);
+
+ expect(parsedResult).toEqual({
+ data: {
+ toolSlug: sampleTool.slug,
+ params: searchParams,
+ },
+ error: null,
+ successful: true,
+ });
});
- it('should throw an error if inputParameters are not defined', () => {
- const toolWithoutParams: Tool = {
- ...mockTool,
- inputParameters: undefined,
- };
+ it('should fail to wrap a tool without toolkit', () => {
+ const invalidTool = { ...sampleTool, toolkit: undefined };
expect(() => {
- provider.wrapTool(toolWithoutParams, mockExecuteToolFn);
- }).toThrow('Tool input parameters are not defined');
+ provider.wrapTool(invalidTool, executeToolFn);
+ }).toThrow('App name is not defined');
});
- it('should create a function that executes the tool with the right parameters', async () => {
- const wrapped = provider.wrapTool(mockTool, mockExecuteToolFn);
-
- // Extract the function from the constructor call
- const executeFunction = (DynamicStructuredTool as any).mock.calls[0][0].func;
+ it('should fail to wrap a tool without input parameters', () => {
+ const invalidTool = { ...sampleTool, inputParameters: undefined };
- // Test the execute function
- const params = { input: 'test-value' };
- const result = await executeFunction(params);
-
- // Check that executeToolFn was called with the right parameters
- expect(mockExecuteToolFn).toHaveBeenCalledWith(mockTool.slug, params);
-
- // Check that the result was stringified
- expect(result).toBe(
- JSON.stringify({
- data: { result: 'success' },
- error: null,
- successful: true,
- })
- );
+ expect(() => {
+ provider.wrapTool(invalidTool, executeToolFn);
+ }).toThrow('Tool input parameters are not defined');
});
});
- describe('wrapTools', () => {
- it('should wrap multiple tools', () => {
+ describe('Multiple Tools Wrapping', () => {
+ it('should wrap multiple tools correctly', () => {
const anotherTool: Tool = {
- ...mockTool,
- slug: 'another-tool',
- name: 'Another Tool',
- };
- const tools = [mockTool, anotherTool];
-
- const wrapped = provider.wrapTools(tools, mockExecuteToolFn);
-
- // Verify the result is an array of the right length
- expect(wrapped).toHaveLength(2);
-
- // Verify the DynamicStructuredTool constructor was called with the right parameters for each tool
- expect(DynamicStructuredTool).toHaveBeenCalledTimes(2);
- expect(DynamicStructuredTool).toHaveBeenCalledWith(
- expect.objectContaining({
- name: mockTool.slug,
- })
- );
- expect(DynamicStructuredTool).toHaveBeenCalledWith(
- expect.objectContaining({
- name: anotherTool.slug,
- })
- );
- });
-
- it('should return an empty array for empty tools array', () => {
- const wrapped = provider.wrapTools([], mockExecuteToolFn);
- expect(wrapped).toEqual([]);
- expect(DynamicStructuredTool).not.toHaveBeenCalled();
- });
- });
-
- describe('executeTool', () => {
- it('should execute a tool using the global execute function', async () => {
- const toolSlug = 'test-tool';
- const toolParams = {
- userId: 'test-user',
- arguments: { input: 'test-value' },
+ ...sampleTool,
+ slug: 'WEATHER_TOOL',
+ name: 'Weather Tool',
+ description: 'Get weather information',
+ inputParameters: {
+ type: 'object',
+ properties: {
+ location: {
+ type: 'string',
+ description: 'Location to get weather for',
+ },
+ },
+ required: ['location'],
+ additionalProperties: false,
+ },
};
- const result = await provider.executeTool(toolSlug, toolParams);
+ const tools = [sampleTool, anotherTool];
+ const wrappedTools = provider.wrapTools(tools, executeToolFn);
- expect(mockExecuteToolFn).toHaveBeenCalledWith(toolSlug, toolParams, undefined);
- expect(result).toEqual({
- data: { result: 'success' },
- error: null,
- successful: true,
- });
+ expect(wrappedTools).toHaveLength(2);
+ expect(wrappedTools[0].name).toBe('SEARCH_TOOL');
+ expect(wrappedTools[1].name).toBe('WEATHER_TOOL');
+ expect(wrappedTools.every(tool => tool instanceof DynamicStructuredTool)).toBe(true);
});
- it('should pass modifiers to the global execute function', async () => {
- const toolSlug = 'test-tool';
- const toolParams = {
- userId: 'test-user',
- arguments: { input: 'test-value' },
- };
-
- const modifiers = {
- beforeExecute: vi.fn(params => params),
- afterExecute: vi.fn(response => response),
- };
-
- await provider.executeTool(toolSlug, toolParams, modifiers);
-
- expect(mockExecuteToolFn).toHaveBeenCalledWith(toolSlug, toolParams, modifiers);
+ it('should handle empty tools array', () => {
+ const wrappedTools = provider.wrapTools([], executeToolFn);
+ expect(wrappedTools).toEqual([]);
});
});
- describe('integration with LangChain', () => {
- it('should produce tools compatible with LangChain', () => {
- const wrapped = provider.wrapTool(mockTool, mockExecuteToolFn) as MockedLangChainTool;
+ describe('LangChain Integration', () => {
+ it('should produce tools that can be used with LangChain', async () => {
+ const wrappedTool = provider.wrapTool(sampleTool, executeToolFn);
- // Verify the wrapped tool has the expected structure
- expect(wrapped).toHaveProperty('name');
- expect(wrapped).toHaveProperty('description');
- expect(wrapped).toHaveProperty('schema');
- expect(wrapped).toHaveProperty('func');
+ // Verify the tool has all required LangChain properties
+ expect(wrappedTool).toHaveProperty('name');
+ expect(wrappedTool).toHaveProperty('description');
+ expect(wrappedTool).toHaveProperty('schema');
+ expect(wrappedTool).toHaveProperty('func');
- // The func property should be a function
- expect(typeof wrapped.func).toBe('function');
+ // Test actual execution through LangChain interface
+ const result = await wrappedTool.func({ query: 'test query' });
+ expect(typeof result).toBe('string');
+ expect(() => JSON.parse(result as string)).not.toThrow();
});
});
});
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 7a1227b15..bcb7d4e95 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -235,6 +235,9 @@ importers:
openai:
specifier: ^4.94.0
+ zod:
+ specifier: ^3.24.2
+ version: 3.24.4
devDependencies:
'@types/bun':
specifier: ^1.2.9
@@ -349,6 +352,9 @@ importers:
'@composio/client':
specifier: 0.1.0-alpha.16
version: 0.1.0-alpha.16
+ '@composio/json-schema-to-zod':
+ specifier: workspace:^
+ version: link:../json-schema-to-zod
chalk:
specifier: ^5.4.1
version: 5.4.1
@@ -387,6 +393,22 @@ importers:
specifier: ^3.1.4
+ packages/json-schema-to-zod:
+ dependencies:
+ zod:
+ specifier: ^3.24.2
+ version: 3.24.4
+ devDependencies:
+ tsup:
+ specifier: ^8.4.0
+ typescript:
+ specifier: ^5.8.3
+ version: 5.8.3
+ vitest:
+ specifier: ^3.1.4
+
packages/providers/anthropic:
dependencies:
'@anthropic-ai/sdk':
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index ba077bfbc..71ebfe615 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -1,5 +1,6 @@
packages:
- 'packages/core'
+ - 'packages/json-schema-to-zod'
- 'packages/providers/*'
- 'packages/wrappers/*'
- 'examples/*'