@devries-cameron20 / composio Mirror · read-only / commits / cbbad1512
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 21, 19:45 UTC

fix(ts): support Zod 4 custom tool schemas (#3495)

## Summary Stacked on #3494. This PR tightens the SDK's Zod boundary now that the TypeScript packages are moving to the newer Node/toolchain baseline. The main issue was asymmetric Zod support: `@composio/json-schema-to-zod` already supports projects with Zod 3 and Zod 4 by generating schemas through `zod/v3`, but custom tools converted schemas in the opposite direction through `zod-to-json-schema` only. With a bare Zod 4 `z.object(...)`, that path degraded to an empty JSON Schema. ## What changed - Added a shared core helper for Zod schema -> JSON Schema conversion. - Supports both `zod/v3` schemas and Zod 4 schemas via `z.toJSONSchema`. - Converts custom-tool input schemas in Zod 4 input mode, so defaulted fields stay optional in the generated JSON Schema. - Uses the shared helper in both custom-tool entrypoints: `createCustomTool(...)` and legacy `composio.tools.createCustomTool(...)`. - Updates custom-tool types so Zod 4 schemas infer their `execute` input type while keeping the session context parameter required for context-using tools. - Exposes `jsonSchemaToZodShape` through the narrow `@composio/core/utils/json-schema` subpath. - Switches the Claude Agent SDK provider to use that core subpath instead of depending directly on `@composio/json-schema-to-zod` or converting to a full Zod object and casting `.shape` out of it. - Adds patch changesets for `@composio/core` and `@composio/claude-agent-sdk`. ## Review hardening Follow-up fixes from a deeper pass over the new conversion boundary: - **Fixes a Zod 3 regression in the v3/v4 discriminator.** The detector keyed on `_def.type` being defined, but Zod 3 stores the element schema there for `z.array()` / `z.promise()` — so a Zod 3 array/promise `outputParams` was misrouted into `z.toJSONSchema` and crashed with `Cannot read properties of undefined (reading 'def')`. It now discriminates on `_def.type` being a string literal (Zod 4) versus a `ZodType` object (Zod 3), with a regression test. - **Mirrors input/output mode on the Zod 3 path.** The `io` mode was applied to the Zod 4 converter but dropped on the Zod 3 branch; it now maps onto `zod-to-json-schema`'s `pipeStrategy`/`effectStrategy` so `.default()` / `.transform()` / `.pipe()` schemas serialize consistently across both runtimes. Added a v3/v4 input-mode parity test. - **Fails loudly on a missing named definition** instead of returning the wrapper document, which downstream silently degraded into an empty object schema. - **Replaces broad `as never` casts** in the Claude Agent SDK provider with a single concrete `tool()` signature — this sidesteps the SDK's deep-instantiation error while keeping the handler's real argument type. - **Trims now-dead code** from the custom-tool schema types and conversion path. ## Verification - `mise exec -- pnpm --filter @composio/core test` (933 passing) - `mise exec -- pnpm --filter @composio/claude-agent-sdk test -- --runInBand` (17 passing) - `mise exec -- pnpm --filter @composio/core build` (publint + attw clean, emits `@composio/core/utils/json-schema`) - `mise exec -- pnpm --filter @composio/claude-agent-sdk exec tsc --noEmit --skipLibCheck` - `mise exec -- pnpm --filter @composio/claude-agent-sdk build` (publint + attw clean) - `mise exec -- pnpm install --frozen-lockfile` - `git diff --check` Note: `mise exec -- pnpm --filter @composio/core typecheck` still fails on the existing `src/utils/pusher.ts` `ChannelAuthorizationHandler` type mismatch. This PR does not touch that file; the core build and full core unit suite pass.

Alberto Schiabel committed Jun 19, 2026 at 23:42 UTC cbbad151266a9e2528e9098893dad93224cdfaab
10 files changed +235 -32
.changeset/zod-schema-compat.md new
+6
@@ -0,0 +1,6 @@
1 +---
2 +'@composio/core': patch
3 +'@composio/claude-agent-sdk': patch
4 +---
5 +
6 +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.
ts/packages/core/package.json
+4
@@ -62,6 +62,10 @@
62 "default": "./dist/platform/node.mjs"
63 }
64 },
65 + "./utils/json-schema": {
66 + "types": "./dist/utils/json-schema.d.mts",
67 + "default": "./dist/utils/json-schema.mjs"
68 + },
69 "./generated": {
70 "types": "./generated/index.d.ts",
71 "default": "./generated/index.js"
ts/packages/core/src/models/CustomTool.ts
+11 -20
@@ -19,12 +19,11 @@
19 * });
20 * ```
21 */
22 -import * as zodToJsonSchema from 'zod-to-json-schema';
23 -import { z } from 'zod/v3';
22 import {
23 CreateCustomToolBaseSchema,
24 CreateCustomToolkitBaseSchema,
25 CustomToolSlugSchema,
26 + type AnyZodSchema,
27 type CreateCustomToolParams,
28 type CreateCustomToolkitParams,
29 type CustomTool,
@@ -41,6 +40,11 @@ import type {
40 } from '@composio/client/resources/tool-router/session/session.mjs';
41 import { ValidationError } from '../errors';
42 import { PRELOAD_TOOLS_ALL } from '../lib/toolRouterConstants';
43 +import {
44 + isZodObjectSchema,
45 + zodObjectSchemaToJsonSchema,
46 + zodSchemaToJsonSchema,
47 +} from '../utils/zodSchema';
48
49 /** Prefix applied by the backend to local tool slugs for disambiguation. */
50 export const LOCAL_TOOL_PREFIX = 'LOCAL_';
@@ -136,7 +140,7 @@ function validateSlugLength(
140 * });
141 * ```
142 */
139 -export function createCustomTool<T extends z.ZodType>(
143 +export function createCustomTool<T extends AnyZodSchema>(
144 slug: string,
145 options: CreateCustomToolParams<T>
146 ): CustomTool {
@@ -155,8 +159,7 @@ export function createCustomTool<T extends z.ZodType>(
159 if (!options.inputParams) {
160 throw new ValidationError('createCustomTool: inputParams is required');
161 }
158 - // Use _def.typeName instead of instanceof to work across different Zod instances
159 - if ((options.inputParams as { _def?: { typeName?: string } })?._def?.typeName !== 'ZodObject') {
162 + if (!isZodObjectSchema(options.inputParams)) {
163 throw new ValidationError(
164 'createCustomTool: inputParams must be a z.object() schema. ' +
165 'Tool input parameters are always an object with named properties.'
@@ -172,24 +175,12 @@ export function createCustomTool<T extends z.ZodType>(
175 const { inputParams, execute } = options;
176
177 // Convert Zod input schema → JSON Schema (inputParams is guaranteed to be z.object)
175 - const paramsSchema = zodToJsonSchema.default(inputParams, {
176 - name: 'input',
177 - }) as InputParamsSchema;
178 - const paramsSchemaJson = paramsSchema.definitions.input;
179 -
180 - const inputSchema: Record<string, unknown> = {
181 - type: 'object',
182 - properties: paramsSchemaJson.properties,
183 - ...(paramsSchemaJson.required ? { required: paramsSchemaJson.required } : {}),
184 - };
178 + const inputSchema = zodObjectSchemaToJsonSchema(inputParams, 'input');
179
180 // Convert Zod output schema → JSON Schema (if provided, any Zod type allowed)
181 let outputSchema: Record<string, unknown> | undefined;
182 if (options.outputParams) {
189 - const outSchema = zodToJsonSchema.default(options.outputParams, {
190 - name: 'output',
191 - }) as { definitions: { output: Record<string, unknown> } };
192 - outputSchema = outSchema.definitions.output;
183 + outputSchema = zodSchemaToJsonSchema(options.outputParams, 'output');
184 }
185
186 return {
@@ -201,7 +192,7 @@ export function createCustomTool<T extends z.ZodType>(
192 inputSchema,
193 outputSchema,
194 inputParams,
204 - execute: execute as CustomToolExecuteFn<z.ZodType>,
195 + execute: execute as CustomToolExecuteFn<AnyZodSchema>,
196 };
197 }
198
ts/packages/core/src/types/customTool.types.ts
+14 -6
@@ -1,4 +1,5 @@
1 import { z } from 'zod/v3';
2 +import type { z as z4 } from 'zod/v4';
3 import type {
4 SessionProxyExecuteParams,
5 ToolRouterSessionExecuteResponse,
@@ -9,6 +10,13 @@ import type {
10 SessionCreateResponse,
11 } from '@composio/client/resources/tool-router/session/session.mjs';
12
13 +export type AnyZodSchema = z.ZodType | z4.ZodType;
14 +export type InferZodSchema<T extends AnyZodSchema> = T extends z.ZodType
15 + ? z.infer<T>
16 + : T extends z4.ZodType
17 + ? z4.infer<T>
18 + : never;
19 +
20 // ────────────────────────────────────────────────────────────────
21 // New custom tool types (for tool router integration via createCustomTool())
22 // ────────────────────────────────────────────────────────────────
@@ -37,8 +45,8 @@ export interface SessionContext {
45 * - `(input) => data` — for tools that don't need session context
46 * - `(input, ctx) => data` — for tools that need to call other tools or proxy APIs
47 */
40 -export type CustomToolExecuteFn<T extends z.ZodType> = (
41 - input: z.infer<T>,
48 +export type CustomToolExecuteFn<T extends AnyZodSchema> = (
49 + input: InferZodSchema<T>,
50 ctx: SessionContext
51 ) => Promise<Record<string, unknown>>;
52
@@ -86,13 +94,13 @@ export const CreateCustomToolBaseSchema = z.object({
94 });
95
96 /** Options for creating a custom tool via `createCustomTool()`. */
89 -export type CreateCustomToolParams<T extends z.ZodType> = z.infer<
97 +export type CreateCustomToolParams<T extends AnyZodSchema> = z.infer<
98 typeof CreateCustomToolBaseSchema
99 > & {
100 /** Zod schema for input parameters */
101 inputParams: T;
102 /** Optional Zod schema for output parameters (sent to backend for documentation) */
95 - outputParams?: z.ZodType;
103 + outputParams?: AnyZodSchema;
104 /** The function that executes the tool */
105 execute: CustomToolExecuteFn<T>;
106 };
@@ -120,9 +128,9 @@ export interface CustomTool {
128 /** JSON Schema representation of the output (for backend documentation) */
129 readonly outputSchema?: Record<string, unknown>;
130 /** @internal Original Zod schema — used for runtime input validation (defaults, coercions, transforms) */
123 - readonly inputParams: z.ZodType;
131 + readonly inputParams: AnyZodSchema;
132 /** Direct reference to the execute function — useful for testing */
125 - readonly execute: CustomToolExecuteFn<z.ZodType>;
133 + readonly execute: CustomToolExecuteFn<AnyZodSchema>;
134 }
135
136 /** Serialized tool definition sent to backend for search indexing. Uses official client type. */
ts/packages/core/src/utils/json-schema.ts new
+1
@@ -0,0 +1 @@
1 +export { jsonSchemaToZodShape } from '@composio/json-schema-to-zod';
ts/packages/core/src/utils/zodSchema.ts new
+90
@@ -0,0 +1,90 @@
1 +import * as z4 from 'zod/v4';
2 +import * as zodToJsonSchema from 'zod-to-json-schema';
3 +import type { AnyZodSchema } from '../types/customTool.types';
4 +
5 +type JsonSchemaObject = Record<string, unknown>;
6 +type ObjectJsonSchema = {
7 + type: 'object';
8 + properties: Record<string, unknown>;
9 + required?: string[];
10 +};
11 +type ZodDef = {
12 + // Zod v4 stores a string literal ('object', 'array', ...) here. Zod v3 leaves it unset for
13 + // most types, but for `z.array()` / `z.promise()` it holds the element/inner ZodType (an object),
14 + // never a string — which is exactly what lets `isZodV4Schema` tell the two runtimes apart.
15 + type?: unknown;
16 + typeName?: string;
17 +};
18 +type ZodJsonSchemaMode = 'input' | 'output';
19 +
20 +const getZodDef = (value: unknown): ZodDef | undefined =>
21 + typeof value === 'object' && value !== null ? (value as { _def?: ZodDef })._def : undefined;
22 +
23 +// Discriminate Zod v4 from the bundled v3 compat layer. v4-native exposes `_def.type` as a string
24 +// literal; v3 exposes `_def.typeName` and, when `_def.type` is present (arrays/promises), it is a
25 +// ZodType object, not a string. Re-verify this invariant on a Zod major bump.
26 +const isZodV4Schema = (schema: AnyZodSchema): schema is z4.ZodType =>
27 + typeof getZodDef(schema)?.type === 'string';
28 +
29 +const stripSchemaKeyword = (schema: JsonSchemaObject): JsonSchemaObject => {
30 + const { $schema: _schema, ...rest } = schema;
31 + return rest;
32 +};
33 +
34 +const getNamedDefinition = (schema: JsonSchemaObject, name: string): JsonSchemaObject => {
35 + const definitions = schema.definitions as Record<string, JsonSchemaObject> | undefined;
36 + const definition = definitions?.[name];
37 + // zod-to-json-schema with `{ name }` always nests the schema under `definitions[name]`. If it's
38 + // missing, the conversion didn't match the expected contract — fail loudly rather than returning
39 + // the wrapper document, which downstream would silently degrade to an empty object schema.
40 + if (typeof definition !== 'object' || definition === null) {
41 + throw new Error(`Expected definition "${name}" in the converted JSON schema.`);
42 + }
43 +
44 + return definition;
45 +};
46 +
47 +export const isZodObjectSchema = (value: unknown): value is AnyZodSchema => {
48 + const def = getZodDef(value);
49 + return def?.typeName === 'ZodObject' || def?.type === 'object';
50 +};
51 +
52 +export const zodSchemaToJsonSchema = (
53 + schema: AnyZodSchema,
54 + name: string = 'schema',
55 + mode: ZodJsonSchemaMode = 'output'
56 +): JsonSchemaObject => {
57 + if (isZodV4Schema(schema)) {
58 + return stripSchemaKeyword(z4.toJSONSchema(schema, { io: mode }));
59 + }
60 +
61 + // Mirror the v4 `io` mode on the v3 converter so the two runtimes serialize `.default()`,
62 + // `.transform()` and `.pipe()` schemas consistently at this boundary.
63 + const converted = zodToJsonSchema.default(schema, {
64 + name,
65 + pipeStrategy: mode,
66 + effectStrategy: mode === 'input' ? 'input' : 'any',
67 + });
68 +
69 + return stripSchemaKeyword(getNamedDefinition(converted, name));
70 +};
71 +
72 +export const zodObjectSchemaToJsonSchema = (
73 + schema: AnyZodSchema,
74 + name: string = 'schema',
75 + mode: ZodJsonSchemaMode = 'input'
76 +): ObjectJsonSchema => {
77 + if (!isZodObjectSchema(schema)) {
78 + throw new Error('Expected a z.object() schema.');
79 + }
80 +
81 + // The schema is a confirmed object and getNamedDefinition guarantees a well-formed conversion,
82 + // so the result always carries `properties` (and `required` only when there are required keys).
83 + const jsonSchema = zodSchemaToJsonSchema(schema, name, mode);
84 +
85 + return {
86 + type: 'object',
87 + properties: (jsonSchema.properties as Record<string, unknown>) ?? {},
88 + ...(jsonSchema.required ? { required: jsonSchema.required as string[] } : {}),
89 + };
90 +};
ts/packages/core/test/models/customTool.test.ts
+81
@@ -1,4 +1,5 @@
1 import { describe, it, expect, vi, beforeEach } from 'vitest';
2 +import { z as z4 } from 'zod';
3 import { z } from 'zod/v3';
4 import {
5 createCustomTool,
@@ -70,6 +71,80 @@ describe('createCustomTool', () => {
71 });
72 });
73
74 + it('should convert Zod v4 input and output schemas correctly', () => {
75 + const tool = createCustomTool('ZOD4_TOOL', {
76 + name: 'Zod 4 tool',
77 + description: 'Tool using Zod 4 schemas',
78 + inputParams: z4.object({
79 + repository: z4.string().describe('Repository name'),
80 + limit: z4.number().optional(),
81 + category: z4.string().default('all'),
82 + }),
83 + outputParams: z4.object({
84 + starred: z4.boolean(),
85 + }),
86 + execute: vi.fn().mockImplementation(async input => ({
87 + repository: input.repository.toUpperCase(),
88 + })),
89 + });
90 +
91 + expect(tool.inputSchema).toMatchObject({
92 + type: 'object',
93 + properties: {
94 + repository: { type: 'string', description: 'Repository name' },
95 + limit: { type: 'number' },
96 + category: expect.objectContaining({ type: 'string', default: 'all' }),
97 + },
98 + required: ['repository'],
99 + });
100 + expect(tool.outputSchema).toMatchObject({
101 + type: 'object',
102 + properties: {
103 + starred: { type: 'boolean' },
104 + },
105 + required: ['starred'],
106 + });
107 + });
108 +
109 + it('should keep v3 and v4 input schemas in parity for defaulted fields (input mode)', () => {
110 + const v3Tool = createCustomTool('ZOD3_DEFAULT', {
111 + ...baseOptions,
112 + inputParams: z.object({
113 + query: z.string(),
114 + category: z.string().default('all'),
115 + }),
116 + });
117 + const v4Tool = createCustomTool('ZOD4_DEFAULT', {
118 + ...baseOptions,
119 + inputParams: z4.object({
120 + query: z4.string(),
121 + category: z4.string().default('all'),
122 + }),
123 + });
124 +
125 + // In input mode a defaulted field is optional in both runtimes: only `query` is required.
126 + expect(v3Tool.inputSchema).toMatchObject({ type: 'object', required: ['query'] });
127 + expect(v4Tool.inputSchema).toMatchObject({ type: 'object', required: ['query'] });
128 + });
129 +
130 + it('should convert a Zod v3 array output schema without misrouting it through the v4 converter', () => {
131 + // Regression: a v3 z.array()/z.promise() stores its element schema on `_def.type`, which used
132 + // to be mistaken for a v4 schema and crash inside z4.toJSONSchema().
133 + const tool = createCustomTool('ZOD3_ARRAY_OUTPUT', {
134 + ...baseOptions,
135 + outputParams: z.array(z.object({ id: z.string() })),
136 + });
137 +
138 + expect(tool.outputSchema).toMatchObject({
139 + type: 'array',
140 + items: {
141 + type: 'object',
142 + properties: { id: { type: 'string' } },
143 + required: ['id'],
144 + },
145 + });
146 + });
147 +
148 it('should not have outputSchema when outputParams is not provided', () => {
149 const tool = createCustomTool('NO_OUTPUT', baseOptions);
150 expect(tool.outputSchema).toBeUndefined();
@@ -162,6 +237,12 @@ describe('createCustomTool', () => {
237 'execute must be a function'
238 );
239 });
240 +
241 + it('should throw if a Zod v4 input schema is not an object', () => {
242 + expect(() =>
243 + createCustomTool('SLUG', { ...baseOptions, inputParams: z4.string() as any })
244 + ).toThrow('inputParams must be a z.object() schema');
245 + });
246 });
247
248 describe('execute function signatures', () => {
ts/packages/core/tsdown.config.ts
+3
@@ -24,6 +24,9 @@ export default defineConfig({
24 // #config_defaults
25 'src/utils/config-defaults/ConfigDefaults.node.ts',
26 'src/utils/config-defaults/ConfigDefaults.workerd.ts',
27 +
28 + // public utility subpaths
29 + 'src/utils/json-schema.ts',
30 ],
31 /**
32 * We don't want to accidentally bundle `node:*` packages (e.g., `node:module`)
ts/packages/providers/claude-agent-sdk/src/index.ts
+16 -6
@@ -14,14 +14,13 @@ import {
14 ExecuteToolFn,
15 McpUrlResponse,
16 McpServerGetResponse,
17 - jsonSchemaToZodSchema,
17 normalizeToolArguments,
18 } from '@composio/core';
19 +import { jsonSchemaToZodShape } from '@composio/core/utils/json-schema';
20 import {
21 tool as sdkTool,
22 type Options as ClaudeAgentOptions,
23 } from '@anthropic-ai/claude-agent-sdk';
24 -import type { ZodObject, ZodRawShape } from 'zod/v3';
24
25 /**
26 * Type for a single Claude Agent SDK MCP tool definition
@@ -103,13 +102,24 @@ export class ClaudeAgentSDKProvider extends BaseAgenticProvider<
102 * ```
103 */
104 wrapTool(composioTool: Tool, executeTool: ExecuteToolFn): ClaudeAgentTool {
106 - const inputZodSchema = jsonSchemaToZodSchema(
105 + const inputZodShape = jsonSchemaToZodShape(
106 composioTool.inputParameters ?? { type: 'object', properties: {} }
107 );
109 - // Some issues with zod types and errors when instantiation is excessively deep and possibly infinite.
110 - const inputZodShape = (inputZodSchema as unknown as ZodObject<ZodRawShape>).shape;
108
112 - return sdkTool(
109 + // The SDK types tool() generically over its zod raw shape, which makes the handler argument
110 + // instantiate excessively deep against the v3 shape returned here (TS2589). Narrow tool() to a
111 + // concrete, monomorphic signature once — this sidesteps the deep instantiation and lets the
112 + // handler keep a precise argument type, instead of scattering `as never` casts at the call.
113 + const defineTool = sdkTool as unknown as (
114 + name: string,
115 + description: string,
116 + inputShape: ReturnType<typeof jsonSchemaToZodShape>,
117 + handler: (
118 + args: Record<string, unknown>
119 + ) => Promise<{ content: Array<{ type: 'text'; text: string }> }>
120 + ) => ClaudeAgentTool;
121 +
122 + return defineTool(
123 composioTool.slug,
124 composioTool.description ?? `Execute ${composioTool.slug}`,
125 inputZodShape,
ts/packages/providers/claude-agent-sdk/test/claude-agent-sdk.test.ts
+9
@@ -108,6 +108,15 @@ describe('ClaudeAgentSDKProvider', () => {
108 expect(wrapped.description).toBe(mockTool.description);
109 });
110
111 + it('should pass a raw Zod shape to the Claude Agent SDK', () => {
112 + provider.wrapTool(mockTool, mockExecuteToolFn);
113 +
114 + const schemaShape = (tool as any).mock.calls[0][2];
115 + expect(Object.keys(schemaShape)).toEqual(['to', 'subject', 'body']);
116 + expect(schemaShape.to.safeParse('test@example.com').success).toBe(true);
117 + expect(schemaShape.to.safeParse(123).success).toBe(false);
118 + });
119 +
120 it('should handle tools without input parameters', () => {
121 const toolWithoutParams: Tool = {
122 ...mockTool,