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
Custom tools documentation and types
haxzie39e2935215ed
diff --git a/docs/api/custom-tools.md b/docs/api/custom-tools.mdindex 842a1dae0..54161b9ec 100644--- a/docs/api/custom-tools.md+++ b/docs/api/custom-tools.md@@ -34,33 +34,43 @@ const tool = await composio.tools.createCustomTool({A toolkit-based tool has access to two ways of making authenticated requests:-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:+1. Using `executeToolRequest` - The recommended way to make authenticated requests to the toolkit's API endpoints. Composio automatically handles credential injection and baseURL resolution:```typescriptconst tool = await composio.tools.createCustomTool({- slug: 'GITHUB_STAR_COMPOSIO_REPOSITORY',- name: 'Star Composios Repository',- description: 'Stars a repository under composiohq org',+ slug: 'GITHUB_STAR_COMPOSIOHQ_REPOSITORY',+ 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('Name of the repository to star'),+ repository: z.string().describe('The repository to star'),+ page: z.number().optional().describe('Page number for pagination'),+ customHeader: z.string().optional().describe('Custom header value'),}),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}`,+ // You can use relative paths - Composio will automatically inject the baseURL+ const result = await executeToolRequest({+ endpoint: `/user/starred/composiohq/${input.repository}`,method: 'PUT',body: {},+ // Add custom headers or query parameters+ parameters: [+ // Add query parameters+ {+ name: 'page',+ value: input.page?.toString() || '1',+ in: 'query',+ },+ // Add custom headers+ {+ name: 'x-custom-header',+ value: input.customHeader || 'default-value',+ in: 'header',+ },+ ],});-- return {- data: {- message: 'Successfully stared repository',- },- error: null,- successful: true,- };+ return result;},});```@@ -76,7 +86,7 @@ const tool = await composio.tools.createCustomTool({inputParams: z.object({repo: z.string().describe('Repository name'),}),- execute: async (input, authCredentials) => {+ execute: async (input, authCredentials, executeToolRequest) => {// Use authCredentials for direct API callsconst result = await fetch(`https://api.github.com/repos/${input.repo}`, {headers: {@@ -93,6 +103,55 @@ const tool = await composio.tools.createCustomTool({});```+### Using Custom Headers and Query Parameters++You can add custom headers and query parameters to your toolkit-based tools using the `parameters` option in `executeToolRequest`:++```typescript+const tool = await composio.tools.createCustomTool({+ slug: 'GITHUB_SEARCH_REPOSITORIES',+ name: 'Search GitHub Repositories',+ description: 'Search for repositories with custom parameters',+ toolkitSlug: 'github',+ inputParams: z.object({+ query: z.string().describe('Search query'),+ perPage: z.number().optional().describe('Results per page'),+ acceptType: z.string().optional().describe('Custom accept header'),+ }),+ execute: async (input, authCredentials, executeToolRequest) => {+ const result = await executeToolRequest({+ endpoint: '/search/repositories',+ method: 'GET',+ parameters: [+ // Add query parameters for pagination+ {+ name: 'q',+ value: input.query,+ in: 'query',+ },+ {+ name: 'per_page',+ value: (input.perPage || 30).toString(),+ in: 'query',+ },+ // Add custom headers+ {+ name: 'Accept',+ value: input.acceptType || 'application/vnd.github.v3+json',+ in: 'header',+ },+ {+ name: 'X-Custom-Header',+ value: 'custom-value',+ in: 'header',+ },+ ],+ });+ return result;+ },+});+```+## Executing Custom ToolsYou can execute custom tools just like any other tool:@@ -123,6 +182,14 @@ The custom tools implementation provides full type safety:3. Handle errors gracefully in your execute function4. For toolkit-based tools:- Prefer `executeToolRequest` over direct API calls when possible+ - Use relative paths with `executeToolRequest` - Composio will automatically inject the correct baseURL+ - Use the `parameters` option to add custom headers or query parameters:+ ```typescript+ parameters: [+ { name: 'page', value: '1', in: 'query' }, // Adds ?page=1 to URL+ { name: 'x-custom', value: 'value', in: 'header' }, // Adds header+ ];+ ```- 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 servicesdiff --git a/examples/custom-tools/src/index.ts b/examples/custom-tools/src/index.tsindex 5119144fb..836419505 100644--- a/examples/custom-tools/src/index.ts+++ b/examples/custom-tools/src/index.ts@@ -37,7 +37,7 @@ const tool = await composio.tools.createCustomTool({console.log('🚀 ~ execute: ~ authCredentials:', authCredentials);const result = await executeToolRequest({- endpoint: `https://api.github.com/user/starred/composiohq/${input.repository}`,+ endpoint: `/user/starred/composiohq/${input.repository}`,method: 'PUT',body: {},});diff --git a/packages/core/src/models/CustomTools.ts b/packages/core/src/models/CustomTools.tsindex 218ed6fb0..90f46d979 100644--- a/packages/core/src/models/CustomTools.ts+++ b/packages/core/src/models/CustomTools.ts@@ -13,8 +13,13 @@ import {InputParamsSchema,} from '../types/customTool.types';import zodToJsonSchema from 'zod-to-json-schema';-import { Tool, ToolExecuteParams, ToolExecuteResponse, ToolList } from '../types/tool.types';-import { ToolProxyParams } from '@composio/client/resources/tools';+import {+ Tool,+ ToolExecuteParams,+ ToolExecuteResponse,+ ToolList,+ ToolProxyParams,+} from '../types/tool.types';import logger from '../utils/logger';import {ComposioInvalidExecuteFunctionError,@@ -315,9 +320,20 @@ export class CustomTools {});}+ // map the parameters to the composio format+ const parameters = data.parameters?.map(param => ({+ name: param.name,+ type: param.in,+ value: param.value.toString(),+ }));++ // execute the toolconst response = await this.client.tools.proxy({- ...data,- connected_account_id: connectedAccountId,+ endpoint: data.endpoint,+ method: data.method,+ parameters: parameters,+ body: data.body,+ connected_account_id: data.connectedAccountId ?? connectedAccountId,});return {diff --git a/packages/core/src/models/Tools.ts b/packages/core/src/models/Tools.tsindex 1b44a87a2..b881e7e93 100644--- a/packages/core/src/models/Tools.ts+++ b/packages/core/src/models/Tools.ts@@ -8,11 +8,13 @@ import {ToolSchema,ToolListParams,ToolExecuteResponseSchema,+ ToolProxyParamsSchema,+ ToolProxyParams,} from '../types/tool.types';import {ToolGetInputParams,ToolGetInputResponse,- ToolProxyParams,+ ToolProxyParams as ComposioToolProxyParams,ToolProxyResponse,ToolRetrieveEnumResponse,ToolRetrieveResponse,@@ -703,7 +705,35 @@ export class Tools<* ```*/async proxyExecute(body: ToolProxyParams): Promise<ToolProxyResponse> {- return this.client.tools.proxy(body);+ const toolProxyParams = ToolProxyParamsSchema.safeParse(body);+ if (!toolProxyParams.success) {+ throw new ValidationError('Invalid tool proxy parameters', { cause: toolProxyParams.error });+ }+ // convert the headers and query to the composio format+ // { name: string, type: 'header' | 'query', value: string }+ const parameters: ComposioToolProxyParams.Parameter[] = [];+ const parameterTypes = {+ header: 'header',+ query: 'query',+ } as const;++ if (toolProxyParams.data.parameters) {+ parameters.push(+ ...Object.entries(toolProxyParams.data.parameters).map(([key, value]) => ({+ name: key,+ type: value.in === 'header' ? parameterTypes.header : parameterTypes.query,+ value: value.value.toString(),+ }))+ );+ }++ return this.client.tools.proxy({+ endpoint: toolProxyParams.data.endpoint,+ method: toolProxyParams.data.method,+ body: toolProxyParams.data.body,+ connected_account_id: toolProxyParams.data.connectedAccountId,+ parameters: parameters,+ });}/**diff --git a/packages/core/src/provider/BaseProvider.ts b/packages/core/src/provider/BaseProvider.tsindex 1183586cb..051c5a02d 100644--- a/packages/core/src/provider/BaseProvider.ts+++ b/packages/core/src/provider/BaseProvider.ts@@ -39,10 +39,11 @@ abstract class BaseProvider {/*** @public* Global function to execute a tool.- * This function is used by provider providers to implement helper functions to execute tools.+ * This function is used by providerds to implement helper functions to execute tools.* This is a 1:1 mapping of the `execute` method in the `Tools` class.* @param {string} toolSlug - The slug of the tool to execute.- * @param {Record<string, unknown>} input - The input to the tool.+ * @param {ToolExecuteParams} body - The body of the tool execution.+ * @param {ExecuteToolModifiers} modifers - The modifiers of the tool execution.* @returns {Promise<string>} The result of the tool execution.*/executeTool(diff --git a/packages/core/src/types/customTool.types.ts b/packages/core/src/types/customTool.types.tsindex cbc3f90f5..787686597 100644--- a/packages/core/src/types/customTool.types.ts+++ b/packages/core/src/types/customTool.types.ts@@ -1,6 +1,6 @@import { z } from 'zod';-import { Tool } from './tool.types';-import { ToolExecuteResponse, ToolProxyParams } from '@composio/client/resources/tools';+import { Tool, ToolProxyParams } from './tool.types';+import { ToolExecuteResponse } from '@composio/client/resources/tools';type BaseCustomToolOptions<T extends z.ZodType> = {name: string;diff --git a/packages/core/src/types/tool.types.ts b/packages/core/src/types/tool.types.tsindex aad49ef63..1fc5bbdb6 100644--- a/packages/core/src/types/tool.types.ts+++ b/packages/core/src/types/tool.types.ts@@ -179,3 +179,18 @@ export const ToolExecuteResponseSchema = z.object({sessionInfo: z.unknown().optional(),});export type ToolExecuteResponse = z.infer<typeof ToolExecuteResponseSchema>;++export const ToolProxyParamsSchema = z.object({+ endpoint: z.string(),+ method: z.enum(['GET', 'POST', 'PUT', 'DELETE', 'PATCH']),+ body: z.unknown().optional(),+ parameters: z.array(+ z.object({+ in: z.enum(['query', 'header']),+ name: z.string(),+ value: z.union([z.string(), z.number()]),+ })+ ),+ connectedAccountId: z.string().optional(),+});+export type ToolProxyParams = z.infer<typeof ToolProxyParamsSchema>;