@devries-cameron20 / composio-1 / commits / 208e320b2
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.

Feat add strict mode in tool fetching (#32)

* Add strict mode to jsonschema parser * Add strict mode to remove non-required fields * Update documentation for strict mode * Update github workflow * Add changeset

Musthaq Ahamad committed Jun 5, 2025 at 18:17 UTC 208e320b2732c2f8a6662bdcc523c18a228a9b93
8 files changed +262 -8
.changeset/wild-items-argue.md new
+13
@@ -0,0 +1,13 @@
1 +---
2 +'@composio/vercel': patch
3 +'@composio/core': patch
4 +'@composio/json-schema-to-zod': patch
5 +'@composio/anthropic': patch
6 +'@composio/cloudflare': patch
7 +'@composio/google': patch
8 +'@composio/langchain': patch
9 +'@composio/mastra': patch
10 +'@composio/openai': patch
11 +---
12 +
13 +Update json schema transformations issues related to strict mode
.github/workflows/release.yml
+4 -3
@@ -48,10 +48,11 @@ jobs:
48 commit: 'Release: update version'
49 title: 'Release: update version'
50
51 - - name: Format published packages for Slack
52 - id: format_packages
51 + - name: Set Version Info
52 + if: steps.changesets.outputs.published == 'true'
53 run: |
54 - echo "SLACK_VERSIONS=$(echo '${{ steps.changesets.outputs.publishedPackages }}' | jq -r '.[] | \"⚡️ \\(.name) -> \\(.version)\"' | paste -sd '\\n' -)" >> $GITHUB_ENV
54 + VERSIONS=$(pnpm changeset status --json | jq -r '.releases[] | "⚡️ \(.name) -> \(.version)"' || echo "No version info available")
55 + echo "SLACK_VERSIONS=$VERSIONS" >> $GITHUB_ENV
56
57 - name: Send Slack Notification
58 if: steps.changesets.outputs.published == 'true'
docs/api/tools.md
+7 -2
@@ -195,7 +195,8 @@ type ToolkitsOnlyParams = {
195 important?: boolean; // Filter for important tools
196 cursor?: string; // Pagination cursor
197 limit?: number; // Limit the number of results
198 - search?: never; // Cannot be used with important flag
198 + search?: never; // Cannot be used with important flag,
199 + strict?: boolean; // Remove non-required properties from input/output parameters
200 };
201
202 type ToolkitSearchOnlyParams = {
@@ -205,6 +206,7 @@ type ToolkitSearchOnlyParams = {
206 cursor?: string; // Pagination cursor
207 limit?: number; // Limit the number of results
208 search: string; // Search term
209 + strict?: boolean; // Remove non-required properties from input/output parameters
210 };
211
212 type ToolListParams = ToolsOnlyParams | ToolkitsOnlyParams | ToolkitSearchOnlyParams;
@@ -216,6 +218,8 @@ Note: The parameters are organized into three mutually exclusive combinations:
218 2. Using `toolkits` with optional `important` flag to fetch tools from specific toolkits
219 3. Using `search` with optional `toolkits` to search for tools by name/description
220
221 +The `strict` parameter is a special flag that can be used with any of the above combinations. When set to `true`, it removes all non-required properties from both input and output parameters of the tools. This is particularly useful when working with providers that have strict parameter requirements, such as VercelAISDK, OpenAI, [where all fields must be marked as required.](https://platform.openai.com/docs/guides/function-calling#strict-mode)
222 +
223 Examples:
224
225 ```typescript
@@ -224,11 +228,12 @@ const specificTools = await composio.tools.get('default', {
228 tools: ['GITHUB_GET_REPO', 'GITHUB_LIST_ISSUES'],
229 });
230
227 -// Get all tools from specific toolkits
231 +// Get all tools from specific toolkits with strict mode enabled
232 const toolkitTools = await composio.tools.get('default', {
233 toolkits: ['github', 'gitlab'],
234 important: true,
235 limit: 10,
236 + strict: true, // This will remove all non-required properties from tool parameters
237 });
238
239 // Search for tools across all or specific toolkits
packages/core/src/models/Tools.ts
+14 -1
@@ -40,6 +40,7 @@ import {
40 } from '../errors/ToolErrors';
41 import { ValidationError } from '../errors/ValidationErrors';
42 import { telemetry } from '../telemetry/Telemetry';
43 +import { removeNonRequiredProperties } from '../utils/jsonSchema';
44 /**
45 * This class is used to manage tools in the Composio SDK.
46 * It provides methods to list, get, and execute tools.
@@ -454,7 +455,19 @@ export class Tools<
455 return this.provider.wrapTools([tool], executeToolFn) as TToolCollection;
456 } else {
457 // if the first argument is an object, get a list of tools
457 - const tools = await this.getRawComposioTools(userId, arg2, options?.modifySchema);
458 + let tools = await this.getRawComposioTools(userId, arg2, options?.modifySchema);
459 + // if the strict flag is true, remove all non-required properties from the input and output parameters
460 + if (arg2?.strict) {
461 + tools = tools.map(tool => ({
462 + ...tool,
463 + inputParameters: tool.inputParameters
464 + ? removeNonRequiredProperties(tool.inputParameters)
465 + : undefined,
466 + outputParameters: tool.outputParameters
467 + ? removeNonRequiredProperties(tool.outputParameters)
468 + : undefined,
469 + }));
470 + }
471 return this.provider.wrapTools(tools, executeToolFn) as TToolCollection;
472 }
473 }
packages/core/src/types/tool.types.ts
+15
@@ -89,6 +89,12 @@ export const ToolListFilterByToolkitsSchema = z.object({
89 cursor: z.string().optional(),
90 limit: z.number().optional(),
91 search: z.string().optional(),
92 + strict: z
93 + .boolean()
94 + .optional()
95 + .describe(
96 + 'If true, all the non-required fields will be removed from the input/output params of the tool'
97 + ),
98 });
99 export type ToolListFilterByToolkits = z.infer<typeof ToolListFilterByToolkitsSchema>;
100
@@ -97,6 +103,12 @@ export const ToolListFilterBySearchSchema = z.object({
103 toolkits: z.array(z.string()).optional(),
104 cursor: z.string().optional(),
105 limit: z.number().optional(),
106 + strict: z
107 + .boolean()
108 + .optional()
109 + .describe(
110 + 'If true, all the non-required fields will be removed from the input/output params of the tool'
111 + ),
112 });
113 export type ToolListFilterBySearch = z.infer<typeof ToolListFilterBySearchSchema>;
114
@@ -107,6 +119,7 @@ type ToolsOnlyParams = {
119 cursor?: never;
120 limit?: never;
121 search?: never;
122 + strict?: boolean;
123 };
124
125 type ToolkitsOnlyParams = {
@@ -116,6 +129,7 @@ type ToolkitsOnlyParams = {
129 cursor?: string;
130 limit?: number;
131 search?: never;
132 + strict?: boolean;
133 };
134
135 type ToolkitSearchOnlyParams = {
@@ -125,6 +139,7 @@ type ToolkitSearchOnlyParams = {
139 cursor?: string;
140 limit?: number;
141 search?: string;
142 + strict?: boolean;
143 };
144 /**
145 * ToolListParams is the parameters for the list of tools.
packages/core/src/utils/jsonSchema.ts
+58 -2
@@ -2,9 +2,32 @@ import { z } from 'zod';
2 import { JsonSchemaToZodError } from '../errors';
3 import { jsonSchemaToZod } from '@composio/json-schema-to-zod';
4
5 +/**
6 + * Removes all non-required properties from the schema
7 + *
8 + * if no items are required, the schema is returned as is
9 + * @param schema - The JSON schema to remove non-required properties from
10 + * @returns The JSON schema with all non-required properties removed
11 + */
12 +export const removeNonRequiredProperties = <
13 + T extends { type: 'object'; properties: Record<string, unknown>; required?: string[] },
14 +>(
15 + schema: T
16 +): T => {
17 + if (schema && schema.type === 'object' && (schema.required as string[])?.length) {
18 + schema.properties = Object.fromEntries(
19 + Object.entries(schema.properties || {}).filter(([key]) =>
20 + (schema.required as string[]).includes(key)
21 + )
22 + );
23 + }
24 + return schema as T;
25 +};
26 +
27 /**
28 * Convert a JSON schema to a Zod schema
29 * @param jsonSchema - The JSON schema to convert
30 + * @param strict - Eliminates all non-required properties from the schema
31 * @returns The Zod schema
32 *
33 * @throws {JsonSchemaToZodError} If the JSON schema is invalid
@@ -20,13 +43,46 @@ import { jsonSchemaToZod } from '@composio/json-schema-to-zod';
43 *
44 * console.log(zodSchema);
45 * ```
46 + *
47 + * @example
48 + * ```ts
49 + * const zodSchema = jsonSchemaToZodSchema({
50 + * type: 'object',
51 + * properties: {
52 + * name: { type: 'string' },
53 + * age: { type: 'number' },
54 + * },
55 + * required: ['name'],
56 + * }, { strict: true });
57 + *
58 + * console.log(zodSchema);
59 + *
60 + * // Output:
61 + * // z.object({
62 + * // name: z.string(),
63 + * // })
64 + * ```
65 */
66 export function jsonSchemaToZodSchema(
25 - jsonSchema: Record<string, unknown>
67 + jsonSchema: Record<string, unknown>,
68 + { strict }: { strict?: boolean } = {
69 + strict: false,
70 + }
71 ): z.ZodObject<Record<string, z.ZodTypeAny>> {
72 try {
73 + let schema = jsonSchema;
74 + // Remove all non-required properties from the schema if strict is true
75 + if (strict && schema) {
76 + schema = removeNonRequiredProperties(
77 + schema as {
78 + type: 'object';
79 + properties: Record<string, unknown>;
80 + required?: string[] | undefined;
81 + }
82 + );
83 + }
84 // Convert the JSON schema properties to Zod schema
29 - return jsonSchemaToZod(jsonSchema);
85 + return jsonSchemaToZod(schema);
86 } catch (error) {
87 throw new JsonSchemaToZodError('Failed to convert JSON Schema to Zod Schema', {
88 cause: error,
packages/core/test/tools/tools.test.ts
+130
@@ -329,6 +329,136 @@ describe('Tools', () => {
329
330 expect(getRawComposioToolBySlugSpy).toHaveBeenCalledWith(userId, slug, schemaModifier);
331 });
332 +
333 + it('should remove non-required properties when strict mode is enabled', async () => {
334 + const userId = 'test-user';
335 + const filters = {
336 + tools: ['TOOL1'],
337 + strict: true,
338 + };
339 +
340 + const toolWithOptionalParams = {
341 + ...toolMocks.transformedTool,
342 + inputParameters: {
343 + type: 'object',
344 + required: ['requiredParam'],
345 + properties: {
346 + requiredParam: {
347 + type: 'string',
348 + description: 'Required parameter',
349 + },
350 + optionalParam: {
351 + type: 'string',
352 + description: 'Optional parameter',
353 + },
354 + },
355 + },
356 + outputParameters: {
357 + type: 'object',
358 + required: ['requiredOutput'],
359 + properties: {
360 + requiredOutput: {
361 + type: 'string',
362 + description: 'Required output',
363 + },
364 + optionalOutput: {
365 + type: 'string',
366 + description: 'Optional output',
367 + },
368 + },
369 + },
370 + };
371 +
372 + const getRawComposioToolsSpy = vi.spyOn(context.tools, 'getRawComposioTools');
373 + getRawComposioToolsSpy.mockResolvedValueOnce([toolWithOptionalParams as unknown as Tool]);
374 +
375 + context.mockProvider.wrapTools.mockReturnValueOnce('wrapped-tools-collection');
376 +
377 + const result = await context.tools.get(userId, filters);
378 +
379 + expect(context.mockProvider.wrapTools).toHaveBeenCalledWith(
380 + [
381 + {
382 + ...toolWithOptionalParams,
383 + inputParameters: {
384 + type: 'object',
385 + required: ['requiredParam'],
386 + properties: {
387 + requiredParam: {
388 + type: 'string',
389 + description: 'Required parameter',
390 + },
391 + },
392 + },
393 + outputParameters: {
394 + type: 'object',
395 + required: ['requiredOutput'],
396 + properties: {
397 + requiredOutput: {
398 + type: 'string',
399 + description: 'Required output',
400 + },
401 + },
402 + },
403 + },
404 + ],
405 + expect.any(Function)
406 + );
407 + expect(result).toEqual('wrapped-tools-collection');
408 + });
409 +
410 + it('should not modify properties when strict mode is disabled', async () => {
411 + const userId = 'test-user';
412 + const filters = {
413 + tools: ['TOOL1'],
414 + strict: false,
415 + };
416 +
417 + const toolWithOptionalParams = {
418 + ...toolMocks.transformedTool,
419 + inputParameters: {
420 + type: 'object',
421 + required: ['requiredParam'],
422 + properties: {
423 + requiredParam: {
424 + type: 'string',
425 + description: 'Required parameter',
426 + },
427 + optionalParam: {
428 + type: 'string',
429 + description: 'Optional parameter',
430 + },
431 + },
432 + },
433 + outputParameters: {
434 + type: 'object',
435 + required: ['requiredOutput'],
436 + properties: {
437 + requiredOutput: {
438 + type: 'string',
439 + description: 'Required output',
440 + },
441 + optionalOutput: {
442 + type: 'string',
443 + description: 'Optional output',
444 + },
445 + },
446 + },
447 + };
448 +
449 + const getRawComposioToolsSpy = vi.spyOn(context.tools, 'getRawComposioTools');
450 + getRawComposioToolsSpy.mockResolvedValueOnce([toolWithOptionalParams as unknown as Tool]);
451 +
452 + context.mockProvider.wrapTools.mockReturnValueOnce('wrapped-tools-collection');
453 +
454 + const result = await context.tools.get(userId, filters);
455 +
456 + expect(context.mockProvider.wrapTools).toHaveBeenCalledWith(
457 + [toolWithOptionalParams],
458 + expect.any(Function)
459 + );
460 + expect(result).toEqual('wrapped-tools-collection');
461 + });
462 });
463
464 describe('execute', () => {
packages/providers/vercel/README.md
+21
@@ -178,6 +178,27 @@ const provider = new VercelProvider({
178 });
179 ```
180
181 +### Strict Mode
182 +
183 +When using tools with Vercel AI SDK, you might need to ensure that all tool parameters are marked as required. This is because Vercel AI SDK's function calling implementation requires all fields to be marked as required. You can enable strict mode when fetching tools to automatically remove all non-required properties from both input and output parameters:
184 +
185 +```typescript
186 +// Get tools with strict mode enabled
187 +const tools = await composio.tools.get('user123', {
188 + toolkits: ['gmail', 'googlecalendar'],
189 + strict: true, // This will remove all non-required properties from tool parameters
190 +});
191 +
192 +// Use these tools with Vercel AI SDK
193 +const stream = streamText({
194 + model: openai('gpt-4'),
195 + messages,
196 + tools, // These tools will only have required parameters
197 +});
198 +```
199 +
200 +For more information about strict mode in function calling, see [OpenAI's documentation](https://platform.openai.com/docs/guides/function-calling#strict-mode).
201 +
202 ## API Reference
203
204 ### VercelProvider Class