Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
TypeScript agentic-aiagentsaiai-agentsaiagentsdeveloper-toolsfunction-callinggpt-4javascriptjsllmllmopsmcppythonremote-mcp-serverssetypescript
Add tests for modifiers
haxzie5bea27d68789
diff --git a/packages/core/test/tools/customTools.test.ts b/packages/core/test/tools/customTools.test.tsindex e69de29bb..12ab5926f 100644--- a/packages/core/test/tools/customTools.test.ts+++ b/packages/core/test/tools/customTools.test.ts@@ -0,0 +1,151 @@+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 ComposioClient from '@composio/client';+import { z } from 'zod';++describe('CustomTools', () => {+ let customTools: CustomTools;++ const toolOptions = {+ slug: 'CUSTOM_TOOL',+ name: 'Custom Tool',+ description: 'A custom tool for testing',+ inputParams: z.object({+ query: z.string().describe('The search query'),+ }),+ execute: vi.fn().mockResolvedValue(toolMocks.toolExecuteResponse),+ };++ beforeEach(() => {+ vi.clearAllMocks();+ customTools = new CustomTools(mockClient as unknown as ComposioClient);+ });++ it('should throw an error if client is not provided', () => {+ expect(() => new CustomTools(null as any)).toThrow('ComposioClient is required');+ });++ describe('createTool', () => {+ it('should create a custom tool and add it to the registry', async () => {+ const result = await customTools.createTool(toolOptions);++ expect(result).toMatchObject({+ slug: toolOptions.slug,+ name: toolOptions.name,+ description: toolOptions.description,+ inputParameters: expect.any(Object),+ outputParameters: expect.any(Object),+ });++ // Verify it's in the registry+ const registryTool = await customTools.getCustomToolBySlug(toolOptions.slug);+ expect(registryTool).toBeDefined();+ expect(registryTool?.slug).toEqual(toolOptions.slug);+ });++ it('should throw an error for invalid tool options', async () => {+ const invalidOptions = {+ slug: 'INVALID_TOOL',+ // Missing required properties+ };++ await expect(customTools.createTool(invalidOptions as any)).rejects.toThrow(+ 'Invalid tool options'+ );+ });+ });++ describe('getCustomTools', () => {+ it('should return all tools from the registry when no slugs provided', async () => {+ // Add tools to the registry+ await customTools.createTool(toolOptions);+ await customTools.createTool({+ ...toolOptions,+ slug: 'ANOTHER_TOOL',+ });++ const result = await customTools.getCustomTools({});++ expect(result).toHaveLength(2);+ expect(result[0].slug).toEqual('CUSTOM_TOOL');+ expect(result[1].slug).toEqual('ANOTHER_TOOL');+ });++ it('should filter tools by slug when provided', async () => {+ // Add tools to the registry+ await customTools.createTool(toolOptions);+ await customTools.createTool({+ ...toolOptions,+ slug: 'ANOTHER_TOOL',+ });++ const result = await customTools.getCustomTools({+ toolSlugs: ['CUSTOM_TOOL'],+ });++ expect(result).toHaveLength(1);+ expect(result[0].slug).toEqual('CUSTOM_TOOL');+ });+ });++ describe('executeCustomTool', () => {+ it('should execute a custom tool with provided parameters', async () => {+ // Add a tool to the registry+ await customTools.createTool(toolOptions);++ const inputParams = { query: 'test query' };+ const metadata = { userId: 'test-user' };++ const result = await customTools.executeCustomTool(toolOptions.slug, inputParams, metadata);++ expect(toolOptions.execute).toHaveBeenCalledWith(inputParams, {}, expect.any(Function));+ expect(result).toEqual(toolMocks.toolExecuteResponse);+ });++ it('should throw an error if tool does not exist', async () => {+ const nonExistentSlug = 'NON_EXISTENT';+ const inputParams = { query: 'test query' };+ const metadata = { userId: 'test-user' };++ await expect(+ customTools.executeCustomTool(nonExistentSlug, inputParams, metadata)+ ).rejects.toThrow(`Tool with slug ${nonExistentSlug} not found`);+ });++ it('should fetch auth credentials for toolkit-based custom tools', async () => {+ // Add a toolkit-based tool+ const toolkitTool = {+ ...toolOptions,+ toolkitSlug: 'TEST_TOOLKIT',+ };+ await customTools.createTool(toolkitTool);++ // Mock toolkit and connected account retrieval+ mockClient.toolkits.retrieve.mockResolvedValueOnce({ slug: 'TEST_TOOLKIT' });+ mockClient.connectedAccounts.list.mockResolvedValueOnce({+ items: [+ {+ id: 'conn-123',+ data: {+ connectionParams: { apiKey: 'test-key' },+ },+ },+ ],+ totalPages: 1,+ });++ const inputParams = { query: 'test query' };+ const metadata = { userId: 'test-user' };++ await customTools.executeCustomTool(toolkitTool.slug, inputParams, metadata);++ expect(toolkitTool.execute).toHaveBeenCalledWith(+ inputParams,+ { apiKey: 'test-key' },+ expect.any(Function)+ );+ });+ });+});diff --git a/packages/core/test/tools/mocks/data.mock.ts b/packages/core/test/tools/mocks/data.mock.tsindex 930332060..c62cb0e54 100644--- a/packages/core/test/tools/mocks/data.mock.ts+++ b/packages/core/test/tools/mocks/data.mock.ts@@ -1,3 +1,5 @@+import { z } from 'zod';+export const toolMocks = {rawTool: {slug: 'COMPOSIO_TOOL',diff --git a/packages/core/test/tools/modifiers.test.ts b/packages/core/test/tools/modifiers.test.tsindex e69de29bb..419103ee7 100644--- a/packages/core/test/tools/modifiers.test.ts+++ b/packages/core/test/tools/modifiers.test.ts@@ -0,0 +1,147 @@+import { describe, it, expect, vi } from 'vitest';+import { mockClient } from './mocks/client.mock';+import { toolMocks } from './mocks/data.mock';+import { Tool } from '../../src/types/tool.types';+import {+ createTestContext,+ setupTest,+ mockToolExecution,+ createSchemaModifier,+ createExecutionModifiers,+} from './test-utils';++describe('Tools Modifiers', () => {+ const context = createTestContext();+ setupTest(context);++ describe('Schema Modifiers', () => {+ it('should modify the tool schema with the provided modifier', async () => {+ const userId = 'test-user';+ const slug = 'COMPOSIO_TOOL';+ const schemaModifier = createSchemaModifier({+ name: 'Modified Name',+ description: 'Modified description',+ });++ mockClient.tools.retrieve.mockResolvedValueOnce(toolMocks.rawTool);++ const result = await context.tools.getComposioToolBySlug(userId, slug, schemaModifier);++ expect(schemaModifier).toHaveBeenCalledTimes(1);+ expect(schemaModifier).toHaveBeenCalledWith(+ slug,+ expect.any(String),+ expect.objectContaining({ slug })+ );+ expect(result.name).toEqual('Modified Name');+ expect(result.description).toEqual('Modified description');+ });++ it('should apply schema modifiers to all tools when getting multiple tools', async () => {+ const userId = 'test-user';+ const schemaModifier = createSchemaModifier((tool: Tool) => ({+ ...tool,+ name: `Modified ${tool.name}`,+ }));++ mockClient.tools.list.mockResolvedValueOnce({+ items: [+ { ...toolMocks.rawTool, slug: 'TOOL1' },+ { ...toolMocks.rawTool, slug: 'TOOL2' },+ ],+ totalPages: 1,+ });++ const result = await context.tools.getComposioTools(userId, {}, schemaModifier);++ expect(schemaModifier).toHaveBeenCalledTimes(2);+ expect(result[0].name).toContain('Modified');+ expect(result[1].name).toContain('Modified');+ });+ });++ describe('Execution Modifiers', () => {+ it('should apply beforeToolExecute modifier before executing a tool', async () => {+ const slug = 'COMPOSIO_TOOL';+ const body = {+ userId: 'test-user',+ arguments: { limit: 5 },+ };++ const { beforeToolExecute } = createExecutionModifiers({+ beforeModifications: {+ arguments: { limit: 10 },+ },+ });++ await mockToolExecution(context.tools);+ await context.tools.execute(slug, body, { beforeToolExecute });++ expect(beforeToolExecute).toHaveBeenCalledTimes(1);+ expect(beforeToolExecute).toHaveBeenCalledWith(slug, expect.any(String), body);+ expect(mockClient.tools.execute).toHaveBeenCalledWith(+ slug,+ expect.objectContaining({+ arguments: { limit: 10 },+ })+ );+ });++ it('should apply afterToolExecute modifier after executing a tool', async () => {+ const slug = 'COMPOSIO_TOOL';+ const body = { userId: 'test-user', arguments: {} };++ const { afterToolExecute } = createExecutionModifiers({+ afterModifications: {+ data: { enhanced: true },+ },+ });++ await mockToolExecution(context.tools);+ const result = await context.tools.execute(slug, body, { afterToolExecute });++ expect(afterToolExecute).toHaveBeenCalledTimes(1);+ expect(afterToolExecute).toHaveBeenCalledWith(+ slug,+ expect.any(String),+ expect.objectContaining({+ data: expect.any(Object),+ successful: expect.any(Boolean),+ })+ );+ expect(result.data).toHaveProperty('enhanced', true);+ });+ });++ describe('Combined Modifiers', () => {+ it('should apply both schema and execution modifiers together', async () => {+ const userId = 'test-user';+ const slug = 'COMPOSIO_TOOL';++ const schemaModifier = createSchemaModifier({+ description: 'Modified schema',+ });++ const executionModifiers = createExecutionModifiers();++ const getComposioToolBySlugSpy = vi.spyOn(context.tools, 'getComposioToolBySlug');+ getComposioToolBySlugSpy.mockResolvedValueOnce({+ ...(toolMocks.transformedTool as unknown as Tool),+ description: 'Modified schema',+ });++ const createExecuteToolFnSpy = vi.spyOn(context.tools as any, 'createExecuteToolFn');++ await context.tools.get(userId, slug, {+ modifyToolSchema: schemaModifier,+ ...executionModifiers,+ });++ expect(getComposioToolBySlugSpy).toHaveBeenCalledWith(userId, slug, schemaModifier);+ expect(createExecuteToolFnSpy).toHaveBeenCalledWith(+ userId,+ expect.objectContaining(executionModifiers)+ );+ });+ });+});diff --git a/packages/core/test/tools/test-utils.ts b/packages/core/test/tools/test-utils.tsnew file mode 100644index 000000000..d2298bf40--- /dev/null+++ b/packages/core/test/tools/test-utils.ts@@ -0,0 +1,100 @@+import { vi, beforeEach } from 'vitest';+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';++export type TestTools = Tools<unknown, unknown, MockToolset>;++export interface TestContext {+ tools: TestTools;+ mockToolset: MockToolset;+}++export const createTestContext = (): TestContext => {+ const mockToolset = new MockToolset();+ const tools = new Tools(mockClient as unknown as ComposioClient, mockToolset);+ return { tools, mockToolset };+};++export const setupTest = (context: TestContext) => {+ beforeEach(() => {+ vi.clearAllMocks();+ context.mockToolset = new MockToolset();+ context.tools = new Tools(mockClient as unknown as ComposioClient, context.mockToolset);+ });+};++export const mockToolExecution = async (+ tools: TestTools,+ {+ slug = 'COMPOSIO_TOOL',+ customToolExists = false,+ connectedAccountId = 'test-connected-account-id',+ } = {}+) => {+ // Mock client responses+ mockClient.tools.retrieve.mockResolvedValueOnce(toolMocks.rawTool);+ mockClient.toolkits.retrieve.mockResolvedValueOnce(toolkitMocks.rawToolkit);+ mockClient.connectedAccounts.list.mockResolvedValueOnce(+ connectedAccountMocks.rawConnectedAccountsResponse+ );++ // Mock custom tool check+ const getCustomToolBySlugSpy = vi.spyOn(tools['customTools'], 'getCustomToolBySlug');+ getCustomToolBySlugSpy.mockResolvedValueOnce(+ customToolExists ? (toolMocks.customTool as unknown as Tool) : undefined+ );++ // Mock composio tool retrieval+ const getComposioToolBySlugSpy = vi.spyOn(tools, 'getComposioToolBySlug');+ getComposioToolBySlugSpy.mockResolvedValueOnce(toolMocks.transformedTool as unknown as Tool);++ // Mock connected account+ const getConnectedAccountIdForToolSpy = vi.spyOn(+ tools as unknown as {+ getConnectedAccountIdForTool: (typeof tools)['getConnectedAccountIdForTool'];+ },+ 'getConnectedAccountIdForTool'+ );+ getConnectedAccountIdForToolSpy.mockResolvedValueOnce(connectedAccountId);++ // Mock tool execution+ mockClient.tools.execute.mockResolvedValueOnce(toolMocks.rawToolExecuteResponse);++ return {+ getCustomToolBySlugSpy,+ getComposioToolBySlugSpy,+ getConnectedAccountIdForToolSpy,+ };+};++export type SchemaModification = Partial<Tool> | ((tool: Tool) => Partial<Tool>);++export const createSchemaModifier = (modifications: SchemaModification) => {+ return vi.fn((toolSlug: string, toolkitSlug: string, tool: Tool) => {+ const mods = typeof modifications === 'function' ? modifications(tool) : modifications;+ return {+ ...tool,+ ...mods,+ };+ });+};++export const createExecutionModifiers = ({+ beforeModifications = {},+ afterModifications = {},+} = {}) => {+ return {+ beforeToolExecute: vi.fn((toolSlug: string, toolkitSlug: string, params: any) => ({+ ...params,+ ...beforeModifications,+ })),+ afterToolExecute: vi.fn((toolSlug: string, toolkitSlug: string, response: any) => ({+ ...response,+ ...afterModifications,+ })),+ };+};