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
Fix custom tools (#21)
Musthaq Ahamad0b15376c97d9
diff --git a/.changeset/seven-mangos-mix.md b/.changeset/seven-mangos-mix.mdnew file mode 100644index 000000000..b59219d06--- /dev/null+++ b/.changeset/seven-mangos-mix.md@@ -0,0 +1,12 @@+---+'@composio/core': patch+'@composio/anthropic': patch+'@composio/cloudflare': patch+'@composio/google': patch+'@composio/langchain': patch+'@composio/mastra': patch+'@composio/openai': patch+'@composio/vercel': patch+---++Add custom toolkit examplesdiff --git a/docs/api/custom-tools.md b/docs/api/custom-tools.mdindex 1e37077c5..842a1dae0 100644--- a/docs/api/custom-tools.md+++ b/docs/api/custom-tools.md@@ -1,279 +1,137 @@-# Custom Tools API+# Custom Tools-Custom Tools allow you to extend Composio's functionality by creating your own tools with custom logic. These tools can be used alongside the built-in tools provided by Composio.+Custom tools allow you to create your own tools that can be used with Composio. There are two types of custom tools:-## Creating Custom Tools+1. Standalone Tools - Simple tools that don't require any authentication+2. Toolkit-based Tools - Tools that require authentication and can use toolkit credentials-You can create custom tools using the `createCustomTool` method of the `Tools` class:+## Creating a Custom Tool++### Standalone Tool++A standalone tool is the simplest form of custom tool. It only requires input parameters and an execute function:```typescript-const customTool = await composio.tools.createCustomTool({- name: 'My Custom Tool',- description: 'A custom tool that does something specific',- slug: 'MY_CUSTOM_TOOL',- inputParameters: {- type: 'object',- properties: {- param1: {- type: 'string',- description: 'First parameter',- },- param2: {- type: 'number',- description: 'Second parameter',- }- },- required: ['param1']- },- outputParameters: {- type: 'object',- properties: {- result: {- type: 'string',- description: 'The result of the operation'- }- }- },- handler: async (params, context) => {- // Custom logic here- const { param1, param2 } = params.arguments;-- // Return a successful response- return {- data: {- result: `Processed ${param1} with value ${param2}`- },+const tool = await composio.tools.createCustomTool({+ slug: 'CALCULATE_SQUARE',+ name: 'Calculate Square',+ description: 'Calculates the square of a number',+ inputParams: z.object({+ number: z.number().describe('The number to calculate the square of'),+ }),+ execute: async input => {+ const { number } = input;+ return {+ data: { result: number * number },+ error: null,successful: true,- error: null};- }+ },});```-## Custom Tool Options--When creating a custom tool, you need to specify the following options:--| Property | Type | Required | Description |-|----------|------|----------|-------------|-| `name` | string | Yes | The name of the custom tool |-| `description` | string | Yes | A description of what the tool does |-| `slug` | string | Yes | A unique identifier for the tool (usually uppercase with underscores) |-| `inputParameters` | JSONSchema | Yes | The JSON Schema defining the input parameters |-| `outputParameters` | JSONSchema | No | The JSON Schema defining the output parameters |-| `handler` | function | Yes | The function that implements the tool's logic |--## Handler Function--The handler function is where you implement the custom tool's logic. It receives the following parameters:--1. `params`: The parameters passed to the tool, including:- - `arguments`: The input arguments as defined in `inputParameters`- - `userId`: The ID of the user executing the tool- - `connectedAccountId`: (optional) The ID of the connected account to use- - Additional properties as defined in `ToolExecuteParams`+### Toolkit-based Tool-2. `context`: Execution metadata, including:- - `userId`: The ID of the user executing the tool- - `connectedAccountId`: (optional) The ID of the connected account being used+A toolkit-based tool has access to two ways of making authenticated requests:-The handler must return a `ToolExecuteResponse` object with the following structure:+1. Using `executeToolRequest` - The recommended way to make authenticated requests to the toolkit's API endpoints. Composio automatically handles credential injection using the connected account:```typescript-{- data: Record<string, unknown>, // The output data matching the outputParameters schema- error: string | null, // Error message (if any)- successful: boolean, // Whether the execution was successful- logId?: string, // Optional log ID for debugging- sessionInfo?: unknown // Optional session information-}-```--## JSON Schema for Parameters--Both `inputParameters` and `outputParameters` should be defined using JSON Schema:--```typescript-const inputParametersSchema = {- type: 'object',- properties: {- query: {- type: 'string',- description: 'The search query'- },- limit: {- type: 'integer',- description: 'Maximum number of results',- default: 10- }- },- required: ['query']-};+const tool = await composio.tools.createCustomTool({+ slug: 'GITHUB_STAR_COMPOSIO_REPOSITORY',+ name: 'Star Composios Repository',+ description: 'Stars a repository under composiohq org',+ toolkitSlug: 'github',+ inputParams: z.object({+ repository: z.string().describe('Name of the repository to star'),+ }),+ execute: async (input, authCredentials, executeToolRequest) => {+ // executeToolRequest makes authenticated requests to the toolkit's API+ // It automatically uses the connected account's credentials+ const starResult = await executeToolRequest({+ endpoint: `https://api.github.com/user/starred/composiohq/${input.repository}`,+ method: 'PUT',+ body: {},+ });-const outputParametersSchema = {- type: 'object',- properties: {- results: {- type: 'array',- items: {- type: 'object',- properties: {- title: { type: 'string' },- url: { type: 'string' }- }- },- description: 'Search results'- },- totalCount: {- type: 'integer',- description: 'Total number of results found'- }- }-};-```--## Error Handling in Custom Tools--Your handler function should handle errors gracefully:--```typescript-handler: async (params, context) => {- try {- // Custom logic here- const { query, limit = 10 } = params.arguments;-- // Simulate an API call- const results = await searchApi(query, limit);-return {data: {- results,- totalCount: results.length+ message: 'Successfully stared repository',},+ error: null,successful: true,- error: null};- } catch (error) {- // Handle errors- return {- data: {},- successful: false,- error: error.message || 'An error occurred during tool execution'- };- }-}+ },+});```-## Using Connected Accounts in Custom Tools--You can use connected accounts in your custom tools to access authenticated services:+2. Using `authCredentials` - For making direct API calls when needed:```typescript-handler: async (params, context) => {- const { userId, connectedAccountId } = context;-- if (!connectedAccountId) {- return {- data: {},- successful: false,- error: 'No connected account provided'- };- }-- try {- // Get the connected account details- const connectedAccount = await composio.connectedAccounts.get(connectedAccountId);-- // Use the authentication tokens- const accessToken = connectedAccount.meta.access_token;-- // Make authenticated API calls- const apiResult = await callExternalApi(accessToken, params.arguments);-+const tool = await composio.tools.createCustomTool({+ slug: 'GITHUB_DIRECT_API',+ name: 'Direct GitHub API Call',+ description: 'Makes direct calls to GitHub API',+ toolkitSlug: 'github',+ inputParams: z.object({+ repo: z.string().describe('Repository name'),+ }),+ execute: async (input, authCredentials) => {+ // Use authCredentials for direct API calls+ const result = await fetch(`https://api.github.com/repos/${input.repo}`, {+ headers: {+ Authorization: `Bearer ${authCredentials.access_token}`,+ },+ });+return {- data: apiResult,+ data: await result.json(),+ error: null,successful: true,- error: null- };- } catch (error) {- return {- data: {},- successful: false,- error: error.message};- }-}+ },+});```-## Accessing Custom Tools+## Executing Custom Tools-Once created, custom tools can be accessed just like built-in tools:+You can execute custom tools just like any other tool:```typescript-// Get the custom tool-const tool = await composio.tools.get('default', 'MY_CUSTOM_TOOL');--// Execute the custom tool-const result = await composio.tools.execute('MY_CUSTOM_TOOL', {- userId: 'default',+const result = await composio.tools.execute('TOOL_SLUG', {arguments: {- param1: 'value1',- param2: 42- }+ // Tool input parameters+ },+ userId: 'user-id',+ connectedAccountId: 'optional-account-id', // Required for toolkit-based tools});--console.log(result.data); // { result: "Processed value1 with value 42" }```-## Types--### CustomToolOptions--```typescript-interface CustomToolOptions {- name: string;- description: string;- slug: string;- inputParameters: JSONSchema;- outputParameters?: JSONSchema;- handler: (- params: ToolExecuteParams,- context: ExecuteMetadata- ) => Promise<ToolExecuteResponse>;-}-```+## Type Safety-### ExecuteMetadata+The custom tools implementation provides full type safety:-```typescript-interface ExecuteMetadata {- userId: string;- connectedAccountId?: string;-}-```+1. Input parameters are validated using Zod schemas+2. The execute function's parameters are inferred based on whether toolkitSlug is provided:+ - Without toolkitSlug: `(input) => Promise<ToolExecuteResponse>`+ - With toolkitSlug: `(input, authCredentials, executeToolRequest) => Promise<ToolExecuteResponse>`-### ToolExecuteParams+## Best Practices-```typescript-interface ToolExecuteParams {- allowTracing?: boolean;- connectedAccountId?: string;- customAuthParams?: CustomAuthParams;- arguments: Record<string, unknown>;- userId: string;- version?: string;- text?: string;-}-```+1. Use descriptive names and slugs for your tools+2. Always provide descriptions for input parameters using `describe()`+3. Handle errors gracefully in your execute function+4. For toolkit-based tools:+ - Prefer `executeToolRequest` over direct API calls when possible+ - Remember that `executeToolRequest` can only call tools from the same toolkit+ - Use `executeToolRequest` to leverage Composio's automatic credential handling+ - Only use `authCredentials` when you need to make direct API calls or interact with different services+5. Chain multiple toolkit operations using `executeToolRequest` for better maintainability-### ToolExecuteResponse+## Limitations-```typescript-interface ToolExecuteResponse {- data: Record<string, unknown>;- error: string | null;- successful: boolean;- logId?: string;- sessionInfo?: unknown;-}-```\ No newline at end of file+1. Custom tools are stored in memory and are not persisted+2. They need to be recreated when the application restarts+3. Toolkit-based tools require a valid connected account with the specified toolkit+4. `executeToolRequest` can only execute tools from the same toolkit that the custom tool belongs to+5. Each toolkit-based tool can only use one connected account at a timediff --git a/examples/custom-tools/.env.example b/examples/custom-tools/.env.examplenew file mode 100644index 000000000..0e728257c--- /dev/null+++ b/examples/custom-tools/.env.example@@ -0,0 +1,6 @@+# Composio API Key - Get it from https://app.composio.dev+COMPOSIO_API_KEY=your_composio_api_key_here++# Add other environment variables as needed for your example+# OPENAI_API_KEY=your_openai_api_key_here+# ANTHROPIC_API_KEY=your_anthropic_api_key_herediff --git a/examples/custom-tools/README.md b/examples/custom-tools/README.mdnew file mode 100644index 000000000..fa4fcb65c--- /dev/null+++ b/examples/custom-tools/README.md@@ -0,0 +1,165 @@+# Custom Tools Examples++This directory contains examples demonstrating how to create and use custom tools with Composio SDK.++## Examples++### 1. Simple Custom Tool (`simple.ts`)++Shows how to create a basic standalone tool that doesn't require authentication. The example creates a tool that calculates the square of a number:++```typescript+const tool = await composio.tools.createCustomTool({+ slug: 'CALCULATE_SQUARE',+ name: 'Calculate Square',+ description: 'Calculates the square of a number',+ inputParams: z.object({+ number: z.number().describe('The number to calculate the square of'),+ }),+ execute: async input => {+ const { number } = input;+ return {+ data: { result: number * number },+ error: null,+ successful: true,+ };+ },+});+```++### 2. Toolkit-based Tools (`auth-credentials.ts`)++Demonstrates two approaches to making authenticated requests in toolkit-based tools:++#### Using executeToolRequest (Recommended)++```typescript+const tool = await composio.tools.createCustomTool({+ slug: 'GITHUB_LIST_AND_STAR',+ name: 'List and Star Repository',+ description: 'Lists repositories and stars them',+ toolkitSlug: 'github',+ inputParams: z.object({+ owner: z.string().describe('Repository owner'),+ }),+ execute: async (input, authCredentials, executeToolRequest) => {+ // executeToolRequest can only call tools from the 'github' toolkit+ // Uses the same connected account credentials automatically+ const listResult = await executeToolRequest({+ slug: 'LIST_REPOSITORIES', // must be a github toolkit tool+ arguments: { owner: input.owner },+ });++ const starResult = await executeToolRequest({+ slug: 'STAR_REPOSITORY', // must be a github toolkit tool+ arguments: {+ owner: input.owner,+ repo: listResult.data.repositories[0].name,+ },+ });++ return {+ data: { listed: listResult.data, starred: starResult.data },+ error: null,+ successful: true,+ };+ },+});+```++#### Using Direct API Calls++```typescript+const tool = await composio.tools.createCustomTool({+ slug: 'GITHUB_STAR_REPO',+ name: 'Star GitHub Repository',+ toolkitSlug: 'github',+ description: 'Stars a GitHub repository using direct API call',+ inputParams: z.object({+ repository: z.string().describe('The repository to star'),+ }),+ execute: async (input, authCredentials) => {+ // Use authCredentials for direct API calls or when interacting with different services+ const result = await fetch(+ `https://api.github.com/user/starred/composiohq/${input.repository}`,+ {+ method: 'PUT',+ headers: {+ Authorization: `Bearer ${authCredentials?.access_token}`,+ },+ }+ );+ return {+ data: await result.json(),+ error: null,+ successful: true,+ };+ },+});+```++## Running the Examples++1. Set up your environment:++ ```bash+ cp .env.example .env+ ```++2. Add your Composio API key to `.env`:++ ```+ COMPOSIO_API_KEY=your_api_key_here+ ```++3. Run an example:++ ```bash+ # Run the simple example+ pnpm start:simple++ # Run the auth credentials example+ pnpm start:auth+ ```++## Key Concepts++1. **Standalone vs Toolkit-based Tools**++ - Standalone tools only receive input parameters+ - Toolkit-based tools have access to both `executeToolRequest` and `authCredentials`++2. **Authentication Methods**++ - `executeToolRequest`: Recommended way to use toolkit tools+ - Can only execute tools from the same toolkit+ - Uses the connected account credentials automatically+ - No need to manage auth tokens+ - Better maintainability and security+ - `authCredentials`: For direct API calls+ - Use when you need to make direct API calls+ - Use when you need to interact with different services+ - Requires manual token management+ - More flexible but requires more maintenance++3. **Type Safety**++ - Input parameters are validated using Zod schemas+ - TypeScript infers the correct execute function signature based on toolkitSlug++4. **Error Handling**++ - Tools should always return a ToolExecuteResponse+ - Handle errors gracefully and provide meaningful error messages++## Related Examples++- [OpenAI Example](../openai) - Shows integration with OpenAI+- [LangChain Example](../langchain) - Shows integration with LangChain+- [More Examples](../) - Browse all available examples++## Support++- [Documentation](https://docs.composio.dev)+- [Discord Community](https://discord.gg/composio)+- [GitHub Issues](https://github.com/composio/composio/issues)diff --git a/examples/custom-tools/package.json b/examples/custom-tools/package.jsonnew file mode 100644index 000000000..e5383884f--- /dev/null+++ b/examples/custom-tools/package.json@@ -0,0 +1,29 @@+{+ "name": "custom-tools-example",+ "private": true,+ "version": "0.1.0",+ "description": "Example project for Custom-tools",+ "main": "src/index.ts",+ "scripts": {+ "start": "bun src/index.ts",+ "dev": "bun --watch src/index.ts",+ "test": "echo \"Error: no test specified\" && exit 1"+ },+ "keywords": [+ "composio",+ "example",+ "custom-tools"+ ],+ "author": "",+ "license": "ISC",+ "packageManager": "[email protected]",+ "dependencies": {+ "@composio/core": "workspace:*",+ "dotenv": "^16.4.1",+ "zod": "^3.24.2"+ },+ "devDependencies": {+ "@types/bun": "^1.2.9",+ "typescript": "^5.8.3"+ }+}diff --git a/examples/custom-tools/src/auth-credentials.ts b/examples/custom-tools/src/auth-credentials.tsnew file mode 100644index 000000000..a4279d42e--- /dev/null+++ b/examples/custom-tools/src/auth-credentials.ts@@ -0,0 +1,88 @@+/**+ * Custom-tools Example+ *+ * This example demonstrates how to use Composio SDK for custom-tools with auth credentials.+ *+ * Prerequisites:+ * 1. Set up your COMPOSIO_API_KEY in the .env file+ * 3. Run the example: pnpm start+ */++import { Composio } from '@composio/core';+import 'dotenv/config';+import { z } from 'zod';++/**+ * Initialize Composio+ */+const composio = new Composio({+ apiKey: process.env.COMPOSIO_API_KEY,+});++/**+ * Create a custom hackernews tool+ * This tool will be registerd in the composio instance and store in memory temporarily.+ */+const customToolSlug = 'GITHUB_STAR_COMPOSIOHQ_REPOSITORY';+const tool = await composio.tools.createCustomTool({+ slug: customToolSlug,+ name: 'Github star composio repositories',+ toolkitSlug: 'github',+ description: 'For any given repository of the user composiohq, star the repository',+ inputParams: z.object({+ repository: z.string().describe('The repository to star'),+ }),+ execute: async (input, authCredentials) => {+ console.log('π ~ execute: ~ params:', input);+ console.log('π ~ execute: ~ authCredentials:', authCredentials);+ /**+ * The auth credentials are the auth credentials for the connected account.+ * You can use them to make requests to the API.+ */+ const result = await fetch(+ `https://api.github.com/user/starred/composiohq/${input.repository}`,+ {+ method: 'PUT',+ headers: {+ Authorization: `Bearer ${authCredentials?.access_token}`,+ },+ }+ );+ const data = await result.json();+ return {+ data: data,+ error: null,+ successful: true,+ };+ },+});++console.log('π created tool:', tool);++/**+ * Main function to run the example+ */+async function main() {+ try {+ console.log('π Starting Custom-tools Example...');++ // Get available tools+ const tools = await composio.tools.get('default', customToolSlug);++ console.log('tools:', tools);++ const result = await composio.tools.execute(customToolSlug, {+ arguments: {+ repository: 'composio',+ },+ userId: 'default',+ });++ console.log('π Result:', result);+ } catch (error) {+ console.error('β Error running example:', error);+ }+}++// Run the example+main().catch(console.error);diff --git a/examples/custom-tools/src/index.ts b/examples/custom-tools/src/index.tsnew file mode 100644index 000000000..5119144fb--- /dev/null+++ b/examples/custom-tools/src/index.ts@@ -0,0 +1,76 @@+/**+ * Custom-tools Example+ *+ * This example demonstrates how to use Composio SDK for custom-tools.+ *+ * Prerequisites:+ * 1. Set up your COMPOSIO_API_KEY in the .env file+ * 3. Run the example: pnpm start+ */++import { Composio } from '@composio/core';+import 'dotenv/config';+import { z } from 'zod';++/**+ * Initialize Composio+ */+const composio = new Composio({+ apiKey: process.env.COMPOSIO_API_KEY,+});++/**+ * Create a custom hackernews tool+ * This tool will be registerd in the composio instance and store in memory temporarily.+ */+const customToolSlug = 'GITHUB_STAR_COMPOSIOHQ_REPOSITORY';+const tool = await composio.tools.createCustomTool({+ slug: customToolSlug,+ name: 'Github star composio repositories',+ toolkitSlug: 'github',+ description: 'For any given repository of the user composiohq, star the repository',+ inputParams: z.object({+ repository: z.string().describe('The repository to star'),+ }),+ execute: async (input, authCredentials, executeToolRequest) => {+ console.log('π ~ execute: ~ params:', input);+ console.log('π ~ execute: ~ authCredentials:', authCredentials);++ const result = await executeToolRequest({+ endpoint: `https://api.github.com/user/starred/composiohq/${input.repository}`,+ method: 'PUT',+ body: {},+ });+ return result;+ },+});++console.log('π created tool:', tool);++/**+ * Main function to run the example+ */+async function main() {+ try {+ console.log('π Starting Custom-tools Example...');++ // Get available tools+ const tools = await composio.tools.get('default', customToolSlug);++ console.log('tools:', tools);++ const result = await composio.tools.execute(customToolSlug, {+ arguments: {+ repository: 'composio',+ },+ userId: 'default',+ });++ console.log('π Result:', result);+ } catch (error) {+ console.error('β Error running example:', error);+ }+}++// Run the example+main().catch(console.error);diff --git a/examples/custom-tools/src/simple.ts b/examples/custom-tools/src/simple.tsnew file mode 100644index 000000000..e7084b1bc--- /dev/null+++ b/examples/custom-tools/src/simple.ts@@ -0,0 +1,76 @@+/**+ * Custom-tools Example+ *+ * This example demonstrates how to use Composio SDK for simple custom-tools.+ *+ * Prerequisites:+ * 1. Set up your COMPOSIO_API_KEY in the .env file+ * 3. Run the example: pnpm start+ */++import { Composio } from '@composio/core';+import 'dotenv/config';+import { z } from 'zod';++/**+ * Initialize Composio+ */+const composio = new Composio({+ apiKey: process.env.COMPOSIO_API_KEY,+});++/**+ * Create a custom calculate square of a number tool+ * This tool will be registerd in the composio instance and store in memory temporarily.+ */+const customToolSlug = 'CALCULATE_SQUARE_OF_A_NUMBER';+const tool = await composio.tools.createCustomTool({+ slug: customToolSlug,+ name: 'Calculate square of a number',+ description: 'For any given number the tool calculates the square of the number',+ inputParams: z.object({+ number: z.number().describe('The number to calculate the square of'),+ }),+ execute: async input => {+ const { number } = input;+ const result = Number(number) * Number(number);++ return {+ data: {+ result,+ },+ error: null,+ successful: true,+ };+ },+});++console.log('π created tool:', tool);++/**+ * Main function to run the example+ */+async function main() {+ try {+ console.log('π Starting Custom-tools Example...');++ // Get available tools+ const tools = await composio.tools.get('default', customToolSlug);++ console.log('tools:', tools);++ const result = await composio.tools.execute(customToolSlug, {+ arguments: {+ number: 2,+ },+ userId: 'default',+ });++ console.log('π Result:', result);+ } catch (error) {+ console.error('β Error running example:', error);+ }+}++// Run the example+main().catch(console.error);diff --git a/examples/custom-tools/tsconfig.json b/examples/custom-tools/tsconfig.jsonnew file mode 100644index 000000000..158c157c8--- /dev/null+++ b/examples/custom-tools/tsconfig.json@@ -0,0 +1,16 @@+{+ "compilerOptions": {+ "target": "ESNext",+ "module": "ESNext",+ "declaration": true,+ "declarationDir": "./dist",+ "outDir": "./dist",+ "rootDir": "./src",+ "strict": true,+ "esModuleInterop": true,+ "moduleResolution": "node",+ "skipLibCheck": true,+ "resolveJsonModule": true+ },+ "include": ["src"]+}diff --git a/packages/core/src/models/CustomTools.ts b/packages/core/src/models/CustomTools.tsindex 492862543..218ed6fb0 100644--- a/packages/core/src/models/CustomTools.ts+++ b/packages/core/src/models/CustomTools.ts@@ -7,15 +7,13 @@*/import ComposioClient from '@composio/client';import {- CustomToolInput,CustomToolInputParameter,CustomToolOptions,CustomToolRegistry,- ExecuteMetadata,InputParamsSchema,} from '../types/customTool.types';import zodToJsonSchema from 'zod-to-json-schema';-import { Tool, ToolExecuteResponse, ToolList } from '../types/tool.types';+import { Tool, ToolExecuteParams, ToolExecuteResponse, ToolList } from '../types/tool.types';import { ToolProxyParams } from '@composio/client/resources/tools';import logger from '../utils/logger';import {@@ -25,6 +23,11 @@ import {import { ComposioConnectedAccountNotFoundError } from '../errors/ConnectedAccountsErrors';import { ComposioError } from '../errors/ComposioError';import { telemetry } from '../telemetry/Telemetry';+import {+ ConnectedAccountRetrieveResponse,+ ConnectedAccountRetrieveResponseSchema,+} from '../types/connectedAccounts.types';+import { ValidationError } from '../errors';export class CustomTools {private readonly client: ComposioClient;@@ -44,7 +47,7 @@ export class CustomTools {* This is just an in memory registry and is not persisted.* @param {CustomToolOptions} toolOptions CustomToolOptions* @returns {Tool} The tool created- *+ ** @example* ```typescript* // Create a custom tool with input parameters@@ -65,7 +68,9 @@ export class CustomTools {* });* ```*/- async createTool(toolOptions: CustomToolOptions): Promise<Tool> {+ async createTool<T extends CustomToolInputParameter>(+ toolOptions: CustomToolOptions<T>+ ): Promise<Tool> {const { slug, execute, inputParams, name, description } = toolOptions;if (!slug || !execute || !inputParams || !name) {throw new Error('Invalid tool options');@@ -93,11 +98,13 @@ export class CustomTools {properties: {},},tags: [],+ // this is never set to the user provided toolkitslug so that we can differentiate+ // the toolkitslug is used via the execute function.toolkit: { name: 'custom', slug: 'custom' },};this.customToolsRegistry.set(slug.toLowerCase(), {- options: toolOptions,+ options: toolOptions as unknown as CustomToolOptions<CustomToolInputParameter>,schema: toolSchema,});return toolSchema;@@ -107,12 +114,12 @@ export class CustomTools {* Get all the custom tools from the registry.* @param {string[]} param0.toolSlugs The slugs of the tools to get* @returns {ToolList} The list of tools- *+ ** @example* ```typescript* // Get all custom tools* const allTools = await composio.customTools.getCustomTools({});- *+ ** // Get specific custom tools by slug* const specificTools = await composio.customTools.getCustomTools({* toolSlugs: ['MY_CUSTOM_TOOL', 'ANOTHER_CUSTOM_TOOL']@@ -142,7 +149,7 @@ export class CustomTools {* Get a custom tool by slug from the registry.* @param {string} slug The slug of the tool to get* @returns {Tool} The tool- *+ ** @example* ```typescript* // Get a specific custom tool by its slug@@ -174,7 +181,11 @@ export class CustomTools {* @param {ExecuteMetadata} metadata The metadata of the execution* @returns {ConnectedAccount} The connected account*/- private async getConnectedAccount(toolkitSlug: string, metadata: ExecuteMetadata) {+ private async getConnectedAccountForToolkit(+ toolkitSlug: string,+ userId: string,+ connectedAccountId?: string+ ): Promise<ConnectedAccountRetrieveResponse> {try {await this.client.toolkits.retrieve(toolkitSlug);} catch (error) {@@ -184,7 +195,7 @@ export class CustomTools {}const connectedAccounts = await this.client.connectedAccounts.list({toolkit_slugs: [toolkitSlug],- user_ids: [metadata.userId],+ user_ids: [userId],});if (!connectedAccounts.items.length) {@@ -192,46 +203,96 @@ export class CustomTools {`No connected accounts found for toolkit ${toolkitSlug}`);}-- return metadata.connectedAccountId- ? connectedAccounts.items.find(item => item.id === metadata.connectedAccountId)+ // if a connected account id is provided, use it, otherwise use the first connected account+ const connectedAccount = connectedAccountId+ ? connectedAccounts.items.find(item => item.id === connectedAccountId): connectedAccounts.items[0];++ if (!connectedAccount) {+ throw new ComposioConnectedAccountNotFoundError(+ `Connected account not found for toolkit ${toolkitSlug} for user ${userId}`+ );+ }++ const connectedAccountResponse = await ConnectedAccountRetrieveResponseSchema.safeParse({+ id: connectedAccount.id,+ authConfig: {+ id: connectedAccount.auth_config.id,+ authScheme: connectedAccount.auth_config.auth_scheme,+ isComposioManaged: connectedAccount.auth_config.is_composio_managed,+ isDisabled: connectedAccount.auth_config.is_disabled,+ },+ userId: connectedAccount.user_id,+ data: connectedAccount.data || {},+ status: connectedAccount.status,+ statusReason: connectedAccount.status_reason,+ toolkit: {+ slug: connectedAccount.toolkit.slug,+ },+ testRequestEndpoint: connectedAccount.test_request_endpoint,+ isDisabled: connectedAccount.is_disabled,+ createdAt: connectedAccount.created_at,+ updatedAt: connectedAccount.updated_at,+ });++ if (!connectedAccountResponse.success) {+ throw new ValidationError(+ `Validation error for connected account of ${toolkitSlug} for user ${userId}`,+ {+ cause: connectedAccountResponse.error,+ }+ );+ }++ return connectedAccountResponse.data;}/*** Execute a custom tool+ *+ * @description If a toolkit is used, the connected account id is used to execute the tool.+ * If a connected account id is provided, it is used to execute the tool.+ * If a connected account id is not provided, the first connected account for the toolkit is used.+ ** @param {slug} slug The slug of the tool to execute* @param {Record<string, unknown>} inputParams The input parameters for the tool* @param {ExecuteMetadata} metadata The metadata of the execution* @returns {Promise<ToolExecuteResponse>} The response from the tool*/- async executeCustomTool(- slug: string,- inputParams: Record<string, unknown>,- metadata: ExecuteMetadata- ): Promise<ToolExecuteResponse> {+ async executeCustomTool(slug: string, body: ToolExecuteParams): Promise<ToolExecuteResponse> {const tool = this.customToolsRegistry.get(slug.toLowerCase());if (!tool) {throw new ComposioToolNotFoundError(`Tool with slug ${slug} not found`);}let authCredentials: Record<string, unknown> = {};- const { toolkitSlug, execute } = tool.options;+ const { toolkitSlug, execute, inputParams } = tool.options;// if a toolkit is used, get the connected account, and auth credentials+ let connectedAccountId: string | undefined = body.connectedAccountId;+if (toolkitSlug && toolkitSlug !== 'custom') {- const connectedAccount = await this.getConnectedAccount(toolkitSlug, metadata);+ const connectedAccount = await this.getConnectedAccountForToolkit(+ toolkitSlug,+ body.userId,+ body.connectedAccountId+ );+ logger.debug(+ `[CustomTool] Connected account for ${toolkitSlug} found for user ${body.userId}`,+ JSON.stringify(connectedAccount, null, 2)+ );if (!connectedAccount) {throw new ComposioConnectedAccountNotFoundError(- `Connected account not found for toolkit ${toolkitSlug} for user ${metadata.userId}`,+ `Connected account not found for toolkit ${toolkitSlug} for user ${body.userId}`,{meta: {toolkitSlug,- userId: metadata.userId,+ userId: body.userId,},});}- authCredentials = connectedAccount.data?.connectionParams as Record<string, unknown>;+ authCredentials = connectedAccount.data as Record<string, unknown>;+ connectedAccountId = connectedAccount.id;}if (typeof execute !== 'function') {@@ -242,17 +303,40 @@ export class CustomTools {});}// create a tool proxy request for users to execute in case of a toolkit being used- const executeToolRequest = async (data: ToolProxyParams) => {- return this.client.tools.proxy({+ const executeToolRequest = async (data: ToolProxyParams): Promise<ToolExecuteResponse> => {+ if (toolkitSlug && toolkitSlug === 'custom') {+ throw new ComposioInvalidExecuteFunctionError(+ 'Custom tools without a toolkit cannot be executed using the executeToolRequest function',+ {+ possibleFixes: [+ 'Please manually execute the tool using your logic.',+ 'Pass a toolkit slug to execute the tool on behalf of a toolkit credentials',+ ],+ }+ );+ }+ const response = await this.client.tools.proxy({...data,- connected_account_id: metadata.connectedAccountId,+ connected_account_id: connectedAccountId,});++ return {+ data: response.data as Record<string, unknown>,+ error: null,+ successful: true,+ logId: undefined,+ sessionInfo: undefined,+ };};- return execute(- inputParams as CustomToolInput<CustomToolInputParameter>,- authCredentials,- executeToolRequest- );+ // Parse and validate the input using the tool's schema+ const parsedInput = inputParams.safeParse(body.arguments);+ if (!parsedInput.success) {+ throw new ValidationError('Invalid input parameters', {+ cause: parsedInput.error,+ });+ }++ return execute(parsedInput.data, authCredentials, executeToolRequest);}}diff --git a/packages/core/src/models/Tools.ts b/packages/core/src/models/Tools.tsindex a28568e7b..1b44a87a2 100644--- a/packages/core/src/models/Tools.ts+++ b/packages/core/src/models/Tools.ts@@ -20,7 +20,7 @@ import {ToolExecuteResponse as ComposioToolExecuteResponse,} from '@composio/client/resources/tools';import { CustomTools } from './CustomTools';-import { CustomToolOptions } from '../types/customTool.types';+import { CustomToolInputParameter, CustomToolOptions } from '../types/customTool.types';import {ExecuteToolModifiers,ProviderOptions,@@ -343,7 +343,10 @@ export class Tools<// check if the tool is a custom toolconst customTool = await this.customTools.getCustomToolBySlug(slug);if (customTool) {+ logger.debug(`Found ${slug} to be a custom tool`, JSON.stringify(customTool, null, 2));return customTool;+ } else {+ logger.debug(`Tool ${slug} is not a custom tool. Fetching from Composio API`);}// if not, fetch the tool from the Composio APIlet tool: ToolRetrieveResponse;@@ -499,10 +502,7 @@ export class Tools<}}- let result = await this.customTools.executeCustomTool(tool.slug, body, {- userId: body.userId || 'default',- connectedAccountId: body.connectedAccountId,- });+ let result = await this.customTools.executeCustomTool(tool.slug, body);if (modifiers?.afterExecute) {if (typeof modifiers.afterExecute === 'function') {@@ -665,7 +665,7 @@ export class Tools<* @param {string} slug - The ID of the tool to find input for* @param {ToolGetInputParams} body - The parameters to be passed to the tool* @returns {Promise<ToolGetInputResponse>} The input parameters schema for the specified tool- *+ ** @example* ```typescript* // Get input parameters for a specific tool@@ -681,13 +681,13 @@ export class Tools</*** Proxies a custom request to a toolkit/integration.- *+ ** This method allows sending custom requests to a specific toolkit or integration* when you need more flexibility than the standard tool execution methods provide.** @param {ToolProxyParams} body - The parameters for the proxy request including toolkit slug and custom data* @returns {Promise<ToolProxyResponse>} The response from the proxied request- *+ ** @example* ```typescript* // Send a custom request to a toolkit@@ -717,31 +717,43 @@ export class Tools<** @example* ```typescript- * const customTool = await composio.tools.createCustomTool({+ * // creating a custom tool with a toolkit+ * await composio.tools.createCustomTool({* name: 'My Custom Tool',* description: 'A custom tool that does something specific',* slug: 'MY_CUSTOM_TOOL',- * inputParameters: {- * param1: {- * type: 'string',- * description: 'First parameter',- * required: true- * }- * },- * outputParameters: {- * result: {- * type: 'string',- * description: 'The result of the operation'- * }- * },- * handler: async (params, context) => {+ * userId: 'default',+ * connectedAccountId: '123',+ * toolkitSlug: 'github',+ * inputParameters: z.object({+ * param1: z.string().describe('First parameter'),+ * }),+ * execute: async (input, authCredentials, executeToolRequest) => {* // Custom logic here* return { data: { result: 'Success!' } };* }* });* ```+ *+ * @example+ * ```typescript+ * // creating a custom tool without a toolkit+ * await composio.tools.createCustomTool({+ * name: 'My Custom Tool',+ * description: 'A custom tool that does something specific',+ * slug: 'MY_CUSTOM_TOOL',+ * inputParameters: z.object({+ * param1: z.string().describe('First parameter'),+ * }),+ * execute: async (input) => {+ * // Custom logic here+ * return { data: { result: 'Success!' } };+ * }+ * });*/- async createCustomTool(body: CustomToolOptions): Promise<Tool> {+ async createCustomTool<T extends CustomToolInputParameter>(+ body: CustomToolOptions<T>+ ): Promise<Tool> {return this.customTools.createTool(body);}}diff --git a/packages/core/src/types/customTool.types.ts b/packages/core/src/types/customTool.types.tsindex f81a1ad4b..cbc3f90f5 100644--- a/packages/core/src/types/customTool.types.ts+++ b/packages/core/src/types/customTool.types.ts@@ -1,48 +1,51 @@-import { z, ZodObject, ZodString, ZodNumber, ZodBoolean, ZodOptional } from 'zod';-import { Tool, ToolExecuteResponse } from './tool.types';-import { ToolProxyParams, ToolProxyResponse } from '@composio/client/resources/tools';-import { JsonSchema7Type } from 'zod-to-json-schema';--export type CustomToolInputParameter = ZodObject<{- [key: string]:- | ZodString- | ZodNumber- | ZodBoolean- | ZodOptional<ZodString | ZodNumber | ZodBoolean>;-}>;--export type CustomToolInput<T extends CustomToolInputParameter> = {- [K in keyof z.infer<T>]: z.infer<T>[K];-};+import { z } from 'zod';+import { Tool } from './tool.types';+import { ToolExecuteResponse, ToolProxyParams } from '@composio/client/resources/tools';-export interface CustomToolOptions<T extends CustomToolInputParameter = CustomToolInputParameter> {- slug: string;+type BaseCustomToolOptions<T extends z.ZodType> = {name: string;- toolkitSlug?: string | null;description?: string;+ slug: string;inputParams: T;+};++type ToolkitBasedExecute<T extends z.ZodType> = {execute: (- input: CustomToolInput<T>,- authCredentials?: Record<string, unknown>,- executeAppRequest?: (data: ToolProxyParams) => Promise<ToolProxyResponse>+ input: z.infer<T>,+ authCredentials: Record<string, unknown>,+ executeToolRequest: (data: ToolProxyParams) => Promise<ToolExecuteResponse>) => Promise<ToolExecuteResponse>;-}+ toolkitSlug: string;+};++type StandaloneExecute<T extends z.ZodType> = {+ execute: (input: z.infer<T>) => Promise<ToolExecuteResponse>;+ toolkitSlug?: never;+};++export type CustomToolOptions<T extends z.ZodType> = BaseCustomToolOptions<T> &+ (ToolkitBasedExecute<T> | StandaloneExecute<T>);export type CustomToolRegistry = Map<string,- {- options: CustomToolOptions;- schema: Tool;- }+ { options: CustomToolOptions<CustomToolInputParameter>; schema: Tool }>;-export interface InputParamsSchema {+export type InputParamsSchema = {definitions: {input: {- properties: Record<string, JsonSchema7Type>;+ type: string;+ properties: Record<string, unknown>;required?: string[];};};+};++export type CustomToolInputParameter = z.ZodType;++export interface CustomToolRegistryItem {+ options: CustomToolOptions<CustomToolInputParameter>;+ schema: Tool;}export interface ExecuteMetadata {diff --git a/packages/core/test/tools/customTools.test.ts b/packages/core/test/tools/customTools.test.tsindex bdf039bb4..613eff89e 100644--- a/packages/core/test/tools/customTools.test.ts+++ b/packages/core/test/tools/customTools.test.ts@@ -4,6 +4,9 @@ import { mockClient } from '../utils/mocks/client.mock';import { toolMocks } from '../utils/mocks/data.mock';import ComposioClient from '@composio/client';import { z } from 'zod';+import { ComposioToolNotFoundError } from '../../src/errors/ToolErrors';+import { ComposioConnectedAccountNotFoundError } from '../../src/errors/ConnectedAccountsErrors';+import { ValidationError } from '../../src/errors';describe('CustomTools', () => {let customTools: CustomTools;@@ -89,61 +92,168 @@ describe('CustomTools', () => {});describe('executeCustomTool', () => {+ const executeParams = {+ arguments: { query: 'test query' },+ userId: 'test-user',+ };+it('should execute a custom tool with provided parameters', async () => {// Add a tool to the registryawait customTools.createTool(toolOptions);- const inputParams = { query: 'test query' };- const metadata = { userId: 'test-user' };-- const result = await customTools.executeCustomTool(toolOptions.slug, inputParams, metadata);+ const result = await customTools.executeCustomTool(toolOptions.slug, executeParams);- expect(toolOptions.execute).toHaveBeenCalledWith(inputParams, {}, expect.any(Function));+ expect(toolOptions.execute).toHaveBeenCalledWith(+ executeParams.arguments,+ {},+ 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`);+ await expect(customTools.executeCustomTool(nonExistentSlug, executeParams)).rejects.toThrow(+ ComposioToolNotFoundError+ );});- it('should fetch auth credentials for toolkit-based custom tools', async () => {- // Add a toolkit-based tool+ it('should throw validation error for invalid input parameters', async () => {+ await customTools.createTool(toolOptions);+ const invalidParams = {+ ...executeParams,+ arguments: { invalidField: 'test' },+ };++ await expect(customTools.executeCustomTool(toolOptions.slug, invalidParams)).rejects.toThrow(+ ValidationError+ );+ });++ describe('toolkit-based custom tools', () => {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 mockConnectedAccount = {+ id: 'conn-123',+ auth_config: {+ id: 'auth-123',+ auth_scheme: 'OAUTH2',+ is_composio_managed: true,+ is_disabled: false,+ },+ user_id: 'test-user',+ data: {+ apiKey: 'test-key',+ },+ status: 'ACTIVE',+ status_reason: null,+ toolkit: {+ slug: 'TEST_TOOLKIT',+ },+ test_request_endpoint: 'https://api.test.com',+ is_disabled: false,+ created_at: '2024-01-01T00:00:00Z',+ updated_at: '2024-01-01T00:00:00Z',+ };++ beforeEach(async () => {+ await customTools.createTool(toolkitTool);+ mockClient.toolkits.retrieve.mockResolvedValue({ slug: 'TEST_TOOLKIT' });});- const inputParams = { query: 'test query' };- const metadata = { userId: 'test-user' };+ it('should fetch and use auth credentials for toolkit-based custom tools', async () => {+ mockClient.connectedAccounts.list.mockResolvedValueOnce({+ items: [mockConnectedAccount],+ totalPages: 1,+ });- await customTools.executeCustomTool(toolkitTool.slug, inputParams, metadata);+ await customTools.executeCustomTool(toolkitTool.slug, executeParams);- expect(toolkitTool.execute).toHaveBeenCalledWith(- inputParams,- { apiKey: 'test-key' },- expect.any(Function)- );+ expect(toolkitTool.execute).toHaveBeenCalledWith(+ executeParams.arguments,+ mockConnectedAccount.data,+ expect.any(Function)+ );+ });++ it('should use specified connected account when connectedAccountId is provided', async () => {+ const specificConnectedAccountId = 'conn-456';+ const specificConnectedAccount = {+ ...mockConnectedAccount,+ id: specificConnectedAccountId,+ };++ mockClient.connectedAccounts.list.mockResolvedValueOnce({+ items: [mockConnectedAccount, specificConnectedAccount],+ totalPages: 1,+ });++ await customTools.executeCustomTool(toolkitTool.slug, {+ ...executeParams,+ connectedAccountId: specificConnectedAccountId,+ });++ expect(toolkitTool.execute).toHaveBeenCalledWith(+ executeParams.arguments,+ specificConnectedAccount.data,+ expect.any(Function)+ );+ });++ it('should throw error when toolkit is not found', async () => {+ mockClient.toolkits.retrieve.mockRejectedValueOnce(new Error('Toolkit not found'));++ await expect(+ customTools.executeCustomTool(toolkitTool.slug, executeParams)+ ).rejects.toThrow(ComposioToolNotFoundError);+ });++ it('should throw error when no connected accounts are found', async () => {+ mockClient.connectedAccounts.list.mockResolvedValueOnce({+ items: [],+ totalPages: 1,+ });++ await expect(+ customTools.executeCustomTool(toolkitTool.slug, executeParams)+ ).rejects.toThrow(ComposioConnectedAccountNotFoundError);+ });++ it('should throw error when specified connected account is not found', async () => {+ mockClient.connectedAccounts.list.mockResolvedValueOnce({+ items: [mockConnectedAccount],+ totalPages: 1,+ });++ await expect(+ customTools.executeCustomTool(toolkitTool.slug, {+ ...executeParams,+ connectedAccountId: 'non-existent-id',+ })+ ).rejects.toThrow(ComposioConnectedAccountNotFoundError);+ });++ it('should throw error when trying to use executeToolRequest with custom toolkit', async () => {+ const customToolkitTool = {+ ...toolOptions,+ toolkitSlug: 'custom',+ execute: async (input: any, auth: any, executeToolRequest: any) => {+ return executeToolRequest({ slug: 'TEST_TOOL', arguments: {} });+ },+ };++ await customTools.createTool(customToolkitTool);++ await expect(+ customTools.executeCustomTool(customToolkitTool.slug, executeParams)+ ).rejects.toThrow(+ 'Custom tools without a toolkit cannot be executed using the executeToolRequest function'+ );+ });});});});diff --git a/packages/core/test/tools/tools.test.ts b/packages/core/test/tools/tools.test.tsindex 26b04b96c..c54793131 100644--- a/packages/core/test/tools/tools.test.ts+++ b/packages/core/test/tools/tools.test.ts@@ -346,7 +346,7 @@ describe('Tools', () => {const result = await context.tools.execute(slug, body);expect(getCustomToolBySlugSpy).toHaveBeenCalledWith(slug);- expect(executeCustomToolSpy).toHaveBeenCalledWith(slug, body, expect.any(Object));+ expect(executeCustomToolSpy).toHaveBeenCalledWith(slug, body);expect(result).toEqual(toolMocks.toolExecuteResponse);});diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 3f8afee92..5241634d8 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -89,6 +89,25 @@ importers:specifier: ^5.8.3version: 5.8.3+ examples/custom-tools:+ dependencies:+ '@composio/core':+ specifier: workspace:*+ version: link:../../packages/core+ dotenv:+ specifier: ^16.4.1+ version: 16.5.0+ zod:+ specifier: ^3.24.2+ version: 3.24.4+ devDependencies:+ '@types/bun':+ specifier: ^1.2.9+ version: 1.2.13+ typescript:+ specifier: ^5.8.3+ version: 5.8.3+examples/error-handling-demo:dependencies:'@composio/core':