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
import ComposioClient from '@composio/client';
import { FileToolModifier } from '#file_tool_modifier';
import {
Tool,
ToolExecuteParams,
ToolListParamsSchema,
ToolExecuteResponse,
ToolList,
ToolSchema,
ToolListParams,
ToolExecuteResponseSchema,
ToolProxyParamsSchema,
ToolProxyParams,
ToolExecuteParamsSchema,
ToolkitVersionParam,
SchemaModifierOptions,
ToolRetrievalOptions,
ToolExecuteMetaParams,
ToolExecuteMetaParamsSchema,
} from '../types/tool.types';
import {
ToolGetInputParams,
ToolGetInputResponse,
ToolProxyParams as ComposioToolProxyParams,
ToolProxyResponse,
ToolRetrieveEnumResponse,
ToolRetrieveResponse,
ToolListResponse as ComposioToolListResponse,
ToolExecuteResponse as ComposioToolExecuteResponse,
ToolListParams as ComposioToolListParams,
ToolExecuteParams as ComposioToolExecuteParams,
} from '@composio/client/resources/tools';
import {
afterExecuteModifier,
ExecuteToolModifiers,
SessionExecuteMetaModifiers,
ProviderOptions,
TransformToolSchemaModifier,
} from '../types/modifiers.types';
import type { BaseComposioProvider } from '../provider/BaseProvider';
import logger from '../utils/logger';
import { ExecuteToolFn, GlobalExecuteToolFn } from '../types/provider.types';
import {
ComposioInvalidModifierError,
ComposioToolNotFoundError,
ComposioProviderNotDefinedError,
ComposioToolVersionRequiredError,
} from '../errors/ToolErrors';
import { ValidationError } from '../errors/ValidationErrors';
import { telemetry } from '../telemetry/Telemetry';
import type { ComposioConfig } from '../composio';
import { getToolkitVersion } from '../utils/toolkitVersion';
import { handleToolExecutionError } from '../errors/ToolErrors';
import type { SessionExecuteParams } from '@composio/client/resources/tool-router/session/session.mjs';
import { CONFIG_DEFAULTS } from '../utils/config-defaults';
import { resolveEffectiveUploadAllowlist } from '../utils/fileDirs';
import {
dropEmptyFileUploads,
schemaHasFileUploadable,
} from '../utils/modifiers/FileToolModifier.utils.neutral';
import { dereferenceJsonSchema } from '../utils/jsonSchema';
import { ComposioRequestOptions } from '../types/requestOptions.types';
import { withCancellation } from '../utils/cancellation';
import { ComposioRequestCancelledError } from '../errors/SDKErrors';
const TOOL_ROUTER_SESSION_TOOLS_PAGE_LIMIT = 500;
type ToolRouterSessionExecuteOptions = {
experimental?: SessionExecuteParams.Experimental;
};
type RawToolParameters =
| ToolRetrieveResponse['input_parameters']
| ComposioToolListResponse['items'][0]['input_parameters'];
/**
* Normalize a raw `input_parameters` / `output_parameters` payload returned by
* the Composio API. Maps `null`, `undefined`, and empty `{}` — all of which
* mean "no declared schema" — to `undefined` so the strict `ParametersSchema`
* validator never sees them. Non-empty objects pass through unchanged and
* remain subject to strict Zod validation.
*
* MCP-backed toolkits (granola_mcp, apify_mcp, tavily_mcp, …) have no
* declared output schema and the API serializes that as `{}`, which would
* otherwise trip `ParametersSchema`. See
* https://github.com/ComposioHQ/composio/issues/3354.
*/
function normalizeRawToolParameters(
params: RawToolParameters | null | undefined
): RawToolParameters | undefined {
if (params == null || Object.keys(params).length === 0) return undefined;
return params;
}
/**
* This class is used to manage tools in the Composio SDK.
* It provides methods to list, get, and execute tools.
*/
export class Tools<
TToolCollection,
TTool,
TProvider extends BaseComposioProvider<TToolCollection, TTool, unknown>,
> {
private client: ComposioClient;
private provider: TProvider;
private autoUploadDownloadFiles: boolean;
private toolkitVersions: ToolkitVersionParam;
private fileUploadPathOptions: {
sensitiveFileUploadProtection?: boolean;
fileUploadPathDenySegments?: string[];
fileUploadAllowlist?: string[];
fileDownloadDir?: string;
};
/**
* Tracks tool slugs we've already warned about to avoid spamming the log when
* the same file-input tool is executed repeatedly while auto-upload is off.
* Scoped per-instance so a fresh `Composio` starts with a clean slate.
*/
private readonly warnedAutoUploadDisabledForTool = new Set<string>();
/**
* Lazily-built sibling client with retries disabled; see `clientWithoutRetries`.
*/
private clientWithoutRetriesCache?: ComposioClient;
constructor(client: ComposioClient, config?: ComposioConfig<TProvider>) {
if (!client) {
throw new Error('ComposioClient is required');
}
if (!config?.provider) {
throw new ComposioProviderNotDefinedError('Provider not passed into Tools instance');
}
this.client = client;
this.provider = config.provider;
this.autoUploadDownloadFiles = config?.dangerouslyAllowAutoUploadDownloadFiles === true;
this.toolkitVersions = config?.toolkitVersions ?? CONFIG_DEFAULTS.toolkitVersions;
this.fileUploadPathOptions = {
sensitiveFileUploadProtection: config?.sensitiveFileUploadProtection,
fileUploadPathDenySegments: config?.fileUploadPathDenySegments,
// The allowlist is only enforced during automatic upload (see
// FileToolModifier). Manual `composio.files.upload()` calls don't see it.
fileUploadAllowlist: this.autoUploadDownloadFiles
? resolveEffectiveUploadAllowlist(config?.fileUploadDirs)
: undefined,
fileDownloadDir: config?.fileDownloadDir,
};
// Bind the execute method to ensure correct 'this' context
this.execute = this.execute.bind(this);
// Set the execute method for the provider.
this.provider._setExecuteToolFn(this.createExecuteFnForProviders());
this.getRawComposioToolBySlug = this.getRawComposioToolBySlug.bind(this);
this.getRawComposioTools = this.getRawComposioTools.bind(this);
telemetry.instrument(this, 'Tools');
}
/**
* A cached sibling client that never retries requests, mirroring Python's
* `client.without_retries`.
*
* Used for non-idempotent writes (`tools.execute` / `tools.proxy`), where a
* silent retry after a read timeout can duplicate a side effect (e.g. send an
* email twice). Reads keep the default retry behaviour, and so do other writes
* (`toolRouter.session.execute`, auth-config and connected-account mutations):
* the durable fix there is backend-honoured idempotency keys, tracked
* separately.
*
* Cached rather than rebuilt per call because `withOptions` constructs a fresh
* client; its options never change, so one per `Tools` instance suffices.
*/
private get clientWithoutRetries(): ComposioClient {
if (!this.clientWithoutRetriesCache) {
this.clientWithoutRetriesCache = this.client.withOptions({ maxRetries: 0 });
}
return this.clientWithoutRetriesCache;
}
/**
* Transforms tool data from snake_case API format to camelCase for internal SDK use.
*
* This method standardizes the property naming convention for tools retrieved from the Composio API,
* making them more consistent with JavaScript/TypeScript conventions.
*
* @param {ToolRetrieveResponse | ComposioToolListResponse['items'][0]} tool - The tool object to transform
* @returns {Tool} The transformed tool with camelCase properties
*
* @private
*/
private transformToolCases(
tool: ToolRetrieveResponse | ComposioToolListResponse['items'][0]
): Tool {
return ToolSchema.parse({
...tool,
inputParameters: normalizeRawToolParameters(tool.input_parameters),
outputParameters: normalizeRawToolParameters(tool.output_parameters),
availableVersions: tool.available_versions,
isDeprecated: tool.deprecated?.is_deprecated ?? false,
isNoAuth: tool.no_auth,
});
}
/**
* Transforms tool execution response from snake_case API format to camelCase.
*
* This method converts the response received from the Composio API to a standardized format
* with consistent property naming that follows JavaScript/TypeScript conventions.
*
* @param {ComposioToolExecuteResponse} response - The raw API response to transform
* @returns {ToolExecuteResponse} The transformed response with camelCase properties
*
* @private
*/
private transformToolExecuteResponse(response: ComposioToolExecuteResponse): ToolExecuteResponse {
return ToolExecuteResponseSchema.parse({
data: response.data,
error: response.error,
successful: response.successful,
logId: response.log_id,
sessionInfo: response.session_info,
});
}
/**
* Applies the default schema modifiers to the tools.
*
* The `file_uploadable` transform (collapsing the backend's internal
* `{ name, mimetype, s3key }` staging shape to `{ type: 'string',
* format: 'path' }`) is **gated on `dangerouslyAllowAutoUploadDownloadFiles`**
* — the collapsed shape is a promise that the SDK will stage local paths
* on your behalf at execute time, and that's only true when the flag is on.
*
* When the flag is off, the raw schema is returned unchanged; callers are
* expected to stage files themselves via `composio.files.upload()` and pass
* the resulting descriptor into `tools.execute`. If an LLM ends up calling
* a file-uploadable tool in this mode, the execute path emits a one-shot
* warning per tool slug (see `applyBeforeExecuteModifiers`).
*
* @param tools - The tools to apply the default schema modifiers to
* @returns The tools with the default schema modifiers applied
*/
private async applyDefaultSchemaModifiers(tools: Tool[]): Promise<Tool[]> {
if (!this.autoUploadDownloadFiles) {
return tools;
}
const fileToolModifier = new FileToolModifier(this.client, this.fileUploadPathOptions);
return await Promise.all(tools.map(tool => fileToolModifier.modifyToolSchema(tool)));
}
/**
* Applies the before execute modifiers to the tool execution params
* @param options.toolSlug - The slug of the tool
* @param options.toolkitSlug - The slug of the toolkit
* @param options.params - The params of the tool execution
* @param modifier - The modifier to apply
* @returns The modified params
*/
private async applyBeforeExecuteModifiers(
tool: Tool,
{
toolSlug,
toolkitSlug,
params,
}: {
toolSlug: string;
toolkitSlug: string;
params: ToolExecuteParams;
},
modifiers?: ExecuteToolModifiers,
requestOptions?: ComposioRequestOptions
): Promise<ToolExecuteParams> {
if (requestOptions?.signal?.aborted) {
throw new ComposioRequestCancelledError();
}
let modifiedParams = await this.applyFileUploadModifiers(
tool,
{ toolSlug, toolkitSlug, params },
modifiers?.beforeFileUpload,
requestOptions
);
// apply the before execute modifiers
if (modifiers?.beforeExecute) {
if (typeof modifiers.beforeExecute === 'function') {
modifiedParams = await modifiers.beforeExecute({
toolSlug,
toolkitSlug,
params: modifiedParams,
});
if (requestOptions?.signal?.aborted) {
throw new ComposioRequestCancelledError();
}
} else {
throw new ComposioInvalidModifierError('Invalid beforeExecute modifier. Not a function.');
}
}
return modifiedParams;
}
/**
* Applies schema-aware file preprocessing shared by direct and Tool Router
* session execution. This always runs before the caller's `beforeExecute`
* hook so the hook observes the exact arguments sent to the backend.
*/
private async applyFileUploadModifiers(
tool: Tool,
{
toolSlug,
toolkitSlug,
params,
}: {
toolSlug: string;
toolkitSlug: string;
params: ToolExecuteParams;
},
beforeFileUpload?: ExecuteToolModifiers['beforeFileUpload'],
requestOptions?: ComposioRequestOptions
): Promise<ToolExecuteParams> {
let modifiedParams = params;
// if auto upload download files is enabled, upload the files to the Composio API
if (this.autoUploadDownloadFiles) {
const fileToolModifier = new FileToolModifier(this.client, {
...this.fileUploadPathOptions,
beforeFileUpload,
});
modifiedParams = await fileToolModifier.fileUploadModifier(tool, {
toolSlug,
toolkitSlug,
params: modifiedParams,
signal: requestOptions?.signal,
});
if (requestOptions?.signal?.aborted) {
throw new ComposioRequestCancelledError();
}
} else if (tool.inputParameters && schemaHasFileUploadable(tool.inputParameters)) {
// Auto-upload is opt-in, but "no file" must still be sent as an
// omitted key rather than `''`, which the backend rejects
// (https://github.com/ComposioHQ/composio/issues/4233).
if (modifiedParams.arguments) {
modifiedParams = {
...modifiedParams,
arguments: (await dropEmptyFileUploads(
modifiedParams.arguments,
dereferenceJsonSchema(tool.inputParameters, { onUnresolved: 'sentinel' })
)) as ToolExecuteParams['arguments'],
};
}
if (!this.warnedAutoUploadDisabledForTool.has(toolSlug)) {
// With auto-upload off, the raw `{ name, mimetype, s3key }` shape is
// what the LLM / caller sees on `tool.inputParameters`. LLMs can't
// produce a valid `s3key` and will hallucinate one, which then fails
// at the staging-lookup step on the backend. Nudge the caller toward
// manual staging or opting into auto-upload.
this.warnedAutoUploadDisabledForTool.add(toolSlug);
logger.warn(
`Tool "${toolSlug}" (toolkit "${toolkitSlug}") has a file-uploadable input, but ` +
`\`dangerouslyAllowAutoUploadDownloadFiles\` is disabled. The SDK will forward ` +
`the file argument as-is; if it isn't already a staged ` +
`{ name, mimetype, s3key } descriptor, the backend will reject the call. Either:\n` +
` 1) Stage the file yourself: \`const f = await composio.files.upload({ file, toolSlug, toolkitSlug }); ` +
`await composio.tools.execute('${toolSlug}', { userId, arguments: { <fileField>: f } })\`, or\n` +
` 2) Enable auto-upload with a scoped allowlist: ` +
`\`new Composio({ dangerouslyAllowAutoUploadDownloadFiles: true, fileUploadDirs: ['/safe/dir'] })\`.`
);
}
}
return modifiedParams;
}
/**
* Applies the after execute modifiers to the tool execution result
* @param options.toolSlug - The slug of the tool
* @param options.toolkitSlug - The slug of the toolkit
* @param options.result - The result of the tool execution
* @param modifier - The modifier to apply
* @returns The modified result
*/
private async applyAfterExecuteModifiers(
tool: Tool,
{
toolSlug,
toolkitSlug,
result,
}: {
toolSlug: string;
toolkitSlug: string;
result: ToolExecuteResponse;
},
modifier?: afterExecuteModifier,
requestOptions?: ComposioRequestOptions
): Promise<ToolExecuteResponse> {
// The tool already executed and may have mutated external state, so a late
// abort does NOT short-circuit post-processing: skipping the caller's
// afterExecute modifier here would leave a half-finished pipeline that
// still looks like success-shaped data. Once the remote call has committed
// we run file download + afterExecute to completion. The signal is still
// forwarded to the download so a stuck transfer degrades gracefully
// (file_downloaded: false) rather than blocking, but it never skips
// afterExecute.
let modifiedResult = result;
// if auto upload download files is enabled, download the files from the Composio API
if (this.autoUploadDownloadFiles) {
const fileToolModifier = new FileToolModifier(this.client, this.fileUploadPathOptions);
modifiedResult = await fileToolModifier.fileDownloadModifier(tool, {
toolSlug,
toolkitSlug,
result: modifiedResult,
signal: requestOptions?.signal,
});
}
// apply the after execute modifiers
if (modifier) {
if (typeof modifier === 'function') {
modifiedResult = await modifier({
toolSlug,
toolkitSlug,
result: modifiedResult,
});
} else {
throw new ComposioInvalidModifierError('Invalid afterExecute modifier. Not a function.');
}
}
return modifiedResult;
}
/**
* Lists Composio API tools available to the SDK.
*
* This method fetches remote Composio tools from the API in raw format. The response can be
* filtered and modified as needed. Local experimental custom tools are session-scoped; attach
* them when creating or reusing a Tool Router session, then use `session.tools()`,
* `session.customTools()`, or `session.execute()`.
* It provides access to the underlying tool data without provider-specific wrapping.
*
* @param {ToolListParams} query - Query parameters to filter the tools (required)
* @param {GetRawComposioToolsOptions} [options] - Optional configuration for tool retrieval
* @param {TransformToolSchemaModifier} [options.modifySchema] - Function to transform tool schemas
* @returns {Promise<ToolList>} List of tools matching the query criteria
*
* @example
* ```typescript
* // Get tools from specific toolkits
* const githubTools = await composio.tools.getRawComposioTools({
* toolkits: ['github'],
* limit: 10
* });
*
* // Get specific tools by slug
* const specificTools = await composio.tools.getRawComposioTools({
* tools: ['GITHUB_GET_REPOS', 'HACKERNEWS_GET_USER']
* });
*
* // Get tools from specific toolkits
* const githubTools = await composio.tools.getRawComposioTools({
* toolkits: ['github'],
* limit: 10
* });
*
* // Get tools with schema transformation
* const customizedTools = await composio.tools.getRawComposioTools({
* toolkits: ['github'],
* limit: 5
* }, {
* modifySchema: ({ toolSlug, toolkitSlug, schema }) => {
* // Add custom properties to tool schema
* return {
* ...schema,
* customProperty: `Modified ${toolSlug} from ${toolkitSlug}`,
* tags: [...(schema.tags || []), 'customized']
* };
* }
* });
*
* // Search for tools
* const searchResults = await composio.tools.getRawComposioTools({
* search: 'user management'
* });
*
* // Get tools by authentication config
* const authSpecificTools = await composio.tools.getRawComposioTools({
* authConfigIds: ['auth_config_123']
* });
* ```
*/
async getRawComposioTools(
query: ToolListParams,
options?: SchemaModifierOptions,
requestOptions?: ComposioRequestOptions
): Promise<ToolList> {
if ('tools' in query && 'toolkits' in query) {
throw new ValidationError(
'Invalid tool list parameters. You should not use tools and toolkits filter together.'
);
}
const queryParams = ToolListParamsSchema.safeParse(query);
if (queryParams.error) {
throw new ValidationError('Invalid tool list parameters', {
cause: queryParams.error,
});
}
const shouldAutoApplyImportant =
'toolkits' in queryParams.data &&
!('tools' in queryParams.data) &&
!('tags' in queryParams.data) &&
!('search' in queryParams.data) &&
// if the user provides a limit, do not apply the important flag
!('limit' in queryParams.data) &&
queryParams.data.important !== false;
const effectiveImportant =
'important' in queryParams.data ? queryParams.data.important : shouldAutoApplyImportant;
// check if the query params contains atleast one of the following: tools, toolkits, search, authConfigIds
if (!(
'tools' in queryParams.data ||
'toolkits' in queryParams.data ||
'search' in queryParams.data ||
'authConfigIds' in queryParams.data
)) {
throw new ValidationError(
'Invalid tool list parameters, atleast one of the following parameters is required: tools, toolkits, search, authConfigIds'
);
}
// if tools are provided, set the limit to 9999 so that all tools are fetched
let limit = 'limit' in queryParams.data ? queryParams.data.limit : undefined;
if ('tools' in queryParams.data) {
limit = 9999;
}
const filters: ComposioToolListParams = {
...('tools' in queryParams.data ? { tool_slugs: queryParams.data.tools?.join(',') } : {}),
...('toolkits' in queryParams.data
? { toolkit_slug: queryParams.data.toolkits?.join(',') }
: {}),
...(limit ? { limit } : {}),
...('tags' in queryParams.data ? { tags: queryParams.data.tags } : {}),
...('scopes' in queryParams.data ? { scopes: queryParams.data.scopes } : {}),
// `search` is the SDK's public option; the API deprecated the `search`
// wire param in favour of `query`, so send the replacement.
...('search' in queryParams.data ? { query: queryParams.data.search } : {}),
...('authConfigIds' in queryParams.data
? { auth_config_ids: queryParams.data.authConfigIds }
: {}),
...(effectiveImportant ? { important: 'true' } : {}),
...{ toolkit_versions: this.toolkitVersions },
};
logger.debug(`Fetching tools with filters: ${JSON.stringify(filters, null, 2)}`);
const tools = await withCancellation(
() => this.client.tools.list(filters, requestOptions),
requestOptions?.signal
);
if (!tools) {
return [];
}
const caseTransformedTools = tools.items.map(tool => this.transformToolCases(tool));
let modifiedTools = await this.applyDefaultSchemaModifiers(caseTransformedTools);
// apply local modifiers if they are provided
if (options?.modifySchema) {
const modifier = options.modifySchema;
if (typeof modifier === 'function') {
const modifiedPromises = modifiedTools.map(tool =>
modifier({
toolSlug: tool.slug,
toolkitSlug: tool.toolkit?.slug ?? 'unknown',
schema: tool,
})
);
modifiedTools = await Promise.all(modifiedPromises);
} else {
throw new ComposioInvalidModifierError('Invalid schema modifier. Not a function.');
}
}
return modifiedTools;
}
/**
* Fetches tools exposed by a tool router session.
* This includes helper/meta tools plus any tools preloaded into the session.
* It provides access to the underlying tool data without provider-specific wrapping.
*
* @param sessionId {string} The session id to get tools for
* @param options {SchemaModifierOptions} Optional configuration for tool retrieval
* @param {TransformToolSchemaModifier} [options.modifySchema] - Function to transform the tool schema
* @returns {Promise<ToolList>} The list of session tools
*
* @example
* ```typescript
* const sessionTools = await composio.tools.getRawToolRouterSessionTools('session_123');
* console.log(sessionTools);
* ```
*/
async getRawToolRouterSessionTools(
sessionId: string,
options?: SchemaModifierOptions,
requestOptions?: ComposioRequestOptions
): Promise<ToolList> {
const tools: ToolList = [];
let cursor: string | null | undefined;
do {
const sessionToolsParams = {
limit: TOOL_ROUTER_SESSION_TOOLS_PAGE_LIMIT,
...(cursor ? { cursor } : {}),
};
const response = await withCancellation(
() => this.client.toolRouter.session.tools(sessionId, sessionToolsParams, requestOptions),
requestOptions?.signal
);
tools.push(...response.items.map(tool => this.transformToolCases(tool)));
cursor = response.next_cursor;
} while (cursor);
let modifiedTools = tools;
// apply local modifiers if they are provided
if (options?.modifySchema) {
const modifier = options.modifySchema;
if (typeof modifier === 'function') {
const modifiedPromises = modifiedTools.map(tool =>
modifier({
toolSlug: tool.slug,
toolkitSlug: tool.toolkit?.slug ?? 'unknown',
schema: tool,
})
);
modifiedTools = await Promise.all(modifiedPromises);
} else {
throw new ComposioInvalidModifierError('Invalid schema modifier. Not a function.');
}
}
return modifiedTools;
}
/**
* Retrieves a specific tool by its slug from the Composio API.
*
* This method fetches a single tool in raw format without provider-specific wrapping,
* providing direct access to the tool's schema and metadata. Tool versions are controlled
* at the Composio SDK initialization level through the `toolkitVersions` configuration.
* Local experimental custom tools are session-scoped; attach them when creating or reusing a
* Tool Router session, then use `session.tools()`, `session.customTools()`, or
* `session.execute()`.
*
* @param {string} slug - The unique identifier of the tool (e.g., 'GITHUB_GET_REPOS')
* @param {GetRawComposioToolBySlugOptions} [options] - Optional configuration for tool retrieval
* @param {TransformToolSchemaModifier} [options.modifySchema] - Function to transform the tool schema
* @returns {Promise<Tool>} The requested tool with its complete schema and metadata
*
* @example
* ```typescript
* // Get a tool by slug
* const tool = await composio.tools.getRawComposioToolBySlug('GITHUB_GET_REPOS');
* console.log(tool.name, tool.description);
*
* // Get a tool with schema transformation
* const customizedTool = await composio.tools.getRawComposioToolBySlug(
* 'SLACK_SEND_MESSAGE',
* {
* modifySchema: ({ toolSlug, toolkitSlug, schema }) => {
* return {
* ...schema,
* description: `Enhanced ${schema.description} with custom modifications`,
* customMetadata: {
* lastModified: new Date().toISOString(),
* toolkit: toolkitSlug
* }
* };
* }
* }
* );
*
* // Access tool properties
* const githubTool = await composio.tools.getRawComposioToolBySlug('GITHUB_CREATE_ISSUE');
* console.log({
* slug: githubTool.slug,
* name: githubTool.name,
* toolkit: githubTool.toolkit?.name,
* version: githubTool.version,
* availableVersions: githubTool.availableVersions,
* inputParameters: githubTool.inputParameters
* });
* ```
*/
async getRawComposioToolBySlug(
slug: string,
options?: ToolRetrievalOptions,
requestOptions?: ComposioRequestOptions
): Promise<Tool> {
let tool: ToolRetrieveResponse;
try {
// Build API call parameters based on version source
const retrieveParams = options?.version
? { version: options.version } // Explicit version → use 'version' param
: { toolkit_versions: this.toolkitVersions }; // SDK config → use 'toolkit_versions' param
tool = await withCancellation(
() => this.client.tools.retrieve(slug, retrieveParams, requestOptions),
requestOptions?.signal
);
} catch (error) {
if (error instanceof ComposioRequestCancelledError) {
throw error;
}
throw new ComposioToolNotFoundError(`Unable to retrieve tool with slug ${slug}`, {
cause: error,
});
}
// change the case of the tool to camel case and apply default modifiers
let [modifiedTool] = await this.applyDefaultSchemaModifiers([this.transformToolCases(tool)]);
// apply local modifiers if they are provided
if (options?.modifySchema) {
const modifier = options.modifySchema;
if (typeof modifier === 'function') {
modifiedTool = await modifier({
toolSlug: slug,
toolkitSlug: modifiedTool.toolkit?.slug ?? 'unknown',
schema: modifiedTool,
});
} else {
throw new ComposioInvalidModifierError('Invalid schema modifier. Not a function.');
}
}
return modifiedTool;
}
/**
* Get a list of tools from Composio based on filters.
* This method fetches the tools from the Composio API and wraps them using the provider.
*
* @param {string} userId - The user id to get the tools for
* @param {ToolListParams} filters - The filters to apply when fetching tools
* @param {ProviderOptions<TProvider> & ComposioRequestOptions} [options] - Provider options, modifiers, and/or AbortSignal
* @returns {Promise<ReturnType<T['wrapTools']>>} The wrapped tools collection
*
* @example
* ```typescript
* // Get tools from the GitHub toolkit
* const tools = await composio.tools.get('default', {
* toolkits: ['github'],
* limit: 10
* });
*
* // Timeout a slow search after 5s
* const emailTools = await composio.tools.get('default', {
* search: 'send email',
* }, { signal: AbortSignal.timeout(5_000) });
* ```
*/
async get<T extends TProvider>(
userId: string,
filters: ToolListParams,
options?: ProviderOptions<TProvider> & ComposioRequestOptions
): Promise<ReturnType<T['wrapTools']>>;
/**
* Get a specific tool by its slug.
* This method fetches the tool from the Composio API and wraps it using the provider.
*
* @param {string} userId - The user id to get the tool for
* @param {string} slug - The slug of the tool to fetch
* @param {ProviderOptions<TProvider> & ComposioRequestOptions} [options] - Optional provider options including modifiers and signal
* @returns {Promise<ReturnType<T['wrapTools']>>} The wrapped tool
*
* @example
* ```typescript
* // Get a specific tool by slug
* const hackerNewsUserTool = await composio.tools.get('default', 'HACKERNEWS_GET_USER');
*
* // Get a tool with schema modifications
* const tool = await composio.tools.get('default', 'GITHUB_GET_REPOS', {
* modifySchema: (toolSlug, toolkitSlug, schema) => {
* // Customize the tool schema
* return {...schema, description: 'Custom description'};
* }
* });
*
* // Timeout after 5s
* const tools = await composio.tools.get('user_1', { search: 'email' }, {
* signal: AbortSignal.timeout(5_000)
* });
* ```
*/
async get<T extends TProvider>(
userId: string,
slug: string,
options?: ProviderOptions<TProvider> & ComposioRequestOptions
): Promise<ReturnType<T['wrapTools']>>;
async get(
userId: string,
arg2: ToolListParams | string,
arg3?: ProviderOptions<TProvider> & ComposioRequestOptions
): Promise<TToolCollection> {
const options = arg3;
const requestOptions: ComposioRequestOptions | undefined =
options?.signal != null ? { signal: options.signal } : undefined;
// Strip signal so it isn't captured in the provider execution closure —
// an expired AbortSignal.timeout() would poison every future tool call.
const { signal: _, ...modifiers } = options ?? {};
if (typeof arg2 === 'string') {
const rawTool = await this.getRawComposioToolBySlug(arg2, undefined, requestOptions);
const [tool] = await this.applySchemaModifiers([rawTool], options?.modifySchema);
return this.wrapToolsForProvider(userId, [tool], modifiers as ExecuteToolModifiers, [
rawTool,
]) as TToolCollection;
} else {
const rawTools = await this.getRawComposioTools(arg2, undefined, requestOptions);
const tools = await this.applySchemaModifiers(rawTools, options?.modifySchema);
return this.wrapToolsForProvider(
userId,
tools,
modifiers as ExecuteToolModifiers,
rawTools
) as TToolCollection;
}
}
private async applySchemaModifiers(
tools: Tool[],
modifier?: TransformToolSchemaModifier
): Promise<Tool[]> {
if (modifier && typeof modifier !== 'function') {
throw new ComposioInvalidModifierError('Invalid schema modifier. Not a function.');
}
return Promise.all(
tools.map(tool => {
const schema = ToolSchema.parse(tool);
return modifier
? modifier({
toolSlug: tool.slug,
toolkitSlug: tool.toolkit?.slug ?? 'unknown',
schema,
})
: schema;
})
);
}
/**
* @internal
* Creates a global execute tool function.
* This function is used by providers to execute tools.
* It skips the version check for provider controlled execution.
* @returns {GlobalExecuteToolFn} The global execute tool function
*/
private createExecuteFnForProviders(): GlobalExecuteToolFn {
return async (slug: string, body: ToolExecuteParams, modifiers?: ExecuteToolModifiers) => {
return await this.execute(
slug,
{ ...body, dangerouslySkipVersionCheck: body.dangerouslySkipVersionCheck ?? true },
modifiers
);
};
}
/**
* @internal
* Utility to wrap a given set of tools in the format expected by the provider
*
* @param userId - The user id to get the tools for
* @param tools - The tools to wrap
* @param modifiers - The modifiers to be applied to the tools
* @param rawTools - The fetched schemas used during execution
* @returns The wrapped tools
*/
wrapToolsForProvider<T extends TProvider>(
userId: string,
tools: Tool[],
modifiers?: ExecuteToolModifiers,
rawTools: Tool[] = tools.map(tool => ToolSchema.parse(tool))
): ReturnType<T['wrapTools']> {
const executeToolFn = this.createExecuteToolFn(userId, modifiers, rawTools);
return this.provider.wrapTools(tools, executeToolFn) as ReturnType<T['wrapTools']>;
}
/**
* @internal
* Utility to wrap a given set of tools in the format expected by the tool router
*
* @param {string} sessionId - The session id to execute the tool for
* @param {Tool[]} tools - The tools to wrap
* @param {SessionExecuteMetaModifiers} modifiers - The modifiers to apply to the tool
* @returns {Tool[]} The wrapped tools
*/
wrapToolsForToolRouter(
sessionId: string,
tools: Tool[],
modifiers?: SessionExecuteMetaModifiers,
rawTools: Tool[] = tools.map(tool => ToolSchema.parse(tool))
): Tool[] {
const executeToolFn = this.createExecuteToolFnForToolRouter(sessionId, rawTools, modifiers);
return this.provider.wrapTools(tools, executeToolFn) as Tool[];
}
/**
* @internal
* @description
* Creates a function that executes a tool.
* This function is used by agentic providers to execute the tool
*
* @param {string} userId - The user id
* @param {ExecuteToolModifiers} modifiers - The modifiers to be applied to the tool
* @param {Tool[]} tools - The fetched tools available to the provider
* @returns {ExecuteToolFn} The execute tool function
*/
private createExecuteToolFn(
userId: string,
modifiers: ExecuteToolModifiers | undefined,
tools: Tool[]
): ExecuteToolFn {
const toolBySlug = new Map(tools.map(tool => [tool.slug.toUpperCase(), tool]));
const executeToolFn = async (toolSlug: string, input: Record<string, unknown>) => {
const body: ToolExecuteParams = {
userId,
arguments: input,
// dangerously skip version check for agentic tool execution via providers
// this can be safe because most agentic flows users fetch latest version and then execute the tool
dangerouslySkipVersionCheck: true,
};
const tool = toolBySlug.get(toolSlug.toUpperCase());
return tool
? this.executeWithTool(toolSlug, this.parseToolExecuteParams(body), modifiers, tool)
: this.execute(toolSlug, body, modifiers);
};
return executeToolFn;
}
/**
* @internal
* Creates a function that executes a tool for a tool router session
*
* @param {string} sessionId - The session id to execute the tool for
* @param {SessionExecuteMetaModifiers} modifiers - The modifiers to apply to the tool
* @returns {ExecuteToolFn} The execute tool function
*/
private createExecuteToolFnForToolRouter(
sessionId: string,
tools: Tool[],
modifiers?: SessionExecuteMetaModifiers
): ExecuteToolFn {
const toolBySlug = new Map(tools.map(tool => [tool.slug.toUpperCase(), tool]));
const executeToolFn = async (
toolSlug: string,
input: Record<string, unknown>
): Promise<ToolExecuteResponse> => {
return await this.executeSessionTool(
toolSlug,
{
sessionId,
arguments: input,
},
modifiers,
toolBySlug.get(toolSlug.toUpperCase())
);
};
return executeToolFn;
}
/**
* @internal
* Executes a composio tool via API without modifiers
* @param tool - The tool to execute
* @param body - The body of the tool execution
* @returns The response from the tool execution
*/
private async executeComposioTool(
tool: Tool,
body: ToolExecuteParams,
requestOptions?: ComposioRequestOptions
): Promise<ToolExecuteResponse> {
const toolkitVersion =
body.version ?? getToolkitVersion(tool.toolkit?.slug ?? 'unknown', this.toolkitVersions);
// if the version is latest and dangerouslySkipVersionCheck is not true, throw an error
if (toolkitVersion === 'latest' && !body.dangerouslySkipVersionCheck) {
throw new ComposioToolVersionRequiredError();
}
try {
const executeBody: ComposioToolExecuteParams = {
allow_tracing: body.allowTracing,
connected_account_id: body.connectedAccountId,
custom_auth_params: body.customAuthParams
? {
base_url: body.customAuthParams.baseURL,
body: body.customAuthParams.body,
parameters: body.customAuthParams.parameters,
}
: undefined,
/**
* @deprecated The `customConnectionData` execute param is deprecated and will be
* removed in a future release. Use `customAuthParams` instead.
*/
custom_connection_data:
body.customConnectionData as ComposioToolExecuteParams['custom_connection_data'],
arguments: body.arguments,
user_id: body.userId,
version: toolkitVersion,
text: body.text,
};
const result = await withCancellation(
// Disable retries: tool execution is a non-idempotent write, and a
// silent retry after a read timeout can duplicate the side effect.
() => this.clientWithoutRetries.tools.execute(tool.slug, executeBody, requestOptions),
requestOptions?.signal
);
// transform the response to the ToolExecuteResponse format
return this.transformToolExecuteResponse(result);
} catch (error) {
if (error instanceof ComposioRequestCancelledError) {
throw error;
}
const toolError = handleToolExecutionError(tool.slug, error as Error);
throw toolError;
}
}
private async executeWithTool(
slug: string,
body: ToolExecuteParams,
options: (ExecuteToolModifiers & ComposioRequestOptions) | undefined,
tool: Tool
): Promise<ToolExecuteResponse> {
const requestOptions: ComposioRequestOptions | undefined =
options?.signal != null ? { signal: options.signal } : undefined;
const { signal: _, ...modifiers } = options ?? {};
const toolkitSlug = tool.toolkit?.slug ?? 'unknown';
const params = await this.applyBeforeExecuteModifiers(
tool,
{
toolSlug: slug,
toolkitSlug,
params: body,
},
modifiers as ExecuteToolModifiers,
requestOptions
);
let result = await this.executeComposioTool(tool, params, requestOptions);
result = await this.applyAfterExecuteModifiers(
tool,
{
toolSlug: slug,
toolkitSlug,
result,
},
(modifiers as ExecuteToolModifiers).afterExecute,
requestOptions
);
return result;
}
private parseToolExecuteParams(body: ToolExecuteParams): ToolExecuteParams {
const executeParams = ToolExecuteParamsSchema.safeParse(body);
if (!executeParams.success) {
throw new ValidationError('Invalid tool execute parameters', { cause: executeParams.error });
}
return executeParams.data;
}
/**
* Executes a given tool with the provided parameters.
*
* This method calls the Composio API to execute the tool and returns the response.
*
* **Version Control:**
* By default, manual tool execution requires a specific toolkit version. If the version resolves to "latest",
* the execution will throw a `ComposioToolVersionRequiredError` unless `dangerouslySkipVersionCheck` is set to `true`.
* This helps prevent unexpected behavior when new toolkit versions are released.
*
* @param {string} slug - The slug/ID of the tool to be executed
* @param {ToolExecuteParams} body - The parameters to be passed to the tool
* @param {string} [body.version] - The specific version of the tool to execute (e.g., "20250909_00")
* @param {boolean} [body.dangerouslySkipVersionCheck] - Skip version validation for "latest" version (use with caution)
* @param {string} [body.userId] - The user ID to execute the tool for
* @param {string} [body.connectedAccountId] - The connected account ID to use for authenticated tools
* @param {Record<string, unknown>} [body.arguments] - The arguments to pass to the tool
* @param {ExecuteToolModifiers & ComposioRequestOptions} [options] - Optional modifiers and request options
* @returns {Promise<ToolExecuteResponse>} The response from the tool execution
*
* @throws {ComposioConnectedAccountNotFoundError} If the connected account is not found
* @throws {ComposioToolNotFoundError} If the tool with the given slug is not found
* @throws {ComposioToolVersionRequiredError} If version resolves to "latest" and dangerouslySkipVersionCheck is not true
* @throws {ComposioToolExecutionError} If there is an error during tool execution
*
* @example Execute with a specific version (recommended for production)
* ```typescript
* const result = await composio.tools.execute('GITHUB_GET_REPOS', {
* userId: 'default',
* version: '20250909_00',
* arguments: { owner: 'composio' }
* });
* ```
*
* @example Execute with dangerouslySkipVersionCheck (not recommended for production)
* ```typescript
* const result = await composio.tools.execute('HACKERNEWS_GET_USER', {
* userId: 'default',
* arguments: { userId: 'pg' },
* dangerouslySkipVersionCheck: true // Allows execution with "latest" version
* });
* ```
*
* @example Execute with SDK-level toolkit versions configuration
* ```typescript
* // If toolkitVersions are set during Composio initialization, no need to pass version
* const composio = new Composio({ toolkitVersions: { github: '20250909_00' } });
* const result = await composio.tools.execute('GITHUB_GET_REPOS', {
* userId: 'default',
* arguments: { owner: 'composio' }
* });
* ```
*
* @example Execute with modifiers
* ```typescript
* const result = await composio.tools.execute('GITHUB_GET_ISSUES', {
* userId: 'default',
* version: '20250909_00',
* arguments: { owner: 'composio', repo: 'sdk' }
* }, {
* beforeExecute: ({ toolSlug, toolkitSlug, params }) => {
* console.log(`Executing ${toolSlug} from ${toolkitSlug}`);
* return params;
* },
* afterExecute: ({ toolSlug, toolkitSlug, result }) => {
* console.log(`Completed ${toolSlug}`);
* return result;
* }
* });
* ```
*
* @example Execute with timeout
* ```typescript
* const result = await composio.tools.execute('HACKERNEWS_GET_FRONTPAGE', {
* userId: 'default',
* arguments: {},
* dangerouslySkipVersionCheck: true,
* }, { signal: AbortSignal.timeout(5_000) });
* ```
*/
async execute(
slug: string,
body: ToolExecuteParams,
options?: ExecuteToolModifiers & ComposioRequestOptions
): Promise<ToolExecuteResponse> {
const executeParams = this.parseToolExecuteParams(body);
const requestOptions: ComposioRequestOptions | undefined =
options?.signal != null ? { signal: options.signal } : undefined;
const tool = await this.getRawComposioToolBySlug(
slug,
{
version: executeParams.version,
},
requestOptions
);
return this.executeWithTool(slug, executeParams, options, tool);
}
/**
* Executes a tool based on a tool router session.
*
* @param {string} toolSlug - The slug of the tool to execute
* @param {ToolExecuteMetaParams} body - The execution parameters
* @param {string} body.sessionId - The session id to execute the tool for
* @param {Record<string, unknown>} body.arguments - The input to pass to the tool
* @param {SessionExecuteMetaModifiers} modifiers - The modifiers to apply to the tool
* @param {Tool} tool - Optional tool schema used to resolve toolkit metadata for modifiers
* @returns {Promise<ToolExecuteResponse>} The response from the tool execution
*/
async executeSessionTool(
toolSlug: string,
body: ToolExecuteMetaParams,
modifiers?: SessionExecuteMetaModifiers,
tool?: Tool,
options?: ToolRouterSessionExecuteOptions,
requestOptions?: ComposioRequestOptions
): Promise<ToolExecuteResponse> {
const executeParams = ToolExecuteMetaParamsSchema.safeParse(body);
if (!executeParams.success) {
throw new ValidationError('Invalid tool execute session parameters', {
cause: executeParams.error,
});
}
let modifiedParams = body.arguments ?? {};
const toolkitSlug = tool?.toolkit?.slug ?? 'composio';
if (tool) {
const fileModifiedParams = await this.applyFileUploadModifiers(
tool,
{
toolSlug,
toolkitSlug,
params: { arguments: modifiedParams },
},
undefined,
requestOptions
);
modifiedParams = fileModifiedParams.arguments ?? {};
}
// Apply beforeExecute modifier after file preprocessing so the hook sees
// the same arguments that will be sent to the Tool Router.
if (modifiers?.beforeExecute) {
modifiedParams = await modifiers.beforeExecute({
toolSlug,
toolkitSlug,
sessionId: body.sessionId,
params: modifiedParams,
});
}
const executePayload: SessionExecuteParams = {
tool_slug: toolSlug,
arguments: modifiedParams,
// Provider-wrapped session tools are agentic calls, so they opt into
// direct tool offload when the backend session workbench allows it.
enable_auto_workbench_offload: true,
};
if (options?.experimental) {
executePayload.experimental = options.experimental;
}
const response = await withCancellation(
() => this.client.toolRouter.session.execute(body.sessionId, executePayload, requestOptions),
requestOptions?.signal
);
// Prepare the result
let result: ToolExecuteResponse = {
data: response.data,
error: response.error,
successful: !response.error,
logId: response.log_id,
};
// Apply afterExecute modifier if provided
if (modifiers?.afterExecute) {
result = await modifiers.afterExecute({
toolSlug,
toolkitSlug,
sessionId: body.sessionId,
result,
});
}
return result;
}
/**
* Fetches the list of all available tools in the Composio SDK.
*
* This method is mostly used by the CLI to get the list of tools.
* No filtering is done on the tools, the list is cached in the backend, no further optimization is required.
* @returns {Promise<ToolRetrieveEnumResponse>} The complete list of all available tools with their metadata
*
* @example
* ```typescript
* // Get all available tools as an enum
* const toolsEnum = await composio.tools.getToolsEnum();
* console.log(toolsEnum.items);
* ```
*/
async getToolsEnum(requestOptions?: ComposioRequestOptions): Promise<ToolRetrieveEnumResponse> {
return withCancellation(
() => this.client.tools.retrieveEnum(requestOptions),
requestOptions?.signal
);
}
/**
* Fetches the input parameters for a given tool.
*
* This method is used to get the input parameters for a tool before executing it.
*
* @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
* const inputParams = await composio.tools.getInput('GITHUB_CREATE_ISSUE', {
* userId: 'default'
* });
* console.log(inputParams.schema);
* ```
*/
async getInput(
slug: string,
body: ToolGetInputParams,
requestOptions?: ComposioRequestOptions
): Promise<ToolGetInputResponse> {
return withCancellation(
() => this.client.tools.getInput(slug, body, requestOptions),
requestOptions?.signal
);
}
/**
* 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
* const response = await composio.tools.proxyExecute({
* toolkitSlug: 'github',
* userId: 'default',
* data: {
* endpoint: '/repos/owner/repo/issues',
* method: 'GET'
* }
* });
* console.log(response.data);
* ```
*/
async proxyExecute(
body: ToolProxyParams,
requestOptions?: ComposioRequestOptions
): Promise<ToolProxyResponse> {
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(
...(toolProxyParams.data.parameters ?? []).map(value => ({
name: value.name,
type: value.in === 'header' ? parameterTypes.header : parameterTypes.query,
value: value.value.toString(),
}))
);
}
const proxyBody = {
endpoint: toolProxyParams.data.endpoint,
method: toolProxyParams.data.method,
body: toolProxyParams.data.body,
connected_account_id: toolProxyParams.data.connectedAccountId,
parameters: parameters,
/**
* @deprecated The `customConnectionData` proxy param is deprecated and will be
* removed in a future release. Use `customAuthParams` instead.
*/
// oxlint-disable-next-line typescript/ban-ts-comment -- generated client versions disagree about this deprecated field
// @ts-ignore
custom_connection_data: toolProxyParams.data.customConnectionData,
} as ComposioToolProxyParams;
return withCancellation(
// Disable retries: a proxied call is a non-idempotent write, and a silent
// retry after a read timeout can duplicate the side effect.
() => this.clientWithoutRetries.tools.proxy(proxyBody, requestOptions),
requestOptions?.signal
);
}
}