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

Add tests

haxzie committed May 19, 2025 at 16:42 UTC 70ca6bfb7af9bb94b266994fd84ec7bb9a4e65e1
17 files changed +1431 -247
packages/core/src/errors/ConnectionRequestError.ts
+12
@@ -2,6 +2,7 @@ import { ComposioError } from './ComposioError';
2
3 export const ConnectionRequestErrorCodes = {
4 CONNECTION_REQUEST_TIMEOUT: 'CONNECTION_REQUEST_TIMEOUT',
5 + CONNECTION_REQUEST_FAILED: 'CONNECTION_REQUEST_FAILED',
6 } as const;
7
8 export class ConnectionRequestTimeoutError extends ComposioError {
@@ -13,5 +14,16 @@ export class ConnectionRequestTimeoutError extends ComposioError {
14 code: ConnectionRequestErrorCodes.CONNECTION_REQUEST_TIMEOUT,
15 meta,
16 });
17 + this.name = 'ConnectionRequestTimeoutError';
18 + }
19 +}
20 +
21 +export class ConnectionRequestFailedError extends ComposioError {
22 + constructor(message: string = 'Connection request failed', meta: Record<string, unknown> = {}) {
23 + super(message, {
24 + code: ConnectionRequestErrorCodes.CONNECTION_REQUEST_FAILED,
25 + meta,
26 + });
27 + this.name = 'ConnectionRequestFailedError';
28 }
29 }
packages/core/src/errors/ToolErrors.ts
+15
@@ -7,6 +7,7 @@ export const ToolErrorCodes = {
7 CUSTOM_TOOLS_NOT_INITIALIZED: 'CUSTOM_TOOLS_NOT_INITIALIZED',
8 TOOL_EXECUTION_ERROR: 'TOOL_EXECUTION_ERROR',
9 INVALID_EXECUTE_FUNCTION: 'INVALID_EXECUTE_FUNCTION',
10 + GLOBAL_EXECUTE_TOOL_FN_NOT_SET: 'GLOBAL_EXECUTE_TOOL_FN_NOT_SET',
11 } as const;
12
13 export class ComposioToolsetNotDefinedError extends ComposioError {
@@ -87,3 +88,17 @@ export class ComposioInvalidExecuteFunctionError extends ComposioError {
88 this.name = 'ComposioInvalidExecuteFunctionError';
89 }
90 }
91 +
92 +export class ComposioGlobalExecuteToolFnNotSetError extends ComposioError {
93 + constructor(
94 + message: string = 'Global execute tool function not set',
95 + meta: Record<string, unknown> = {}
96 + ) {
97 + super(message, {
98 + code: ToolErrorCodes.GLOBAL_EXECUTE_TOOL_FN_NOT_SET,
99 + meta,
100 + possibleFixes: ['Ensure the global execute tool function is set in the toolset'],
101 + });
102 + this.name = 'ComposioGlobalExecuteToolFnNotSetError';
103 + }
104 +}
packages/core/src/models/ConnectionRequest.ts
+41 -23
@@ -15,7 +15,10 @@ import {
15 import { ConnectedAccountRetrieveResponse as OriginalConnectedAccountResponse } from '@composio/client/resources/connected-accounts';
16 import { ZodError } from 'zod';
17 import logger from '../utils/logger';
18 -import { ConnectionRequestTimeoutError } from '../errors/ConnectionRequestError';
18 +import {
19 + ConnectionRequestFailedError,
20 + ConnectionRequestTimeoutError,
21 +} from '../errors/ConnectionRequestError';
22 export class ConnectionRequest {
23 private client: ComposioClient;
24 private connectedAccountId: string;
@@ -77,31 +80,46 @@ export class ConnectionRequest {
80 async waitForConnection(timeout: number = 60000): Promise<ConnectedAccountRetrieveResponse> {
81 if (this.connectedAccountStatus === ConnectedAccountStatuses.ACTIVE) {
82 const response = await this.client.connectedAccounts.retrieve(this.connectedAccountId);
80 - return Promise.resolve(this.transformResponse(response));
83 + return this.transformResponse(response);
84 }
85
83 - return new Promise((resolve, reject) => {
84 - const interval = setInterval(async () => {
85 - try {
86 - const response = await this.client.connectedAccounts.retrieve(this.connectedAccountId);
87 - if (response.status === ConnectedAccountStatuses.ACTIVE) {
88 - clearInterval(interval);
89 - resolve(this.transformResponse(response));
90 - }
91 - } catch (error) {
92 - clearInterval(interval);
93 - reject(error);
86 + const terminalErrorStates: ConnectedAccountStatus[] = [
87 + ConnectedAccountStatuses.FAILED,
88 + ConnectedAccountStatuses.EXPIRED,
89 + ConnectedAccountStatuses.DELETED,
90 + ];
91 +
92 + const start = Date.now();
93 + const pollInterval = 1000;
94 +
95 + while (Date.now() - start < timeout) {
96 + try {
97 + const response = await this.client.connectedAccounts.retrieve(this.connectedAccountId);
98 +
99 + if (response.status === ConnectedAccountStatuses.ACTIVE) {
100 + return this.transformResponse(response);
101 }
95 - }, 1000);
102
97 - setTimeout(() => {
98 - clearInterval(interval);
99 - reject(
100 - new ConnectionRequestTimeoutError(
101 - `Connection request timed out for ${this.connectedAccountId}`
102 - )
103 - );
104 - }, timeout);
105 - });
103 + if (terminalErrorStates.includes(response.status)) {
104 + throw new ConnectionRequestFailedError(
105 + `Connection request failed with status: ${response.status}${response.status_reason ? `, reason: ${response.status_reason}` : ''}`,
106 + {
107 + userId: response.user_id,
108 + connectedAccountId: this.connectedAccountId,
109 + status: response.status,
110 + statusReason: response.status_reason,
111 + }
112 + );
113 + }
114 +
115 + await new Promise(resolve => setTimeout(resolve, pollInterval));
116 + } catch (error) {
117 + throw error;
118 + }
119 + }
120 +
121 + throw new ConnectionRequestTimeoutError(
122 + `Connection request timed out for ${this.connectedAccountId}`
123 + );
124 }
125 }
packages/core/src/toolset/BaseToolset.ts
+5 -1
@@ -1,3 +1,4 @@
1 +import { ComposioGlobalExecuteToolFnNotSetError } from '../errors/ToolErrors';
2 import { ExecuteToolModifiers } from '../types/modifiers.types';
3 import type { Tool, ToolExecuteParams, ToolExecuteResponse } from '../types/tool.types';
4 import { ExecuteToolFn, GlobalExecuteToolFn } from '../types/toolset.types';
@@ -29,7 +30,7 @@ abstract class BaseToolset {
30 /**
31 * @internal
32 * Set the function to execute a tool.
32 - * This is set automatically injected by the core SDK.
33 + * This is set automatically and injected by the core SDK.
34 */
35 _setExecuteToolFn(executeToolFn: GlobalExecuteToolFn): void {
36 this._globalExecuteToolFn = executeToolFn;
@@ -49,6 +50,9 @@ abstract class BaseToolset {
50 body: ToolExecuteParams,
51 modifers?: ExecuteToolModifiers
52 ): Promise<ToolExecuteResponse> {
53 + if (!this._globalExecuteToolFn) {
54 + throw new ComposioGlobalExecuteToolFnNotSetError('executeToolFn is not set');
55 + }
56 return this._globalExecuteToolFn(toolSlug, body, modifers);
57 }
58 }
packages/core/src/toolset/ToolsRegistry.ts deleted
-50
@@ -1,50 +0,0 @@
1 -import { Tool, ToolSchema } from '../types/tool.types';
2 -
3 -/**
4 - * TOOLS REGISTRY
5 - *
6 - * This singlton class is used to register user provided tools in the toolset.
7 - *
8 - *
9 - */
10 -export class ToolsRegistry {
11 - private tools: Map<string, Tool> = new Map<string, Tool>();
12 -
13 - constructor() {}
14 -
15 - /**
16 - * Create a tool in the registry.
17 - * @param {Tool} tool - The tool to create.
18 - * @returns {Tool} The created tool.
19 - */
20 - createTool(tool: Tool): Tool {
21 - try {
22 - const parsedTool = ToolSchema.parse(tool);
23 - const lowerCaseSlug = parsedTool.slug.toLowerCase();
24 - this.tools.set(lowerCaseSlug, parsedTool);
25 - return parsedTool;
26 - } catch (error) {
27 - throw new Error(`Failed to create tool ${tool.slug}: ${error}`);
28 - }
29 - }
30 -
31 - /**
32 - * Get a tool from the registry.
33 - * @param {string} slug - The slug of the tool.
34 - * @returns {Tool | undefined} The tool.
35 - */
36 - getToolBySlug(slug: string): Tool | undefined {
37 - const lowerCaseSlug = slug.toLowerCase();
38 - return this.tools.get(lowerCaseSlug);
39 - }
40 -
41 - /**
42 - * Get all the tools from the registry.
43 - * @returns {Tool[]} The tools.
44 - */
45 - getTools(): Tool[] {
46 - return Array.from(this.tools.values());
47 - }
48 -}
49 -
50 -export const toolsRegistry = new ToolsRegistry();
packages/core/src/types/connectedAccounts.types.ts
+2 -2
@@ -6,7 +6,7 @@ import { z } from 'zod';
6 export const ConnectedAccountStatuses = {
7 ACTIVE: 'ACTIVE',
8 INACTIVE: 'INACTIVE',
9 - PENDING: 'DELETED',
9 + DELETED: 'DELETED',
10 INITIATED: 'INITIATED',
11 EXPIRED: 'EXPIRED',
12 FAILED: 'FAILED',
@@ -14,7 +14,7 @@ export const ConnectedAccountStatuses = {
14 export const ConnectedAccountStatusSchema = z.enum([
15 ConnectedAccountStatuses.ACTIVE,
16 ConnectedAccountStatuses.INACTIVE,
17 - ConnectedAccountStatuses.PENDING,
17 + ConnectedAccountStatuses.DELETED,
18 ConnectedAccountStatuses.INITIATED,
19 ConnectedAccountStatuses.EXPIRED,
20 ConnectedAccountStatuses.FAILED,
packages/core/test/connectedAccounts/connectedAccounts.test.ts new
+250
@@ -0,0 +1,250 @@
1 +import { describe, it, expect, vi, beforeEach } from 'vitest';
2 +import { mockClient } from '../utils/mocks/client.mock';
3 +import { ConnectedAccounts } from '../../src/models/ConnectedAccounts';
4 +import ComposioClient from '@composio/client';
5 +import { ConnectionRequest } from '../../src/models/ConnectionRequest';
6 +import { ConnectedAccountRetrieveResponse } from '@composio/client/resources/connected-accounts.mjs';
7 +
8 +// Extend the mock client object for ConnectedAccounts testing
9 +const extendedMockClient = {
10 + ...mockClient,
11 + connectedAccounts: {
12 + ...mockClient.connectedAccounts,
13 + create: vi.fn(),
14 + retrieve: vi.fn(),
15 + delete: vi.fn(),
16 + refresh: vi.fn(),
17 + updateStatus: vi.fn(),
18 + },
19 +};
20 +
21 +describe('ConnectedAccounts', () => {
22 + let connectedAccounts: ConnectedAccounts;
23 +
24 + beforeEach(() => {
25 + vi.clearAllMocks();
26 + connectedAccounts = new ConnectedAccounts(extendedMockClient as unknown as ComposioClient);
27 + });
28 +
29 + describe('constructor', () => {
30 + it('should create an instance successfully with valid client', () => {
31 + expect(connectedAccounts).toBeInstanceOf(ConnectedAccounts);
32 + });
33 +
34 + it('should not throw an error if client is provided', () => {
35 + expect(
36 + () => new ConnectedAccounts(extendedMockClient as unknown as ComposioClient)
37 + ).not.toThrow();
38 + });
39 + });
40 +
41 + describe('list', () => {
42 + it('should call client.connectedAccounts.list with the provided query', async () => {
43 + const query = { limit: 10 };
44 + const mockResponse = { items: [], totalPages: 0 };
45 +
46 + extendedMockClient.connectedAccounts.list.mockResolvedValueOnce(mockResponse);
47 +
48 + const result = await connectedAccounts.list(query);
49 +
50 + expect(extendedMockClient.connectedAccounts.list).toHaveBeenCalledWith(query);
51 + expect(result).toEqual(mockResponse);
52 + });
53 +
54 + it('should call client.connectedAccounts.list without query if none provided', async () => {
55 + const mockResponse = { items: [], totalPages: 0 };
56 +
57 + extendedMockClient.connectedAccounts.list.mockResolvedValueOnce(mockResponse);
58 +
59 + const result = await connectedAccounts.list();
60 +
61 + expect(extendedMockClient.connectedAccounts.list).toHaveBeenCalledWith(undefined);
62 + expect(result).toEqual(mockResponse);
63 + });
64 + });
65 +
66 + describe('initiate', () => {
67 + it('should create a new connected account and return a ConnectionRequest and wait for it to be active', async () => {
68 + const userId = 'user_123';
69 + const authConfigId = 'auth_config_123';
70 + const options = {
71 + data: { name: 'Test Account' },
72 + redirectUrl: 'https://example.com/callback',
73 + };
74 +
75 + const mockResponse = {
76 + id: 'conn_123',
77 + status: 'pending',
78 + redirect_uri: 'https://auth.example.com/connect',
79 + };
80 +
81 + extendedMockClient.connectedAccounts.create.mockResolvedValueOnce(mockResponse);
82 +
83 + const connectionRequest = await connectedAccounts.initiate(userId, authConfigId, options);
84 +
85 + expect(extendedMockClient.connectedAccounts.create).toHaveBeenCalledWith({
86 + auth_config: {
87 + id: authConfigId,
88 + },
89 + connection: {
90 + data: options.data,
91 + redirect_uri: options.redirectUrl,
92 + user_id: userId,
93 + },
94 + });
95 +
96 + expect(connectionRequest).toBeInstanceOf(ConnectionRequest);
97 + expect(connectionRequest).toHaveProperty('connectedAccountId', mockResponse.id);
98 + expect(connectionRequest).toHaveProperty('connectedAccountStatus', mockResponse.status);
99 + expect(connectionRequest).toHaveProperty('redirectUrl', mockResponse.redirect_uri);
100 +
101 + extendedMockClient.connectedAccounts.retrieve.mockResolvedValueOnce({
102 + id: 'nanoid',
103 + status: 'ACTIVE',
104 + auth_scopes: ['read:user', 'write:user'],
105 + auth_config: {
106 + id: authConfigId,
107 + auth_scheme: 'OAUTH2',
108 + is_composio_managed: true,
109 + is_disabled: false,
110 + },
111 + user_id: userId,
112 + data: {},
113 + params: {},
114 + is_disabled: false,
115 + created_at: '2023-01-01T00:00:00Z',
116 + updated_at: '2023-01-01T00:00:00Z',
117 + status_reason: null,
118 + toolkit: {
119 + slug: 'test-toolkit',
120 + },
121 + } as unknown as ConnectedAccountRetrieveResponse);
122 +
123 + const connectedAccount = await connectionRequest.waitForConnection();
124 +
125 + expect(extendedMockClient.connectedAccounts.retrieve).toHaveBeenCalledWith(mockResponse.id);
126 + expect(connectedAccount).toHaveProperty('id', 'nanoid');
127 + expect(connectedAccount).toHaveProperty('status', 'ACTIVE');
128 + });
129 +
130 + it('should work without optional parameters', async () => {
131 + const userId = 'user_123';
132 + const authConfigId = 'auth_config_123';
133 +
134 + const mockResponse = {
135 + id: 'conn_123',
136 + status: 'pending',
137 + redirect_uri: 'https://auth.example.com/connect',
138 + };
139 +
140 + extendedMockClient.connectedAccounts.create.mockResolvedValueOnce(mockResponse);
141 +
142 + const result = await connectedAccounts.initiate(userId, authConfigId);
143 +
144 + expect(extendedMockClient.connectedAccounts.create).toHaveBeenCalledWith({
145 + auth_config: {
146 + id: authConfigId,
147 + },
148 + connection: {
149 + data: undefined,
150 + redirect_uri: undefined,
151 + user_id: userId,
152 + },
153 + });
154 +
155 + expect(result).toBeInstanceOf(ConnectionRequest);
156 + });
157 + });
158 +
159 + describe('get', () => {
160 + it('should retrieve a connected account by nanoid', async () => {
161 + const nanoid = 'conn_123';
162 + const mockResponse = { id: nanoid, name: 'Test Account' };
163 +
164 + extendedMockClient.connectedAccounts.retrieve.mockResolvedValueOnce(mockResponse);
165 +
166 + const result = await connectedAccounts.get(nanoid);
167 +
168 + expect(extendedMockClient.connectedAccounts.retrieve).toHaveBeenCalledWith(nanoid);
169 + expect(result).toEqual(mockResponse);
170 + });
171 + });
172 +
173 + describe('delete', () => {
174 + it('should delete a connected account by nanoid', async () => {
175 + const nanoid = 'conn_123';
176 + const mockResponse = { success: true };
177 +
178 + extendedMockClient.connectedAccounts.delete.mockResolvedValueOnce(mockResponse);
179 +
180 + const result = await connectedAccounts.delete(nanoid);
181 +
182 + expect(extendedMockClient.connectedAccounts.delete).toHaveBeenCalledWith(nanoid);
183 + expect(result).toEqual(mockResponse);
184 + });
185 + });
186 +
187 + describe('refresh', () => {
188 + it('should refresh a connected account by nanoid', async () => {
189 + const nanoid = 'conn_123';
190 + const mockResponse = { id: nanoid, refreshed: true };
191 +
192 + extendedMockClient.connectedAccounts.refresh.mockResolvedValueOnce(mockResponse);
193 +
194 + const result = await connectedAccounts.refresh(nanoid);
195 +
196 + expect(extendedMockClient.connectedAccounts.refresh).toHaveBeenCalledWith(nanoid);
197 + expect(result).toEqual(mockResponse);
198 + });
199 + });
200 +
201 + describe('updateStatus', () => {
202 + it('should update the status of a connected account', async () => {
203 + const nanoid = 'conn_123';
204 + const params = { enabled: true };
205 + const mockResponse = { id: nanoid, enabled: true };
206 +
207 + extendedMockClient.connectedAccounts.updateStatus.mockResolvedValueOnce(mockResponse);
208 +
209 + const result = await connectedAccounts.updateStatus(nanoid, params);
210 +
211 + expect(extendedMockClient.connectedAccounts.updateStatus).toHaveBeenCalledWith(
212 + nanoid,
213 + params
214 + );
215 + expect(result).toEqual(mockResponse);
216 + });
217 + });
218 +
219 + describe('enable', () => {
220 + it('should enable a connected account', async () => {
221 + const nanoid = 'conn_123';
222 + const mockResponse = { id: nanoid, enabled: true };
223 +
224 + extendedMockClient.connectedAccounts.updateStatus.mockResolvedValueOnce(mockResponse);
225 +
226 + const result = await connectedAccounts.enable(nanoid);
227 +
228 + expect(extendedMockClient.connectedAccounts.updateStatus).toHaveBeenCalledWith(nanoid, {
229 + enabled: true,
230 + });
231 + expect(result).toEqual(mockResponse);
232 + });
233 + });
234 +
235 + describe('disable', () => {
236 + it('should disable a connected account', async () => {
237 + const nanoid = 'conn_123';
238 + const mockResponse = { id: nanoid, enabled: false };
239 +
240 + extendedMockClient.connectedAccounts.updateStatus.mockResolvedValueOnce(mockResponse);
241 +
242 + const result = await connectedAccounts.disable(nanoid);
243 +
244 + expect(extendedMockClient.connectedAccounts.updateStatus).toHaveBeenCalledWith(nanoid, {
245 + enabled: false,
246 + });
247 + expect(result).toEqual(mockResponse);
248 + });
249 + });
250 +});
packages/core/test/connectedAccounts/connectionRequest.test.ts new
+239
@@ -0,0 +1,239 @@
1 +import { describe, it, expect, vi, beforeEach } from 'vitest';
2 +import { ConnectionRequest } from '../../src/models/ConnectionRequest';
3 +import ComposioClient, { ComposioError } from '@composio/client';
4 +import { ConnectionRequestTimeoutError } from '../../src/errors/ConnectionRequestError';
5 +import { ConnectedAccountStatuses } from '../../src/types/connectedAccounts.types';
6 +
7 +// Mock ComposioClient
8 +const mockClient = {
9 + connectedAccounts: {
10 + retrieve: vi.fn(),
11 + },
12 +};
13 +
14 +describe('ConnectionRequest', () => {
15 + let connectionRequest: ConnectionRequest;
16 + const connectedAccountId = 'conn_123';
17 + const redirectUrl = 'https://example.com/callback';
18 +
19 + beforeEach(() => {
20 + vi.clearAllMocks();
21 + // Reset timers before each test
22 + vi.useRealTimers();
23 + });
24 +
25 + describe('constructor', () => {
26 + it('should create an instance with an ACTIVE status', () => {
27 + connectionRequest = new ConnectionRequest(
28 + mockClient as unknown as ComposioClient,
29 + connectedAccountId,
30 + ConnectedAccountStatuses.ACTIVE,
31 + redirectUrl
32 + );
33 +
34 + expect(connectionRequest).toBeInstanceOf(ConnectionRequest);
35 + expect(connectionRequest).toHaveProperty('connectedAccountId', connectedAccountId);
36 + expect(connectionRequest).toHaveProperty(
37 + 'connectedAccountStatus',
38 + ConnectedAccountStatuses.ACTIVE
39 + );
40 + expect(connectionRequest).toHaveProperty('redirectUrl', redirectUrl);
41 + });
42 +
43 + it('should create an instance with a INITIATED status', () => {
44 + connectionRequest = new ConnectionRequest(
45 + mockClient as unknown as ComposioClient,
46 + connectedAccountId,
47 + ConnectedAccountStatuses.INITIATED,
48 + redirectUrl
49 + );
50 +
51 + expect(connectionRequest).toBeInstanceOf(ConnectionRequest);
52 + expect(connectionRequest).toHaveProperty(
53 + 'connectedAccountStatus',
54 + ConnectedAccountStatuses.INITIATED
55 + );
56 + });
57 +
58 + it('should create an instance without a redirectUrl', () => {
59 + connectionRequest = new ConnectionRequest(
60 + mockClient as unknown as ComposioClient,
61 + connectedAccountId,
62 + ConnectedAccountStatuses.ACTIVE
63 + );
64 +
65 + expect(connectionRequest).toBeInstanceOf(ConnectionRequest);
66 + expect(connectionRequest).toHaveProperty('redirectUrl', undefined);
67 + });
68 + });
69 +
70 + describe('waitForConnection', () => {
71 + it('should immediately resolve if status is already ACTIVE', async () => {
72 + // Create the connection request with ACTIVE status
73 + connectionRequest = new ConnectionRequest(
74 + mockClient as unknown as ComposioClient,
75 + connectedAccountId,
76 + ConnectedAccountStatuses.ACTIVE,
77 + redirectUrl
78 + );
79 +
80 + // Mock the retrieve response
81 + const mockResponse = {
82 + id: connectedAccountId,
83 + status: ConnectedAccountStatuses.ACTIVE,
84 + auth_config: {
85 + id: 'auth_config_123',
86 + auth_scheme: 'OAUTH2',
87 + is_composio_managed: true,
88 + is_disabled: false,
89 + },
90 + user_id: 'user_123',
91 + data: {},
92 + params: {},
93 + is_disabled: false,
94 + created_at: '2023-01-01T00:00:00Z',
95 + updated_at: '2023-01-01T00:00:00Z',
96 + status_reason: null,
97 + toolkit: {
98 + slug: 'test-toolkit',
99 + },
100 + };
101 +
102 + mockClient.connectedAccounts.retrieve.mockResolvedValueOnce(mockResponse);
103 +
104 + const result = await connectionRequest.waitForConnection();
105 +
106 + expect(mockClient.connectedAccounts.retrieve).toHaveBeenCalledWith(connectedAccountId);
107 + expect(mockClient.connectedAccounts.retrieve).toHaveBeenCalledTimes(1);
108 + expect(result).toHaveProperty('id', connectedAccountId);
109 + expect(result).toHaveProperty('status', ConnectedAccountStatuses.ACTIVE);
110 + expect(result).toHaveProperty('authConfig.authScheme', 'OAUTH2');
111 + });
112 +
113 + it('should poll until status becomes ACTIVE', async () => {
114 + // Use fake timers to control timing
115 + vi.useFakeTimers();
116 +
117 + // Create the connection request with INITIATED status
118 + connectionRequest = new ConnectionRequest(
119 + mockClient as unknown as ComposioClient,
120 + connectedAccountId,
121 + ConnectedAccountStatuses.INITIATED,
122 + redirectUrl
123 + );
124 +
125 + // Mock initial "initiated" response
126 + const pendingResponse = {
127 + id: connectedAccountId,
128 + status: ConnectedAccountStatuses.INITIATED,
129 + auth_config: {
130 + id: 'auth_config_123',
131 + auth_scheme: 'OAUTH2',
132 + is_composio_managed: true,
133 + is_disabled: false,
134 + },
135 + user_id: 'user_123',
136 + data: {},
137 + params: {},
138 + is_disabled: false,
139 + created_at: '2023-01-01T00:00:00Z',
140 + updated_at: '2023-01-01T00:00:00Z',
141 + status_reason: null,
142 + toolkit: {
143 + slug: 'test-toolkit',
144 + },
145 + };
146 +
147 + // Mock "active" response for the second call
148 + const activeResponse = {
149 + ...pendingResponse,
150 + status: ConnectedAccountStatuses.ACTIVE,
151 + };
152 +
153 + mockClient.connectedAccounts.retrieve
154 + .mockResolvedValueOnce(pendingResponse)
155 + .mockResolvedValueOnce(activeResponse);
156 +
157 + // Start the waitForConnection call but don't await it yet
158 + const connectionPromise = connectionRequest.waitForConnection();
159 +
160 + // Advance timer by 1 second (first poll)
161 + await vi.advanceTimersByTimeAsync(1000);
162 +
163 + // Advance timer by 1 more second (second poll)
164 + await vi.advanceTimersByTimeAsync(1000);
165 +
166 + // Resolve the promise
167 + const result = await connectionPromise;
168 +
169 + expect(mockClient.connectedAccounts.retrieve).toHaveBeenCalledWith(connectedAccountId);
170 + expect(mockClient.connectedAccounts.retrieve).toHaveBeenCalledTimes(2);
171 + expect(result).toHaveProperty('id', connectedAccountId);
172 + expect(result).toHaveProperty('status', ConnectedAccountStatuses.ACTIVE);
173 + });
174 +
175 + it('should throw ConnectionRequestTimeoutError if the request times out', async () => {
176 + // Create connection request with INITIATED status
177 + connectionRequest = new ConnectionRequest(
178 + mockClient as unknown as ComposioClient,
179 + connectedAccountId,
180 + ConnectedAccountStatuses.INITIATED,
181 + redirectUrl
182 + );
183 +
184 + // Mock initiated response that never changes to active
185 + const initiatedResponse = {
186 + id: connectedAccountId,
187 + status: ConnectedAccountStatuses.INITIATED,
188 + auth_config: {
189 + id: 'auth_config_123',
190 + auth_scheme: 'OAUTH2',
191 + is_composio_managed: true,
192 + is_disabled: false,
193 + },
194 + user_id: 'user_123',
195 + data: {},
196 + params: {},
197 + is_disabled: false,
198 + created_at: '2023-01-01T00:00:00Z',
199 + updated_at: '2023-01-01T00:00:00Z',
200 + status_reason: null,
201 + toolkit: {
202 + slug: 'test-toolkit',
203 + },
204 + };
205 +
206 + mockClient.connectedAccounts.retrieve.mockResolvedValue(initiatedResponse);
207 +
208 + // Start the waitForConnection call with a short timeout
209 + try {
210 + await connectionRequest.waitForConnection(3000);
211 + } catch (error) {
212 + expect(error).toBeInstanceOf(ConnectionRequestTimeoutError);
213 + }
214 + });
215 +
216 + it('should reject if the API call fails', async () => {
217 + // Use fake timers to control timing
218 + vi.useFakeTimers();
219 +
220 + // Create connection request with INITIATED status
221 + connectionRequest = new ConnectionRequest(
222 + mockClient as unknown as ComposioClient,
223 + connectedAccountId,
224 + ConnectedAccountStatuses.INITIATED,
225 + redirectUrl
226 + );
227 +
228 + // Mock the API call to fail
229 + const apiError = new ComposioError('API error');
230 + mockClient.connectedAccounts.retrieve.mockRejectedValueOnce(apiError);
231 +
232 + // Start the waitForConnection call but don't await it yet
233 + const connectionPromise = connectionRequest.waitForConnection(50000);
234 +
235 + // Now check for the rejection
236 + await expect(connectionPromise).rejects.toBe(apiError);
237 + });
238 + });
239 +});
packages/core/test/tools/customTools.test.ts
+2 -2
@@ -1,7 +1,7 @@
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';
3 +import { mockClient } from '../utils/mocks/client.mock';
4 +import { toolMocks } from '../utils/mocks/data.mock';
5 import ComposioClient from '@composio/client';
6 import { z } from 'zod';
7
packages/core/test/tools/modifiers.test.ts
+4 -3
@@ -1,6 +1,6 @@
1 import { describe, it, expect, vi } from 'vitest';
2 -import { mockClient } from './mocks/client.mock';
3 -import { toolMocks } from './mocks/data.mock';
2 +import { mockClient } from '../utils/mocks/client.mock';
3 +import { toolMocks } from '../utils/mocks/data.mock';
4 import { Tool } from '../../src/types/tool.types';
5 import {
6 createTestContext,
@@ -8,7 +8,7 @@ import {
8 mockToolExecution,
9 createSchemaModifier,
10 createExecutionModifiers,
11 -} from './test-utils';
11 +} from '../utils/toolExecuteUtils';
12
13 describe('Tools Modifiers', () => {
14 const context = createTestContext();
@@ -23,6 +23,7 @@ describe('Tools Modifiers', () => {
23 description: 'Modified description',
24 });
25
26 + // mock client to send back the tool
27 mockClient.tools.retrieve.mockResolvedValueOnce(toolMocks.rawTool);
28
29 const result = await context.tools.getComposioToolBySlug(userId, slug, schemaModifier);
packages/core/test/tools/tools.test.ts
+58 -161
@@ -1,24 +1,25 @@
1 -import { describe, it, expect, vi, beforeEach } from 'vitest';
1 +import { describe, it, expect, vi } from 'vitest';
2 +import { mockClient } from '../utils/mocks/client.mock';
3 +import { toolMocks } from '../utils/mocks/data.mock';
4 +import { Tool } from '../../src/types/tool.types';
5 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';
7 +import {
8 + createTestContext,
9 + setupTest,
10 + mockToolExecution,
11 + createSchemaModifier,
12 +} from '../utils/toolExecuteUtils';
13
14 describe('Tools', () => {
10 - let tools: Tools<unknown, unknown, MockToolset>;
11 - let mockToolset: MockToolset;
12 -
13 - beforeEach(() => {
14 - vi.clearAllMocks();
15 - mockToolset = new MockToolset();
16 - tools = new Tools(mockClient as unknown as ComposioClient, mockToolset);
17 - });
15 + const context = createTestContext();
16 + setupTest(context);
17
18 describe('constructor', () => {
19 it('should throw an error if client is not provided', () => {
21 - expect(() => new Tools(null as any, mockToolset)).toThrow('ComposioClient is required');
20 + expect(() => new Tools(null as any, context.mockToolset)).toThrow(
21 + 'ComposioClient is required'
22 + );
23 });
24
25 it('should throw an error if toolset is not provided', () => {
@@ -28,7 +29,7 @@ describe('Tools', () => {
29 });
30
31 it('should create an instance successfully with valid parameters', () => {
31 - expect(tools).toBeInstanceOf(Tools);
32 + expect(context.tools).toBeInstanceOf(Tools);
33 });
34 });
35
@@ -36,13 +37,12 @@ describe('Tools', () => {
37 it('should fetch tools from the API', async () => {
38 const userId = 'test-user';
39
39 - // Mock the API response
40 mockClient.tools.list.mockResolvedValueOnce({
41 items: [toolMocks.rawTool],
42 totalPages: 1,
43 });
44
45 - const result = await tools.getComposioTools(userId);
45 + const result = await context.tools.getComposioTools(userId);
46
47 expect(mockClient.tools.list).toHaveBeenCalledTimes(1);
48 expect(result).toHaveLength(1);
@@ -62,7 +62,7 @@ describe('Tools', () => {
62 totalPages: 1,
63 });
64
65 - await tools.getComposioTools(userId, query);
65 + await context.tools.getComposioTools(userId, query);
66
67 expect(mockClient.tools.list).toHaveBeenCalledWith({
68 tool_slugs: 'TOOL1,TOOL2',
@@ -82,7 +82,7 @@ describe('Tools', () => {
82 totalPages: 1,
83 });
84
85 - const result = await tools.getComposioTools(userId);
85 + const result = await context.tools.getComposioTools(userId);
86
87 expect(result[0].inputParameters).toEqual(toolMocks.transformedTool.inputParameters);
88 expect(result[0].outputParameters).toEqual(toolMocks.transformedTool.outputParameters);
@@ -96,11 +96,10 @@ describe('Tools', () => {
96 totalPages: 1,
97 });
98
99 - // Mock custom tools
100 - const getCustomToolsSpy = vi.spyOn(tools['customTools'], 'getCustomTools');
99 + const getCustomToolsSpy = vi.spyOn(context.tools['customTools'], 'getCustomTools');
100 getCustomToolsSpy.mockResolvedValueOnce([toolMocks.customTool as unknown as Tool]);
101
103 - const result = await tools.getComposioTools(userId);
102 + const result = await context.tools.getComposioTools(userId);
103
104 expect(result).toHaveLength(2);
105 expect(result[1].slug).toEqual(toolMocks.customTool.slug);
@@ -108,19 +107,18 @@ describe('Tools', () => {
107
108 it('should apply schema modifiers when provided', async () => {
109 const userId = 'test-user';
111 - const modifier = vi.fn((slug, toolkit, tool) => ({
112 - ...tool,
110 + const schemaModifier = createSchemaModifier({
111 description: 'Modified description',
114 - }));
112 + });
113
114 mockClient.tools.list.mockResolvedValueOnce({
115 items: [toolMocks.rawTool],
116 totalPages: 1,
117 });
118
121 - const result = await tools.getComposioTools(userId, {}, modifier);
119 + const result = await context.tools.getComposioTools(userId, {}, schemaModifier);
120
123 - expect(modifier).toHaveBeenCalled();
121 + expect(schemaModifier).toHaveBeenCalled();
122 expect(result[0].description).toEqual('Modified description');
123 });
124
@@ -133,7 +131,7 @@ describe('Tools', () => {
131 totalPages: 1,
132 });
133
136 - await expect(tools.getComposioTools(userId, {}, invalidModifier)).rejects.toThrow(
134 + await expect(context.tools.getComposioTools(userId, {}, invalidModifier)).rejects.toThrow(
135 'Invalid schema modifier. Not a function.'
136 );
137 });
@@ -146,7 +144,7 @@ describe('Tools', () => {
144
145 mockClient.tools.retrieve.mockResolvedValueOnce(toolMocks.rawTool);
146
149 - const result = await tools.getComposioToolBySlug(userId, slug);
147 + const result = await context.tools.getComposioToolBySlug(userId, slug);
148
149 expect(mockClient.tools.retrieve).toHaveBeenCalledWith(slug);
150 expect(result.slug).toEqual(toolMocks.transformedTool.slug);
@@ -156,11 +154,10 @@ describe('Tools', () => {
154 const userId = 'test-user';
155 const slug = 'CUSTOM_TOOL';
156
159 - // Mock that a custom tool exists
160 - const getCustomToolBySlugSpy = vi.spyOn(tools['customTools'], 'getCustomToolBySlug');
157 + const getCustomToolBySlugSpy = vi.spyOn(context.tools['customTools'], 'getCustomToolBySlug');
158 getCustomToolBySlugSpy.mockResolvedValueOnce(toolMocks.customTool as unknown as Tool);
159
163 - const result = await tools.getComposioToolBySlug(userId, slug);
160 + const result = await context.tools.getComposioToolBySlug(userId, slug);
161
162 expect(getCustomToolBySlugSpy).toHaveBeenCalledWith(slug);
163 expect(mockClient.tools.retrieve).not.toHaveBeenCalled();
@@ -171,12 +168,11 @@ describe('Tools', () => {
168 const userId = 'test-user';
169 const slug = 'NONEXISTENT_TOOL';
170
174 - // Mock that no custom tool exists and API returns null
175 - const getCustomToolBySlugSpy = vi.spyOn(tools['customTools'], 'getCustomToolBySlug');
171 + const getCustomToolBySlugSpy = vi.spyOn(context.tools['customTools'], 'getCustomToolBySlug');
172 getCustomToolBySlugSpy.mockResolvedValueOnce(undefined);
173 mockClient.tools.retrieve.mockResolvedValueOnce(null);
174
179 - await expect(tools.getComposioToolBySlug(userId, slug)).rejects.toThrow(
175 + await expect(context.tools.getComposioToolBySlug(userId, slug)).rejects.toThrow(
176 `Tool with slug ${slug} not found`
177 );
178 });
@@ -184,16 +180,15 @@ describe('Tools', () => {
180 it('should apply schema modifiers when provided', async () => {
181 const userId = 'test-user';
182 const slug = 'TOOL_SLUG';
187 - const modifier = vi.fn((slug, toolkit, tool) => ({
188 - ...tool,
183 + const schemaModifier = createSchemaModifier({
184 description: 'Modified description',
190 - }));
185 + });
186
187 mockClient.tools.retrieve.mockResolvedValueOnce(toolMocks.rawTool);
188
194 - const result = await tools.getComposioToolBySlug(userId, slug, modifier);
189 + const result = await context.tools.getComposioToolBySlug(userId, slug, schemaModifier);
190
196 - expect(modifier).toHaveBeenCalled();
191 + expect(schemaModifier).toHaveBeenCalled();
192 expect(result.description).toEqual('Modified description');
193 });
194 });
@@ -203,17 +198,15 @@ describe('Tools', () => {
198 const userId = 'test-user';
199 const slug = 'TOOL_SLUG';
200
206 - // Mock ComposioToolBySlug
207 - const getComposioToolBySlugSpy = vi.spyOn(tools, 'getComposioToolBySlug');
201 + const getComposioToolBySlugSpy = vi.spyOn(context.tools, 'getComposioToolBySlug');
202 getComposioToolBySlugSpy.mockResolvedValueOnce(toolMocks.transformedTool as unknown as Tool);
203
210 - // Mock toolset's wrapTool
211 - mockToolset.wrapTool.mockReturnValueOnce('wrapped-tool');
204 + context.mockToolset.wrapTool.mockReturnValueOnce('wrapped-tool');
205
213 - const result = await tools.get(userId, slug);
206 + const result = await context.tools.get(userId, slug);
207
208 expect(getComposioToolBySlugSpy).toHaveBeenCalledWith(userId, slug, undefined);
216 - expect(mockToolset.wrapTool).toHaveBeenCalled();
209 + expect(context.mockToolset.wrapTool).toHaveBeenCalled();
210 expect(result).toEqual('wrapped-tool');
211 });
212
@@ -221,36 +214,31 @@ describe('Tools', () => {
214 const userId = 'test-user';
215 const filters = { tools: ['TOOL1', 'TOOL2'] };
216
224 - // Mock ComposioTools
225 - const getComposioToolsSpy = vi.spyOn(tools, 'getComposioTools');
217 + const getComposioToolsSpy = vi.spyOn(context.tools, 'getComposioTools');
218 getComposioToolsSpy.mockResolvedValueOnce([toolMocks.transformedTool as unknown as Tool]);
219
228 - // Mock toolset's wrapTools
229 - mockToolset.wrapTools.mockReturnValueOnce('wrapped-tools');
220 + context.mockToolset.wrapTools.mockReturnValueOnce('wrapped-tools');
221
231 - const result = await tools.get(userId, filters);
222 + const result = await context.tools.get(userId, filters);
223
224 expect(getComposioToolsSpy).toHaveBeenCalledWith(userId, filters, undefined);
234 - expect(mockToolset.wrapTools).toHaveBeenCalled();
225 + expect(context.mockToolset.wrapTools).toHaveBeenCalled();
226 expect(result).toEqual('wrapped-tools');
227 });
228
229 it('should pass modifiers to the underlying methods', async () => {
230 const userId = 'test-user';
231 const slug = 'TOOL_SLUG';
241 - const options = {
242 - modifyToolSchema: vi.fn(),
243 - beforeToolExecute: vi.fn(),
244 - afterToolExecute: vi.fn(),
245 - };
232 + const schemaModifier = createSchemaModifier({
233 + description: 'Modified description',
234 + });
235
247 - // Mock ComposioToolBySlug
248 - const getComposioToolBySlugSpy = vi.spyOn(tools, 'getComposioToolBySlug');
236 + const getComposioToolBySlugSpy = vi.spyOn(context.tools, 'getComposioToolBySlug');
237 getComposioToolBySlugSpy.mockResolvedValueOnce(toolMocks.transformedTool as unknown as Tool);
238
251 - await tools.get(userId, slug, options);
239 + await context.tools.get(userId, slug, { modifyToolSchema: schemaModifier });
240
253 - expect(getComposioToolBySlugSpy).toHaveBeenCalledWith(userId, slug, options.modifyToolSchema);
241 + expect(getComposioToolBySlugSpy).toHaveBeenCalledWith(userId, slug, schemaModifier);
242 });
243 });
244
@@ -259,19 +247,14 @@ describe('Tools', () => {
247 const slug = 'CUSTOM_TOOL';
248 const body = { userId: 'test-user', arguments: { query: 'test' } };
249
262 - // mock client to send back the tool
263 - mockClient.tools.retrieve.mockResolvedValueOnce(toolMocks.rawTool);
264 - mockClient.toolkits.retrieve.mockResolvedValueOnce(toolkitMocks.rawToolkit);
265 -
266 - // Mock that a custom tool exists
267 - const getCustomToolBySlugSpy = vi.spyOn(tools['customTools'], 'getCustomToolBySlug');
268 - getCustomToolBySlugSpy.mockResolvedValueOnce(toolMocks.customTool as unknown as Tool);
250 + const { getCustomToolBySlugSpy } = await mockToolExecution(context.tools, {
251 + customToolExists: true,
252 + });
253
270 - // Mock custom tool execution
271 - const executeCustomToolSpy = vi.spyOn(tools['customTools'], 'executeCustomTool');
254 + const executeCustomToolSpy = vi.spyOn(context.tools['customTools'], 'executeCustomTool');
255 executeCustomToolSpy.mockResolvedValueOnce(toolMocks.toolExecuteResponse);
256
274 - const result = await tools.execute(slug, body);
257 + const result = await context.tools.execute(slug, body);
258
259 expect(getCustomToolBySlugSpy).toHaveBeenCalledWith(slug);
260 expect(executeCustomToolSpy).toHaveBeenCalledWith(slug, body, expect.any(Object));
@@ -286,35 +269,10 @@ describe('Tools', () => {
269 arguments: { query: 'test' },
270 };
271
289 - // mock the connected account
290 - mockClient.connectedAccounts.list.mockResolvedValueOnce(
291 - connectedAccountMocks.rawConnectedAccountsResponse
292 - );
293 -
294 - // Mock that no custom tool exists
295 - const getCustomToolBySlugSpy = vi.spyOn(tools['customTools'], 'getCustomToolBySlug');
296 - getCustomToolBySlugSpy.mockResolvedValueOnce(undefined);
297 -
298 - // Mock composio tool retrieval and execution
299 - const getComposioToolBySlugSpy = vi.spyOn(tools, 'getComposioToolBySlug');
300 - getComposioToolBySlugSpy.mockResolvedValueOnce(toolMocks.transformedTool as unknown as Tool);
301 -
302 - // Mock the connected account for tool call
303 - const getConnectedAccountIdForToolSpy = vi.spyOn(
304 - tools as unknown as {
305 - getConnectedAccountIdForTool: (typeof tools)['getConnectedAccountIdForTool'];
306 - },
307 - 'getConnectedAccountIdForTool'
308 - );
309 - getConnectedAccountIdForToolSpy.mockResolvedValueOnce('test-connected-account-id');
272 + await mockToolExecution(context.tools);
273
311 - mockClient.tools.execute.mockResolvedValueOnce(toolMocks.rawToolExecuteResponse);
274 + const result = await context.tools.execute(slug, body);
275
313 - const result = await tools.execute(slug, body);
314 -
315 - expect(getCustomToolBySlugSpy).toHaveBeenCalledWith(slug);
316 - expect(getComposioToolBySlugSpy).toHaveBeenCalledWith(body.userId, slug);
317 - expect(getConnectedAccountIdForToolSpy).toHaveBeenCalledWith(body.userId, slug);
276 expect(mockClient.tools.execute).toHaveBeenCalledWith(slug, {
277 allow_tracing: undefined,
278 connected_account_id: undefined,
@@ -335,25 +293,10 @@ describe('Tools', () => {
293 arguments: { query: 'test' },
294 };
295
338 - // mock the connected account
339 - mockClient.connectedAccounts.list.mockResolvedValueOnce(
340 - connectedAccountMocks.rawConnectedAccountsResponse
341 - );
296 + await mockToolExecution(context.tools);
297
343 - // Mock that no custom tool exists
344 - const getCustomToolBySlugSpy = vi.spyOn(tools['customTools'], 'getCustomToolBySlug');
345 - getCustomToolBySlugSpy.mockResolvedValueOnce(undefined);
346 -
347 - // Mock composio tool retrieval and execution
348 - const getComposioToolBySlugSpy = vi.spyOn(tools, 'getComposioToolBySlug');
349 - getComposioToolBySlugSpy.mockResolvedValueOnce(toolMocks.transformedTool as unknown as Tool);
298 + const result = await context.tools.execute(slug, body);
299
351 - mockClient.tools.execute.mockResolvedValueOnce(toolMocks.rawToolExecuteResponse);
352 -
353 - const result = await tools.execute(slug, body);
354 -
355 - expect(getCustomToolBySlugSpy).toHaveBeenCalledWith(slug);
356 - expect(getComposioToolBySlugSpy).toHaveBeenCalledWith(body.userId, slug);
300 expect(mockClient.tools.execute).toHaveBeenCalledWith(slug, {
301 allow_tracing: undefined,
302 connected_account_id: 'test-connected-account-id',
@@ -365,51 +308,5 @@ describe('Tools', () => {
308 });
309 expect(result).toEqual(toolMocks.toolExecuteResponse);
310 });
368 -
369 - it('should apply beforeToolExecute and afterToolExecute modifiers', async () => {
370 - const slug = 'COMPOSIO_TOOL';
371 - const body = { userId: 'test-user', arguments: { query: 'test' } };
372 - const modifiers = {
373 - beforeToolExecute: vi.fn((slug, toolkit, params) => {
374 - return {
375 - ...params,
376 - arguments: { query: 'modified-query' },
377 - };
378 - }),
379 - afterToolExecute: vi.fn((slug, toolkit, response) => {
380 - return {
381 - ...response,
382 - data: {
383 - ...response.data,
384 - extraKey: 'modified-results',
385 - },
386 - };
387 - }),
388 - };
389 -
390 - // Mock that no custom tool exists
391 - const getCustomToolBySlugSpy = vi.spyOn(tools['customTools'], 'getCustomToolBySlug');
392 - getCustomToolBySlugSpy.mockResolvedValueOnce(undefined);
393 -
394 - // Mock composio tool retrieval and execution
395 - const getComposioToolBySlugSpy = vi.spyOn(tools, 'getComposioToolBySlug');
396 - getComposioToolBySlugSpy.mockResolvedValueOnce(toolMocks.transformedTool as unknown as Tool);
397 -
398 - mockClient.tools.execute.mockResolvedValueOnce(toolMocks.rawToolExecuteResponse);
399 -
400 - const result = await tools.execute(slug, body, modifiers);
401 -
402 - expect(modifiers.beforeToolExecute).toHaveBeenCalled();
403 - expect(modifiers.afterToolExecute).toHaveBeenCalled();
404 - expect(mockClient.tools.execute).toHaveBeenCalledWith(slug, {
405 - entity_id: body.userId,
406 - connected_account_id: undefined,
407 - arguments: { query: 'modified-query' },
408 - });
409 - expect(result).toEqual({
410 - ...toolMocks.toolExecuteResponse,
411 - data: { ...toolMocks.toolExecuteResponse.data, extraKey: 'modified-results' },
412 - });
413 - });
311 });
312 });
packages/core/test/toolset/openai-toolset.test.ts new
+556
@@ -0,0 +1,556 @@
1 +import { describe, it, expect, vi, beforeEach } from 'vitest';
2 +import { OpenAIToolset } from '../../src/toolset/OpenAIToolset';
3 +import { Tool } from '../../src/types/tool.types';
4 +import { OpenAI } from 'openai';
5 +import { Stream } from 'openai/streaming';
6 +import { toolMocks } from '../utils/mocks/data.mock';
7 +import { ExecuteToolModifiers } from '../../src/types/modifiers.types';
8 +
9 +// Create mocks
10 +vi.mock('openai', () => {
11 + return {
12 + OpenAI: vi.fn(),
13 + };
14 +});
15 +
16 +vi.mock('openai/streaming', () => {
17 + return {
18 + Stream: vi.fn(),
19 + };
20 +});
21 +
22 +describe('OpenAIToolset', () => {
23 + let toolset: OpenAIToolset;
24 + let mockTool: Tool;
25 + let mockExecuteToolFn: any;
26 +
27 + // Sample tool data
28 + beforeEach(() => {
29 + toolset = new OpenAIToolset();
30 +
31 + // Mock the global execute tool function
32 + mockExecuteToolFn = vi.fn().mockResolvedValue({ result: 'success' });
33 + toolset._setExecuteToolFn(mockExecuteToolFn);
34 +
35 + // Use the transformed tool mock from existing test utilities
36 + mockTool = {
37 + ...toolMocks.transformedTool,
38 + tags: [],
39 + } as Tool;
40 + });
41 +
42 + describe('name property', () => {
43 + it('should have the correct name', () => {
44 + expect(toolset.name).toBe('openai');
45 + });
46 + });
47 +
48 + describe('_isAgentic property', () => {
49 + it('should be non-agentic', () => {
50 + expect(toolset._isAgentic).toBe(false);
51 + });
52 + });
53 +
54 + describe('wrapTool', () => {
55 + it('should wrap a tool in OpenAI function format', () => {
56 + const wrapped = toolset.wrapTool(mockTool);
57 +
58 + expect(wrapped).toEqual({
59 + type: 'function',
60 + function: {
61 + name: mockTool.slug,
62 + description: mockTool.description,
63 + parameters: mockTool.inputParameters,
64 + },
65 + });
66 + });
67 + });
68 +
69 + describe('wrapTools', () => {
70 + it('should wrap multiple tools', () => {
71 + const anotherTool = { ...mockTool, slug: 'another-tool' };
72 + const tools = [mockTool, anotherTool];
73 +
74 + const wrapped = toolset.wrapTools(tools);
75 +
76 + expect(wrapped).toHaveLength(2);
77 + expect(wrapped[0].function.name).toBe(mockTool.slug);
78 + expect(wrapped[1].function.name).toBe(anotherTool.slug);
79 + });
80 + });
81 +
82 + describe('executeToolCall', () => {
83 + it('should execute a tool call and return the result as string', async () => {
84 + const userId = 'test-user';
85 + const toolCall = {
86 + id: 'call-123',
87 + type: 'function',
88 + function: {
89 + name: 'test-tool',
90 + arguments: JSON.stringify({ input: 'test-value' }),
91 + },
92 + } as OpenAI.ChatCompletionMessageToolCall;
93 +
94 + const result = await toolset.executeToolCall(userId, toolCall);
95 +
96 + expect(mockExecuteToolFn).toHaveBeenCalledWith(
97 + 'test-tool',
98 + {
99 + arguments: { input: 'test-value' },
100 + userId: 'test-user',
101 + connectedAccountId: undefined,
102 + customAuthParams: undefined,
103 + },
104 + undefined
105 + );
106 + expect(result).toBe(JSON.stringify({ result: 'success' }));
107 + });
108 +
109 + it('should pass options to executeTool', async () => {
110 + const userId = 'test-user';
111 + const toolCall = {
112 + id: 'call-123',
113 + type: 'function',
114 + function: {
115 + name: 'test-tool',
116 + arguments: JSON.stringify({ input: 'test-value' }),
117 + },
118 + } as OpenAI.ChatCompletionMessageToolCall;
119 +
120 + const options = {
121 + connectedAccountId: 'conn-123',
122 + customAuthParams: {
123 + parameters: [{ name: 'token', value: 'abc123', in: 'header' as const }],
124 + },
125 + };
126 +
127 + // Create a valid ExecuteToolModifiers object with beforeToolExecute and afterToolExecute functions
128 + const modifiers: ExecuteToolModifiers = {
129 + beforeToolExecute: vi.fn((toolSlug, toolkitSlug, params) => {
130 + return {
131 + ...params,
132 + allowTracing: true,
133 + };
134 + }),
135 + afterToolExecute: vi.fn((toolSlug, toolkitSlug, response) => {
136 + return response;
137 + }),
138 + };
139 +
140 + await toolset.executeToolCall(userId, toolCall, options, modifiers);
141 +
142 + expect(mockExecuteToolFn).toHaveBeenCalledWith(
143 + 'test-tool',
144 + {
145 + arguments: { input: 'test-value' },
146 + userId: 'test-user',
147 + connectedAccountId: 'conn-123',
148 + customAuthParams: options.customAuthParams,
149 + },
150 + modifiers
151 + );
152 + });
153 + });
154 +
155 + describe('handleToolCall', () => {
156 + it('should handle tool calls from chat completion', async () => {
157 + const userId = 'test-user';
158 + const chatCompletion = {
159 + id: 'chat-123',
160 + model: 'gpt-4',
161 + created: 123456789,
162 + object: 'chat.completion',
163 + choices: [
164 + {
165 + message: {
166 + role: 'assistant',
167 + content: null,
168 + tool_calls: [
169 + {
170 + id: 'call-123',
171 + type: 'function',
172 + function: {
173 + name: 'test-tool',
174 + arguments: JSON.stringify({ input: 'test-value' }),
175 + },
176 + } as const,
177 + ],
178 + refusal: null,
179 + },
180 + index: 0,
181 + finish_reason: 'tool_calls',
182 + },
183 + ],
184 + usage: {
185 + prompt_tokens: 10,
186 + completion_tokens: 20,
187 + total_tokens: 30,
188 + },
189 + } as OpenAI.ChatCompletion;
190 +
191 + const executeToolCallSpy = vi.spyOn(toolset, 'executeToolCall');
192 + executeToolCallSpy.mockResolvedValue(JSON.stringify({ result: 'success' }));
193 +
194 + const results = await toolset.handleToolCall(userId, chatCompletion);
195 +
196 + expect(executeToolCallSpy).toHaveBeenCalledWith(
197 + userId,
198 + chatCompletion.choices[0].message.tool_calls![0],
199 + undefined,
200 + undefined
201 + );
202 + expect(results).toEqual([JSON.stringify({ result: 'success' })]);
203 + });
204 +
205 + it('should handle multiple tool calls', async () => {
206 + const userId = 'test-user';
207 + // Create a mock with correct TypeScript type but using casting to avoid property errors
208 + const chatCompletion = {
209 + id: 'chat-123',
210 + model: 'gpt-4',
211 + created: 123456789,
212 + object: 'chat.completion',
213 + choices: [
214 + {
215 + message: {
216 + role: 'assistant',
217 + content: null,
218 + tool_calls: [
219 + {
220 + id: 'call-123',
221 + type: 'function',
222 + function: {
223 + name: 'test-tool',
224 + arguments: JSON.stringify({ input: 'test-value' }),
225 + },
226 + } as const,
227 + ],
228 + refusal: null,
229 + },
230 + index: 0,
231 + finish_reason: 'tool_calls',
232 + },
233 + ],
234 + usage: {
235 + prompt_tokens: 10,
236 + completion_tokens: 20,
237 + total_tokens: 30,
238 + },
239 + } as OpenAI.ChatCompletion;
240 +
241 + const executeToolCallSpy = vi.spyOn(toolset, 'executeToolCall');
242 + executeToolCallSpy.mockResolvedValue(JSON.stringify({ result: 'success' }));
243 +
244 + const results = await toolset.handleToolCall(userId, chatCompletion);
245 +
246 + expect(executeToolCallSpy).toHaveBeenCalledTimes(1);
247 + expect(results).toEqual([JSON.stringify({ result: 'success' })]);
248 + });
249 + });
250 +
251 + describe('handleAssistantMessage', () => {
252 + it('should handle assistant message with tool calls', async () => {
253 + const userId = 'test-user';
254 + // Cast to OpenAI.Beta.Threads.Run to bypass property requirements
255 + const run = {
256 + id: 'run-123',
257 + object: 'thread.run',
258 + status: 'requires_action',
259 + created_at: 123456789,
260 + thread_id: 'thread-123',
261 + assistant_id: 'asst-123',
262 + required_action: {
263 + type: 'submit_tool_outputs',
264 + submit_tool_outputs: {
265 + tool_calls: [
266 + {
267 + id: 'call-123',
268 + type: 'function',
269 + function: {
270 + name: 'test-tool',
271 + arguments: JSON.stringify({ input: 'test-value' }),
272 + },
273 + },
274 + ],
275 + },
276 + },
277 + } as unknown as OpenAI.Beta.Threads.Run;
278 +
279 + const executeToolCallSpy = vi.spyOn(toolset, 'executeToolCall');
280 + executeToolCallSpy.mockResolvedValue(JSON.stringify({ result: 'success' }));
281 +
282 + const toolOutputs = await toolset.handleAssistantMessage(userId, run);
283 +
284 + expect(executeToolCallSpy).toHaveBeenCalledWith(
285 + userId,
286 + run.required_action!.submit_tool_outputs!
287 + .tool_calls[0] as OpenAI.ChatCompletionMessageToolCall,
288 + undefined,
289 + undefined
290 + );
291 + expect(toolOutputs).toEqual([
292 + {
293 + tool_call_id: 'call-123',
294 + output: JSON.stringify(JSON.stringify({ result: 'success' })),
295 + },
296 + ]);
297 + });
298 +
299 + it('should handle run with no tool calls', async () => {
300 + const userId = 'test-user';
301 + const run = {
302 + id: 'run-123',
303 + object: 'thread.run',
304 + status: 'completed',
305 + created_at: 123456789,
306 + thread_id: 'thread-123',
307 + assistant_id: 'asst-123',
308 + } as unknown as OpenAI.Beta.Threads.Run;
309 +
310 + const executeToolCallSpy = vi.spyOn(toolset, 'executeToolCall');
311 +
312 + const toolOutputs = await toolset.handleAssistantMessage(userId, run);
313 +
314 + expect(executeToolCallSpy).not.toHaveBeenCalled();
315 + expect(toolOutputs).toEqual([]);
316 + });
317 + });
318 +
319 + describe('waitAndHandleAssistantToolCalls', () => {
320 + it('should handle assistant tool calls until complete', async () => {
321 + const userId = 'test-user';
322 + // Create a mock OpenAI client with the necessary functions
323 + const client = {
324 + beta: {
325 + threads: {
326 + runs: {
327 + retrieve: vi.fn(),
328 + submitToolOutputs: vi.fn(),
329 + },
330 + },
331 + },
332 + } as unknown as OpenAI;
333 +
334 + // Initial run requiring action
335 + const initialRun = {
336 + id: 'run-123',
337 + object: 'thread.run',
338 + status: 'requires_action',
339 + created_at: 123456789,
340 + thread_id: 'thread-123',
341 + assistant_id: 'asst-123',
342 + required_action: {
343 + type: 'submit_tool_outputs',
344 + submit_tool_outputs: {
345 + tool_calls: [
346 + {
347 + id: 'call-123',
348 + type: 'function',
349 + function: {
350 + name: 'test-tool',
351 + arguments: JSON.stringify({ input: 'test-value' }),
352 + },
353 + },
354 + ],
355 + },
356 + },
357 + } as unknown as OpenAI.Beta.Threads.Run;
358 +
359 + // Run after submitting tool outputs, now in progress
360 + const inProgressRun = {
361 + id: 'run-123',
362 + object: 'thread.run',
363 + status: 'in_progress',
364 + created_at: 123456789,
365 + thread_id: 'thread-123',
366 + assistant_id: 'asst-123',
367 + } as unknown as OpenAI.Beta.Threads.Run;
368 +
369 + // Final completed run
370 + const completedRun = {
371 + id: 'run-123',
372 + object: 'thread.run',
373 + status: 'completed',
374 + created_at: 123456789,
375 + thread_id: 'thread-123',
376 + assistant_id: 'asst-123',
377 + } as unknown as OpenAI.Beta.Threads.Run;
378 +
379 + const thread = {
380 + id: 'thread-123',
381 + object: 'thread',
382 + created_at: 123456789,
383 + metadata: {},
384 + tool_resources: {},
385 + } as unknown as OpenAI.Beta.Threads.Thread;
386 +
387 + // Mock the handleAssistantMessage method
388 + const handleAssistantMessageSpy = vi.spyOn(toolset, 'handleAssistantMessage');
389 + handleAssistantMessageSpy.mockResolvedValue([
390 + {
391 + tool_call_id: 'call-123',
392 + output: JSON.stringify({ result: 'success' }),
393 + },
394 + ]);
395 +
396 + // Setup the client mock behavior
397 + client.beta.threads.runs.submitToolOutputs = vi.fn().mockResolvedValue(inProgressRun);
398 + client.beta.threads.runs.retrieve = vi
399 + .fn()
400 + .mockResolvedValueOnce(inProgressRun)
401 + .mockResolvedValue(completedRun);
402 +
403 + // Test the method
404 + const result = await toolset.waitAndHandleAssistantToolCalls(
405 + userId,
406 + client,
407 + initialRun,
408 + thread
409 + );
410 +
411 + // Verify the behavior
412 + expect(handleAssistantMessageSpy).toHaveBeenCalledWith(
413 + userId,
414 + initialRun,
415 + undefined,
416 + undefined
417 + );
418 + expect(client.beta.threads.runs.submitToolOutputs).toHaveBeenCalledWith(
419 + 'thread-123',
420 + 'run-123',
421 + {
422 + tool_outputs: [
423 + {
424 + tool_call_id: 'call-123',
425 + output: JSON.stringify({ result: 'success' }),
426 + },
427 + ],
428 + }
429 + );
430 + expect(client.beta.threads.runs.retrieve).toHaveBeenCalledWith('thread-123', 'run-123');
431 + expect(result).toEqual(completedRun);
432 + });
433 + });
434 +
435 + describe('waitAndHandleAssistantStreamToolCalls', () => {
436 + it('should handle streamed assistant tool calls', async () => {
437 + const userId = 'test-user';
438 + const client = {
439 + beta: {
440 + threads: {
441 + runs: {
442 + retrieve: vi.fn(),
443 + submitToolOutputs: vi.fn(),
444 + },
445 + },
446 + },
447 + } as unknown as OpenAI;
448 +
449 + const thread = {
450 + id: 'thread-123',
451 + object: 'thread',
452 + created_at: 123456789,
453 + metadata: {},
454 + tool_resources: {},
455 + } as unknown as OpenAI.Beta.Threads.Thread;
456 +
457 + // Mock events in the stream
458 + const mockEvents = [
459 + {
460 + event: 'thread.run.created',
461 + data: { id: 'run-123' },
462 + },
463 + {
464 + event: 'thread.run.requires_action',
465 + data: {
466 + id: 'run-123',
467 + status: 'requires_action',
468 + required_action: {
469 + type: 'submit_tool_outputs',
470 + submit_tool_outputs: {
471 + tool_calls: [
472 + {
473 + id: 'call-123',
474 + type: 'function',
475 + function: {
476 + name: 'test-tool',
477 + arguments: JSON.stringify({ input: 'test-value' }),
478 + },
479 + },
480 + ],
481 + },
482 + },
483 + },
484 + },
485 + {
486 + event: 'thread.run.completed',
487 + data: { id: 'run-123', status: 'completed' },
488 + },
489 + ];
490 +
491 + // Create a mock async iterator for the stream
492 + const mockStream = {
493 + [Symbol.asyncIterator]: async function* () {
494 + for (const event of mockEvents) {
495 + yield event;
496 + }
497 + },
498 + } as unknown as Stream<OpenAI.Beta.Assistants.AssistantStreamEvent>;
499 +
500 + // Mock final run
501 + const finalRun = {
502 + id: 'run-123',
503 + object: 'thread.run',
504 + status: 'completed',
505 + created_at: 123456789,
506 + thread_id: 'thread-123',
507 + assistant_id: 'asst-123',
508 + } as unknown as OpenAI.Beta.Threads.Run;
509 +
510 + // Mock the handleAssistantMessage method
511 + const handleAssistantMessageSpy = vi.spyOn(toolset, 'handleAssistantMessage');
512 + handleAssistantMessageSpy.mockResolvedValue([
513 + {
514 + tool_call_id: 'call-123',
515 + output: JSON.stringify({ result: 'success' }),
516 + },
517 + ]);
518 +
519 + // Setup the client mock behavior
520 + client.beta.threads.runs.submitToolOutputs = vi.fn().mockResolvedValue(finalRun);
521 + client.beta.threads.runs.retrieve = vi.fn().mockResolvedValue(finalRun);
522 +
523 + // Collect the yielded events
524 + const collectedEvents: any[] = [];
525 + for await (const event of toolset.waitAndHandleAssistantStreamToolCalls(
526 + userId,
527 + client,
528 + mockStream,
529 + thread
530 + )) {
531 + collectedEvents.push(event);
532 + }
533 +
534 + // Verify the behavior
535 + expect(collectedEvents).toEqual(mockEvents);
536 + expect(handleAssistantMessageSpy).toHaveBeenCalledWith(
537 + userId,
538 + mockEvents[1].data,
539 + undefined,
540 + undefined
541 + );
542 + expect(client.beta.threads.runs.submitToolOutputs).toHaveBeenCalledWith(
543 + 'thread-123',
544 + 'run-123',
545 + {
546 + tool_outputs: [
547 + {
548 + tool_call_id: 'call-123',
549 + output: JSON.stringify({ result: 'success' }),
550 + },
551 + ],
552 + }
553 + );
554 + });
555 + });
556 +});
packages/core/test/toolset/toolset.test.ts new
+246
@@ -0,0 +1,246 @@
1 +import { describe, it, expect, vi, beforeEach } from 'vitest';
2 +import { BaseAgenticToolset, BaseNonAgenticToolset } from '../../src/toolset/BaseToolset';
3 +import { Tool, ToolExecuteParams, ToolExecuteResponse } from '../../src/types/tool.types';
4 +import { ExecuteToolFn } from '../../src/types/toolset.types';
5 +import { ComposioGlobalExecuteToolFnNotSetError } from '../../src/errors/ToolErrors';
6 +
7 +// Mock implementations of the abstract classes for testing
8 +class MockNonAgenticToolset extends BaseNonAgenticToolset<string[], string> {
9 + readonly name = 'MockNonAgenticToolset';
10 +
11 + wrapTool = vi.fn((tool: Tool): string => {
12 + return `wrapped-non-agentic-tool:${tool.slug}`;
13 + });
14 +
15 + wrapTools = vi.fn((tools: Tool[]): string[] => {
16 + return tools.map(tool => this.wrapTool(tool));
17 + });
18 +}
19 +
20 +class MockAgenticToolset extends BaseAgenticToolset<string[], string> {
21 + readonly name = 'MockAgenticToolset';
22 +
23 + wrapTool = vi.fn((tool: Tool, executeTool: ExecuteToolFn): string => {
24 + return `wrapped-agentic-tool:${tool.slug}`;
25 + });
26 +
27 + wrapTools = vi.fn((tools: Tool[], executeTool: ExecuteToolFn): string[] => {
28 + return tools.map(tool => this.wrapTool(tool, executeTool));
29 + });
30 +}
31 +
32 +describe('BaseToolset', () => {
33 + describe('BaseNonAgenticToolset', () => {
34 + let nonAgenticToolset: MockNonAgenticToolset;
35 +
36 + beforeEach(() => {
37 + nonAgenticToolset = new MockNonAgenticToolset();
38 + nonAgenticToolset._setExecuteToolFn(
39 + vi.fn().mockResolvedValue({
40 + data: { result: 'success' },
41 + error: null,
42 + successful: true,
43 + })
44 + );
45 + vi.resetAllMocks();
46 + });
47 +
48 + it('should have _isAgentic property set to false', () => {
49 + expect(nonAgenticToolset._isAgentic).toBe(false);
50 + });
51 +
52 + it('should have the correct name', () => {
53 + expect(nonAgenticToolset.name).toBe('MockNonAgenticToolset');
54 + });
55 +
56 + it('should wrap a single tool correctly', () => {
57 + const mockTool: Tool = {
58 + slug: 'test-tool',
59 + name: 'Test Tool',
60 + description: 'A tool for testing',
61 + tags: [],
62 + };
63 +
64 + const wrapped = nonAgenticToolset.wrapTool(mockTool);
65 +
66 + expect(nonAgenticToolset.wrapTool).toHaveBeenCalledWith(mockTool);
67 + expect(wrapped).toBe('wrapped-non-agentic-tool:test-tool');
68 + });
69 +
70 + it('should wrap multiple tools correctly', () => {
71 + const mockTools: Tool[] = [
72 + {
73 + slug: 'tool-1',
74 + name: 'Tool One',
75 + description: 'First test tool',
76 + tags: [],
77 + },
78 + {
79 + slug: 'tool-2',
80 + name: 'Tool Two',
81 + description: 'Second test tool',
82 + tags: [],
83 + },
84 + ];
85 +
86 + const wrapped = nonAgenticToolset.wrapTools(mockTools);
87 +
88 + expect(nonAgenticToolset.wrapTools).toHaveBeenCalledWith(mockTools);
89 + expect(wrapped).toEqual([
90 + 'wrapped-non-agentic-tool:tool-1',
91 + 'wrapped-non-agentic-tool:tool-2',
92 + ]);
93 + });
94 +
95 + it('should execute a tool using the global execute function', async () => {
96 + // Create a mock for the global execute function
97 + const mockGlobalExecute = vi.fn().mockResolvedValue({
98 + data: { result: 'success' },
99 + error: null,
100 + successful: true,
101 + });
102 +
103 + // Set the execute function
104 + nonAgenticToolset._setExecuteToolFn(mockGlobalExecute);
105 +
106 + // Execute a tool
107 + const toolSlug = 'test-tool';
108 + const toolParams: ToolExecuteParams = {
109 + userId: 'test-user',
110 + arguments: { query: 'test' },
111 + };
112 + const modifiers = {
113 + beforeToolExecute: vi.fn(x => x),
114 + afterToolExecute: vi.fn(x => x),
115 + };
116 +
117 + const result = await nonAgenticToolset.executeTool(toolSlug, toolParams, modifiers);
118 +
119 + // Verify the global execute function was called with the correct parameters
120 + expect(mockGlobalExecute).toHaveBeenCalledWith(toolSlug, toolParams, modifiers);
121 + expect(result).toEqual({
122 + data: { result: 'success' },
123 + error: null,
124 + successful: true,
125 + });
126 + });
127 + });
128 +
129 + describe('BaseAgenticToolset', () => {
130 + let agenticToolset: MockAgenticToolset;
131 + let mockExecuteTool: ExecuteToolFn;
132 +
133 + beforeEach(() => {
134 + agenticToolset = new MockAgenticToolset();
135 + agenticToolset._setExecuteToolFn(
136 + vi.fn().mockResolvedValue({
137 + data: { result: 'success' },
138 + error: null,
139 + successful: true,
140 + })
141 + );
142 + mockExecuteTool = vi.fn().mockResolvedValue({
143 + data: { result: 'success' },
144 + error: null,
145 + successful: true,
146 + });
147 + vi.resetAllMocks();
148 + });
149 +
150 + it('should have _isAgentic property set to true', () => {
151 + expect(agenticToolset._isAgentic).toBe(true);
152 + });
153 +
154 + it('should have the correct name', () => {
155 + expect(agenticToolset.name).toBe('MockAgenticToolset');
156 + });
157 +
158 + it('should wrap a single tool correctly with execute function', () => {
159 + const mockTool: Tool = {
160 + slug: 'test-tool',
161 + name: 'Test Tool',
162 + description: 'A tool for testing',
163 + tags: [],
164 + };
165 +
166 + const wrapped = agenticToolset.wrapTool(mockTool, mockExecuteTool);
167 +
168 + expect(agenticToolset.wrapTool).toHaveBeenCalledWith(mockTool, mockExecuteTool);
169 + expect(wrapped).toBe('wrapped-agentic-tool:test-tool');
170 + });
171 +
172 + it('should wrap multiple tools correctly with execute function', () => {
173 + const mockTools: Tool[] = [
174 + {
175 + slug: 'tool-1',
176 + name: 'Tool One',
177 + description: 'First test tool',
178 + tags: [],
179 + },
180 + {
181 + slug: 'tool-2',
182 + name: 'Tool Two',
183 + description: 'Second test tool',
184 + tags: [],
185 + },
186 + ];
187 +
188 + const wrapped = agenticToolset.wrapTools(mockTools, mockExecuteTool);
189 +
190 + expect(agenticToolset.wrapTools).toHaveBeenCalledWith(mockTools, mockExecuteTool);
191 + expect(wrapped).toEqual(['wrapped-agentic-tool:tool-1', 'wrapped-agentic-tool:tool-2']);
192 + });
193 +
194 + it('should execute a tool using the global execute function', async () => {
195 + // Create a mock for the global execute function
196 + const mockGlobalExecute = vi.fn().mockResolvedValue({
197 + data: { result: 'success' },
198 + error: null,
199 + successful: true,
200 + });
201 +
202 + // Set the execute function
203 + agenticToolset._setExecuteToolFn(mockGlobalExecute);
204 +
205 + // Execute a tool
206 + const toolSlug = 'test-tool';
207 + const toolParams: ToolExecuteParams = {
208 + userId: 'test-user',
209 + arguments: { query: 'test' },
210 + };
211 + const modifiers = {
212 + beforeToolExecute: vi.fn(x => x),
213 + afterToolExecute: vi.fn(x => x),
214 + };
215 +
216 + const result = await agenticToolset.executeTool(toolSlug, toolParams, modifiers);
217 +
218 + // Verify the global execute function was called with the correct parameters
219 + expect(mockGlobalExecute).toHaveBeenCalledWith(toolSlug, toolParams, modifiers);
220 + expect(result).toEqual({
221 + data: { result: 'success' },
222 + error: null,
223 + successful: true,
224 + });
225 + });
226 + });
227 +
228 + describe('_setExecuteToolFn', () => {
229 + it('should throw an error if trying to execute a tool without setting the execute function', async () => {
230 + const toolset = new MockNonAgenticToolset();
231 +
232 + const toolSlug = 'test-tool';
233 + const toolParams: ToolExecuteParams = {
234 + userId: 'test-user',
235 + arguments: { query: 'test' },
236 + };
237 +
238 + // This should throw an error because _globalExecuteToolFn is not set
239 + try {
240 + await toolset.executeTool(toolSlug, toolParams);
241 + } catch (error) {
242 + expect(error).toBeInstanceOf(ComposioGlobalExecuteToolFnNotSetError);
243 + }
244 + });
245 + });
246 +});
packages/core/test/utils/mocks/client.mock.ts renamed
packages/core/test/utils/mocks/data.mock.ts renamed
packages/core/test/utils/mocks/toolset.mock.ts renamed
packages/core/test/utils/toolExecuteUtils.ts renamed
+1 -5
@@ -29,11 +29,7 @@ export const setupTest = (context: TestContext) => {
29
30 export const mockToolExecution = async (
31 tools: TestTools,
32 - {
33 - slug = 'COMPOSIO_TOOL',
34 - customToolExists = false,
35 - connectedAccountId = 'test-connected-account-id',
36 - } = {}
32 + { customToolExists = false, connectedAccountId = 'test-connected-account-id' } = {}
33 ) => {
34 // Mock client responses
35 mockClient.tools.retrieve.mockResolvedValueOnce(toolMocks.rawTool);