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 23, 03:00 UTC
Add tests to all the toolsets
haxzie committed
May 19, 2025 at 18:09 UTC
1b951eede8bcf172ef8a7ca0cc60b1208786bacf
3 files changed
+1047
-12
packages/toolsets/cloudflare/test/cloudflare.test.ts
+310
-4
@@ -1,7 +1,313 @@
1
-import { describe, it, expect } from 'vitest';
1
+import { describe, it, expect, vi, beforeEach } from 'vitest';
2
+import { CloudflareToolset } from '../src';
3
+import { Tool } from '@composio/core';
4
3
-describe('Vercel', () => {
4
- it('should be a test', () => {
5
- expect(true).toBe(true);
5
+// Instead of importing and mocking the actual Cloudflare types, let's define our own for testing
6
+interface AiTextGenerationFunction {
7
+ name: string;
8
+ description: string;
9
+ parameters: any;
10
+}
11
+
12
+interface MockedCloudflareToolInput {
13
+ type: 'function';
14
+ function: {
15
+ name: string;
16
+ description?: string;
17
+ parameters?: any;
18
+ };
19
+}
20
+
21
+// Mock the types we need from Cloudflare
22
+vi.mock('@cloudflare/workers-types', () => {
23
+ return {};
24
+});
25
+
26
+describe('CloudflareToolset', () => {
27
+ let toolset: CloudflareToolset;
28
+ let mockTool: Tool;
29
+ let mockExecuteToolFn: any;
30
+
31
+ beforeEach(() => {
32
+ toolset = new CloudflareToolset();
33
+
34
+ // Mock the global execute tool function
35
+ mockExecuteToolFn = vi.fn().mockResolvedValue({
36
+ data: { result: 'success' },
37
+ error: null,
38
+ successful: true,
39
+ });
40
+ toolset._setExecuteToolFn(mockExecuteToolFn);
41
+
42
+ // Create a mock Composio tool
43
+ mockTool = {
44
+ slug: 'test-tool',
45
+ name: 'Test Tool',
46
+ description: 'A tool for testing',
47
+ inputParameters: {
48
+ type: 'object',
49
+ properties: {
50
+ input: {
51
+ type: 'string',
52
+ description: 'Test input',
53
+ },
54
+ },
55
+ required: ['input'],
56
+ },
57
+ tags: [],
58
+ };
59
+
60
+ // Reset mocks before each test
61
+ vi.clearAllMocks();
62
+ });
63
+
64
+ describe('name property', () => {
65
+ it('should have the correct name', () => {
66
+ expect(toolset.name).toBe('cloudflare');
67
+ });
68
+ });
69
+
70
+ describe('_isAgentic property', () => {
71
+ it('should be non-agentic', () => {
72
+ expect(toolset._isAgentic).toBe(false);
73
+ });
74
+ });
75
+
76
+ describe('wrapTool', () => {
77
+ it('should wrap a tool in Cloudflare AiTextGenerationToolInput format', () => {
78
+ const wrapped = toolset.wrapTool(mockTool) as MockedCloudflareToolInput;
79
+
80
+ expect(wrapped).toEqual({
81
+ type: 'function',
82
+ function: {
83
+ name: mockTool.slug,
84
+ description: mockTool.description,
85
+ parameters: mockTool.inputParameters,
86
+ },
87
+ });
88
+ });
89
+
90
+ it('should handle tools without input parameters', () => {
91
+ const toolWithoutParams: Tool = {
92
+ ...mockTool,
93
+ inputParameters: undefined,
94
+ };
95
+
96
+ // This would normally throw an error due to the type casting in the function,
97
+ // but we're testing the behavior, not the types
98
+ const wrapped = toolset.wrapTool(toolWithoutParams) as MockedCloudflareToolInput;
99
+
100
+ expect(wrapped).toEqual({
101
+ type: 'function',
102
+ function: {
103
+ name: toolWithoutParams.slug,
104
+ description: toolWithoutParams.description,
105
+ parameters: undefined,
106
+ },
107
+ });
108
+ });
109
+
110
+ it('should handle tools without description', () => {
111
+ const toolWithoutDescription: Tool = {
112
+ ...mockTool,
113
+ description: undefined,
114
+ };
115
+
116
+ const wrapped = toolset.wrapTool(toolWithoutDescription) as MockedCloudflareToolInput;
117
+
118
+ expect(wrapped).toEqual({
119
+ type: 'function',
120
+ function: {
121
+ name: toolWithoutDescription.slug,
122
+ description: undefined,
123
+ parameters: toolWithoutDescription.inputParameters,
124
+ },
125
+ });
126
+ });
127
+ });
128
+
129
+ describe('wrapTools', () => {
130
+ it('should wrap multiple tools into a dictionary', () => {
131
+ const anotherTool: Tool = {
132
+ ...mockTool,
133
+ slug: 'another-tool',
134
+ name: 'Another Tool',
135
+ };
136
+ const tools = [mockTool, anotherTool];
137
+
138
+ const wrapped = toolset.wrapTools(tools);
139
+
140
+ // Verify the result has the expected properties
141
+ expect(Object.keys(wrapped)).toHaveLength(2);
142
+ expect(wrapped['test-tool']).toBeDefined();
143
+ expect(wrapped['another-tool']).toBeDefined();
144
+
145
+ // Verify each tool was properly wrapped
146
+ expect(wrapped['test-tool']).toEqual({
147
+ type: 'function',
148
+ function: {
149
+ name: mockTool.slug,
150
+ description: mockTool.description,
151
+ parameters: mockTool.inputParameters,
152
+ },
153
+ });
154
+
155
+ expect(wrapped['another-tool']).toEqual({
156
+ type: 'function',
157
+ function: {
158
+ name: anotherTool.slug,
159
+ description: anotherTool.description,
160
+ parameters: anotherTool.inputParameters,
161
+ },
162
+ });
163
+ });
164
+
165
+ it('should return an empty object for empty tools array', () => {
166
+ const wrapped = toolset.wrapTools([]);
167
+ expect(wrapped).toEqual({});
168
+ });
169
+ });
170
+
171
+ describe('executeToolCall', () => {
172
+ it('should execute a tool call and return the result as string', async () => {
173
+ const userId = 'test-user';
174
+ const toolCall = {
175
+ name: 'test-tool',
176
+ arguments: { input: 'test-value' },
177
+ };
178
+
179
+ const result = await toolset.executeToolCall(userId, toolCall, {});
180
+
181
+ expect(mockExecuteToolFn).toHaveBeenCalledWith(
182
+ 'test-tool',
183
+ {
184
+ arguments: { input: 'test-value' },
185
+ userId: 'test-user',
186
+ connectedAccountId: undefined,
187
+ customAuthParams: undefined,
188
+ },
189
+ undefined
190
+ );
191
+ expect(result).toBe(
192
+ JSON.stringify({
193
+ data: { result: 'success' },
194
+ error: null,
195
+ successful: true,
196
+ })
197
+ );
198
+ });
199
+
200
+ it('should handle string arguments by parsing them', async () => {
201
+ const userId = 'test-user';
202
+ const toolCall = {
203
+ name: 'test-tool',
204
+ arguments: JSON.stringify({ input: 'test-value' }),
205
+ };
206
+
207
+ const result = await toolset.executeToolCall(userId, toolCall, {});
208
+
209
+ expect(mockExecuteToolFn).toHaveBeenCalledWith(
210
+ 'test-tool',
211
+ {
212
+ arguments: { input: 'test-value' },
213
+ userId: 'test-user',
214
+ connectedAccountId: undefined,
215
+ customAuthParams: undefined,
216
+ },
217
+ undefined
218
+ );
219
+ expect(result).toBe(
220
+ JSON.stringify({
221
+ data: { result: 'success' },
222
+ error: null,
223
+ successful: true,
224
+ })
225
+ );
226
+ });
227
+
228
+ it('should pass options to executeTool', async () => {
229
+ const userId = 'test-user';
230
+ const toolCall = {
231
+ name: 'test-tool',
232
+ arguments: { input: 'test-value' },
233
+ };
234
+
235
+ const options = {
236
+ connectedAccountId: 'conn-123',
237
+ customAuthParams: {
238
+ parameters: [{ name: 'token', value: 'abc123', in: 'header' as const }],
239
+ },
240
+ };
241
+
242
+ const modifiers = {
243
+ beforeToolExecute: vi.fn(params => params),
244
+ afterToolExecute: vi.fn(response => response),
245
+ };
246
+
247
+ await toolset.executeToolCall(userId, toolCall, options, modifiers);
248
+
249
+ expect(mockExecuteToolFn).toHaveBeenCalledWith(
250
+ 'test-tool',
251
+ {
252
+ arguments: { input: 'test-value' },
253
+ userId: 'test-user',
254
+ connectedAccountId: 'conn-123',
255
+ customAuthParams: options.customAuthParams,
256
+ },
257
+ modifiers
258
+ );
259
+ });
260
+ });
261
+
262
+ describe('executeTool', () => {
263
+ it('should execute a tool using the global execute function', async () => {
264
+ const toolSlug = 'test-tool';
265
+ const toolParams = {
266
+ userId: 'test-user',
267
+ arguments: { input: 'test-value' },
268
+ };
269
+
270
+ const result = await toolset.executeTool(toolSlug, toolParams);
271
+
272
+ expect(mockExecuteToolFn).toHaveBeenCalledWith(toolSlug, toolParams, undefined);
273
+ expect(result).toEqual({
274
+ data: { result: 'success' },
275
+ error: null,
276
+ successful: true,
277
+ });
278
+ });
279
+
280
+ it('should pass modifiers to the global execute function', async () => {
281
+ const toolSlug = 'test-tool';
282
+ const toolParams = {
283
+ userId: 'test-user',
284
+ arguments: { input: 'test-value' },
285
+ };
286
+
287
+ const modifiers = {
288
+ beforeToolExecute: vi.fn(params => params),
289
+ afterToolExecute: vi.fn(response => response),
290
+ };
291
+
292
+ await toolset.executeTool(toolSlug, toolParams, modifiers);
293
+
294
+ expect(mockExecuteToolFn).toHaveBeenCalledWith(toolSlug, toolParams, modifiers);
295
+ });
296
+ });
297
+
298
+ describe('integration with Cloudflare AI', () => {
299
+ it('should produce tools compatible with Cloudflare AI', () => {
300
+ const wrapped = toolset.wrapTool(mockTool) as MockedCloudflareToolInput;
301
+
302
+ // Verify the wrapped tool has the expected structure
303
+ expect(wrapped).toHaveProperty('type', 'function');
304
+ expect(wrapped).toHaveProperty('function');
305
+ expect(wrapped.function).toHaveProperty('name', mockTool.slug);
306
+ expect(wrapped.function).toHaveProperty('description', mockTool.description);
307
+ expect(wrapped.function).toHaveProperty('parameters', mockTool.inputParameters);
308
+
309
+ // The structure should match what Cloudflare AI expects
310
+ expect(wrapped.type).toBe('function');
311
+ });
312
});
313
});
packages/toolsets/langchain/test/langchain.test.ts
+236
-4
@@ -1,7 +1,239 @@
1
-import { describe, it, expect } from 'vitest';
1
+import { describe, it, expect, vi, beforeEach } from 'vitest';
2
+import { LangchainToolset } from '../src';
3
+import { Tool } from '@composio/core';
4
+import { DynamicStructuredTool } from '@langchain/core/tools';
5
3
-describe('Vercel', () => {
4
- it('should be a test', () => {
5
- expect(true).toBe(true);
6
+// Define an interface for our mocked LangChain tool
7
+interface MockedLangChainTool extends DynamicStructuredTool {
8
+ _isMockedLangChainTool: boolean;
9
+}
10
+
11
+// Mock the @langchain/core/tools module
12
+vi.mock('@langchain/core/tools', () => {
13
+ return {
14
+ DynamicStructuredTool: vi.fn().mockImplementation(config => {
15
+ return {
16
+ name: config.name,
17
+ description: config.description,
18
+ schema: config.schema,
19
+ func: config.func,
20
+ _isMockedLangChainTool: true,
21
+ } as MockedLangChainTool;
22
+ }),
23
+ };
24
+});
25
+
26
+// Mock the jsonSchemaToModel function from @composio/core
27
+vi.mock('@composio/core', async () => {
28
+ const actual = await vi.importActual('@composio/core');
29
+ return {
30
+ ...(actual as object),
31
+ jsonSchemaToModel: vi.fn().mockImplementation(schema => {
32
+ return { type: 'mock-schema', originalSchema: schema };
33
+ }),
34
+ };
35
+});
36
+
37
+describe('LangchainToolset', () => {
38
+ let toolset: LangchainToolset;
39
+ let mockTool: Tool;
40
+ let mockExecuteToolFn: any;
41
+
42
+ beforeEach(() => {
43
+ toolset = new LangchainToolset();
44
+
45
+ // Mock the global execute tool function
46
+ mockExecuteToolFn = vi.fn().mockResolvedValue({
47
+ data: { result: 'success' },
48
+ error: null,
49
+ successful: true,
50
+ });
51
+ toolset._setExecuteToolFn(mockExecuteToolFn);
52
+
53
+ // Create a mock Composio tool
54
+ mockTool = {
55
+ slug: 'test-tool',
56
+ name: 'Test Tool',
57
+ description: 'A tool for testing',
58
+ inputParameters: {
59
+ type: 'object',
60
+ properties: {
61
+ input: {
62
+ type: 'string',
63
+ description: 'Test input',
64
+ },
65
+ },
66
+ required: ['input'],
67
+ },
68
+ toolkit: {
69
+ slug: 'test-toolkit',
70
+ name: 'Test Toolkit',
71
+ },
72
+ tags: [],
73
+ };
74
+
75
+ // Reset mocks before each test
76
+ vi.clearAllMocks();
77
+ });
78
+
79
+ describe('name property', () => {
80
+ it('should have the correct name', () => {
81
+ expect(toolset.name).toBe('langchain');
82
+ });
83
+ });
84
+
85
+ describe('_isAgentic property', () => {
86
+ it('should be agentic', () => {
87
+ expect(toolset._isAgentic).toBe(true);
88
+ });
89
+ });
90
+
91
+ describe('wrapTool', () => {
92
+ it('should wrap a tool in LangChain DynamicStructuredTool format', () => {
93
+ const wrapped = toolset.wrapTool(mockTool, mockExecuteToolFn) as MockedLangChainTool;
94
+
95
+ expect(DynamicStructuredTool).toHaveBeenCalledWith({
96
+ name: mockTool.slug,
97
+ description: mockTool.description,
98
+ schema: expect.objectContaining({
99
+ type: 'mock-schema',
100
+ originalSchema: mockTool.inputParameters,
101
+ }),
102
+ func: expect.any(Function),
103
+ });
104
+
105
+ expect(wrapped._isMockedLangChainTool).toBe(true);
106
+ });
107
+
108
+ it('should throw an error if toolkit name is not defined', () => {
109
+ const toolWithoutToolkit: Tool = {
110
+ ...mockTool,
111
+ toolkit: undefined,
112
+ };
113
+
114
+ expect(() => {
115
+ toolset.wrapTool(toolWithoutToolkit, mockExecuteToolFn);
116
+ }).toThrow('App name is not defined');
117
+ });
118
+
119
+ it('should throw an error if inputParameters are not defined', () => {
120
+ const toolWithoutParams: Tool = {
121
+ ...mockTool,
122
+ inputParameters: undefined,
123
+ };
124
+
125
+ expect(() => {
126
+ toolset.wrapTool(toolWithoutParams, mockExecuteToolFn);
127
+ }).toThrow('Tool input parameters are not defined');
128
+ });
129
+
130
+ it('should create a function that executes the tool with the right parameters', async () => {
131
+ const wrapped = toolset.wrapTool(mockTool, mockExecuteToolFn);
132
+
133
+ // Extract the function from the constructor call
134
+ const executeFunction = (DynamicStructuredTool as any).mock.calls[0][0].func;
135
+
136
+ // Test the execute function
137
+ const params = { input: 'test-value' };
138
+ const result = await executeFunction(params);
139
+
140
+ // Check that executeToolFn was called with the right parameters
141
+ expect(mockExecuteToolFn).toHaveBeenCalledWith(mockTool.slug, params);
142
+
143
+ // Check that the result was stringified
144
+ expect(result).toBe(
145
+ JSON.stringify({
146
+ data: { result: 'success' },
147
+ error: null,
148
+ successful: true,
149
+ })
150
+ );
151
+ });
152
+ });
153
+
154
+ describe('wrapTools', () => {
155
+ it('should wrap multiple tools', () => {
156
+ const anotherTool: Tool = {
157
+ ...mockTool,
158
+ slug: 'another-tool',
159
+ name: 'Another Tool',
160
+ };
161
+ const tools = [mockTool, anotherTool];
162
+
163
+ const wrapped = toolset.wrapTools(tools, mockExecuteToolFn);
164
+
165
+ // Verify the result is an array of the right length
166
+ expect(wrapped).toHaveLength(2);
167
+
168
+ // Verify the DynamicStructuredTool constructor was called with the right parameters for each tool
169
+ expect(DynamicStructuredTool).toHaveBeenCalledTimes(2);
170
+ expect(DynamicStructuredTool).toHaveBeenCalledWith(
171
+ expect.objectContaining({
172
+ name: mockTool.slug,
173
+ })
174
+ );
175
+ expect(DynamicStructuredTool).toHaveBeenCalledWith(
176
+ expect.objectContaining({
177
+ name: anotherTool.slug,
178
+ })
179
+ );
180
+ });
181
+
182
+ it('should return an empty array for empty tools array', () => {
183
+ const wrapped = toolset.wrapTools([], mockExecuteToolFn);
184
+ expect(wrapped).toEqual([]);
185
+ expect(DynamicStructuredTool).not.toHaveBeenCalled();
186
+ });
187
+ });
188
+
189
+ describe('executeTool', () => {
190
+ it('should execute a tool using the global execute function', async () => {
191
+ const toolSlug = 'test-tool';
192
+ const toolParams = {
193
+ userId: 'test-user',
194
+ arguments: { input: 'test-value' },
195
+ };
196
+
197
+ const result = await toolset.executeTool(toolSlug, toolParams);
198
+
199
+ expect(mockExecuteToolFn).toHaveBeenCalledWith(toolSlug, toolParams, undefined);
200
+ expect(result).toEqual({
201
+ data: { result: 'success' },
202
+ error: null,
203
+ successful: true,
204
+ });
205
+ });
206
+
207
+ it('should pass modifiers to the global execute function', async () => {
208
+ const toolSlug = 'test-tool';
209
+ const toolParams = {
210
+ userId: 'test-user',
211
+ arguments: { input: 'test-value' },
212
+ };
213
+
214
+ const modifiers = {
215
+ beforeToolExecute: vi.fn(params => params),
216
+ afterToolExecute: vi.fn(response => response),
217
+ };
218
+
219
+ await toolset.executeTool(toolSlug, toolParams, modifiers);
220
+
221
+ expect(mockExecuteToolFn).toHaveBeenCalledWith(toolSlug, toolParams, modifiers);
222
+ });
223
+ });
224
+
225
+ describe('integration with LangChain', () => {
226
+ it('should produce tools compatible with LangChain', () => {
227
+ const wrapped = toolset.wrapTool(mockTool, mockExecuteToolFn) as MockedLangChainTool;
228
+
229
+ // Verify the wrapped tool has the expected structure
230
+ expect(wrapped).toHaveProperty('name');
231
+ expect(wrapped).toHaveProperty('description');
232
+ expect(wrapped).toHaveProperty('schema');
233
+ expect(wrapped).toHaveProperty('func');
234
+
235
+ // The func property should be a function
236
+ expect(typeof wrapped.func).toBe('function');
237
+ });
238
});
239
});
packages/toolsets/openai/test/openai.test.ts
+501
-4
@@ -1,7 +1,504 @@
1
-import { describe, it, expect } from 'vitest';
1
+import { describe, it, expect, vi, beforeEach } from 'vitest';
2
+import { OpenAIToolset } from '../src';
3
+import { Tool } from '@composio/core';
4
+import { OpenAI } from 'openai';
5
3
-describe('Vercel', () => {
4
- it('should be a test', () => {
5
- expect(true).toBe(true);
6
+// Mock the openai modules
7
+vi.mock('openai', () => {
8
+ return {
9
+ OpenAI: vi.fn().mockImplementation(() => ({
10
+ beta: {
11
+ threads: {
12
+ runs: {
13
+ retrieve: vi.fn().mockImplementation((threadId, runId) => {
14
+ return { id: runId, status: 'completed' };
15
+ }),
16
+ submitToolOutputs: vi.fn().mockImplementation((threadId, runId, options) => {
17
+ return { id: runId, status: 'completed' };
18
+ }),
19
+ },
20
+ },
21
+ },
22
+ })),
23
+ };
24
+});
25
+
26
+vi.mock('openai/streaming', () => {
27
+ return {
28
+ Stream: vi.fn(),
29
+ };
30
+});
31
+
32
+// Define interfaces for our OpenAI mocked types
33
+interface MockedOpenAIChatCompletionTool {
34
+ type: 'function';
35
+ function: {
36
+ name: string;
37
+ description?: string;
38
+ parameters?: any;
39
+ };
40
+}
41
+
42
+describe('OpenAIToolset', () => {
43
+ let toolset: OpenAIToolset;
44
+ let mockTool: Tool;
45
+ let mockExecuteToolFn: any;
46
+
47
+ beforeEach(() => {
48
+ toolset = new OpenAIToolset();
49
+
50
+ // Mock the global execute tool function
51
+ mockExecuteToolFn = vi.fn().mockResolvedValue({
52
+ data: { result: 'success' },
53
+ error: null,
54
+ successful: true,
55
+ });
56
+ toolset._setExecuteToolFn(mockExecuteToolFn);
57
+
58
+ // Create a mock Composio tool
59
+ mockTool = {
60
+ slug: 'test-tool',
61
+ name: 'Test Tool',
62
+ description: 'A tool for testing',
63
+ inputParameters: {
64
+ type: 'object',
65
+ properties: {
66
+ input: {
67
+ type: 'string',
68
+ description: 'Test input',
69
+ },
70
+ },
71
+ required: ['input'],
72
+ },
73
+ tags: [],
74
+ };
75
+
76
+ // Reset mocks before each test
77
+ vi.clearAllMocks();
78
+ });
79
+
80
+ describe('name property', () => {
81
+ it('should have the correct name', () => {
82
+ expect(toolset.name).toBe('openai');
83
+ });
84
+ });
85
+
86
+ describe('_isAgentic property', () => {
87
+ it('should be non-agentic', () => {
88
+ expect(toolset._isAgentic).toBe(false);
89
+ });
90
+ });
91
+
92
+ describe('wrapTool', () => {
93
+ it('should wrap a tool in OpenAI function format', () => {
94
+ const wrapped = toolset.wrapTool(mockTool) as MockedOpenAIChatCompletionTool;
95
+
96
+ expect(wrapped).toEqual({
97
+ type: 'function',
98
+ function: {
99
+ name: mockTool.slug,
100
+ description: mockTool.description,
101
+ parameters: mockTool.inputParameters,
102
+ },
103
+ });
104
+ });
105
+
106
+ it('should handle tools without input parameters', () => {
107
+ const toolWithoutParams: Tool = {
108
+ ...mockTool,
109
+ inputParameters: undefined,
110
+ };
111
+
112
+ const wrapped = toolset.wrapTool(toolWithoutParams) as MockedOpenAIChatCompletionTool;
113
+
114
+ expect(wrapped).toEqual({
115
+ type: 'function',
116
+ function: {
117
+ name: toolWithoutParams.slug,
118
+ description: toolWithoutParams.description,
119
+ parameters: undefined,
120
+ },
121
+ });
122
+ });
123
+ });
124
+
125
+ describe('wrapTools', () => {
126
+ it('should wrap multiple tools', () => {
127
+ const anotherTool: Tool = {
128
+ ...mockTool,
129
+ slug: 'another-tool',
130
+ name: 'Another Tool',
131
+ };
132
+ const tools = [mockTool, anotherTool];
133
+
134
+ const wrapped = toolset.wrapTools(tools);
135
+
136
+ // Verify the result is an array of the right length
137
+ expect(wrapped).toHaveLength(2);
138
+
139
+ // Verify each tool was properly wrapped
140
+ expect(wrapped[0]).toEqual({
141
+ type: 'function',
142
+ function: {
143
+ name: mockTool.slug,
144
+ description: mockTool.description,
145
+ parameters: mockTool.inputParameters,
146
+ },
147
+ });
148
+
149
+ expect(wrapped[1]).toEqual({
150
+ type: 'function',
151
+ function: {
152
+ name: anotherTool.slug,
153
+ description: anotherTool.description,
154
+ parameters: anotherTool.inputParameters,
155
+ },
156
+ });
157
+ });
158
+
159
+ it('should return an empty array for empty tools array', () => {
160
+ const wrapped = toolset.wrapTools([]);
161
+ expect(wrapped).toEqual([]);
162
+ });
163
+ });
164
+
165
+ describe('executeToolCall', () => {
166
+ it('should execute a tool call and return the result as string', async () => {
167
+ const userId = 'test-user';
168
+ const toolCall = {
169
+ id: 'call-123',
170
+ type: 'function',
171
+ function: {
172
+ name: 'test-tool',
173
+ arguments: JSON.stringify({ input: 'test-value' }),
174
+ },
175
+ } as OpenAI.ChatCompletionMessageToolCall;
176
+
177
+ const result = await toolset.executeToolCall(userId, toolCall);
178
+
179
+ expect(mockExecuteToolFn).toHaveBeenCalledWith(
180
+ 'test-tool',
181
+ {
182
+ arguments: { input: 'test-value' },
183
+ userId: 'test-user',
184
+ connectedAccountId: undefined,
185
+ customAuthParams: undefined,
186
+ },
187
+ undefined
188
+ );
189
+ expect(result).toBe(
190
+ JSON.stringify({
191
+ data: { result: 'success' },
192
+ error: null,
193
+ successful: true,
194
+ })
195
+ );
196
+ });
197
+
198
+ it('should pass options to executeTool', async () => {
199
+ const userId = 'test-user';
200
+ const toolCall = {
201
+ id: 'call-123',
202
+ type: 'function',
203
+ function: {
204
+ name: 'test-tool',
205
+ arguments: JSON.stringify({ input: 'test-value' }),
206
+ },
207
+ } as OpenAI.ChatCompletionMessageToolCall;
208
+
209
+ const options = {
210
+ connectedAccountId: 'conn-123',
211
+ customAuthParams: {
212
+ parameters: [{ name: 'token', value: 'abc123', in: 'header' as const }],
213
+ },
214
+ };
215
+
216
+ const modifiers = {
217
+ beforeToolExecute: vi.fn(params => params),
218
+ afterToolExecute: vi.fn(response => response),
219
+ };
220
+
221
+ await toolset.executeToolCall(userId, toolCall, options, modifiers);
222
+
223
+ expect(mockExecuteToolFn).toHaveBeenCalledWith(
224
+ 'test-tool',
225
+ {
226
+ arguments: { input: 'test-value' },
227
+ userId: 'test-user',
228
+ connectedAccountId: 'conn-123',
229
+ customAuthParams: options.customAuthParams,
230
+ },
231
+ modifiers
232
+ );
233
+ });
234
+ });
235
+
236
+ describe('handleToolCall', () => {
237
+ it('should handle tool calls from chat completion', async () => {
238
+ const userId = 'test-user';
239
+ const chatCompletion = {
240
+ id: 'chat-123',
241
+ model: 'gpt-4',
242
+ created: 123456789,
243
+ object: 'chat.completion',
244
+ choices: [
245
+ {
246
+ message: {
247
+ role: 'assistant',
248
+ content: null,
249
+ tool_calls: [
250
+ {
251
+ id: 'call-123',
252
+ type: 'function',
253
+ function: {
254
+ name: 'test-tool',
255
+ arguments: JSON.stringify({ input: 'test-value' }),
256
+ },
257
+ } as const,
258
+ ],
259
+ },
260
+ index: 0,
261
+ finish_reason: 'tool_calls' as const,
262
+ },
263
+ ],
264
+ usage: {
265
+ prompt_tokens: 10,
266
+ completion_tokens: 20,
267
+ total_tokens: 30,
268
+ },
269
+ } as OpenAI.ChatCompletion;
270
+
271
+ const executeToolCallSpy = vi.spyOn(toolset, 'executeToolCall');
272
+ executeToolCallSpy.mockResolvedValue(JSON.stringify({ result: 'success' }));
273
+
274
+ const results = await toolset.handleToolCall(userId, chatCompletion);
275
+
276
+ expect(executeToolCallSpy).toHaveBeenCalledWith(
277
+ userId,
278
+ chatCompletion.choices[0].message.tool_calls![0],
279
+ undefined,
280
+ undefined
281
+ );
282
+ expect(results).toEqual([JSON.stringify({ result: 'success' })]);
283
+ });
284
+
285
+ it('should handle multiple tool calls', async () => {
286
+ const userId = 'test-user';
287
+ const chatCompletion = {
288
+ id: 'chat-123',
289
+ model: 'gpt-4',
290
+ created: 123456789,
291
+ object: 'chat.completion',
292
+ choices: [
293
+ {
294
+ message: {
295
+ role: 'assistant',
296
+ content: null,
297
+ tool_calls: [
298
+ {
299
+ id: 'call-123',
300
+ type: 'function',
301
+ function: {
302
+ name: 'test-tool',
303
+ arguments: JSON.stringify({ input: 'test-value-1' }),
304
+ },
305
+ } as const,
306
+ ],
307
+ },
308
+ index: 0,
309
+ finish_reason: 'tool_calls' as const,
310
+ },
311
+ {
312
+ message: {
313
+ role: 'assistant',
314
+ content: null,
315
+ tool_calls: [
316
+ {
317
+ id: 'call-456',
318
+ type: 'function',
319
+ function: {
320
+ name: 'another-tool',
321
+ arguments: JSON.stringify({ input: 'test-value-2' }),
322
+ },
323
+ } as const,
324
+ ],
325
+ },
326
+ index: 1,
327
+ finish_reason: 'tool_calls' as const,
328
+ },
329
+ ],
330
+ usage: {
331
+ prompt_tokens: 10,
332
+ completion_tokens: 20,
333
+ total_tokens: 30,
334
+ },
335
+ } as OpenAI.ChatCompletion;
336
+
337
+ const executeToolCallSpy = vi.spyOn(toolset, 'executeToolCall');
338
+ executeToolCallSpy
339
+ .mockResolvedValueOnce(JSON.stringify({ result: 'success-1' }))
340
+ .mockResolvedValueOnce(JSON.stringify({ result: 'success-2' }));
341
+
342
+ const results = await toolset.handleToolCall(userId, chatCompletion);
343
+
344
+ expect(executeToolCallSpy).toHaveBeenCalledTimes(2);
345
+ expect(executeToolCallSpy).toHaveBeenNthCalledWith(
346
+ 1,
347
+ userId,
348
+ chatCompletion.choices[0].message.tool_calls![0],
349
+ undefined,
350
+ undefined
351
+ );
352
+ expect(executeToolCallSpy).toHaveBeenNthCalledWith(
353
+ 2,
354
+ userId,
355
+ chatCompletion.choices[1].message.tool_calls![0],
356
+ undefined,
357
+ undefined
358
+ );
359
+ expect(results).toEqual([
360
+ JSON.stringify({ result: 'success-1' }),
361
+ JSON.stringify({ result: 'success-2' }),
362
+ ]);
363
+ });
364
+ });
365
+
366
+ describe('handleAssistantMessage', () => {
367
+ it('should process tool calls from an assistant run', async () => {
368
+ const userId = 'test-user';
369
+ const run = {
370
+ id: 'run-123',
371
+ required_action: {
372
+ submit_tool_outputs: {
373
+ tool_calls: [
374
+ {
375
+ id: 'tool-call-123',
376
+ type: 'function',
377
+ function: {
378
+ name: 'test-tool',
379
+ arguments: JSON.stringify({ input: 'test-value' }),
380
+ },
381
+ },
382
+ ],
383
+ },
384
+ },
385
+ } as unknown as OpenAI.Beta.Threads.Run;
386
+
387
+ const executeToolCallSpy = vi.spyOn(toolset, 'executeToolCall');
388
+ executeToolCallSpy.mockResolvedValue(JSON.stringify({ result: 'success' }));
389
+
390
+ const toolOutputs = await toolset.handleAssistantMessage(userId, run);
391
+
392
+ expect(executeToolCallSpy).toHaveBeenCalledWith(
393
+ userId,
394
+ run.required_action?.submit_tool_outputs
395
+ ?.tool_calls[0] as OpenAI.ChatCompletionMessageToolCall,
396
+ undefined,
397
+ undefined
398
+ );
399
+ expect(toolOutputs).toEqual([
400
+ {
401
+ tool_call_id: 'tool-call-123',
402
+ output: JSON.stringify(JSON.stringify({ result: 'success' })),
403
+ },
404
+ ]);
405
+ });
406
+
407
+ it('should handle runs without tool calls', async () => {
408
+ const userId = 'test-user';
409
+ const run = {
410
+ id: 'run-123',
411
+ } as OpenAI.Beta.Threads.Run;
412
+
413
+ const executeToolCallSpy = vi.spyOn(toolset, 'executeToolCall');
414
+
415
+ const toolOutputs = await toolset.handleAssistantMessage(userId, run);
416
+
417
+ expect(executeToolCallSpy).not.toHaveBeenCalled();
418
+ expect(toolOutputs).toEqual([]);
419
+ });
420
+ });
421
+
422
+ describe('executeTool', () => {
423
+ it('should execute a tool using the global execute function', async () => {
424
+ const toolSlug = 'test-tool';
425
+ const toolParams = {
426
+ userId: 'test-user',
427
+ arguments: { input: 'test-value' },
428
+ };
429
+
430
+ const result = await toolset.executeTool(toolSlug, toolParams);
431
+
432
+ expect(mockExecuteToolFn).toHaveBeenCalledWith(toolSlug, toolParams, undefined);
433
+ expect(result).toEqual({
434
+ data: { result: 'success' },
435
+ error: null,
436
+ successful: true,
437
+ });
438
+ });
439
+
440
+ it('should pass modifiers to the global execute function', async () => {
441
+ const toolSlug = 'test-tool';
442
+ const toolParams = {
443
+ userId: 'test-user',
444
+ arguments: { input: 'test-value' },
445
+ };
446
+
447
+ const modifiers = {
448
+ beforeToolExecute: vi.fn(params => params),
449
+ afterToolExecute: vi.fn(response => response),
450
+ };
451
+
452
+ await toolset.executeTool(toolSlug, toolParams, modifiers);
453
+
454
+ expect(mockExecuteToolFn).toHaveBeenCalledWith(toolSlug, toolParams, modifiers);
455
+ });
456
+ });
457
+
458
+ describe('waitAndHandleAssistantToolCalls', () => {
459
+ it('should handle and submit tool outputs for an assistant run', async () => {
460
+ const userId = 'test-user';
461
+ const client = new OpenAI();
462
+ const thread = { id: 'thread-123' } as OpenAI.Beta.Threads.Thread;
463
+ const run = {
464
+ id: 'run-123',
465
+ status: 'requires_action',
466
+ required_action: {
467
+ submit_tool_outputs: {
468
+ tool_calls: [
469
+ {
470
+ id: 'tool-call-123',
471
+ type: 'function',
472
+ function: {
473
+ name: 'test-tool',
474
+ arguments: JSON.stringify({ input: 'test-value' }),
475
+ },
476
+ },
477
+ ],
478
+ },
479
+ },
480
+ } as OpenAI.Beta.Threads.Run;
481
+
482
+ const handleAssistantMessageSpy = vi.spyOn(toolset, 'handleAssistantMessage');
483
+ handleAssistantMessageSpy.mockResolvedValue([
484
+ {
485
+ tool_call_id: 'tool-call-123',
486
+ output: JSON.stringify({ result: 'success' }),
487
+ },
488
+ ]);
489
+
490
+ const result = await toolset.waitAndHandleAssistantToolCalls(userId, client, run, thread);
491
+
492
+ expect(handleAssistantMessageSpy).toHaveBeenCalledWith(userId, run, undefined, undefined);
493
+ expect(client.beta.threads.runs.submitToolOutputs).toHaveBeenCalledWith(thread.id, run.id, {
494
+ tool_outputs: [
495
+ {
496
+ tool_call_id: 'tool-call-123',
497
+ output: JSON.stringify({ result: 'success' }),
498
+ },
499
+ ],
500
+ });
501
+ expect(result).toEqual({ id: 'run-123', status: 'completed' });
502
+ });
503
});
504
});