Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
Add tests for modifiers
haxzie committed
May 19, 2025 at 15:06 UTC
5bea27d68789db489ec18c1e48828465e1f9fb3d
4 files changed
+400
packages/core/test/tools/customTools.test.ts
+151
@@ -0,0 +1,151 @@
1
+import { describe, it, expect, vi, beforeEach } from 'vitest';
2
+import { CustomTools } from '../../src/models/CustomTools';
3
+import { mockClient } from './mocks/client.mock';
4
+import { toolMocks } from './mocks/data.mock';
5
+import ComposioClient from '@composio/client';
6
+import { z } from 'zod';
7
+
8
+describe('CustomTools', () => {
9
+ let customTools: CustomTools;
10
+
11
+ const toolOptions = {
12
+ slug: 'CUSTOM_TOOL',
13
+ name: 'Custom Tool',
14
+ description: 'A custom tool for testing',
15
+ inputParams: z.object({
16
+ query: z.string().describe('The search query'),
17
+ }),
18
+ execute: vi.fn().mockResolvedValue(toolMocks.toolExecuteResponse),
19
+ };
20
+
21
+ beforeEach(() => {
22
+ vi.clearAllMocks();
23
+ customTools = new CustomTools(mockClient as unknown as ComposioClient);
24
+ });
25
+
26
+ it('should throw an error if client is not provided', () => {
27
+ expect(() => new CustomTools(null as any)).toThrow('ComposioClient is required');
28
+ });
29
+
30
+ describe('createTool', () => {
31
+ it('should create a custom tool and add it to the registry', async () => {
32
+ const result = await customTools.createTool(toolOptions);
33
+
34
+ expect(result).toMatchObject({
35
+ slug: toolOptions.slug,
36
+ name: toolOptions.name,
37
+ description: toolOptions.description,
38
+ inputParameters: expect.any(Object),
39
+ outputParameters: expect.any(Object),
40
+ });
41
+
42
+ // Verify it's in the registry
43
+ const registryTool = await customTools.getCustomToolBySlug(toolOptions.slug);
44
+ expect(registryTool).toBeDefined();
45
+ expect(registryTool?.slug).toEqual(toolOptions.slug);
46
+ });
47
+
48
+ it('should throw an error for invalid tool options', async () => {
49
+ const invalidOptions = {
50
+ slug: 'INVALID_TOOL',
51
+ // Missing required properties
52
+ };
53
+
54
+ await expect(customTools.createTool(invalidOptions as any)).rejects.toThrow(
55
+ 'Invalid tool options'
56
+ );
57
+ });
58
+ });
59
+
60
+ describe('getCustomTools', () => {
61
+ it('should return all tools from the registry when no slugs provided', async () => {
62
+ // Add tools to the registry
63
+ await customTools.createTool(toolOptions);
64
+ await customTools.createTool({
65
+ ...toolOptions,
66
+ slug: 'ANOTHER_TOOL',
67
+ });
68
+
69
+ const result = await customTools.getCustomTools({});
70
+
71
+ expect(result).toHaveLength(2);
72
+ expect(result[0].slug).toEqual('CUSTOM_TOOL');
73
+ expect(result[1].slug).toEqual('ANOTHER_TOOL');
74
+ });
75
+
76
+ it('should filter tools by slug when provided', async () => {
77
+ // Add tools to the registry
78
+ await customTools.createTool(toolOptions);
79
+ await customTools.createTool({
80
+ ...toolOptions,
81
+ slug: 'ANOTHER_TOOL',
82
+ });
83
+
84
+ const result = await customTools.getCustomTools({
85
+ toolSlugs: ['CUSTOM_TOOL'],
86
+ });
87
+
88
+ expect(result).toHaveLength(1);
89
+ expect(result[0].slug).toEqual('CUSTOM_TOOL');
90
+ });
91
+ });
92
+
93
+ describe('executeCustomTool', () => {
94
+ it('should execute a custom tool with provided parameters', async () => {
95
+ // Add a tool to the registry
96
+ await customTools.createTool(toolOptions);
97
+
98
+ const inputParams = { query: 'test query' };
99
+ const metadata = { userId: 'test-user' };
100
+
101
+ const result = await customTools.executeCustomTool(toolOptions.slug, inputParams, metadata);
102
+
103
+ expect(toolOptions.execute).toHaveBeenCalledWith(inputParams, {}, expect.any(Function));
104
+ expect(result).toEqual(toolMocks.toolExecuteResponse);
105
+ });
106
+
107
+ it('should throw an error if tool does not exist', async () => {
108
+ const nonExistentSlug = 'NON_EXISTENT';
109
+ const inputParams = { query: 'test query' };
110
+ const metadata = { userId: 'test-user' };
111
+
112
+ await expect(
113
+ customTools.executeCustomTool(nonExistentSlug, inputParams, metadata)
114
+ ).rejects.toThrow(`Tool with slug ${nonExistentSlug} not found`);
115
+ });
116
+
117
+ it('should fetch auth credentials for toolkit-based custom tools', async () => {
118
+ // Add a toolkit-based tool
119
+ const toolkitTool = {
120
+ ...toolOptions,
121
+ toolkitSlug: 'TEST_TOOLKIT',
122
+ };
123
+ await customTools.createTool(toolkitTool);
124
+
125
+ // Mock toolkit and connected account retrieval
126
+ mockClient.toolkits.retrieve.mockResolvedValueOnce({ slug: 'TEST_TOOLKIT' });
127
+ mockClient.connectedAccounts.list.mockResolvedValueOnce({
128
+ items: [
129
+ {
130
+ id: 'conn-123',
131
+ data: {
132
+ connectionParams: { apiKey: 'test-key' },
133
+ },
134
+ },
135
+ ],
136
+ totalPages: 1,
137
+ });
138
+
139
+ const inputParams = { query: 'test query' };
140
+ const metadata = { userId: 'test-user' };
141
+
142
+ await customTools.executeCustomTool(toolkitTool.slug, inputParams, metadata);
143
+
144
+ expect(toolkitTool.execute).toHaveBeenCalledWith(
145
+ inputParams,
146
+ { apiKey: 'test-key' },
147
+ expect.any(Function)
148
+ );
149
+ });
150
+ });
151
+});
packages/core/test/tools/mocks/data.mock.ts
+2
@@ -1,3 +1,5 @@
1
+import { z } from 'zod';
2
+
3
export const toolMocks = {
4
rawTool: {
5
slug: 'COMPOSIO_TOOL',
packages/core/test/tools/modifiers.test.ts
+147
@@ -0,0 +1,147 @@
1
+import { describe, it, expect, vi } from 'vitest';
2
+import { mockClient } from './mocks/client.mock';
3
+import { toolMocks } from './mocks/data.mock';
4
+import { Tool } from '../../src/types/tool.types';
5
+import {
6
+ createTestContext,
7
+ setupTest,
8
+ mockToolExecution,
9
+ createSchemaModifier,
10
+ createExecutionModifiers,
11
+} from './test-utils';
12
+
13
+describe('Tools Modifiers', () => {
14
+ const context = createTestContext();
15
+ setupTest(context);
16
+
17
+ describe('Schema Modifiers', () => {
18
+ it('should modify the tool schema with the provided modifier', async () => {
19
+ const userId = 'test-user';
20
+ const slug = 'COMPOSIO_TOOL';
21
+ const schemaModifier = createSchemaModifier({
22
+ name: 'Modified Name',
23
+ description: 'Modified description',
24
+ });
25
+
26
+ mockClient.tools.retrieve.mockResolvedValueOnce(toolMocks.rawTool);
27
+
28
+ const result = await context.tools.getComposioToolBySlug(userId, slug, schemaModifier);
29
+
30
+ expect(schemaModifier).toHaveBeenCalledTimes(1);
31
+ expect(schemaModifier).toHaveBeenCalledWith(
32
+ slug,
33
+ expect.any(String),
34
+ expect.objectContaining({ slug })
35
+ );
36
+ expect(result.name).toEqual('Modified Name');
37
+ expect(result.description).toEqual('Modified description');
38
+ });
39
+
40
+ it('should apply schema modifiers to all tools when getting multiple tools', async () => {
41
+ const userId = 'test-user';
42
+ const schemaModifier = createSchemaModifier((tool: Tool) => ({
43
+ ...tool,
44
+ name: `Modified ${tool.name}`,
45
+ }));
46
+
47
+ mockClient.tools.list.mockResolvedValueOnce({
48
+ items: [
49
+ { ...toolMocks.rawTool, slug: 'TOOL1' },
50
+ { ...toolMocks.rawTool, slug: 'TOOL2' },
51
+ ],
52
+ totalPages: 1,
53
+ });
54
+
55
+ const result = await context.tools.getComposioTools(userId, {}, schemaModifier);
56
+
57
+ expect(schemaModifier).toHaveBeenCalledTimes(2);
58
+ expect(result[0].name).toContain('Modified');
59
+ expect(result[1].name).toContain('Modified');
60
+ });
61
+ });
62
+
63
+ describe('Execution Modifiers', () => {
64
+ it('should apply beforeToolExecute modifier before executing a tool', async () => {
65
+ const slug = 'COMPOSIO_TOOL';
66
+ const body = {
67
+ userId: 'test-user',
68
+ arguments: { limit: 5 },
69
+ };
70
+
71
+ const { beforeToolExecute } = createExecutionModifiers({
72
+ beforeModifications: {
73
+ arguments: { limit: 10 },
74
+ },
75
+ });
76
+
77
+ await mockToolExecution(context.tools);
78
+ await context.tools.execute(slug, body, { beforeToolExecute });
79
+
80
+ expect(beforeToolExecute).toHaveBeenCalledTimes(1);
81
+ expect(beforeToolExecute).toHaveBeenCalledWith(slug, expect.any(String), body);
82
+ expect(mockClient.tools.execute).toHaveBeenCalledWith(
83
+ slug,
84
+ expect.objectContaining({
85
+ arguments: { limit: 10 },
86
+ })
87
+ );
88
+ });
89
+
90
+ it('should apply afterToolExecute modifier after executing a tool', async () => {
91
+ const slug = 'COMPOSIO_TOOL';
92
+ const body = { userId: 'test-user', arguments: {} };
93
+
94
+ const { afterToolExecute } = createExecutionModifiers({
95
+ afterModifications: {
96
+ data: { enhanced: true },
97
+ },
98
+ });
99
+
100
+ await mockToolExecution(context.tools);
101
+ const result = await context.tools.execute(slug, body, { afterToolExecute });
102
+
103
+ expect(afterToolExecute).toHaveBeenCalledTimes(1);
104
+ expect(afterToolExecute).toHaveBeenCalledWith(
105
+ slug,
106
+ expect.any(String),
107
+ expect.objectContaining({
108
+ data: expect.any(Object),
109
+ successful: expect.any(Boolean),
110
+ })
111
+ );
112
+ expect(result.data).toHaveProperty('enhanced', true);
113
+ });
114
+ });
115
+
116
+ describe('Combined Modifiers', () => {
117
+ it('should apply both schema and execution modifiers together', async () => {
118
+ const userId = 'test-user';
119
+ const slug = 'COMPOSIO_TOOL';
120
+
121
+ const schemaModifier = createSchemaModifier({
122
+ description: 'Modified schema',
123
+ });
124
+
125
+ const executionModifiers = createExecutionModifiers();
126
+
127
+ const getComposioToolBySlugSpy = vi.spyOn(context.tools, 'getComposioToolBySlug');
128
+ getComposioToolBySlugSpy.mockResolvedValueOnce({
129
+ ...(toolMocks.transformedTool as unknown as Tool),
130
+ description: 'Modified schema',
131
+ });
132
+
133
+ const createExecuteToolFnSpy = vi.spyOn(context.tools as any, 'createExecuteToolFn');
134
+
135
+ await context.tools.get(userId, slug, {
136
+ modifyToolSchema: schemaModifier,
137
+ ...executionModifiers,
138
+ });
139
+
140
+ expect(getComposioToolBySlugSpy).toHaveBeenCalledWith(userId, slug, schemaModifier);
141
+ expect(createExecuteToolFnSpy).toHaveBeenCalledWith(
142
+ userId,
143
+ expect.objectContaining(executionModifiers)
144
+ );
145
+ });
146
+ });
147
+});
packages/core/test/tools/test-utils.ts
new
+100
@@ -0,0 +1,100 @@
1
+import { vi, beforeEach } from 'vitest';
2
+import { Tools } from '../../src/models/Tools';
3
+import { mockClient } from './mocks/client.mock';
4
+import { MockToolset } from './mocks/toolset.mock';
5
+import { connectedAccountMocks, toolkitMocks, toolMocks } from './mocks/data.mock';
6
+import ComposioClient from '@composio/client';
7
+import { Tool } from '../../src/types/tool.types';
8
+
9
+export type TestTools = Tools<unknown, unknown, MockToolset>;
10
+
11
+export interface TestContext {
12
+ tools: TestTools;
13
+ mockToolset: MockToolset;
14
+}
15
+
16
+export const createTestContext = (): TestContext => {
17
+ const mockToolset = new MockToolset();
18
+ const tools = new Tools(mockClient as unknown as ComposioClient, mockToolset);
19
+ return { tools, mockToolset };
20
+};
21
+
22
+export const setupTest = (context: TestContext) => {
23
+ beforeEach(() => {
24
+ vi.clearAllMocks();
25
+ context.mockToolset = new MockToolset();
26
+ context.tools = new Tools(mockClient as unknown as ComposioClient, context.mockToolset);
27
+ });
28
+};
29
+
30
+export const mockToolExecution = async (
31
+ tools: TestTools,
32
+ {
33
+ slug = 'COMPOSIO_TOOL',
34
+ customToolExists = false,
35
+ connectedAccountId = 'test-connected-account-id',
36
+ } = {}
37
+) => {
38
+ // Mock client responses
39
+ mockClient.tools.retrieve.mockResolvedValueOnce(toolMocks.rawTool);
40
+ mockClient.toolkits.retrieve.mockResolvedValueOnce(toolkitMocks.rawToolkit);
41
+ mockClient.connectedAccounts.list.mockResolvedValueOnce(
42
+ connectedAccountMocks.rawConnectedAccountsResponse
43
+ );
44
+
45
+ // Mock custom tool check
46
+ const getCustomToolBySlugSpy = vi.spyOn(tools['customTools'], 'getCustomToolBySlug');
47
+ getCustomToolBySlugSpy.mockResolvedValueOnce(
48
+ customToolExists ? (toolMocks.customTool as unknown as Tool) : undefined
49
+ );
50
+
51
+ // Mock composio tool retrieval
52
+ const getComposioToolBySlugSpy = vi.spyOn(tools, 'getComposioToolBySlug');
53
+ getComposioToolBySlugSpy.mockResolvedValueOnce(toolMocks.transformedTool as unknown as Tool);
54
+
55
+ // Mock connected account
56
+ const getConnectedAccountIdForToolSpy = vi.spyOn(
57
+ tools as unknown as {
58
+ getConnectedAccountIdForTool: (typeof tools)['getConnectedAccountIdForTool'];
59
+ },
60
+ 'getConnectedAccountIdForTool'
61
+ );
62
+ getConnectedAccountIdForToolSpy.mockResolvedValueOnce(connectedAccountId);
63
+
64
+ // Mock tool execution
65
+ mockClient.tools.execute.mockResolvedValueOnce(toolMocks.rawToolExecuteResponse);
66
+
67
+ return {
68
+ getCustomToolBySlugSpy,
69
+ getComposioToolBySlugSpy,
70
+ getConnectedAccountIdForToolSpy,
71
+ };
72
+};
73
+
74
+export type SchemaModification = Partial<Tool> | ((tool: Tool) => Partial<Tool>);
75
+
76
+export const createSchemaModifier = (modifications: SchemaModification) => {
77
+ return vi.fn((toolSlug: string, toolkitSlug: string, tool: Tool) => {
78
+ const mods = typeof modifications === 'function' ? modifications(tool) : modifications;
79
+ return {
80
+ ...tool,
81
+ ...mods,
82
+ };
83
+ });
84
+};
85
+
86
+export const createExecutionModifiers = ({
87
+ beforeModifications = {},
88
+ afterModifications = {},
89
+} = {}) => {
90
+ return {
91
+ beforeToolExecute: vi.fn((toolSlug: string, toolkitSlug: string, params: any) => ({
92
+ ...params,
93
+ ...beforeModifications,
94
+ })),
95
+ afterToolExecute: vi.fn((toolSlug: string, toolkitSlug: string, response: any) => ({
96
+ ...response,
97
+ ...afterModifications,
98
+ })),
99
+ };
100
+};