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(ts): support Zod 4 custom tool schemas (#3495)

Alberto Schiabelcbbad151266a
diff --git a/.changeset/zod-schema-compat.md b/.changeset/zod-schema-compat.md
new file mode 100644
index 000000000..c575224fe
--- /dev/null
+++ b/.changeset/zod-schema-compat.md
@@ -0,0 +1,6 @@
+---
+'@composio/core': patch
+'@composio/claude-agent-sdk': patch
+---
+
+Improve Zod compatibility at the SDK schema boundary. Custom tools now convert both `zod/v3` and Zod v4 schemas to JSON Schema correctly instead of degrading Zod v4 object schemas to empty schemas. `@composio/core` now exposes `jsonSchemaToZodShape` via `@composio/core/utils/json-schema`, and the Claude Agent SDK provider uses that core subpath instead of converting to a full Zod object and casting `.shape` out of it.
diff --git a/ts/packages/core/package.json b/ts/packages/core/package.json
index c01c55896..f0a29cf3a 100644
--- a/ts/packages/core/package.json
+++ b/ts/packages/core/package.json
@@ -62,6 +62,10 @@
"default": "./dist/platform/node.mjs"
}
},
+ "./utils/json-schema": {
+ "types": "./dist/utils/json-schema.d.mts",
+ "default": "./dist/utils/json-schema.mjs"
+ },
"./generated": {
"types": "./generated/index.d.ts",
"default": "./generated/index.js"
diff --git a/ts/packages/core/src/models/CustomTool.ts b/ts/packages/core/src/models/CustomTool.ts
index 3c4cb9d30..53cb9a5fe 100644
--- a/ts/packages/core/src/models/CustomTool.ts
+++ b/ts/packages/core/src/models/CustomTool.ts
@@ -19,12 +19,11 @@
* });
* ```
*/
-import * as zodToJsonSchema from 'zod-to-json-schema';
-import { z } from 'zod/v3';
import {
CreateCustomToolBaseSchema,
CreateCustomToolkitBaseSchema,
CustomToolSlugSchema,
+ type AnyZodSchema,
type CreateCustomToolParams,
type CreateCustomToolkitParams,
type CustomTool,
@@ -41,6 +40,11 @@ import type {
} from '@composio/client/resources/tool-router/session/session.mjs';
import { ValidationError } from '../errors';
import { PRELOAD_TOOLS_ALL } from '../lib/toolRouterConstants';
+import {
+ isZodObjectSchema,
+ zodObjectSchemaToJsonSchema,
+ zodSchemaToJsonSchema,
+} from '../utils/zodSchema';
/** Prefix applied by the backend to local tool slugs for disambiguation. */
export const LOCAL_TOOL_PREFIX = 'LOCAL_';
@@ -136,7 +140,7 @@ function validateSlugLength(
* });
* ```
*/
-export function createCustomTool<T extends z.ZodType>(
+export function createCustomTool<T extends AnyZodSchema>(
slug: string,
options: CreateCustomToolParams<T>
): CustomTool {
@@ -155,8 +159,7 @@ export function createCustomTool<T extends z.ZodType>(
if (!options.inputParams) {
throw new ValidationError('createCustomTool: inputParams is required');
}
- // Use _def.typeName instead of instanceof to work across different Zod instances
- if ((options.inputParams as { _def?: { typeName?: string } })?._def?.typeName !== 'ZodObject') {
+ if (!isZodObjectSchema(options.inputParams)) {
throw new ValidationError(
'createCustomTool: inputParams must be a z.object() schema. ' +
'Tool input parameters are always an object with named properties.'
@@ -172,24 +175,12 @@ export function createCustomTool<T extends z.ZodType>(
const { inputParams, execute } = options;
// Convert Zod input schema → JSON Schema (inputParams is guaranteed to be z.object)
- const paramsSchema = zodToJsonSchema.default(inputParams, {
- name: 'input',
- }) as InputParamsSchema;
- const paramsSchemaJson = paramsSchema.definitions.input;
-
- const inputSchema: Record<string, unknown> = {
- type: 'object',
- properties: paramsSchemaJson.properties,
- ...(paramsSchemaJson.required ? { required: paramsSchemaJson.required } : {}),
- };
+ const inputSchema = zodObjectSchemaToJsonSchema(inputParams, 'input');
// Convert Zod output schema → JSON Schema (if provided, any Zod type allowed)
let outputSchema: Record<string, unknown> | undefined;
if (options.outputParams) {
- const outSchema = zodToJsonSchema.default(options.outputParams, {
- name: 'output',
- }) as { definitions: { output: Record<string, unknown> } };
- outputSchema = outSchema.definitions.output;
+ outputSchema = zodSchemaToJsonSchema(options.outputParams, 'output');
}
return {
@@ -201,7 +192,7 @@ export function createCustomTool<T extends z.ZodType>(
inputSchema,
outputSchema,
inputParams,
- execute: execute as CustomToolExecuteFn<z.ZodType>,
+ execute: execute as CustomToolExecuteFn<AnyZodSchema>,
};
}
diff --git a/ts/packages/core/src/types/customTool.types.ts b/ts/packages/core/src/types/customTool.types.ts
index 788bf6e09..20cacb605 100644
--- a/ts/packages/core/src/types/customTool.types.ts
+++ b/ts/packages/core/src/types/customTool.types.ts
@@ -1,4 +1,5 @@
import { z } from 'zod/v3';
+import type { z as z4 } from 'zod/v4';
import type {
SessionProxyExecuteParams,
ToolRouterSessionExecuteResponse,
@@ -9,6 +10,13 @@ import type {
SessionCreateResponse,
} from '@composio/client/resources/tool-router/session/session.mjs';
+export type AnyZodSchema = z.ZodType | z4.ZodType;
+export type InferZodSchema<T extends AnyZodSchema> = T extends z.ZodType
+ ? z.infer<T>
+ : T extends z4.ZodType
+ ? z4.infer<T>
+ : never;
+
// ────────────────────────────────────────────────────────────────
// New custom tool types (for tool router integration via createCustomTool())
// ────────────────────────────────────────────────────────────────
@@ -37,8 +45,8 @@ export interface SessionContext {
* - `(input) => data` — for tools that don't need session context
* - `(input, ctx) => data` — for tools that need to call other tools or proxy APIs
*/
-export type CustomToolExecuteFn<T extends z.ZodType> = (
- input: z.infer<T>,
+export type CustomToolExecuteFn<T extends AnyZodSchema> = (
+ input: InferZodSchema<T>,
ctx: SessionContext
) => Promise<Record<string, unknown>>;
@@ -86,13 +94,13 @@ export const CreateCustomToolBaseSchema = z.object({
});
/** Options for creating a custom tool via `createCustomTool()`. */
-export type CreateCustomToolParams<T extends z.ZodType> = z.infer<
+export type CreateCustomToolParams<T extends AnyZodSchema> = z.infer<
typeof CreateCustomToolBaseSchema
> & {
/** Zod schema for input parameters */
inputParams: T;
/** Optional Zod schema for output parameters (sent to backend for documentation) */
- outputParams?: z.ZodType;
+ outputParams?: AnyZodSchema;
/** The function that executes the tool */
execute: CustomToolExecuteFn<T>;
};
@@ -120,9 +128,9 @@ export interface CustomTool {
/** JSON Schema representation of the output (for backend documentation) */
readonly outputSchema?: Record<string, unknown>;
/** @internal Original Zod schema — used for runtime input validation (defaults, coercions, transforms) */
- readonly inputParams: z.ZodType;
+ readonly inputParams: AnyZodSchema;
/** Direct reference to the execute function — useful for testing */
- readonly execute: CustomToolExecuteFn<z.ZodType>;
+ readonly execute: CustomToolExecuteFn<AnyZodSchema>;
}
/** Serialized tool definition sent to backend for search indexing. Uses official client type. */
diff --git a/ts/packages/core/src/utils/json-schema.ts b/ts/packages/core/src/utils/json-schema.ts
new file mode 100644
index 000000000..e55437c31
--- /dev/null
+++ b/ts/packages/core/src/utils/json-schema.ts
@@ -0,0 +1 @@
+export { jsonSchemaToZodShape } from '@composio/json-schema-to-zod';
diff --git a/ts/packages/core/src/utils/zodSchema.ts b/ts/packages/core/src/utils/zodSchema.ts
new file mode 100644
index 000000000..e83ec6248
--- /dev/null
+++ b/ts/packages/core/src/utils/zodSchema.ts
@@ -0,0 +1,90 @@
+import * as z4 from 'zod/v4';
+import * as zodToJsonSchema from 'zod-to-json-schema';
+import type { AnyZodSchema } from '../types/customTool.types';
+
+type JsonSchemaObject = Record<string, unknown>;
+type ObjectJsonSchema = {
+ type: 'object';
+ properties: Record<string, unknown>;
+ required?: string[];
+};
+type ZodDef = {
+ // Zod v4 stores a string literal ('object', 'array', ...) here. Zod v3 leaves it unset for
+ // most types, but for `z.array()` / `z.promise()` it holds the element/inner ZodType (an object),
+ // never a string — which is exactly what lets `isZodV4Schema` tell the two runtimes apart.
+ type?: unknown;
+ typeName?: string;
+};
+type ZodJsonSchemaMode = 'input' | 'output';
+
+const getZodDef = (value: unknown): ZodDef | undefined =>
+ typeof value === 'object' && value !== null ? (value as { _def?: ZodDef })._def : undefined;
+
+// Discriminate Zod v4 from the bundled v3 compat layer. v4-native exposes `_def.type` as a string
+// literal; v3 exposes `_def.typeName` and, when `_def.type` is present (arrays/promises), it is a
+// ZodType object, not a string. Re-verify this invariant on a Zod major bump.
+const isZodV4Schema = (schema: AnyZodSchema): schema is z4.ZodType =>
+ typeof getZodDef(schema)?.type === 'string';
+
+const stripSchemaKeyword = (schema: JsonSchemaObject): JsonSchemaObject => {
+ const { $schema: _schema, ...rest } = schema;
+ return rest;
+};
+
+const getNamedDefinition = (schema: JsonSchemaObject, name: string): JsonSchemaObject => {
+ const definitions = schema.definitions as Record<string, JsonSchemaObject> | undefined;
+ const definition = definitions?.[name];
+ // zod-to-json-schema with `{ name }` always nests the schema under `definitions[name]`. If it's
+ // missing, the conversion didn't match the expected contract — fail loudly rather than returning
+ // the wrapper document, which downstream would silently degrade to an empty object schema.
+ if (typeof definition !== 'object' || definition === null) {
+ throw new Error(`Expected definition "${name}" in the converted JSON schema.`);
+ }
+
+ return definition;
+};
+
+export const isZodObjectSchema = (value: unknown): value is AnyZodSchema => {
+ const def = getZodDef(value);
+ return def?.typeName === 'ZodObject' || def?.type === 'object';
+};
+
+export const zodSchemaToJsonSchema = (
+ schema: AnyZodSchema,
+ name: string = 'schema',
+ mode: ZodJsonSchemaMode = 'output'
+): JsonSchemaObject => {
+ if (isZodV4Schema(schema)) {
+ return stripSchemaKeyword(z4.toJSONSchema(schema, { io: mode }));
+ }
+
+ // Mirror the v4 `io` mode on the v3 converter so the two runtimes serialize `.default()`,
+ // `.transform()` and `.pipe()` schemas consistently at this boundary.
+ const converted = zodToJsonSchema.default(schema, {
+ name,
+ pipeStrategy: mode,
+ effectStrategy: mode === 'input' ? 'input' : 'any',
+ });
+
+ return stripSchemaKeyword(getNamedDefinition(converted, name));
+};
+
+export const zodObjectSchemaToJsonSchema = (
+ schema: AnyZodSchema,
+ name: string = 'schema',
+ mode: ZodJsonSchemaMode = 'input'
+): ObjectJsonSchema => {
+ if (!isZodObjectSchema(schema)) {
+ throw new Error('Expected a z.object() schema.');
+ }
+
+ // The schema is a confirmed object and getNamedDefinition guarantees a well-formed conversion,
+ // so the result always carries `properties` (and `required` only when there are required keys).
+ const jsonSchema = zodSchemaToJsonSchema(schema, name, mode);
+
+ return {
+ type: 'object',
+ properties: (jsonSchema.properties as Record<string, unknown>) ?? {},
+ ...(jsonSchema.required ? { required: jsonSchema.required as string[] } : {}),
+ };
+};
diff --git a/ts/packages/core/test/models/customTool.test.ts b/ts/packages/core/test/models/customTool.test.ts
index 7ed05edca..2b3028781 100644
--- a/ts/packages/core/test/models/customTool.test.ts
+++ b/ts/packages/core/test/models/customTool.test.ts
@@ -1,4 +1,5 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { z as z4 } from 'zod';
import { z } from 'zod/v3';
import {
createCustomTool,
@@ -70,6 +71,80 @@ describe('createCustomTool', () => {
});
});
+ it('should convert Zod v4 input and output schemas correctly', () => {
+ const tool = createCustomTool('ZOD4_TOOL', {
+ name: 'Zod 4 tool',
+ description: 'Tool using Zod 4 schemas',
+ inputParams: z4.object({
+ repository: z4.string().describe('Repository name'),
+ limit: z4.number().optional(),
+ category: z4.string().default('all'),
+ }),
+ outputParams: z4.object({
+ starred: z4.boolean(),
+ }),
+ execute: vi.fn().mockImplementation(async input => ({
+ repository: input.repository.toUpperCase(),
+ })),
+ });
+
+ expect(tool.inputSchema).toMatchObject({
+ type: 'object',
+ properties: {
+ repository: { type: 'string', description: 'Repository name' },
+ limit: { type: 'number' },
+ category: expect.objectContaining({ type: 'string', default: 'all' }),
+ },
+ required: ['repository'],
+ });
+ expect(tool.outputSchema).toMatchObject({
+ type: 'object',
+ properties: {
+ starred: { type: 'boolean' },
+ },
+ required: ['starred'],
+ });
+ });
+
+ it('should keep v3 and v4 input schemas in parity for defaulted fields (input mode)', () => {
+ const v3Tool = createCustomTool('ZOD3_DEFAULT', {
+ ...baseOptions,
+ inputParams: z.object({
+ query: z.string(),
+ category: z.string().default('all'),
+ }),
+ });
+ const v4Tool = createCustomTool('ZOD4_DEFAULT', {
+ ...baseOptions,
+ inputParams: z4.object({
+ query: z4.string(),
+ category: z4.string().default('all'),
+ }),
+ });
+
+ // In input mode a defaulted field is optional in both runtimes: only `query` is required.
+ expect(v3Tool.inputSchema).toMatchObject({ type: 'object', required: ['query'] });
+ expect(v4Tool.inputSchema).toMatchObject({ type: 'object', required: ['query'] });
+ });
+
+ it('should convert a Zod v3 array output schema without misrouting it through the v4 converter', () => {
+ // Regression: a v3 z.array()/z.promise() stores its element schema on `_def.type`, which used
+ // to be mistaken for a v4 schema and crash inside z4.toJSONSchema().
+ const tool = createCustomTool('ZOD3_ARRAY_OUTPUT', {
+ ...baseOptions,
+ outputParams: z.array(z.object({ id: z.string() })),
+ });
+
+ expect(tool.outputSchema).toMatchObject({
+ type: 'array',
+ items: {
+ type: 'object',
+ properties: { id: { type: 'string' } },
+ required: ['id'],
+ },
+ });
+ });
+
it('should not have outputSchema when outputParams is not provided', () => {
const tool = createCustomTool('NO_OUTPUT', baseOptions);
expect(tool.outputSchema).toBeUndefined();
@@ -162,6 +237,12 @@ describe('createCustomTool', () => {
'execute must be a function'
);
});
+
+ it('should throw if a Zod v4 input schema is not an object', () => {
+ expect(() =>
+ createCustomTool('SLUG', { ...baseOptions, inputParams: z4.string() as any })
+ ).toThrow('inputParams must be a z.object() schema');
+ });
});
describe('execute function signatures', () => {
diff --git a/ts/packages/core/tsdown.config.ts b/ts/packages/core/tsdown.config.ts
index ee090dacc..fa3a331df 100644
--- a/ts/packages/core/tsdown.config.ts
+++ b/ts/packages/core/tsdown.config.ts
@@ -24,6 +24,9 @@ export default defineConfig({
// #config_defaults
'src/utils/config-defaults/ConfigDefaults.node.ts',
'src/utils/config-defaults/ConfigDefaults.workerd.ts',
+
+ // public utility subpaths
+ 'src/utils/json-schema.ts',
],
/**
* We don't want to accidentally bundle `node:*` packages (e.g., `node:module`)
diff --git a/ts/packages/providers/claude-agent-sdk/src/index.ts b/ts/packages/providers/claude-agent-sdk/src/index.ts
index 41750cd11..aff8a055e 100644
--- a/ts/packages/providers/claude-agent-sdk/src/index.ts
+++ b/ts/packages/providers/claude-agent-sdk/src/index.ts
@@ -14,14 +14,13 @@ import {
ExecuteToolFn,
McpUrlResponse,
McpServerGetResponse,
- jsonSchemaToZodSchema,
normalizeToolArguments,
} from '@composio/core';
+import { jsonSchemaToZodShape } from '@composio/core/utils/json-schema';
import {
tool as sdkTool,
type Options as ClaudeAgentOptions,
} from '@anthropic-ai/claude-agent-sdk';
-import type { ZodObject, ZodRawShape } from 'zod/v3';
/**
* Type for a single Claude Agent SDK MCP tool definition
@@ -103,13 +102,24 @@ export class ClaudeAgentSDKProvider extends BaseAgenticProvider<
* ```
*/
wrapTool(composioTool: Tool, executeTool: ExecuteToolFn): ClaudeAgentTool {
- const inputZodSchema = jsonSchemaToZodSchema(
+ const inputZodShape = jsonSchemaToZodShape(
composioTool.inputParameters ?? { type: 'object', properties: {} }
);
- // Some issues with zod types and errors when instantiation is excessively deep and possibly infinite.
- const inputZodShape = (inputZodSchema as unknown as ZodObject<ZodRawShape>).shape;
- return sdkTool(
+ // The SDK types tool() generically over its zod raw shape, which makes the handler argument
+ // instantiate excessively deep against the v3 shape returned here (TS2589). Narrow tool() to a
+ // concrete, monomorphic signature once — this sidesteps the deep instantiation and lets the
+ // handler keep a precise argument type, instead of scattering `as never` casts at the call.
+ const defineTool = sdkTool as unknown as (
+ name: string,
+ description: string,
+ inputShape: ReturnType<typeof jsonSchemaToZodShape>,
+ handler: (
+ args: Record<string, unknown>
+ ) => Promise<{ content: Array<{ type: 'text'; text: string }> }>
+ ) => ClaudeAgentTool;
+
+ return defineTool(
composioTool.slug,
composioTool.description ?? `Execute ${composioTool.slug}`,
inputZodShape,
diff --git a/ts/packages/providers/claude-agent-sdk/test/claude-agent-sdk.test.ts b/ts/packages/providers/claude-agent-sdk/test/claude-agent-sdk.test.ts
index 2ec1fb841..e8157d263 100644
--- a/ts/packages/providers/claude-agent-sdk/test/claude-agent-sdk.test.ts
+++ b/ts/packages/providers/claude-agent-sdk/test/claude-agent-sdk.test.ts
@@ -108,6 +108,15 @@ describe('ClaudeAgentSDKProvider', () => {
expect(wrapped.description).toBe(mockTool.description);
});
+ it('should pass a raw Zod shape to the Claude Agent SDK', () => {
+ provider.wrapTool(mockTool, mockExecuteToolFn);
+
+ const schemaShape = (tool as any).mock.calls[0][2];
+ expect(Object.keys(schemaShape)).toEqual(['to', 'subject', 'body']);
+ expect(schemaShape.to.safeParse('[email protected]').success).toBe(true);
+ expect(schemaShape.to.safeParse(123).success).toBe(false);
+ });
+
it('should handle tools without input parameters', () => {
const toolWithoutParams: Tool = {
...mockTool,