Skip to content

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

haxzie70ca6bfb7af9
diff --git a/packages/core/src/errors/ConnectionRequestError.ts b/packages/core/src/errors/ConnectionRequestError.ts
index a95a06d87..dd31f0f5e 100644
--- a/packages/core/src/errors/ConnectionRequestError.ts
+++ b/packages/core/src/errors/ConnectionRequestError.ts
@@ -2,6 +2,7 @@ import { ComposioError } from './ComposioError';
export const ConnectionRequestErrorCodes = {
CONNECTION_REQUEST_TIMEOUT: 'CONNECTION_REQUEST_TIMEOUT',
+ CONNECTION_REQUEST_FAILED: 'CONNECTION_REQUEST_FAILED',
} as const;
export class ConnectionRequestTimeoutError extends ComposioError {
@@ -13,5 +14,16 @@ export class ConnectionRequestTimeoutError extends ComposioError {
code: ConnectionRequestErrorCodes.CONNECTION_REQUEST_TIMEOUT,
meta,
});
+ this.name = 'ConnectionRequestTimeoutError';
+ }
+}
+
+export class ConnectionRequestFailedError extends ComposioError {
+ constructor(message: string = 'Connection request failed', meta: Record<string, unknown> = {}) {
+ super(message, {
+ code: ConnectionRequestErrorCodes.CONNECTION_REQUEST_FAILED,
+ meta,
+ });
+ this.name = 'ConnectionRequestFailedError';
}
}
diff --git a/packages/core/src/errors/ToolErrors.ts b/packages/core/src/errors/ToolErrors.ts
index 52a60e918..d2515bf6e 100644
--- a/packages/core/src/errors/ToolErrors.ts
+++ b/packages/core/src/errors/ToolErrors.ts
@@ -7,6 +7,7 @@ export const ToolErrorCodes = {
CUSTOM_TOOLS_NOT_INITIALIZED: 'CUSTOM_TOOLS_NOT_INITIALIZED',
TOOL_EXECUTION_ERROR: 'TOOL_EXECUTION_ERROR',
INVALID_EXECUTE_FUNCTION: 'INVALID_EXECUTE_FUNCTION',
+ GLOBAL_EXECUTE_TOOL_FN_NOT_SET: 'GLOBAL_EXECUTE_TOOL_FN_NOT_SET',
} as const;
export class ComposioToolsetNotDefinedError extends ComposioError {
@@ -87,3 +88,17 @@ export class ComposioInvalidExecuteFunctionError extends ComposioError {
this.name = 'ComposioInvalidExecuteFunctionError';
}
}
+
+export class ComposioGlobalExecuteToolFnNotSetError extends ComposioError {
+ constructor(
+ message: string = 'Global execute tool function not set',
+ meta: Record<string, unknown> = {}
+ ) {
+ super(message, {
+ code: ToolErrorCodes.GLOBAL_EXECUTE_TOOL_FN_NOT_SET,
+ meta,
+ possibleFixes: ['Ensure the global execute tool function is set in the toolset'],
+ });
+ this.name = 'ComposioGlobalExecuteToolFnNotSetError';
+ }
+}
diff --git a/packages/core/src/models/ConnectionRequest.ts b/packages/core/src/models/ConnectionRequest.ts
index 5e2b0b3f7..23b66e1b1 100644
--- a/packages/core/src/models/ConnectionRequest.ts
+++ b/packages/core/src/models/ConnectionRequest.ts
@@ -15,7 +15,10 @@ import {
import { ConnectedAccountRetrieveResponse as OriginalConnectedAccountResponse } from '@composio/client/resources/connected-accounts';
import { ZodError } from 'zod';
import logger from '../utils/logger';
-import { ConnectionRequestTimeoutError } from '../errors/ConnectionRequestError';
+import {
+ ConnectionRequestFailedError,
+ ConnectionRequestTimeoutError,
+} from '../errors/ConnectionRequestError';
export class ConnectionRequest {
private client: ComposioClient;
private connectedAccountId: string;
@@ -77,31 +80,46 @@ export class ConnectionRequest {
async waitForConnection(timeout: number = 60000): Promise<ConnectedAccountRetrieveResponse> {
if (this.connectedAccountStatus === ConnectedAccountStatuses.ACTIVE) {
const response = await this.client.connectedAccounts.retrieve(this.connectedAccountId);
- return Promise.resolve(this.transformResponse(response));
+ return this.transformResponse(response);
}
- return new Promise((resolve, reject) => {
- const interval = setInterval(async () => {
- try {
- const response = await this.client.connectedAccounts.retrieve(this.connectedAccountId);
- if (response.status === ConnectedAccountStatuses.ACTIVE) {
- clearInterval(interval);
- resolve(this.transformResponse(response));
- }
- } catch (error) {
- clearInterval(interval);
- reject(error);
+ const terminalErrorStates: ConnectedAccountStatus[] = [
+ ConnectedAccountStatuses.FAILED,
+ ConnectedAccountStatuses.EXPIRED,
+ ConnectedAccountStatuses.DELETED,
+ ];
+
+ const start = Date.now();
+ const pollInterval = 1000;
+
+ while (Date.now() - start < timeout) {
+ try {
+ const response = await this.client.connectedAccounts.retrieve(this.connectedAccountId);
+
+ if (response.status === ConnectedAccountStatuses.ACTIVE) {
+ return this.transformResponse(response);
}
- }, 1000);
- setTimeout(() => {
- clearInterval(interval);
- reject(
- new ConnectionRequestTimeoutError(
- `Connection request timed out for ${this.connectedAccountId}`
- )
- );
- }, timeout);
- });
+ if (terminalErrorStates.includes(response.status)) {
+ throw new ConnectionRequestFailedError(
+ `Connection request failed with status: ${response.status}${response.status_reason ? `, reason: ${response.status_reason}` : ''}`,
+ {
+ userId: response.user_id,
+ connectedAccountId: this.connectedAccountId,
+ status: response.status,
+ statusReason: response.status_reason,
+ }
+ );
+ }
+
+ await new Promise(resolve => setTimeout(resolve, pollInterval));
+ } catch (error) {
+ throw error;
+ }
+ }
+
+ throw new ConnectionRequestTimeoutError(
+ `Connection request timed out for ${this.connectedAccountId}`
+ );
}
}
diff --git a/packages/core/src/toolset/BaseToolset.ts b/packages/core/src/toolset/BaseToolset.ts
index 2b85a0660..9595eda54 100644
--- a/packages/core/src/toolset/BaseToolset.ts
+++ b/packages/core/src/toolset/BaseToolset.ts
@@ -1,3 +1,4 @@
+import { ComposioGlobalExecuteToolFnNotSetError } from '../errors/ToolErrors';
import { ExecuteToolModifiers } from '../types/modifiers.types';
import type { Tool, ToolExecuteParams, ToolExecuteResponse } from '../types/tool.types';
import { ExecuteToolFn, GlobalExecuteToolFn } from '../types/toolset.types';
@@ -29,7 +30,7 @@ abstract class BaseToolset {
/**
* @internal
* Set the function to execute a tool.
- * This is set automatically injected by the core SDK.
+ * This is set automatically and injected by the core SDK.
*/
_setExecuteToolFn(executeToolFn: GlobalExecuteToolFn): void {
this._globalExecuteToolFn = executeToolFn;
@@ -49,6 +50,9 @@ abstract class BaseToolset {
body: ToolExecuteParams,
modifers?: ExecuteToolModifiers
): Promise<ToolExecuteResponse> {
+ if (!this._globalExecuteToolFn) {
+ throw new ComposioGlobalExecuteToolFnNotSetError('executeToolFn is not set');
+ }
return this._globalExecuteToolFn(toolSlug, body, modifers);
}
}
diff --git a/packages/core/src/toolset/ToolsRegistry.ts b/packages/core/src/toolset/ToolsRegistry.ts
deleted file mode 100644
index 5c47ca54c..000000000
--- a/packages/core/src/toolset/ToolsRegistry.ts
+++ /dev/null
@@ -1,50 +0,0 @@
-import { Tool, ToolSchema } from '../types/tool.types';
-
-/**
- * TOOLS REGISTRY
- *
- * This singlton class is used to register user provided tools in the toolset.
- *
- *
- */
-export class ToolsRegistry {
- private tools: Map<string, Tool> = new Map<string, Tool>();
-
- constructor() {}
-
- /**
- * Create a tool in the registry.
- * @param {Tool} tool - The tool to create.
- * @returns {Tool} The created tool.
- */
- createTool(tool: Tool): Tool {
- try {
- const parsedTool = ToolSchema.parse(tool);
- const lowerCaseSlug = parsedTool.slug.toLowerCase();
- this.tools.set(lowerCaseSlug, parsedTool);
- return parsedTool;
- } catch (error) {
- throw new Error(`Failed to create tool ${tool.slug}: ${error}`);
- }
- }
-
- /**
- * Get a tool from the registry.
- * @param {string} slug - The slug of the tool.
- * @returns {Tool | undefined} The tool.
- */
- getToolBySlug(slug: string): Tool | undefined {
- const lowerCaseSlug = slug.toLowerCase();
- return this.tools.get(lowerCaseSlug);
- }
-
- /**
- * Get all the tools from the registry.
- * @returns {Tool[]} The tools.
- */
- getTools(): Tool[] {
- return Array.from(this.tools.values());
- }
-}
-
-export const toolsRegistry = new ToolsRegistry();
diff --git a/packages/core/src/types/connectedAccounts.types.ts b/packages/core/src/types/connectedAccounts.types.ts
index 44a6b6a43..caf276972 100644
--- a/packages/core/src/types/connectedAccounts.types.ts
+++ b/packages/core/src/types/connectedAccounts.types.ts
@@ -6,7 +6,7 @@ import { z } from 'zod';
export const ConnectedAccountStatuses = {
ACTIVE: 'ACTIVE',
INACTIVE: 'INACTIVE',
- PENDING: 'DELETED',
+ DELETED: 'DELETED',
INITIATED: 'INITIATED',
EXPIRED: 'EXPIRED',
FAILED: 'FAILED',
@@ -14,7 +14,7 @@ export const ConnectedAccountStatuses = {
export const ConnectedAccountStatusSchema = z.enum([
ConnectedAccountStatuses.ACTIVE,
ConnectedAccountStatuses.INACTIVE,
- ConnectedAccountStatuses.PENDING,
+ ConnectedAccountStatuses.DELETED,
ConnectedAccountStatuses.INITIATED,
ConnectedAccountStatuses.EXPIRED,
ConnectedAccountStatuses.FAILED,
diff --git a/packages/core/test/connectedAccounts/connectedAccounts.test.ts b/packages/core/test/connectedAccounts/connectedAccounts.test.ts
new file mode 100644
index 000000000..1806b55c7
--- /dev/null
+++ b/packages/core/test/connectedAccounts/connectedAccounts.test.ts
@@ -0,0 +1,250 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { mockClient } from '../utils/mocks/client.mock';
+import { ConnectedAccounts } from '../../src/models/ConnectedAccounts';
+import ComposioClient from '@composio/client';
+import { ConnectionRequest } from '../../src/models/ConnectionRequest';
+import { ConnectedAccountRetrieveResponse } from '@composio/client/resources/connected-accounts.mjs';
+
+// Extend the mock client object for ConnectedAccounts testing
+const extendedMockClient = {
+ ...mockClient,
+ connectedAccounts: {
+ ...mockClient.connectedAccounts,
+ create: vi.fn(),
+ retrieve: vi.fn(),
+ delete: vi.fn(),
+ refresh: vi.fn(),
+ updateStatus: vi.fn(),
+ },
+};
+
+describe('ConnectedAccounts', () => {
+ let connectedAccounts: ConnectedAccounts;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ connectedAccounts = new ConnectedAccounts(extendedMockClient as unknown as ComposioClient);
+ });
+
+ describe('constructor', () => {
+ it('should create an instance successfully with valid client', () => {
+ expect(connectedAccounts).toBeInstanceOf(ConnectedAccounts);
+ });
+
+ it('should not throw an error if client is provided', () => {
+ expect(
+ () => new ConnectedAccounts(extendedMockClient as unknown as ComposioClient)
+ ).not.toThrow();
+ });
+ });
+
+ describe('list', () => {
+ it('should call client.connectedAccounts.list with the provided query', async () => {
+ const query = { limit: 10 };
+ const mockResponse = { items: [], totalPages: 0 };
+
+ extendedMockClient.connectedAccounts.list.mockResolvedValueOnce(mockResponse);
+
+ const result = await connectedAccounts.list(query);
+
+ expect(extendedMockClient.connectedAccounts.list).toHaveBeenCalledWith(query);
+ expect(result).toEqual(mockResponse);
+ });
+
+ it('should call client.connectedAccounts.list without query if none provided', async () => {
+ const mockResponse = { items: [], totalPages: 0 };
+
+ extendedMockClient.connectedAccounts.list.mockResolvedValueOnce(mockResponse);
+
+ const result = await connectedAccounts.list();
+
+ expect(extendedMockClient.connectedAccounts.list).toHaveBeenCalledWith(undefined);
+ expect(result).toEqual(mockResponse);
+ });
+ });
+
+ describe('initiate', () => {
+ it('should create a new connected account and return a ConnectionRequest and wait for it to be active', async () => {
+ const userId = 'user_123';
+ const authConfigId = 'auth_config_123';
+ const options = {
+ data: { name: 'Test Account' },
+ redirectUrl: 'https://example.com/callback',
+ };
+
+ const mockResponse = {
+ id: 'conn_123',
+ status: 'pending',
+ redirect_uri: 'https://auth.example.com/connect',
+ };
+
+ extendedMockClient.connectedAccounts.create.mockResolvedValueOnce(mockResponse);
+
+ const connectionRequest = await connectedAccounts.initiate(userId, authConfigId, options);
+
+ expect(extendedMockClient.connectedAccounts.create).toHaveBeenCalledWith({
+ auth_config: {
+ id: authConfigId,
+ },
+ connection: {
+ data: options.data,
+ redirect_uri: options.redirectUrl,
+ user_id: userId,
+ },
+ });
+
+ expect(connectionRequest).toBeInstanceOf(ConnectionRequest);
+ expect(connectionRequest).toHaveProperty('connectedAccountId', mockResponse.id);
+ expect(connectionRequest).toHaveProperty('connectedAccountStatus', mockResponse.status);
+ expect(connectionRequest).toHaveProperty('redirectUrl', mockResponse.redirect_uri);
+
+ extendedMockClient.connectedAccounts.retrieve.mockResolvedValueOnce({
+ id: 'nanoid',
+ status: 'ACTIVE',
+ auth_scopes: ['read:user', 'write:user'],
+ auth_config: {
+ id: authConfigId,
+ auth_scheme: 'OAUTH2',
+ is_composio_managed: true,
+ is_disabled: false,
+ },
+ user_id: userId,
+ data: {},
+ params: {},
+ is_disabled: false,
+ created_at: '2023-01-01T00:00:00Z',
+ updated_at: '2023-01-01T00:00:00Z',
+ status_reason: null,
+ toolkit: {
+ slug: 'test-toolkit',
+ },
+ } as unknown as ConnectedAccountRetrieveResponse);
+
+ const connectedAccount = await connectionRequest.waitForConnection();
+
+ expect(extendedMockClient.connectedAccounts.retrieve).toHaveBeenCalledWith(mockResponse.id);
+ expect(connectedAccount).toHaveProperty('id', 'nanoid');
+ expect(connectedAccount).toHaveProperty('status', 'ACTIVE');
+ });
+
+ it('should work without optional parameters', async () => {
+ const userId = 'user_123';
+ const authConfigId = 'auth_config_123';
+
+ const mockResponse = {
+ id: 'conn_123',
+ status: 'pending',
+ redirect_uri: 'https://auth.example.com/connect',
+ };
+
+ extendedMockClient.connectedAccounts.create.mockResolvedValueOnce(mockResponse);
+
+ const result = await connectedAccounts.initiate(userId, authConfigId);
+
+ expect(extendedMockClient.connectedAccounts.create).toHaveBeenCalledWith({
+ auth_config: {
+ id: authConfigId,
+ },
+ connection: {
+ data: undefined,
+ redirect_uri: undefined,
+ user_id: userId,
+ },
+ });
+
+ expect(result).toBeInstanceOf(ConnectionRequest);
+ });
+ });
+
+ describe('get', () => {
+ it('should retrieve a connected account by nanoid', async () => {
+ const nanoid = 'conn_123';
+ const mockResponse = { id: nanoid, name: 'Test Account' };
+
+ extendedMockClient.connectedAccounts.retrieve.mockResolvedValueOnce(mockResponse);
+
+ const result = await connectedAccounts.get(nanoid);
+
+ expect(extendedMockClient.connectedAccounts.retrieve).toHaveBeenCalledWith(nanoid);
+ expect(result).toEqual(mockResponse);
+ });
+ });
+
+ describe('delete', () => {
+ it('should delete a connected account by nanoid', async () => {
+ const nanoid = 'conn_123';
+ const mockResponse = { success: true };
+
+ extendedMockClient.connectedAccounts.delete.mockResolvedValueOnce(mockResponse);
+
+ const result = await connectedAccounts.delete(nanoid);
+
+ expect(extendedMockClient.connectedAccounts.delete).toHaveBeenCalledWith(nanoid);
+ expect(result).toEqual(mockResponse);
+ });
+ });
+
+ describe('refresh', () => {
+ it('should refresh a connected account by nanoid', async () => {
+ const nanoid = 'conn_123';
+ const mockResponse = { id: nanoid, refreshed: true };
+
+ extendedMockClient.connectedAccounts.refresh.mockResolvedValueOnce(mockResponse);
+
+ const result = await connectedAccounts.refresh(nanoid);
+
+ expect(extendedMockClient.connectedAccounts.refresh).toHaveBeenCalledWith(nanoid);
+ expect(result).toEqual(mockResponse);
+ });
+ });
+
+ describe('updateStatus', () => {
+ it('should update the status of a connected account', async () => {
+ const nanoid = 'conn_123';
+ const params = { enabled: true };
+ const mockResponse = { id: nanoid, enabled: true };
+
+ extendedMockClient.connectedAccounts.updateStatus.mockResolvedValueOnce(mockResponse);
+
+ const result = await connectedAccounts.updateStatus(nanoid, params);
+
+ expect(extendedMockClient.connectedAccounts.updateStatus).toHaveBeenCalledWith(
+ nanoid,
+ params
+ );
+ expect(result).toEqual(mockResponse);
+ });
+ });
+
+ describe('enable', () => {
+ it('should enable a connected account', async () => {
+ const nanoid = 'conn_123';
+ const mockResponse = { id: nanoid, enabled: true };
+
+ extendedMockClient.connectedAccounts.updateStatus.mockResolvedValueOnce(mockResponse);
+
+ const result = await connectedAccounts.enable(nanoid);
+
+ expect(extendedMockClient.connectedAccounts.updateStatus).toHaveBeenCalledWith(nanoid, {
+ enabled: true,
+ });
+ expect(result).toEqual(mockResponse);
+ });
+ });
+
+ describe('disable', () => {
+ it('should disable a connected account', async () => {
+ const nanoid = 'conn_123';
+ const mockResponse = { id: nanoid, enabled: false };
+
+ extendedMockClient.connectedAccounts.updateStatus.mockResolvedValueOnce(mockResponse);
+
+ const result = await connectedAccounts.disable(nanoid);
+
+ expect(extendedMockClient.connectedAccounts.updateStatus).toHaveBeenCalledWith(nanoid, {
+ enabled: false,
+ });
+ expect(result).toEqual(mockResponse);
+ });
+ });
+});
diff --git a/packages/core/test/connectedAccounts/connectionRequest.test.ts b/packages/core/test/connectedAccounts/connectionRequest.test.ts
new file mode 100644
index 000000000..442d6a4d6
--- /dev/null
+++ b/packages/core/test/connectedAccounts/connectionRequest.test.ts
@@ -0,0 +1,239 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { ConnectionRequest } from '../../src/models/ConnectionRequest';
+import ComposioClient, { ComposioError } from '@composio/client';
+import { ConnectionRequestTimeoutError } from '../../src/errors/ConnectionRequestError';
+import { ConnectedAccountStatuses } from '../../src/types/connectedAccounts.types';
+
+// Mock ComposioClient
+const mockClient = {
+ connectedAccounts: {
+ retrieve: vi.fn(),
+ },
+};
+
+describe('ConnectionRequest', () => {
+ let connectionRequest: ConnectionRequest;
+ const connectedAccountId = 'conn_123';
+ const redirectUrl = 'https://example.com/callback';
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ // Reset timers before each test
+ vi.useRealTimers();
+ });
+
+ describe('constructor', () => {
+ it('should create an instance with an ACTIVE status', () => {
+ connectionRequest = new ConnectionRequest(
+ mockClient as unknown as ComposioClient,
+ connectedAccountId,
+ ConnectedAccountStatuses.ACTIVE,
+ redirectUrl
+ );
+
+ expect(connectionRequest).toBeInstanceOf(ConnectionRequest);
+ expect(connectionRequest).toHaveProperty('connectedAccountId', connectedAccountId);
+ expect(connectionRequest).toHaveProperty(
+ 'connectedAccountStatus',
+ ConnectedAccountStatuses.ACTIVE
+ );
+ expect(connectionRequest).toHaveProperty('redirectUrl', redirectUrl);
+ });
+
+ it('should create an instance with a INITIATED status', () => {
+ connectionRequest = new ConnectionRequest(
+ mockClient as unknown as ComposioClient,
+ connectedAccountId,
+ ConnectedAccountStatuses.INITIATED,
+ redirectUrl
+ );
+
+ expect(connectionRequest).toBeInstanceOf(ConnectionRequest);
+ expect(connectionRequest).toHaveProperty(
+ 'connectedAccountStatus',
+ ConnectedAccountStatuses.INITIATED
+ );
+ });
+
+ it('should create an instance without a redirectUrl', () => {
+ connectionRequest = new ConnectionRequest(
+ mockClient as unknown as ComposioClient,
+ connectedAccountId,
+ ConnectedAccountStatuses.ACTIVE
+ );
+
+ expect(connectionRequest).toBeInstanceOf(ConnectionRequest);
+ expect(connectionRequest).toHaveProperty('redirectUrl', undefined);
+ });
+ });
+
+ describe('waitForConnection', () => {
+ it('should immediately resolve if status is already ACTIVE', async () => {
+ // Create the connection request with ACTIVE status
+ connectionRequest = new ConnectionRequest(
+ mockClient as unknown as ComposioClient,
+ connectedAccountId,
+ ConnectedAccountStatuses.ACTIVE,
+ redirectUrl
+ );
+
+ // Mock the retrieve response
+ const mockResponse = {
+ id: connectedAccountId,
+ status: ConnectedAccountStatuses.ACTIVE,
+ auth_config: {
+ id: 'auth_config_123',
+ auth_scheme: 'OAUTH2',
+ is_composio_managed: true,
+ is_disabled: false,
+ },
+ user_id: 'user_123',
+ data: {},
+ params: {},
+ is_disabled: false,
+ created_at: '2023-01-01T00:00:00Z',
+ updated_at: '2023-01-01T00:00:00Z',
+ status_reason: null,
+ toolkit: {
+ slug: 'test-toolkit',
+ },
+ };
+
+ mockClient.connectedAccounts.retrieve.mockResolvedValueOnce(mockResponse);
+
+ const result = await connectionRequest.waitForConnection();
+
+ expect(mockClient.connectedAccounts.retrieve).toHaveBeenCalledWith(connectedAccountId);
+ expect(mockClient.connectedAccounts.retrieve).toHaveBeenCalledTimes(1);
+ expect(result).toHaveProperty('id', connectedAccountId);
+ expect(result).toHaveProperty('status', ConnectedAccountStatuses.ACTIVE);
+ expect(result).toHaveProperty('authConfig.authScheme', 'OAUTH2');
+ });
+
+ it('should poll until status becomes ACTIVE', async () => {
+ // Use fake timers to control timing
+ vi.useFakeTimers();
+
+ // Create the connection request with INITIATED status
+ connectionRequest = new ConnectionRequest(
+ mockClient as unknown as ComposioClient,
+ connectedAccountId,
+ ConnectedAccountStatuses.INITIATED,
+ redirectUrl
+ );
+
+ // Mock initial "initiated" response
+ const pendingResponse = {
+ id: connectedAccountId,
+ status: ConnectedAccountStatuses.INITIATED,
+ auth_config: {
+ id: 'auth_config_123',
+ auth_scheme: 'OAUTH2',
+ is_composio_managed: true,
+ is_disabled: false,
+ },
+ user_id: 'user_123',
+ data: {},
+ params: {},
+ is_disabled: false,
+ created_at: '2023-01-01T00:00:00Z',
+ updated_at: '2023-01-01T00:00:00Z',
+ status_reason: null,
+ toolkit: {
+ slug: 'test-toolkit',
+ },
+ };
+
+ // Mock "active" response for the second call
+ const activeResponse = {
+ ...pendingResponse,
+ status: ConnectedAccountStatuses.ACTIVE,
+ };
+
+ mockClient.connectedAccounts.retrieve
+ .mockResolvedValueOnce(pendingResponse)
+ .mockResolvedValueOnce(activeResponse);
+
+ // Start the waitForConnection call but don't await it yet
+ const connectionPromise = connectionRequest.waitForConnection();
+
+ // Advance timer by 1 second (first poll)
+ await vi.advanceTimersByTimeAsync(1000);
+
+ // Advance timer by 1 more second (second poll)
+ await vi.advanceTimersByTimeAsync(1000);
+
+ // Resolve the promise
+ const result = await connectionPromise;
+
+ expect(mockClient.connectedAccounts.retrieve).toHaveBeenCalledWith(connectedAccountId);
+ expect(mockClient.connectedAccounts.retrieve).toHaveBeenCalledTimes(2);
+ expect(result).toHaveProperty('id', connectedAccountId);
+ expect(result).toHaveProperty('status', ConnectedAccountStatuses.ACTIVE);
+ });
+
+ it('should throw ConnectionRequestTimeoutError if the request times out', async () => {
+ // Create connection request with INITIATED status
+ connectionRequest = new ConnectionRequest(
+ mockClient as unknown as ComposioClient,
+ connectedAccountId,
+ ConnectedAccountStatuses.INITIATED,
+ redirectUrl
+ );
+
+ // Mock initiated response that never changes to active
+ const initiatedResponse = {
+ id: connectedAccountId,
+ status: ConnectedAccountStatuses.INITIATED,
+ auth_config: {
+ id: 'auth_config_123',
+ auth_scheme: 'OAUTH2',
+ is_composio_managed: true,
+ is_disabled: false,
+ },
+ user_id: 'user_123',
+ data: {},
+ params: {},
+ is_disabled: false,
+ created_at: '2023-01-01T00:00:00Z',
+ updated_at: '2023-01-01T00:00:00Z',
+ status_reason: null,
+ toolkit: {
+ slug: 'test-toolkit',
+ },
+ };
+
+ mockClient.connectedAccounts.retrieve.mockResolvedValue(initiatedResponse);
+
+ // Start the waitForConnection call with a short timeout
+ try {
+ await connectionRequest.waitForConnection(3000);
+ } catch (error) {
+ expect(error).toBeInstanceOf(ConnectionRequestTimeoutError);
+ }
+ });
+
+ it('should reject if the API call fails', async () => {
+ // Use fake timers to control timing
+ vi.useFakeTimers();
+
+ // Create connection request with INITIATED status
+ connectionRequest = new ConnectionRequest(
+ mockClient as unknown as ComposioClient,
+ connectedAccountId,
+ ConnectedAccountStatuses.INITIATED,
+ redirectUrl
+ );
+
+ // Mock the API call to fail
+ const apiError = new ComposioError('API error');
+ mockClient.connectedAccounts.retrieve.mockRejectedValueOnce(apiError);
+
+ // Start the waitForConnection call but don't await it yet
+ const connectionPromise = connectionRequest.waitForConnection(50000);
+
+ // Now check for the rejection
+ await expect(connectionPromise).rejects.toBe(apiError);
+ });
+ });
+});
diff --git a/packages/core/test/tools/customTools.test.ts b/packages/core/test/tools/customTools.test.ts
index 12ab5926f..d48d43ceb 100644
--- a/packages/core/test/tools/customTools.test.ts
+++ b/packages/core/test/tools/customTools.test.ts
@@ -1,7 +1,7 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { CustomTools } from '../../src/models/CustomTools';
-import { mockClient } from './mocks/client.mock';
-import { toolMocks } from './mocks/data.mock';
+import { mockClient } from '../utils/mocks/client.mock';
+import { toolMocks } from '../utils/mocks/data.mock';
import ComposioClient from '@composio/client';
import { z } from 'zod';
diff --git a/packages/core/test/tools/modifiers.test.ts b/packages/core/test/tools/modifiers.test.ts
index 419103ee7..6a84bc269 100644
--- a/packages/core/test/tools/modifiers.test.ts
+++ b/packages/core/test/tools/modifiers.test.ts
@@ -1,6 +1,6 @@
import { describe, it, expect, vi } from 'vitest';
-import { mockClient } from './mocks/client.mock';
-import { toolMocks } from './mocks/data.mock';
+import { mockClient } from '../utils/mocks/client.mock';
+import { toolMocks } from '../utils/mocks/data.mock';
import { Tool } from '../../src/types/tool.types';
import {
createTestContext,
@@ -8,7 +8,7 @@ import {
mockToolExecution,
createSchemaModifier,
createExecutionModifiers,
-} from './test-utils';
+} from '../utils/toolExecuteUtils';
describe('Tools Modifiers', () => {
const context = createTestContext();
@@ -23,6 +23,7 @@ describe('Tools Modifiers', () => {
description: 'Modified description',
});
+ // mock client to send back the tool
mockClient.tools.retrieve.mockResolvedValueOnce(toolMocks.rawTool);
const result = await context.tools.getComposioToolBySlug(userId, slug, schemaModifier);
diff --git a/packages/core/test/tools/tools.test.ts b/packages/core/test/tools/tools.test.ts
index e5f3cfc53..b596faf45 100644
--- a/packages/core/test/tools/tools.test.ts
+++ b/packages/core/test/tools/tools.test.ts
@@ -1,24 +1,25 @@
-import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { describe, it, expect, vi } from 'vitest';
+import { mockClient } from '../utils/mocks/client.mock';
+import { toolMocks } from '../utils/mocks/data.mock';
+import { Tool } from '../../src/types/tool.types';
import { Tools } from '../../src/models/Tools';
-import { mockClient } from './mocks/client.mock';
-import { MockToolset } from './mocks/toolset.mock';
-import { connectedAccountMocks, toolkitMocks, toolMocks } from './mocks/data.mock';
import ComposioClient from '@composio/client';
-import { Tool } from '../../src/types/tool.types';
+import {
+ createTestContext,
+ setupTest,
+ mockToolExecution,
+ createSchemaModifier,
+} from '../utils/toolExecuteUtils';
describe('Tools', () => {
- let tools: Tools<unknown, unknown, MockToolset>;
- let mockToolset: MockToolset;
-
- beforeEach(() => {
- vi.clearAllMocks();
- mockToolset = new MockToolset();
- tools = new Tools(mockClient as unknown as ComposioClient, mockToolset);
- });
+ const context = createTestContext();
+ setupTest(context);
describe('constructor', () => {
it('should throw an error if client is not provided', () => {
- expect(() => new Tools(null as any, mockToolset)).toThrow('ComposioClient is required');
+ expect(() => new Tools(null as any, context.mockToolset)).toThrow(
+ 'ComposioClient is required'
+ );
});
it('should throw an error if toolset is not provided', () => {
@@ -28,7 +29,7 @@ describe('Tools', () => {
});
it('should create an instance successfully with valid parameters', () => {
- expect(tools).toBeInstanceOf(Tools);
+ expect(context.tools).toBeInstanceOf(Tools);
});
});
@@ -36,13 +37,12 @@ describe('Tools', () => {
it('should fetch tools from the API', async () => {
const userId = 'test-user';
- // Mock the API response
mockClient.tools.list.mockResolvedValueOnce({
items: [toolMocks.rawTool],
totalPages: 1,
});
- const result = await tools.getComposioTools(userId);
+ const result = await context.tools.getComposioTools(userId);
expect(mockClient.tools.list).toHaveBeenCalledTimes(1);
expect(result).toHaveLength(1);
@@ -62,7 +62,7 @@ describe('Tools', () => {
totalPages: 1,
});
- await tools.getComposioTools(userId, query);
+ await context.tools.getComposioTools(userId, query);
expect(mockClient.tools.list).toHaveBeenCalledWith({
tool_slugs: 'TOOL1,TOOL2',
@@ -82,7 +82,7 @@ describe('Tools', () => {
totalPages: 1,
});
- const result = await tools.getComposioTools(userId);
+ const result = await context.tools.getComposioTools(userId);
expect(result[0].inputParameters).toEqual(toolMocks.transformedTool.inputParameters);
expect(result[0].outputParameters).toEqual(toolMocks.transformedTool.outputParameters);
@@ -96,11 +96,10 @@ describe('Tools', () => {
totalPages: 1,
});
- // Mock custom tools
- const getCustomToolsSpy = vi.spyOn(tools['customTools'], 'getCustomTools');
+ const getCustomToolsSpy = vi.spyOn(context.tools['customTools'], 'getCustomTools');
getCustomToolsSpy.mockResolvedValueOnce([toolMocks.customTool as unknown as Tool]);
- const result = await tools.getComposioTools(userId);
+ const result = await context.tools.getComposioTools(userId);
expect(result).toHaveLength(2);
expect(result[1].slug).toEqual(toolMocks.customTool.slug);
@@ -108,19 +107,18 @@ describe('Tools', () => {
it('should apply schema modifiers when provided', async () => {
const userId = 'test-user';
- const modifier = vi.fn((slug, toolkit, tool) => ({
- ...tool,
+ const schemaModifier = createSchemaModifier({
description: 'Modified description',
- }));
+ });
mockClient.tools.list.mockResolvedValueOnce({
items: [toolMocks.rawTool],
totalPages: 1,
});
- const result = await tools.getComposioTools(userId, {}, modifier);
+ const result = await context.tools.getComposioTools(userId, {}, schemaModifier);
- expect(modifier).toHaveBeenCalled();
+ expect(schemaModifier).toHaveBeenCalled();
expect(result[0].description).toEqual('Modified description');
});
@@ -133,7 +131,7 @@ describe('Tools', () => {
totalPages: 1,
});
- await expect(tools.getComposioTools(userId, {}, invalidModifier)).rejects.toThrow(
+ await expect(context.tools.getComposioTools(userId, {}, invalidModifier)).rejects.toThrow(
'Invalid schema modifier. Not a function.'
);
});
@@ -146,7 +144,7 @@ describe('Tools', () => {
mockClient.tools.retrieve.mockResolvedValueOnce(toolMocks.rawTool);
- const result = await tools.getComposioToolBySlug(userId, slug);
+ const result = await context.tools.getComposioToolBySlug(userId, slug);
expect(mockClient.tools.retrieve).toHaveBeenCalledWith(slug);
expect(result.slug).toEqual(toolMocks.transformedTool.slug);
@@ -156,11 +154,10 @@ describe('Tools', () => {
const userId = 'test-user';
const slug = 'CUSTOM_TOOL';
- // Mock that a custom tool exists
- const getCustomToolBySlugSpy = vi.spyOn(tools['customTools'], 'getCustomToolBySlug');
+ const getCustomToolBySlugSpy = vi.spyOn(context.tools['customTools'], 'getCustomToolBySlug');
getCustomToolBySlugSpy.mockResolvedValueOnce(toolMocks.customTool as unknown as Tool);
- const result = await tools.getComposioToolBySlug(userId, slug);
+ const result = await context.tools.getComposioToolBySlug(userId, slug);
expect(getCustomToolBySlugSpy).toHaveBeenCalledWith(slug);
expect(mockClient.tools.retrieve).not.toHaveBeenCalled();
@@ -171,12 +168,11 @@ describe('Tools', () => {
const userId = 'test-user';
const slug = 'NONEXISTENT_TOOL';
- // Mock that no custom tool exists and API returns null
- const getCustomToolBySlugSpy = vi.spyOn(tools['customTools'], 'getCustomToolBySlug');
+ const getCustomToolBySlugSpy = vi.spyOn(context.tools['customTools'], 'getCustomToolBySlug');
getCustomToolBySlugSpy.mockResolvedValueOnce(undefined);
mockClient.tools.retrieve.mockResolvedValueOnce(null);
- await expect(tools.getComposioToolBySlug(userId, slug)).rejects.toThrow(
+ await expect(context.tools.getComposioToolBySlug(userId, slug)).rejects.toThrow(
`Tool with slug ${slug} not found`
);
});
@@ -184,16 +180,15 @@ describe('Tools', () => {
it('should apply schema modifiers when provided', async () => {
const userId = 'test-user';
const slug = 'TOOL_SLUG';
- const modifier = vi.fn((slug, toolkit, tool) => ({
- ...tool,
+ const schemaModifier = createSchemaModifier({
description: 'Modified description',
- }));
+ });
mockClient.tools.retrieve.mockResolvedValueOnce(toolMocks.rawTool);
- const result = await tools.getComposioToolBySlug(userId, slug, modifier);
+ const result = await context.tools.getComposioToolBySlug(userId, slug, schemaModifier);
- expect(modifier).toHaveBeenCalled();
+ expect(schemaModifier).toHaveBeenCalled();
expect(result.description).toEqual('Modified description');
});
});
@@ -203,17 +198,15 @@ describe('Tools', () => {
const userId = 'test-user';
const slug = 'TOOL_SLUG';
- // Mock ComposioToolBySlug
- const getComposioToolBySlugSpy = vi.spyOn(tools, 'getComposioToolBySlug');
+ const getComposioToolBySlugSpy = vi.spyOn(context.tools, 'getComposioToolBySlug');
getComposioToolBySlugSpy.mockResolvedValueOnce(toolMocks.transformedTool as unknown as Tool);
- // Mock toolset's wrapTool
- mockToolset.wrapTool.mockReturnValueOnce('wrapped-tool');
+ context.mockToolset.wrapTool.mockReturnValueOnce('wrapped-tool');
- const result = await tools.get(userId, slug);
+ const result = await context.tools.get(userId, slug);
expect(getComposioToolBySlugSpy).toHaveBeenCalledWith(userId, slug, undefined);
- expect(mockToolset.wrapTool).toHaveBeenCalled();
+ expect(context.mockToolset.wrapTool).toHaveBeenCalled();
expect(result).toEqual('wrapped-tool');
});
@@ -221,36 +214,31 @@ describe('Tools', () => {
const userId = 'test-user';
const filters = { tools: ['TOOL1', 'TOOL2'] };
- // Mock ComposioTools
- const getComposioToolsSpy = vi.spyOn(tools, 'getComposioTools');
+ const getComposioToolsSpy = vi.spyOn(context.tools, 'getComposioTools');
getComposioToolsSpy.mockResolvedValueOnce([toolMocks.transformedTool as unknown as Tool]);
- // Mock toolset's wrapTools
- mockToolset.wrapTools.mockReturnValueOnce('wrapped-tools');
+ context.mockToolset.wrapTools.mockReturnValueOnce('wrapped-tools');
- const result = await tools.get(userId, filters);
+ const result = await context.tools.get(userId, filters);
expect(getComposioToolsSpy).toHaveBeenCalledWith(userId, filters, undefined);
- expect(mockToolset.wrapTools).toHaveBeenCalled();
+ expect(context.mockToolset.wrapTools).toHaveBeenCalled();
expect(result).toEqual('wrapped-tools');
});
it('should pass modifiers to the underlying methods', async () => {
const userId = 'test-user';
const slug = 'TOOL_SLUG';
- const options = {
- modifyToolSchema: vi.fn(),
- beforeToolExecute: vi.fn(),
- afterToolExecute: vi.fn(),
- };
+ const schemaModifier = createSchemaModifier({
+ description: 'Modified description',
+ });
- // Mock ComposioToolBySlug
- const getComposioToolBySlugSpy = vi.spyOn(tools, 'getComposioToolBySlug');
+ const getComposioToolBySlugSpy = vi.spyOn(context.tools, 'getComposioToolBySlug');
getComposioToolBySlugSpy.mockResolvedValueOnce(toolMocks.transformedTool as unknown as Tool);
- await tools.get(userId, slug, options);
+ await context.tools.get(userId, slug, { modifyToolSchema: schemaModifier });
- expect(getComposioToolBySlugSpy).toHaveBeenCalledWith(userId, slug, options.modifyToolSchema);
+ expect(getComposioToolBySlugSpy).toHaveBeenCalledWith(userId, slug, schemaModifier);
});
});
@@ -259,19 +247,14 @@ describe('Tools', () => {
const slug = 'CUSTOM_TOOL';
const body = { userId: 'test-user', arguments: { query: 'test' } };
- // mock client to send back the tool
- mockClient.tools.retrieve.mockResolvedValueOnce(toolMocks.rawTool);
- mockClient.toolkits.retrieve.mockResolvedValueOnce(toolkitMocks.rawToolkit);
-
- // Mock that a custom tool exists
- const getCustomToolBySlugSpy = vi.spyOn(tools['customTools'], 'getCustomToolBySlug');
- getCustomToolBySlugSpy.mockResolvedValueOnce(toolMocks.customTool as unknown as Tool);
+ const { getCustomToolBySlugSpy } = await mockToolExecution(context.tools, {
+ customToolExists: true,
+ });
- // Mock custom tool execution
- const executeCustomToolSpy = vi.spyOn(tools['customTools'], 'executeCustomTool');
+ const executeCustomToolSpy = vi.spyOn(context.tools['customTools'], 'executeCustomTool');
executeCustomToolSpy.mockResolvedValueOnce(toolMocks.toolExecuteResponse);
- const result = await tools.execute(slug, body);
+ const result = await context.tools.execute(slug, body);
expect(getCustomToolBySlugSpy).toHaveBeenCalledWith(slug);
expect(executeCustomToolSpy).toHaveBeenCalledWith(slug, body, expect.any(Object));
@@ -286,35 +269,10 @@ describe('Tools', () => {
arguments: { query: 'test' },
};
- // mock the connected account
- mockClient.connectedAccounts.list.mockResolvedValueOnce(
- connectedAccountMocks.rawConnectedAccountsResponse
- );
-
- // Mock that no custom tool exists
- const getCustomToolBySlugSpy = vi.spyOn(tools['customTools'], 'getCustomToolBySlug');
- getCustomToolBySlugSpy.mockResolvedValueOnce(undefined);
-
- // Mock composio tool retrieval and execution
- const getComposioToolBySlugSpy = vi.spyOn(tools, 'getComposioToolBySlug');
- getComposioToolBySlugSpy.mockResolvedValueOnce(toolMocks.transformedTool as unknown as Tool);
-
- // Mock the connected account for tool call
- const getConnectedAccountIdForToolSpy = vi.spyOn(
- tools as unknown as {
- getConnectedAccountIdForTool: (typeof tools)['getConnectedAccountIdForTool'];
- },
- 'getConnectedAccountIdForTool'
- );
- getConnectedAccountIdForToolSpy.mockResolvedValueOnce('test-connected-account-id');
+ await mockToolExecution(context.tools);
- mockClient.tools.execute.mockResolvedValueOnce(toolMocks.rawToolExecuteResponse);
+ const result = await context.tools.execute(slug, body);
- const result = await tools.execute(slug, body);
-
- expect(getCustomToolBySlugSpy).toHaveBeenCalledWith(slug);
- expect(getComposioToolBySlugSpy).toHaveBeenCalledWith(body.userId, slug);
- expect(getConnectedAccountIdForToolSpy).toHaveBeenCalledWith(body.userId, slug);
expect(mockClient.tools.execute).toHaveBeenCalledWith(slug, {
allow_tracing: undefined,
connected_account_id: undefined,
@@ -335,25 +293,10 @@ describe('Tools', () => {
arguments: { query: 'test' },
};
- // mock the connected account
- mockClient.connectedAccounts.list.mockResolvedValueOnce(
- connectedAccountMocks.rawConnectedAccountsResponse
- );
+ await mockToolExecution(context.tools);
- // Mock that no custom tool exists
- const getCustomToolBySlugSpy = vi.spyOn(tools['customTools'], 'getCustomToolBySlug');
- getCustomToolBySlugSpy.mockResolvedValueOnce(undefined);
-
- // Mock composio tool retrieval and execution
- const getComposioToolBySlugSpy = vi.spyOn(tools, 'getComposioToolBySlug');
- getComposioToolBySlugSpy.mockResolvedValueOnce(toolMocks.transformedTool as unknown as Tool);
+ const result = await context.tools.execute(slug, body);
- mockClient.tools.execute.mockResolvedValueOnce(toolMocks.rawToolExecuteResponse);
-
- const result = await tools.execute(slug, body);
-
- expect(getCustomToolBySlugSpy).toHaveBeenCalledWith(slug);
- expect(getComposioToolBySlugSpy).toHaveBeenCalledWith(body.userId, slug);
expect(mockClient.tools.execute).toHaveBeenCalledWith(slug, {
allow_tracing: undefined,
connected_account_id: 'test-connected-account-id',
@@ -365,51 +308,5 @@ describe('Tools', () => {
});
expect(result).toEqual(toolMocks.toolExecuteResponse);
});
-
- it('should apply beforeToolExecute and afterToolExecute modifiers', async () => {
- const slug = 'COMPOSIO_TOOL';
- const body = { userId: 'test-user', arguments: { query: 'test' } };
- const modifiers = {
- beforeToolExecute: vi.fn((slug, toolkit, params) => {
- return {
- ...params,
- arguments: { query: 'modified-query' },
- };
- }),
- afterToolExecute: vi.fn((slug, toolkit, response) => {
- return {
- ...response,
- data: {
- ...response.data,
- extraKey: 'modified-results',
- },
- };
- }),
- };
-
- // Mock that no custom tool exists
- const getCustomToolBySlugSpy = vi.spyOn(tools['customTools'], 'getCustomToolBySlug');
- getCustomToolBySlugSpy.mockResolvedValueOnce(undefined);
-
- // Mock composio tool retrieval and execution
- const getComposioToolBySlugSpy = vi.spyOn(tools, 'getComposioToolBySlug');
- getComposioToolBySlugSpy.mockResolvedValueOnce(toolMocks.transformedTool as unknown as Tool);
-
- mockClient.tools.execute.mockResolvedValueOnce(toolMocks.rawToolExecuteResponse);
-
- const result = await tools.execute(slug, body, modifiers);
-
- expect(modifiers.beforeToolExecute).toHaveBeenCalled();
- expect(modifiers.afterToolExecute).toHaveBeenCalled();
- expect(mockClient.tools.execute).toHaveBeenCalledWith(slug, {
- entity_id: body.userId,
- connected_account_id: undefined,
- arguments: { query: 'modified-query' },
- });
- expect(result).toEqual({
- ...toolMocks.toolExecuteResponse,
- data: { ...toolMocks.toolExecuteResponse.data, extraKey: 'modified-results' },
- });
- });
});
});
diff --git a/packages/core/test/toolset/openai-toolset.test.ts b/packages/core/test/toolset/openai-toolset.test.ts
new file mode 100644
index 000000000..e106adbc8
--- /dev/null
+++ b/packages/core/test/toolset/openai-toolset.test.ts
@@ -0,0 +1,556 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { OpenAIToolset } from '../../src/toolset/OpenAIToolset';
+import { Tool } from '../../src/types/tool.types';
+import { OpenAI } from 'openai';
+import { Stream } from 'openai/streaming';
+import { toolMocks } from '../utils/mocks/data.mock';
+import { ExecuteToolModifiers } from '../../src/types/modifiers.types';
+
+// Create mocks
+vi.mock('openai', () => {
+ return {
+ OpenAI: vi.fn(),
+ };
+});
+
+vi.mock('openai/streaming', () => {
+ return {
+ Stream: vi.fn(),
+ };
+});
+
+describe('OpenAIToolset', () => {
+ let toolset: OpenAIToolset;
+ let mockTool: Tool;
+ let mockExecuteToolFn: any;
+
+ // Sample tool data
+ beforeEach(() => {
+ toolset = new OpenAIToolset();
+
+ // Mock the global execute tool function
+ mockExecuteToolFn = vi.fn().mockResolvedValue({ result: 'success' });
+ toolset._setExecuteToolFn(mockExecuteToolFn);
+
+ // Use the transformed tool mock from existing test utilities
+ mockTool = {
+ ...toolMocks.transformedTool,
+ tags: [],
+ } as Tool;
+ });
+
+ describe('name property', () => {
+ it('should have the correct name', () => {
+ expect(toolset.name).toBe('openai');
+ });
+ });
+
+ describe('_isAgentic property', () => {
+ it('should be non-agentic', () => {
+ expect(toolset._isAgentic).toBe(false);
+ });
+ });
+
+ describe('wrapTool', () => {
+ it('should wrap a tool in OpenAI function format', () => {
+ const wrapped = toolset.wrapTool(mockTool);
+
+ expect(wrapped).toEqual({
+ type: 'function',
+ function: {
+ name: mockTool.slug,
+ description: mockTool.description,
+ parameters: mockTool.inputParameters,
+ },
+ });
+ });
+ });
+
+ describe('wrapTools', () => {
+ it('should wrap multiple tools', () => {
+ const anotherTool = { ...mockTool, slug: 'another-tool' };
+ const tools = [mockTool, anotherTool];
+
+ const wrapped = toolset.wrapTools(tools);
+
+ expect(wrapped).toHaveLength(2);
+ expect(wrapped[0].function.name).toBe(mockTool.slug);
+ expect(wrapped[1].function.name).toBe(anotherTool.slug);
+ });
+ });
+
+ describe('executeToolCall', () => {
+ it('should execute a tool call and return the result as string', async () => {
+ const userId = 'test-user';
+ const toolCall = {
+ id: 'call-123',
+ type: 'function',
+ function: {
+ name: 'test-tool',
+ arguments: JSON.stringify({ input: 'test-value' }),
+ },
+ } as OpenAI.ChatCompletionMessageToolCall;
+
+ const result = await toolset.executeToolCall(userId, toolCall);
+
+ expect(mockExecuteToolFn).toHaveBeenCalledWith(
+ 'test-tool',
+ {
+ arguments: { input: 'test-value' },
+ userId: 'test-user',
+ connectedAccountId: undefined,
+ customAuthParams: undefined,
+ },
+ undefined
+ );
+ expect(result).toBe(JSON.stringify({ result: 'success' }));
+ });
+
+ it('should pass options to executeTool', async () => {
+ const userId = 'test-user';
+ const toolCall = {
+ id: 'call-123',
+ type: 'function',
+ function: {
+ name: 'test-tool',
+ arguments: JSON.stringify({ input: 'test-value' }),
+ },
+ } as OpenAI.ChatCompletionMessageToolCall;
+
+ const options = {
+ connectedAccountId: 'conn-123',
+ customAuthParams: {
+ parameters: [{ name: 'token', value: 'abc123', in: 'header' as const }],
+ },
+ };
+
+ // Create a valid ExecuteToolModifiers object with beforeToolExecute and afterToolExecute functions
+ const modifiers: ExecuteToolModifiers = {
+ beforeToolExecute: vi.fn((toolSlug, toolkitSlug, params) => {
+ return {
+ ...params,
+ allowTracing: true,
+ };
+ }),
+ afterToolExecute: vi.fn((toolSlug, toolkitSlug, response) => {
+ return response;
+ }),
+ };
+
+ await toolset.executeToolCall(userId, toolCall, options, modifiers);
+
+ expect(mockExecuteToolFn).toHaveBeenCalledWith(
+ 'test-tool',
+ {
+ arguments: { input: 'test-value' },
+ userId: 'test-user',
+ connectedAccountId: 'conn-123',
+ customAuthParams: options.customAuthParams,
+ },
+ modifiers
+ );
+ });
+ });
+
+ describe('handleToolCall', () => {
+ it('should handle tool calls from chat completion', async () => {
+ const userId = 'test-user';
+ const chatCompletion = {
+ id: 'chat-123',
+ model: 'gpt-4',
+ created: 123456789,
+ object: 'chat.completion',
+ choices: [
+ {
+ message: {
+ role: 'assistant',
+ content: null,
+ tool_calls: [
+ {
+ id: 'call-123',
+ type: 'function',
+ function: {
+ name: 'test-tool',
+ arguments: JSON.stringify({ input: 'test-value' }),
+ },
+ } as const,
+ ],
+ refusal: null,
+ },
+ index: 0,
+ finish_reason: 'tool_calls',
+ },
+ ],
+ usage: {
+ prompt_tokens: 10,
+ completion_tokens: 20,
+ total_tokens: 30,
+ },
+ } as OpenAI.ChatCompletion;
+
+ const executeToolCallSpy = vi.spyOn(toolset, 'executeToolCall');
+ executeToolCallSpy.mockResolvedValue(JSON.stringify({ result: 'success' }));
+
+ const results = await toolset.handleToolCall(userId, chatCompletion);
+
+ expect(executeToolCallSpy).toHaveBeenCalledWith(
+ userId,
+ chatCompletion.choices[0].message.tool_calls![0],
+ undefined,
+ undefined
+ );
+ expect(results).toEqual([JSON.stringify({ result: 'success' })]);
+ });
+
+ it('should handle multiple tool calls', async () => {
+ const userId = 'test-user';
+ // Create a mock with correct TypeScript type but using casting to avoid property errors
+ const chatCompletion = {
+ id: 'chat-123',
+ model: 'gpt-4',
+ created: 123456789,
+ object: 'chat.completion',
+ choices: [
+ {
+ message: {
+ role: 'assistant',
+ content: null,
+ tool_calls: [
+ {
+ id: 'call-123',
+ type: 'function',
+ function: {
+ name: 'test-tool',
+ arguments: JSON.stringify({ input: 'test-value' }),
+ },
+ } as const,
+ ],
+ refusal: null,
+ },
+ index: 0,
+ finish_reason: 'tool_calls',
+ },
+ ],
+ usage: {
+ prompt_tokens: 10,
+ completion_tokens: 20,
+ total_tokens: 30,
+ },
+ } as OpenAI.ChatCompletion;
+
+ const executeToolCallSpy = vi.spyOn(toolset, 'executeToolCall');
+ executeToolCallSpy.mockResolvedValue(JSON.stringify({ result: 'success' }));
+
+ const results = await toolset.handleToolCall(userId, chatCompletion);
+
+ expect(executeToolCallSpy).toHaveBeenCalledTimes(1);
+ expect(results).toEqual([JSON.stringify({ result: 'success' })]);
+ });
+ });
+
+ describe('handleAssistantMessage', () => {
+ it('should handle assistant message with tool calls', async () => {
+ const userId = 'test-user';
+ // Cast to OpenAI.Beta.Threads.Run to bypass property requirements
+ const run = {
+ id: 'run-123',
+ object: 'thread.run',
+ status: 'requires_action',
+ created_at: 123456789,
+ thread_id: 'thread-123',
+ assistant_id: 'asst-123',
+ required_action: {
+ type: 'submit_tool_outputs',
+ submit_tool_outputs: {
+ tool_calls: [
+ {
+ id: 'call-123',
+ type: 'function',
+ function: {
+ name: 'test-tool',
+ arguments: JSON.stringify({ input: 'test-value' }),
+ },
+ },
+ ],
+ },
+ },
+ } as unknown as OpenAI.Beta.Threads.Run;
+
+ const executeToolCallSpy = vi.spyOn(toolset, 'executeToolCall');
+ executeToolCallSpy.mockResolvedValue(JSON.stringify({ result: 'success' }));
+
+ const toolOutputs = await toolset.handleAssistantMessage(userId, run);
+
+ expect(executeToolCallSpy).toHaveBeenCalledWith(
+ userId,
+ run.required_action!.submit_tool_outputs!
+ .tool_calls[0] as OpenAI.ChatCompletionMessageToolCall,
+ undefined,
+ undefined
+ );
+ expect(toolOutputs).toEqual([
+ {
+ tool_call_id: 'call-123',
+ output: JSON.stringify(JSON.stringify({ result: 'success' })),
+ },
+ ]);
+ });
+
+ it('should handle run with no tool calls', async () => {
+ const userId = 'test-user';
+ const run = {
+ id: 'run-123',
+ object: 'thread.run',
+ status: 'completed',
+ created_at: 123456789,
+ thread_id: 'thread-123',
+ assistant_id: 'asst-123',
+ } as unknown as OpenAI.Beta.Threads.Run;
+
+ const executeToolCallSpy = vi.spyOn(toolset, 'executeToolCall');
+
+ const toolOutputs = await toolset.handleAssistantMessage(userId, run);
+
+ expect(executeToolCallSpy).not.toHaveBeenCalled();
+ expect(toolOutputs).toEqual([]);
+ });
+ });
+
+ describe('waitAndHandleAssistantToolCalls', () => {
+ it('should handle assistant tool calls until complete', async () => {
+ const userId = 'test-user';
+ // Create a mock OpenAI client with the necessary functions
+ const client = {
+ beta: {
+ threads: {
+ runs: {
+ retrieve: vi.fn(),
+ submitToolOutputs: vi.fn(),
+ },
+ },
+ },
+ } as unknown as OpenAI;
+
+ // Initial run requiring action
+ const initialRun = {
+ id: 'run-123',
+ object: 'thread.run',
+ status: 'requires_action',
+ created_at: 123456789,
+ thread_id: 'thread-123',
+ assistant_id: 'asst-123',
+ required_action: {
+ type: 'submit_tool_outputs',
+ submit_tool_outputs: {
+ tool_calls: [
+ {
+ id: 'call-123',
+ type: 'function',
+ function: {
+ name: 'test-tool',
+ arguments: JSON.stringify({ input: 'test-value' }),
+ },
+ },
+ ],
+ },
+ },
+ } as unknown as OpenAI.Beta.Threads.Run;
+
+ // Run after submitting tool outputs, now in progress
+ const inProgressRun = {
+ id: 'run-123',
+ object: 'thread.run',
+ status: 'in_progress',
+ created_at: 123456789,
+ thread_id: 'thread-123',
+ assistant_id: 'asst-123',
+ } as unknown as OpenAI.Beta.Threads.Run;
+
+ // Final completed run
+ const completedRun = {
+ id: 'run-123',
+ object: 'thread.run',
+ status: 'completed',
+ created_at: 123456789,
+ thread_id: 'thread-123',
+ assistant_id: 'asst-123',
+ } as unknown as OpenAI.Beta.Threads.Run;
+
+ const thread = {
+ id: 'thread-123',
+ object: 'thread',
+ created_at: 123456789,
+ metadata: {},
+ tool_resources: {},
+ } as unknown as OpenAI.Beta.Threads.Thread;
+
+ // Mock the handleAssistantMessage method
+ const handleAssistantMessageSpy = vi.spyOn(toolset, 'handleAssistantMessage');
+ handleAssistantMessageSpy.mockResolvedValue([
+ {
+ tool_call_id: 'call-123',
+ output: JSON.stringify({ result: 'success' }),
+ },
+ ]);
+
+ // Setup the client mock behavior
+ client.beta.threads.runs.submitToolOutputs = vi.fn().mockResolvedValue(inProgressRun);
+ client.beta.threads.runs.retrieve = vi
+ .fn()
+ .mockResolvedValueOnce(inProgressRun)
+ .mockResolvedValue(completedRun);
+
+ // Test the method
+ const result = await toolset.waitAndHandleAssistantToolCalls(
+ userId,
+ client,
+ initialRun,
+ thread
+ );
+
+ // Verify the behavior
+ expect(handleAssistantMessageSpy).toHaveBeenCalledWith(
+ userId,
+ initialRun,
+ undefined,
+ undefined
+ );
+ expect(client.beta.threads.runs.submitToolOutputs).toHaveBeenCalledWith(
+ 'thread-123',
+ 'run-123',
+ {
+ tool_outputs: [
+ {
+ tool_call_id: 'call-123',
+ output: JSON.stringify({ result: 'success' }),
+ },
+ ],
+ }
+ );
+ expect(client.beta.threads.runs.retrieve).toHaveBeenCalledWith('thread-123', 'run-123');
+ expect(result).toEqual(completedRun);
+ });
+ });
+
+ describe('waitAndHandleAssistantStreamToolCalls', () => {
+ it('should handle streamed assistant tool calls', async () => {
+ const userId = 'test-user';
+ const client = {
+ beta: {
+ threads: {
+ runs: {
+ retrieve: vi.fn(),
+ submitToolOutputs: vi.fn(),
+ },
+ },
+ },
+ } as unknown as OpenAI;
+
+ const thread = {
+ id: 'thread-123',
+ object: 'thread',
+ created_at: 123456789,
+ metadata: {},
+ tool_resources: {},
+ } as unknown as OpenAI.Beta.Threads.Thread;
+
+ // Mock events in the stream
+ const mockEvents = [
+ {
+ event: 'thread.run.created',
+ data: { id: 'run-123' },
+ },
+ {
+ event: 'thread.run.requires_action',
+ data: {
+ id: 'run-123',
+ status: 'requires_action',
+ required_action: {
+ type: 'submit_tool_outputs',
+ submit_tool_outputs: {
+ tool_calls: [
+ {
+ id: 'call-123',
+ type: 'function',
+ function: {
+ name: 'test-tool',
+ arguments: JSON.stringify({ input: 'test-value' }),
+ },
+ },
+ ],
+ },
+ },
+ },
+ },
+ {
+ event: 'thread.run.completed',
+ data: { id: 'run-123', status: 'completed' },
+ },
+ ];
+
+ // Create a mock async iterator for the stream
+ const mockStream = {
+ [Symbol.asyncIterator]: async function* () {
+ for (const event of mockEvents) {
+ yield event;
+ }
+ },
+ } as unknown as Stream<OpenAI.Beta.Assistants.AssistantStreamEvent>;
+
+ // Mock final run
+ const finalRun = {
+ id: 'run-123',
+ object: 'thread.run',
+ status: 'completed',
+ created_at: 123456789,
+ thread_id: 'thread-123',
+ assistant_id: 'asst-123',
+ } as unknown as OpenAI.Beta.Threads.Run;
+
+ // Mock the handleAssistantMessage method
+ const handleAssistantMessageSpy = vi.spyOn(toolset, 'handleAssistantMessage');
+ handleAssistantMessageSpy.mockResolvedValue([
+ {
+ tool_call_id: 'call-123',
+ output: JSON.stringify({ result: 'success' }),
+ },
+ ]);
+
+ // Setup the client mock behavior
+ client.beta.threads.runs.submitToolOutputs = vi.fn().mockResolvedValue(finalRun);
+ client.beta.threads.runs.retrieve = vi.fn().mockResolvedValue(finalRun);
+
+ // Collect the yielded events
+ const collectedEvents: any[] = [];
+ for await (const event of toolset.waitAndHandleAssistantStreamToolCalls(
+ userId,
+ client,
+ mockStream,
+ thread
+ )) {
+ collectedEvents.push(event);
+ }
+
+ // Verify the behavior
+ expect(collectedEvents).toEqual(mockEvents);
+ expect(handleAssistantMessageSpy).toHaveBeenCalledWith(
+ userId,
+ mockEvents[1].data,
+ undefined,
+ undefined
+ );
+ expect(client.beta.threads.runs.submitToolOutputs).toHaveBeenCalledWith(
+ 'thread-123',
+ 'run-123',
+ {
+ tool_outputs: [
+ {
+ tool_call_id: 'call-123',
+ output: JSON.stringify({ result: 'success' }),
+ },
+ ],
+ }
+ );
+ });
+ });
+});
diff --git a/packages/core/test/toolset/toolset.test.ts b/packages/core/test/toolset/toolset.test.ts
new file mode 100644
index 000000000..8941c8c50
--- /dev/null
+++ b/packages/core/test/toolset/toolset.test.ts
@@ -0,0 +1,246 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { BaseAgenticToolset, BaseNonAgenticToolset } from '../../src/toolset/BaseToolset';
+import { Tool, ToolExecuteParams, ToolExecuteResponse } from '../../src/types/tool.types';
+import { ExecuteToolFn } from '../../src/types/toolset.types';
+import { ComposioGlobalExecuteToolFnNotSetError } from '../../src/errors/ToolErrors';
+
+// Mock implementations of the abstract classes for testing
+class MockNonAgenticToolset extends BaseNonAgenticToolset<string[], string> {
+ readonly name = 'MockNonAgenticToolset';
+
+ wrapTool = vi.fn((tool: Tool): string => {
+ return `wrapped-non-agentic-tool:${tool.slug}`;
+ });
+
+ wrapTools = vi.fn((tools: Tool[]): string[] => {
+ return tools.map(tool => this.wrapTool(tool));
+ });
+}
+
+class MockAgenticToolset extends BaseAgenticToolset<string[], string> {
+ readonly name = 'MockAgenticToolset';
+
+ wrapTool = vi.fn((tool: Tool, executeTool: ExecuteToolFn): string => {
+ return `wrapped-agentic-tool:${tool.slug}`;
+ });
+
+ wrapTools = vi.fn((tools: Tool[], executeTool: ExecuteToolFn): string[] => {
+ return tools.map(tool => this.wrapTool(tool, executeTool));
+ });
+}
+
+describe('BaseToolset', () => {
+ describe('BaseNonAgenticToolset', () => {
+ let nonAgenticToolset: MockNonAgenticToolset;
+
+ beforeEach(() => {
+ nonAgenticToolset = new MockNonAgenticToolset();
+ nonAgenticToolset._setExecuteToolFn(
+ vi.fn().mockResolvedValue({
+ data: { result: 'success' },
+ error: null,
+ successful: true,
+ })
+ );
+ vi.resetAllMocks();
+ });
+
+ it('should have _isAgentic property set to false', () => {
+ expect(nonAgenticToolset._isAgentic).toBe(false);
+ });
+
+ it('should have the correct name', () => {
+ expect(nonAgenticToolset.name).toBe('MockNonAgenticToolset');
+ });
+
+ it('should wrap a single tool correctly', () => {
+ const mockTool: Tool = {
+ slug: 'test-tool',
+ name: 'Test Tool',
+ description: 'A tool for testing',
+ tags: [],
+ };
+
+ const wrapped = nonAgenticToolset.wrapTool(mockTool);
+
+ expect(nonAgenticToolset.wrapTool).toHaveBeenCalledWith(mockTool);
+ expect(wrapped).toBe('wrapped-non-agentic-tool:test-tool');
+ });
+
+ it('should wrap multiple tools correctly', () => {
+ const mockTools: Tool[] = [
+ {
+ slug: 'tool-1',
+ name: 'Tool One',
+ description: 'First test tool',
+ tags: [],
+ },
+ {
+ slug: 'tool-2',
+ name: 'Tool Two',
+ description: 'Second test tool',
+ tags: [],
+ },
+ ];
+
+ const wrapped = nonAgenticToolset.wrapTools(mockTools);
+
+ expect(nonAgenticToolset.wrapTools).toHaveBeenCalledWith(mockTools);
+ expect(wrapped).toEqual([
+ 'wrapped-non-agentic-tool:tool-1',
+ 'wrapped-non-agentic-tool:tool-2',
+ ]);
+ });
+
+ it('should execute a tool using the global execute function', async () => {
+ // Create a mock for the global execute function
+ const mockGlobalExecute = vi.fn().mockResolvedValue({
+ data: { result: 'success' },
+ error: null,
+ successful: true,
+ });
+
+ // Set the execute function
+ nonAgenticToolset._setExecuteToolFn(mockGlobalExecute);
+
+ // Execute a tool
+ const toolSlug = 'test-tool';
+ const toolParams: ToolExecuteParams = {
+ userId: 'test-user',
+ arguments: { query: 'test' },
+ };
+ const modifiers = {
+ beforeToolExecute: vi.fn(x => x),
+ afterToolExecute: vi.fn(x => x),
+ };
+
+ const result = await nonAgenticToolset.executeTool(toolSlug, toolParams, modifiers);
+
+ // Verify the global execute function was called with the correct parameters
+ expect(mockGlobalExecute).toHaveBeenCalledWith(toolSlug, toolParams, modifiers);
+ expect(result).toEqual({
+ data: { result: 'success' },
+ error: null,
+ successful: true,
+ });
+ });
+ });
+
+ describe('BaseAgenticToolset', () => {
+ let agenticToolset: MockAgenticToolset;
+ let mockExecuteTool: ExecuteToolFn;
+
+ beforeEach(() => {
+ agenticToolset = new MockAgenticToolset();
+ agenticToolset._setExecuteToolFn(
+ vi.fn().mockResolvedValue({
+ data: { result: 'success' },
+ error: null,
+ successful: true,
+ })
+ );
+ mockExecuteTool = vi.fn().mockResolvedValue({
+ data: { result: 'success' },
+ error: null,
+ successful: true,
+ });
+ vi.resetAllMocks();
+ });
+
+ it('should have _isAgentic property set to true', () => {
+ expect(agenticToolset._isAgentic).toBe(true);
+ });
+
+ it('should have the correct name', () => {
+ expect(agenticToolset.name).toBe('MockAgenticToolset');
+ });
+
+ it('should wrap a single tool correctly with execute function', () => {
+ const mockTool: Tool = {
+ slug: 'test-tool',
+ name: 'Test Tool',
+ description: 'A tool for testing',
+ tags: [],
+ };
+
+ const wrapped = agenticToolset.wrapTool(mockTool, mockExecuteTool);
+
+ expect(agenticToolset.wrapTool).toHaveBeenCalledWith(mockTool, mockExecuteTool);
+ expect(wrapped).toBe('wrapped-agentic-tool:test-tool');
+ });
+
+ it('should wrap multiple tools correctly with execute function', () => {
+ const mockTools: Tool[] = [
+ {
+ slug: 'tool-1',
+ name: 'Tool One',
+ description: 'First test tool',
+ tags: [],
+ },
+ {
+ slug: 'tool-2',
+ name: 'Tool Two',
+ description: 'Second test tool',
+ tags: [],
+ },
+ ];
+
+ const wrapped = agenticToolset.wrapTools(mockTools, mockExecuteTool);
+
+ expect(agenticToolset.wrapTools).toHaveBeenCalledWith(mockTools, mockExecuteTool);
+ expect(wrapped).toEqual(['wrapped-agentic-tool:tool-1', 'wrapped-agentic-tool:tool-2']);
+ });
+
+ it('should execute a tool using the global execute function', async () => {
+ // Create a mock for the global execute function
+ const mockGlobalExecute = vi.fn().mockResolvedValue({
+ data: { result: 'success' },
+ error: null,
+ successful: true,
+ });
+
+ // Set the execute function
+ agenticToolset._setExecuteToolFn(mockGlobalExecute);
+
+ // Execute a tool
+ const toolSlug = 'test-tool';
+ const toolParams: ToolExecuteParams = {
+ userId: 'test-user',
+ arguments: { query: 'test' },
+ };
+ const modifiers = {
+ beforeToolExecute: vi.fn(x => x),
+ afterToolExecute: vi.fn(x => x),
+ };
+
+ const result = await agenticToolset.executeTool(toolSlug, toolParams, modifiers);
+
+ // Verify the global execute function was called with the correct parameters
+ expect(mockGlobalExecute).toHaveBeenCalledWith(toolSlug, toolParams, modifiers);
+ expect(result).toEqual({
+ data: { result: 'success' },
+ error: null,
+ successful: true,
+ });
+ });
+ });
+
+ describe('_setExecuteToolFn', () => {
+ it('should throw an error if trying to execute a tool without setting the execute function', async () => {
+ const toolset = new MockNonAgenticToolset();
+
+ const toolSlug = 'test-tool';
+ const toolParams: ToolExecuteParams = {
+ userId: 'test-user',
+ arguments: { query: 'test' },
+ };
+
+ // This should throw an error because _globalExecuteToolFn is not set
+ try {
+ await toolset.executeTool(toolSlug, toolParams);
+ } catch (error) {
+ expect(error).toBeInstanceOf(ComposioGlobalExecuteToolFnNotSetError);
+ }
+ });
+ });
+});
diff --git a/packages/core/test/tools/mocks/client.mock.ts b/packages/core/test/utils/mocks/client.mock.ts
similarity index 100%
rename from packages/core/test/tools/mocks/client.mock.ts
rename to packages/core/test/utils/mocks/client.mock.ts
diff --git a/packages/core/test/tools/mocks/data.mock.ts b/packages/core/test/utils/mocks/data.mock.ts
similarity index 100%
rename from packages/core/test/tools/mocks/data.mock.ts
rename to packages/core/test/utils/mocks/data.mock.ts
diff --git a/packages/core/test/tools/mocks/toolset.mock.ts b/packages/core/test/utils/mocks/toolset.mock.ts
similarity index 100%
rename from packages/core/test/tools/mocks/toolset.mock.ts
rename to packages/core/test/utils/mocks/toolset.mock.ts
diff --git a/packages/core/test/tools/test-utils.ts b/packages/core/test/utils/toolExecuteUtils.ts
similarity index 96%
rename from packages/core/test/tools/test-utils.ts
rename to packages/core/test/utils/toolExecuteUtils.ts
index d2298bf40..be60cd25b 100644
--- a/packages/core/test/tools/test-utils.ts
+++ b/packages/core/test/utils/toolExecuteUtils.ts
@@ -29,11 +29,7 @@ export const setupTest = (context: TestContext) => {
export const mockToolExecution = async (
tools: TestTools,
- {
- slug = 'COMPOSIO_TOOL',
- customToolExists = false,
- connectedAccountId = 'test-connected-account-id',
- } = {}
+ { customToolExists = false, connectedAccountId = 'test-connected-account-id' } = {}
) => {
// Mock client responses
mockClient.tools.retrieve.mockResolvedValueOnce(toolMocks.rawTool);