Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
| 1 | import ComposioClient, { APIError } from '@composio/client'; |
| 2 | import { FileToolModifier } from '#file_tool_modifier'; |
| 3 | import { z } from 'zod/v3'; |
| 4 | import { |
| 5 | Tool, |
| 6 | ToolExecuteParams, |
| 7 | ToolListParamsSchema, |
| 8 | ToolExecuteResponse, |
| 9 | ToolList, |
| 10 | ToolSchema, |
| 11 | ToolListParams, |
| 12 | ToolExecuteResponseSchema, |
| 13 | ToolProxyParamsSchema, |
| 14 | ToolProxyParams, |
| 15 | ToolExecuteParamsSchema, |
| 16 | ToolkitVersionParam, |
| 17 | SchemaModifierOptions, |
| 18 | ToolRetrievalOptions, |
| 19 | ToolExecuteMetaParams, |
| 20 | ToolExecuteMetaParamsSchema, |
| 21 | } from '../types/tool.types'; |
| 22 | import { |
| 23 | ToolGetInputParams, |
| 24 | ToolGetInputResponse, |
| 25 | ToolProxyParams as ComposioToolProxyParams, |
| 26 | ToolProxyResponse, |
| 27 | ToolRetrieveEnumResponse, |
| 28 | ToolRetrieveResponse, |
| 29 | ToolListResponse as ComposioToolListResponse, |
| 30 | ToolExecuteResponse as ComposioToolExecuteResponse, |
| 31 | ToolListParams as ComposioToolListParams, |
| 32 | ToolExecuteParams as ComposioToolExecuteParams, |
| 33 | } from '@composio/client/resources/tools'; |
| 34 | import { |
| 35 | afterExecuteModifier, |
| 36 | ExecuteToolModifiers, |
| 37 | SessionExecuteMetaModifiers, |
| 38 | ProviderOptions, |
| 39 | TransformToolSchemaModifier, |
| 40 | } from '../types/modifiers.types'; |
| 41 | import type { BaseComposioProvider } from '../provider/BaseProvider'; |
| 42 | import logger from '../utils/logger'; |
| 43 | import { ExecuteToolFn, GlobalExecuteToolFn } from '../types/provider.types'; |
| 44 | import { |
| 45 | ComposioInvalidModifierError, |
| 46 | ComposioToolFetchError, |
| 47 | ComposioToolFetchRateLimitError, |
| 48 | ComposioToolNotFoundError, |
| 49 | ComposioProviderNotDefinedError, |
| 50 | ComposioToolSchemaInvalidError, |
| 51 | ComposioToolVersionRequiredError, |
| 52 | } from '../errors/ToolErrors'; |
| 53 | import { ValidationError } from '../errors/ValidationErrors'; |
| 54 | import { telemetry } from '../telemetry/Telemetry'; |
| 55 | import type { ComposioConfig } from '../composio'; |
| 56 | import { getToolkitVersion } from '../utils/toolkitVersion'; |
| 57 | import { handleToolExecutionError } from '../errors/ToolErrors'; |
| 58 | import { apiErrorSuggestedFixes, withApiErrorMessage } from '../errors/apiErrorDetails'; |
| 59 | import type { SessionExecuteParams } from '@composio/client/resources/tool-router/session'; |
| 60 | import { CONFIG_DEFAULTS } from '../utils/config-defaults'; |
| 61 | import { resolveEffectiveUploadAllowlist } from '../utils/fileDirs'; |
| 62 | import { |
| 63 | dropEmptyFileUploads, |
| 64 | schemaHasFileUploadable, |
| 65 | } from '../utils/modifiers/FileToolModifier.utils.neutral'; |
| 66 | import { dereferenceJsonSchema } from '../utils/jsonSchema'; |
| 67 | import { ComposioRequestOptions } from '../types/requestOptions.types'; |
| 68 | import { withCancellation } from '../utils/cancellation'; |
| 69 | import { withoutRetries } from '../utils/retries'; |
| 70 | import { |
| 71 | isExecutionSuccessful, |
| 72 | transformExecuteResponse, |
| 73 | } from '../utils/transformers/toolRouterResponseTransform'; |
| 74 | import { ComposioRequestCancelledError } from '../errors/SDKErrors'; |
| 75 | import { isRateLimitResponse } from '../utils/rateLimit'; |
| 76 | |
| 77 | const TOOL_ROUTER_SESSION_TOOLS_PAGE_LIMIT = 500; |
| 78 | |
| 79 | type ToolRouterSessionExecuteOptions = { |
| 80 | experimental?: NonNullable<SessionExecuteParams['experimental']>; |
| 81 | }; |
| 82 | |
| 83 | type RawToolParameters = |
| 84 | | ToolRetrieveResponse['input_parameters'] |
| 85 | | ComposioToolListResponse['items'][0]['input_parameters']; |
| 86 | |
| 87 | type JsonSchemaNode = Record<string, unknown>; |
| 88 | |
| 89 | const isSchemaRecord = (value: unknown): value is JsonSchemaNode => |
| 90 | typeof value === 'object' && value !== null && !Array.isArray(value); |
| 91 | |
| 92 | /** |
| 93 | * Flatten a value for interpolation into a log line. |
| 94 | * |
| 95 | * The logger writes straight to the console sink, and the slug and the zod |
| 96 | * issue paths here are built from property names a remote toolkit controls. A |
| 97 | * name carrying a newline could otherwise forge or erase a line in the host's |
| 98 | * log, and an ANSI clear-line sequence could hide what came before it. |
| 99 | */ |
| 100 | const sanitizeForLog = (value: string): string => |
| 101 | // eslint-disable-next-line no-control-regex |
| 102 | value.replace(/[\u0000-\u001F\u007F-\u009F]/g, ' '); |
| 103 | |
| 104 | /** |
| 105 | * Rewrite one JSON-Schema node into the strict subset `ParametersSchema` |
| 106 | * accepts, preserving its meaning: |
| 107 | * |
| 108 | * - boolean nodes (`items: true` / `items: false`) become `{}` / `{ not: {} }` |
| 109 | * — the strict subset's way to express "anything" and "nothing", so the |
| 110 | * meaning survives; booleans are still valid JSON Schema (draft-04 style) |
| 111 | * that MCP toolkits emit; |
| 112 | * - draft-04 boolean `exclusiveMinimum`/`exclusiveMaximum` (paired with |
| 113 | * `minimum`/`maximum`) become the numeric form draft-07+ uses; |
| 114 | * |
| 115 | * Children are rewritten recursively. `additionalProperties` legitimately |
| 116 | * accepts a boolean, so it is only recursed into when it is a schema. |
| 117 | */ |
| 118 | function sanitizeJsonSchemaNode(node: unknown): unknown { |
| 119 | // Boolean JSON-Schema nodes (draft-04 style, still emitted by MCP toolkits): |
| 120 | // `true` accepts anything, which `{}` also expresses; `false` accepts |
| 121 | // nothing, which the strict subset (an object node) expresses as `not: {}`. |
| 122 | // Coercing `false` to `{}` would invert the schema's meaning. |
| 123 | if (typeof node === 'boolean') return node ? {} : { not: {} }; |
| 124 | if (Array.isArray(node)) return node.map(sanitizeJsonSchemaNode); |
| 125 | if (!isSchemaRecord(node)) return node; |
| 126 | |
| 127 | const schema: JsonSchemaNode = { ...node }; |
| 128 | |
| 129 | for (const [bound, limit] of [ |
| 130 | ['exclusiveMinimum', 'minimum'], |
| 131 | ['exclusiveMaximum', 'maximum'], |
| 132 | ] as const) { |
| 133 | if (typeof schema[bound] !== 'boolean') continue; |
| 134 | if (schema[bound] && typeof schema[limit] === 'number') { |
| 135 | schema[bound] = schema[limit]; |
| 136 | } else { |
| 137 | delete schema[bound]; |
| 138 | } |
| 139 | } |
| 140 | |
| 141 | for (const key of ['items', 'not', 'if', 'then', 'else', 'additionalProperties'] as const) { |
| 142 | const child = schema[key]; |
| 143 | if (child === undefined) continue; |
| 144 | // Every keyword here takes a schema node except `additionalProperties`, |
| 145 | // which also accepts a boolean; the sanitizer coerces boolean nodes. |
| 146 | if (key === 'additionalProperties' && typeof child === 'boolean') continue; |
| 147 | schema[key] = sanitizeJsonSchemaNode(child); |
| 148 | } |
| 149 | |
| 150 | for (const key of ['anyOf', 'oneOf', 'allOf'] as const) { |
| 151 | if (Array.isArray(schema[key])) { |
| 152 | schema[key] = sanitizeJsonSchemaNode(schema[key]); |
| 153 | } |
| 154 | } |
| 155 | |
| 156 | for (const key of ['properties', 'patternProperties', '$defs', 'definitions'] as const) { |
| 157 | const children = schema[key]; |
| 158 | if (!isSchemaRecord(children)) continue; |
| 159 | const mapped: JsonSchemaNode = {}; |
| 160 | for (const [name, child] of Object.entries(children)) { |
| 161 | mapped[name] = sanitizeJsonSchemaNode(child); |
| 162 | } |
| 163 | schema[key] = mapped; |
| 164 | } |
| 165 | |
| 166 | return schema; |
| 167 | } |
| 168 | |
| 169 | /** |
| 170 | * Normalize a raw `input_parameters` / `output_parameters` payload returned by |
| 171 | * the Composio API. Maps `null`, `undefined`, and empty `{}` — all of which |
| 172 | * mean "no declared schema" — to `undefined` so the strict `ParametersSchema` |
| 173 | * validator never sees them, and rewrites the valid-but-unusual JSON Schema |
| 174 | * shapes MCP toolkits ship (boolean nodes, draft-04 boolean bounds, a bare |
| 175 | * combinator root) into the strict subset. |
| 176 | * |
| 177 | * MCP-backed toolkits (granola_mcp, apify_mcp, tavily_mcp, …) have no |
| 178 | * declared output schema and the API serializes that as `{}`, which would |
| 179 | * otherwise trip `ParametersSchema`. See |
| 180 | * https://github.com/ComposioHQ/composio/issues/3354. The malformed-shape |
| 181 | * handling covers the toolkits listed in |
| 182 | * https://github.com/ComposioHQ/composio/issues/4757. |
| 183 | */ |
| 184 | function normalizeRawToolParameters( |
| 185 | params: RawToolParameters | null | undefined |
| 186 | ): RawToolParameters | undefined { |
| 187 | if (params == null || Object.keys(params).length === 0) return undefined; |
| 188 | const sanitized = sanitizeJsonSchemaNode(params); |
| 189 | // A parameters root is a tool's named-argument object, so a bare combinator |
| 190 | // root (`oneOf`/`anyOf`/`allOf` with no `type`) still needs `type: "object"` |
| 191 | // to satisfy the strict schema. |
| 192 | if ( |
| 193 | isSchemaRecord(sanitized) && |
| 194 | sanitized.type === undefined && |
| 195 | (Array.isArray(sanitized.anyOf) || |
| 196 | Array.isArray(sanitized.oneOf) || |
| 197 | Array.isArray(sanitized.allOf)) |
| 198 | ) { |
| 199 | return { ...sanitized, type: 'object' } as RawToolParameters; |
| 200 | } |
| 201 | return sanitized as RawToolParameters; |
| 202 | } |
| 203 | |
| 204 | /** How long `execute()` reuses a schema fetched for `latest`, which can change at any release. */ |
| 205 | const LATEST_TOOL_SCHEMA_TTL_MS = 5 * 60 * 1000; |
| 206 | /** How long `execute()` reuses a schema fetched for a pinned toolkit version. */ |
| 207 | const PINNED_TOOL_SCHEMA_TTL_MS = 60 * 60 * 1000; |
| 208 | /** Most schemas `execute()` keeps per `Tools` instance; the oldest is dropped first. */ |
| 209 | const MAX_CACHED_TOOL_SCHEMAS = 500; |
| 210 | |
| 211 | /** |
| 212 | * This class is used to manage tools in the Composio SDK. |
| 213 | * It provides methods to list, get, and execute tools. |
| 214 | */ |
| 215 | export class Tools< |
| 216 | TToolCollection, |
| 217 | TTool, |
| 218 | TProvider extends BaseComposioProvider<TToolCollection, TTool, unknown>, |
| 219 | > { |
| 220 | private client: ComposioClient; |
| 221 | private provider: TProvider; |
| 222 | private autoUploadDownloadFiles: boolean; |
| 223 | private toolkitVersions: ToolkitVersionParam; |
| 224 | private fileUploadPathOptions: { |
| 225 | sensitiveFileUploadProtection?: boolean; |
| 226 | fileUploadPathDenySegments?: string[]; |
| 227 | fileUploadAllowlist?: string[]; |
| 228 | fileDownloadDir?: string; |
| 229 | }; |
| 230 | /** |
| 231 | * Tracks tool slugs we've already warned about to avoid spamming the log when |
| 232 | * the same file-input tool is executed repeatedly while auto-upload is off. |
| 233 | * Scoped per-instance so a fresh `Composio` starts with a clean slate. |
| 234 | */ |
| 235 | private readonly warnedAutoUploadDisabledForTool = new Set<string>(); |
| 236 | /** Tools whose parameters were dropped by `transformToolCases`; warn once each. */ |
| 237 | private readonly warnedMalformedToolParametersSlugs = new Set<string>(); |
| 238 | |
| 239 | /** |
| 240 | * Schemas `execute()` already fetched, so repeated executions don't each spend a request. |
| 241 | * Holds what `getRawComposioToolBySlug` returned with no `modifySchema`, so a caller's schema |
| 242 | * modifiers never reach it. |
| 243 | */ |
| 244 | private readonly executeToolSchemas = new Map<string, { tool: Tool; expiresAt: number }>(); |
| 245 | |
| 246 | constructor(client: ComposioClient, config?: ComposioConfig<TProvider>) { |
| 247 | if (!client) { |
| 248 | throw new Error('ComposioClient is required'); |
| 249 | } |
| 250 | if (!config?.provider) { |
| 251 | throw new ComposioProviderNotDefinedError('Provider not passed into Tools instance'); |
| 252 | } |
| 253 | |
| 254 | this.client = client; |
| 255 | this.provider = config.provider; |
| 256 | this.autoUploadDownloadFiles = config?.dangerouslyAllowAutoUploadDownloadFiles === true; |
| 257 | this.toolkitVersions = config?.toolkitVersions ?? CONFIG_DEFAULTS.toolkitVersions; |
| 258 | this.fileUploadPathOptions = { |
| 259 | sensitiveFileUploadProtection: config?.sensitiveFileUploadProtection, |
| 260 | fileUploadPathDenySegments: config?.fileUploadPathDenySegments, |
| 261 | // The allowlist is only enforced during automatic upload (see |
| 262 | // FileToolModifier). Manual `composio.files.upload()` calls don't see it. |
| 263 | fileUploadAllowlist: this.autoUploadDownloadFiles |
| 264 | ? resolveEffectiveUploadAllowlist(config?.fileUploadDirs) |
| 265 | : undefined, |
| 266 | fileDownloadDir: config?.fileDownloadDir, |
| 267 | }; |
| 268 | // Bind the execute method to ensure correct 'this' context |
| 269 | this.execute = this.execute.bind(this); |
| 270 | // Set the execute method for the provider. |
| 271 | this.provider._setExecuteToolFn(this.createExecuteFnForProviders()); |
| 272 | this.getRawComposioToolBySlug = this.getRawComposioToolBySlug.bind(this); |
| 273 | this.getRawComposioTools = this.getRawComposioTools.bind(this); |
| 274 | |
| 275 | telemetry.instrument(this, 'Tools'); |
| 276 | } |
| 277 | |
| 278 | /** |
| 279 | * Transforms tool data from snake_case API format to camelCase for internal SDK use. |
| 280 | * |
| 281 | * This method standardizes the property naming convention for tools retrieved from the Composio API, |
| 282 | * making them more consistent with JavaScript/TypeScript conventions. |
| 283 | * |
| 284 | * @param {ToolRetrieveResponse | ComposioToolListResponse['items'][0]} tool - The tool object to transform |
| 285 | * @returns {Tool} The transformed tool with camelCase properties, or |
| 286 | * `undefined` when its input schema is unrepairable and the tool is skipped |
| 287 | * |
| 288 | * @private |
| 289 | */ |
| 290 | private transformToolCases( |
| 291 | tool: ToolRetrieveResponse | ComposioToolListResponse['items'][0] |
| 292 | ): Tool | undefined { |
| 293 | const candidate = { |
| 294 | ...tool, |
| 295 | inputParameters: normalizeRawToolParameters(tool.input_parameters), |
| 296 | outputParameters: normalizeRawToolParameters(tool.output_parameters), |
| 297 | availableVersions: tool.available_versions, |
| 298 | isDeprecated: tool.deprecated?.is_deprecated ?? false, |
| 299 | isNoAuth: tool.no_auth, |
| 300 | }; |
| 301 | |
| 302 | const parsed = ToolSchema.safeParse(candidate); |
| 303 | if (parsed.success) return parsed.data; |
| 304 | |
| 305 | // One malformed schema must not take down a whole toolkit's tool list |
| 306 | // (#4757). The output side degrades to "no schema"; the input side cannot, |
| 307 | // because providers build their call schema from it and a tool without one |
| 308 | // is not callable — @composio/langchain's wrapTool throws |
| 309 | // "Tool input parameters are not defined", so an unrepairable input schema |
| 310 | // would fail the provider's whole wrapTools pass one layer later. Such a |
| 311 | // tool is skipped instead, with the same warning. A failure outside the |
| 312 | // parameters is genuinely broken data and stays loud — including alongside |
| 313 | // a parameter failure, where skipping the tool would otherwise hide it. |
| 314 | const failingSides = new Set<'inputParameters' | 'outputParameters'>(); |
| 315 | let hasNonParameterIssue = false; |
| 316 | for (const issue of parsed.error.issues) { |
| 317 | const root = issue.path[0]; |
| 318 | if (root === 'inputParameters' || root === 'outputParameters') { |
| 319 | failingSides.add(root); |
| 320 | } else { |
| 321 | hasNonParameterIssue = true; |
| 322 | } |
| 323 | } |
| 324 | if (hasNonParameterIssue || failingSides.size === 0) throw parsed.error; |
| 325 | |
| 326 | this.warnMalformedToolParameters(tool, parsed.error, [...failingSides]); |
| 327 | if (failingSides.has('inputParameters')) return undefined; |
| 328 | const degradedCandidate = { ...candidate }; |
| 329 | for (const side of failingSides) { |
| 330 | degradedCandidate[side] = undefined; |
| 331 | } |
| 332 | const degraded = ToolSchema.safeParse(degradedCandidate); |
| 333 | if (degraded.success) return degraded.data; |
| 334 | throw parsed.error; |
| 335 | } |
| 336 | |
| 337 | /** |
| 338 | * Warn once per tool that its declared parameters could not be parsed and |
| 339 | * were dropped, so a caller sees why a tool carries no schema instead of a |
| 340 | * bare TypeError from deep inside Zod. |
| 341 | */ |
| 342 | private warnMalformedToolParameters( |
| 343 | tool: ToolRetrieveResponse | ComposioToolListResponse['items'][0], |
| 344 | error: z.ZodError, |
| 345 | droppedSides: Array<'inputParameters' | 'outputParameters'> |
| 346 | ): void { |
| 347 | const slug = String((tool as { slug?: unknown }).slug ?? ''); |
| 348 | if (slug && this.warnedMalformedToolParametersSlugs.has(slug)) return; |
| 349 | if (slug) this.warnedMalformedToolParametersSlugs.add(slug); |
| 350 | const inputFailed = droppedSides.includes('inputParameters'); |
| 351 | logger.warn( |
| 352 | `Tool "${sanitizeForLog(slug) || '(unknown slug)'}" has ${droppedSides.join(' and ')} that do not ` + |
| 353 | `match the expected schema, so the tool was ` + |
| 354 | `${inputFailed ? 'skipped' : 'returned without those parameters'}. ` + |
| 355 | `${inputFailed ? 'It cannot be offered without an input schema.' : 'The tool still executes, but LLM callers will not see those parameters.'} ` + |
| 356 | `Issues: ${error.issues.map(issue => `${sanitizeForLog(issue.path.join('.'))}: ${sanitizeForLog(issue.message)}`).join('; ')}` |
| 357 | ); |
| 358 | } |
| 359 | |
| 360 | /** |
| 361 | * Transforms tool execution response from snake_case API format to camelCase. |
| 362 | * |
| 363 | * This method converts the response received from the Composio API to a standardized format |
| 364 | * with consistent property naming that follows JavaScript/TypeScript conventions. |
| 365 | * |
| 366 | * @param {ComposioToolExecuteResponse} response - The raw API response to transform |
| 367 | * @returns {ToolExecuteResponse} The transformed response with camelCase properties |
| 368 | * |
| 369 | * @private |
| 370 | */ |
| 371 | private transformToolExecuteResponse(response: ComposioToolExecuteResponse): ToolExecuteResponse { |
| 372 | return ToolExecuteResponseSchema.parse({ |
| 373 | data: response.data, |
| 374 | error: response.error, |
| 375 | successful: response.successful, |
| 376 | logId: response.log_id, |
| 377 | sessionInfo: response.session_info, |
| 378 | }); |
| 379 | } |
| 380 | |
| 381 | /** |
| 382 | * Applies the default schema modifiers to the tools. |
| 383 | * |
| 384 | * The `file_uploadable` transform (collapsing the backend's internal |
| 385 | * `{ name, mimetype, s3key }` staging shape to `{ type: 'string', |
| 386 | * format: 'path' }`) is **gated on `dangerouslyAllowAutoUploadDownloadFiles`** |
| 387 | * — the collapsed shape is a promise that the SDK will stage local paths |
| 388 | * on your behalf at execute time, and that's only true when the flag is on. |
| 389 | * |
| 390 | * When the flag is off, the raw schema is returned unchanged; callers are |
| 391 | * expected to stage files themselves via `composio.files.upload()` and pass |
| 392 | * the resulting descriptor into `tools.execute`. If an LLM ends up calling |
| 393 | * a file-uploadable tool in this mode, the execute path emits a one-shot |
| 394 | * warning per tool slug (see `applyBeforeExecuteModifiers`). |
| 395 | * |
| 396 | * @param tools - The tools to apply the default schema modifiers to |
| 397 | * @returns The tools with the default schema modifiers applied |
| 398 | */ |
| 399 | private async applyDefaultSchemaModifiers(tools: Tool[]): Promise<Tool[]> { |
| 400 | if (!this.autoUploadDownloadFiles) { |
| 401 | return tools; |
| 402 | } |
| 403 | const fileToolModifier = new FileToolModifier(this.client, this.fileUploadPathOptions); |
| 404 | return await Promise.all(tools.map(tool => fileToolModifier.modifyToolSchema(tool))); |
| 405 | } |
| 406 | |
| 407 | /** |
| 408 | * Applies the before execute modifiers to the tool execution params |
| 409 | * @param options.toolSlug - The slug of the tool |
| 410 | * @param options.toolkitSlug - The slug of the toolkit |
| 411 | * @param options.params - The params of the tool execution |
| 412 | * @param modifier - The modifier to apply |
| 413 | * @returns The modified params |
| 414 | */ |
| 415 | private async applyBeforeExecuteModifiers( |
| 416 | tool: Tool, |
| 417 | { |
| 418 | toolSlug, |
| 419 | toolkitSlug, |
| 420 | params, |
| 421 | }: { |
| 422 | toolSlug: string; |
| 423 | toolkitSlug: string; |
| 424 | params: ToolExecuteParams; |
| 425 | }, |
| 426 | modifiers?: ExecuteToolModifiers, |
| 427 | requestOptions?: ComposioRequestOptions |
| 428 | ): Promise<ToolExecuteParams> { |
| 429 | if (requestOptions?.signal?.aborted) { |
| 430 | throw new ComposioRequestCancelledError(); |
| 431 | } |
| 432 | let modifiedParams = await this.applyFileUploadModifiers( |
| 433 | tool, |
| 434 | { toolSlug, toolkitSlug, params }, |
| 435 | modifiers?.beforeFileUpload, |
| 436 | requestOptions |
| 437 | ); |
| 438 | |
| 439 | // apply the before execute modifiers |
| 440 | if (modifiers?.beforeExecute) { |
| 441 | if (typeof modifiers.beforeExecute === 'function') { |
| 442 | modifiedParams = await modifiers.beforeExecute({ |
| 443 | toolSlug, |
| 444 | toolkitSlug, |
| 445 | params: modifiedParams, |
| 446 | }); |
| 447 | if (requestOptions?.signal?.aborted) { |
| 448 | throw new ComposioRequestCancelledError(); |
| 449 | } |
| 450 | } else { |
| 451 | throw new ComposioInvalidModifierError('Invalid beforeExecute modifier. Not a function.'); |
| 452 | } |
| 453 | } |
| 454 | return modifiedParams; |
| 455 | } |
| 456 | |
| 457 | /** |
| 458 | * Applies schema-aware file preprocessing shared by direct and Tool Router |
| 459 | * session execution. This always runs before the caller's `beforeExecute` |
| 460 | * hook so the hook observes the exact arguments sent to the backend. |
| 461 | */ |
| 462 | private async applyFileUploadModifiers( |
| 463 | tool: Tool, |
| 464 | { |
| 465 | toolSlug, |
| 466 | toolkitSlug, |
| 467 | params, |
| 468 | }: { |
| 469 | toolSlug: string; |
| 470 | toolkitSlug: string; |
| 471 | params: ToolExecuteParams; |
| 472 | }, |
| 473 | beforeFileUpload?: ExecuteToolModifiers['beforeFileUpload'], |
| 474 | requestOptions?: ComposioRequestOptions |
| 475 | ): Promise<ToolExecuteParams> { |
| 476 | let modifiedParams = params; |
| 477 | // if auto upload download files is enabled, upload the files to the Composio API |
| 478 | if (this.autoUploadDownloadFiles) { |
| 479 | const fileToolModifier = new FileToolModifier(this.client, { |
| 480 | ...this.fileUploadPathOptions, |
| 481 | beforeFileUpload, |
| 482 | }); |
| 483 | modifiedParams = await fileToolModifier.fileUploadModifier(tool, { |
| 484 | toolSlug, |
| 485 | toolkitSlug, |
| 486 | params: modifiedParams, |
| 487 | signal: requestOptions?.signal, |
| 488 | }); |
| 489 | if (requestOptions?.signal?.aborted) { |
| 490 | throw new ComposioRequestCancelledError(); |
| 491 | } |
| 492 | } else if (tool.inputParameters && schemaHasFileUploadable(tool.inputParameters)) { |
| 493 | // Auto-upload is opt-in, but "no file" must still be sent as an |
| 494 | // omitted key rather than `''`, which the backend rejects |
| 495 | // (https://github.com/ComposioHQ/composio/issues/4233). |
| 496 | if (modifiedParams.arguments) { |
| 497 | modifiedParams = { |
| 498 | ...modifiedParams, |
| 499 | arguments: (await dropEmptyFileUploads( |
| 500 | modifiedParams.arguments, |
| 501 | dereferenceJsonSchema(tool.inputParameters, { onUnresolved: 'sentinel' }) |
| 502 | )) as ToolExecuteParams['arguments'], |
| 503 | }; |
| 504 | } |
| 505 | |
| 506 | if (!this.warnedAutoUploadDisabledForTool.has(toolSlug)) { |
| 507 | // With auto-upload off, the raw `{ name, mimetype, s3key }` shape is |
| 508 | // what the LLM / caller sees on `tool.inputParameters`. LLMs can't |
| 509 | // produce a valid `s3key` and will hallucinate one, which then fails |
| 510 | // at the staging-lookup step on the backend. Nudge the caller toward |
| 511 | // manual staging or opting into auto-upload. |
| 512 | this.warnedAutoUploadDisabledForTool.add(toolSlug); |
| 513 | logger.warn( |
| 514 | `Tool "${toolSlug}" (toolkit "${toolkitSlug}") has a file-uploadable input, but ` + |
| 515 | `\`dangerouslyAllowAutoUploadDownloadFiles\` is disabled. The SDK will forward ` + |
| 516 | `the file argument as-is; if it isn't already a staged ` + |
| 517 | `{ name, mimetype, s3key } descriptor, the backend will reject the call. Either:\n` + |
| 518 | ` 1) Stage the file yourself: \`const f = await composio.files.upload({ file, toolSlug, toolkitSlug }); ` + |
| 519 | `await composio.tools.execute('${toolSlug}', { userId, arguments: { <fileField>: f } })\`, or\n` + |
| 520 | ` 2) Enable auto-upload with a scoped allowlist: ` + |
| 521 | `\`new Composio({ dangerouslyAllowAutoUploadDownloadFiles: true, fileUploadDirs: ['/safe/dir'] })\`.` |
| 522 | ); |
| 523 | } |
| 524 | } |
| 525 | return modifiedParams; |
| 526 | } |
| 527 | |
| 528 | /** |
| 529 | * Applies the after execute modifiers to the tool execution result |
| 530 | * @param options.toolSlug - The slug of the tool |
| 531 | * @param options.toolkitSlug - The slug of the toolkit |
| 532 | * @param options.result - The result of the tool execution |
| 533 | * @param modifier - The modifier to apply |
| 534 | * @returns The modified result |
| 535 | */ |
| 536 | private async applyAfterExecuteModifiers( |
| 537 | tool: Tool, |
| 538 | { |
| 539 | toolSlug, |
| 540 | toolkitSlug, |
| 541 | result, |
| 542 | }: { |
| 543 | toolSlug: string; |
| 544 | toolkitSlug: string; |
| 545 | result: ToolExecuteResponse; |
| 546 | }, |
| 547 | modifier?: afterExecuteModifier, |
| 548 | requestOptions?: ComposioRequestOptions |
| 549 | ): Promise<ToolExecuteResponse> { |
| 550 | // The tool already executed and may have mutated external state, so a late |
| 551 | // abort does NOT short-circuit post-processing: skipping the caller's |
| 552 | // afterExecute modifier here would leave a half-finished pipeline that |
| 553 | // still looks like success-shaped data. Once the remote call has committed |
| 554 | // we run file download + afterExecute to completion. The signal is still |
| 555 | // forwarded to the download so a stuck transfer degrades gracefully |
| 556 | // (file_downloaded: false) rather than blocking, but it never skips |
| 557 | // afterExecute. |
| 558 | let modifiedResult = result; |
| 559 | // if auto upload download files is enabled, download the files from the Composio API |
| 560 | if (this.autoUploadDownloadFiles) { |
| 561 | const fileToolModifier = new FileToolModifier(this.client, this.fileUploadPathOptions); |
| 562 | modifiedResult = await fileToolModifier.fileDownloadModifier(tool, { |
| 563 | toolSlug, |
| 564 | toolkitSlug, |
| 565 | result: modifiedResult, |
| 566 | signal: requestOptions?.signal, |
| 567 | }); |
| 568 | } |
| 569 | // apply the after execute modifiers |
| 570 | if (modifier) { |
| 571 | if (typeof modifier === 'function') { |
| 572 | modifiedResult = await modifier({ |
| 573 | toolSlug, |
| 574 | toolkitSlug, |
| 575 | result: modifiedResult, |
| 576 | }); |
| 577 | } else { |
| 578 | throw new ComposioInvalidModifierError('Invalid afterExecute modifier. Not a function.'); |
| 579 | } |
| 580 | } |
| 581 | |
| 582 | return modifiedResult; |
| 583 | } |
| 584 | |
| 585 | /** |
| 586 | * Lists Composio API tools available to the SDK. |
| 587 | * |
| 588 | * This method fetches remote Composio tools from the API in raw format. The response can be |
| 589 | * filtered and modified as needed. Experimental local tools are session-scoped; attach |
| 590 | * them when creating or reusing a Tool Router session, then use `session.tools()`, |
| 591 | * `session.localTools()`, or `session.execute()`. |
| 592 | * It provides access to the underlying tool data without provider-specific wrapping. |
| 593 | * |
| 594 | * @param {ToolListParams} query - Query parameters to filter the tools (required) |
| 595 | * @param {GetRawComposioToolsOptions} [options] - Optional configuration for tool retrieval |
| 596 | * @param {TransformToolSchemaModifier} [options.modifySchema] - Function to transform tool schemas |
| 597 | * @returns {Promise<ToolList>} List of tools matching the query criteria |
| 598 | * |
| 599 | * @example |
| 600 | * ```typescript |
| 601 | * // Get tools from specific toolkits |
| 602 | * const githubTools = await composio.tools.getRawComposioTools({ |
| 603 | * toolkits: ['github'], |
| 604 | * limit: 10 |
| 605 | * }); |
| 606 | * |
| 607 | * // Get specific tools by slug |
| 608 | * const specificTools = await composio.tools.getRawComposioTools({ |
| 609 | * tools: ['GITHUB_GET_REPOS', 'HACKERNEWS_GET_USER'] |
| 610 | * }); |
| 611 | * |
| 612 | * // Get tools from specific toolkits |
| 613 | * const githubTools = await composio.tools.getRawComposioTools({ |
| 614 | * toolkits: ['github'], |
| 615 | * limit: 10 |
| 616 | * }); |
| 617 | * |
| 618 | * // Get tools with schema transformation |
| 619 | * const customizedTools = await composio.tools.getRawComposioTools({ |
| 620 | * toolkits: ['github'], |
| 621 | * limit: 5 |
| 622 | * }, { |
| 623 | * modifySchema: ({ toolSlug, toolkitSlug, schema }) => { |
| 624 | * // Add custom properties to tool schema |
| 625 | * return { |
| 626 | * ...schema, |
| 627 | * customProperty: `Modified ${toolSlug} from ${toolkitSlug}`, |
| 628 | * tags: [...(schema.tags || []), 'customized'] |
| 629 | * }; |
| 630 | * } |
| 631 | * }); |
| 632 | * |
| 633 | * // Search for tools |
| 634 | * const searchResults = await composio.tools.getRawComposioTools({ |
| 635 | * search: 'user management' |
| 636 | * }); |
| 637 | * |
| 638 | * // Get tools by authentication config |
| 639 | * const authSpecificTools = await composio.tools.getRawComposioTools({ |
| 640 | * authConfigIds: ['auth_config_123'] |
| 641 | * }); |
| 642 | * ``` |
| 643 | */ |
| 644 | async getRawComposioTools( |
| 645 | query: ToolListParams, |
| 646 | options?: SchemaModifierOptions, |
| 647 | requestOptions?: ComposioRequestOptions |
| 648 | ): Promise<ToolList> { |
| 649 | if ('tools' in query && 'toolkits' in query) { |
| 650 | throw new ValidationError( |
| 651 | 'Invalid tool list parameters. You should not use tools and toolkits filter together.' |
| 652 | ); |
| 653 | } |
| 654 | |
| 655 | const queryParams = ToolListParamsSchema.safeParse(query); |
| 656 | if (queryParams.error) { |
| 657 | throw new ValidationError('Invalid tool list parameters', { |
| 658 | cause: queryParams.error, |
| 659 | }); |
| 660 | } |
| 661 | |
| 662 | const shouldAutoApplyImportant = |
| 663 | 'toolkits' in queryParams.data && |
| 664 | !('tools' in queryParams.data) && |
| 665 | !('tags' in queryParams.data) && |
| 666 | !('search' in queryParams.data) && |
| 667 | // if the user provides a limit, do not apply the important flag |
| 668 | !('limit' in queryParams.data) && |
| 669 | queryParams.data.important !== false; |
| 670 | |
| 671 | const effectiveImportant = |
| 672 | 'important' in queryParams.data ? queryParams.data.important : shouldAutoApplyImportant; |
| 673 | |
| 674 | // check if the query params contains atleast one of the following: tools, toolkits, search, authConfigIds |
| 675 | if (!( |
| 676 | 'tools' in queryParams.data || |
| 677 | 'toolkits' in queryParams.data || |
| 678 | 'search' in queryParams.data || |
| 679 | 'authConfigIds' in queryParams.data |
| 680 | )) { |
| 681 | throw new ValidationError( |
| 682 | 'Invalid tool list parameters, atleast one of the following parameters is required: tools, toolkits, search, authConfigIds' |
| 683 | ); |
| 684 | } |
| 685 | |
| 686 | // if tools are provided, set the limit to 9999 so that all tools are fetched |
| 687 | let limit = 'limit' in queryParams.data ? queryParams.data.limit : undefined; |
| 688 | if ('tools' in queryParams.data) { |
| 689 | limit = 9999; |
| 690 | } |
| 691 | |
| 692 | const filters: ComposioToolListParams = { |
| 693 | ...('tools' in queryParams.data ? { tool_slugs: queryParams.data.tools?.join(',') } : {}), |
| 694 | ...('toolkits' in queryParams.data |
| 695 | ? { toolkit_slug: queryParams.data.toolkits?.join(',') } |
| 696 | : {}), |
| 697 | ...(limit ? { limit } : {}), |
| 698 | ...('tags' in queryParams.data ? { tags: queryParams.data.tags } : {}), |
| 699 | ...('scopes' in queryParams.data ? { scopes: queryParams.data.scopes } : {}), |
| 700 | // `search` is the SDK's public option; the API deprecated the `search` |
| 701 | // wire param in favour of `query`, so send the replacement. |
| 702 | ...('search' in queryParams.data ? { query: queryParams.data.search } : {}), |
| 703 | ...('authConfigIds' in queryParams.data |
| 704 | ? { auth_config_ids: queryParams.data.authConfigIds } |
| 705 | : {}), |
| 706 | ...(effectiveImportant ? { important: 'true' } : {}), |
| 707 | ...{ toolkit_versions: this.toolkitVersions }, |
| 708 | }; |
| 709 | |
| 710 | logger.debug(`Fetching tools with filters: ${JSON.stringify(filters, null, 2)}`); |
| 711 | |
| 712 | const tools = await withCancellation( |
| 713 | () => this.client.tools.list(filters, requestOptions), |
| 714 | requestOptions?.signal |
| 715 | ); |
| 716 | |
| 717 | if (!tools) { |
| 718 | return []; |
| 719 | } |
| 720 | const caseTransformedTools = tools.items |
| 721 | .map(tool => this.transformToolCases(tool)) |
| 722 | .filter((tool): tool is Tool => tool !== undefined); |
| 723 | |
| 724 | let modifiedTools = await this.applyDefaultSchemaModifiers(caseTransformedTools); |
| 725 | |
| 726 | // apply local modifiers if they are provided |
| 727 | if (options?.modifySchema) { |
| 728 | const modifier = options.modifySchema; |
| 729 | if (typeof modifier === 'function') { |
| 730 | const modifiedPromises = modifiedTools.map(tool => |
| 731 | modifier({ |
| 732 | toolSlug: tool.slug, |
| 733 | toolkitSlug: tool.toolkit?.slug ?? 'unknown', |
| 734 | schema: tool, |
| 735 | }) |
| 736 | ); |
| 737 | modifiedTools = await Promise.all(modifiedPromises); |
| 738 | } else { |
| 739 | throw new ComposioInvalidModifierError('Invalid schema modifier. Not a function.'); |
| 740 | } |
| 741 | } |
| 742 | |
| 743 | return modifiedTools; |
| 744 | } |
| 745 | |
| 746 | /** |
| 747 | * Fetches tools exposed by a tool router session. |
| 748 | * This includes helper/meta tools plus any tools preloaded into the session. |
| 749 | * It provides access to the underlying tool data without provider-specific wrapping. |
| 750 | * |
| 751 | * @param sessionId {string} The session id to get tools for |
| 752 | * @param options {SchemaModifierOptions} Optional configuration for tool retrieval |
| 753 | * @param {TransformToolSchemaModifier} [options.modifySchema] - Function to transform the tool schema |
| 754 | * @returns {Promise<ToolList>} The list of session tools |
| 755 | * |
| 756 | * @example |
| 757 | * ```typescript |
| 758 | * const sessionTools = await composio.tools.getRawToolRouterSessionTools('session_123'); |
| 759 | * console.log(sessionTools); |
| 760 | * ``` |
| 761 | */ |
| 762 | async getRawToolRouterSessionTools( |
| 763 | sessionId: string, |
| 764 | options?: SchemaModifierOptions, |
| 765 | requestOptions?: ComposioRequestOptions |
| 766 | ): Promise<ToolList> { |
| 767 | const tools: ToolList = []; |
| 768 | let cursor: string | null | undefined; |
| 769 | |
| 770 | do { |
| 771 | const sessionToolsParams = { |
| 772 | limit: TOOL_ROUTER_SESSION_TOOLS_PAGE_LIMIT, |
| 773 | ...(cursor ? { cursor } : {}), |
| 774 | }; |
| 775 | const response = await withCancellation( |
| 776 | () => this.client.toolRouter.session.tools(sessionId, sessionToolsParams, requestOptions), |
| 777 | requestOptions?.signal |
| 778 | ); |
| 779 | tools.push( |
| 780 | ...response.items |
| 781 | .map(tool => this.transformToolCases(tool)) |
| 782 | .filter((tool): tool is Tool => tool !== undefined) |
| 783 | ); |
| 784 | cursor = response.next_cursor; |
| 785 | } while (cursor); |
| 786 | |
| 787 | let modifiedTools = tools; |
| 788 | // apply local modifiers if they are provided |
| 789 | if (options?.modifySchema) { |
| 790 | const modifier = options.modifySchema; |
| 791 | if (typeof modifier === 'function') { |
| 792 | const modifiedPromises = modifiedTools.map(tool => |
| 793 | modifier({ |
| 794 | toolSlug: tool.slug, |
| 795 | toolkitSlug: tool.toolkit?.slug ?? 'unknown', |
| 796 | schema: tool, |
| 797 | }) |
| 798 | ); |
| 799 | modifiedTools = await Promise.all(modifiedPromises); |
| 800 | } else { |
| 801 | throw new ComposioInvalidModifierError('Invalid schema modifier. Not a function.'); |
| 802 | } |
| 803 | } |
| 804 | |
| 805 | return modifiedTools; |
| 806 | } |
| 807 | |
| 808 | /** |
| 809 | * Retrieves a specific tool by its slug from the Composio API. |
| 810 | * |
| 811 | * This method fetches a single tool in raw format without provider-specific wrapping, |
| 812 | * providing direct access to the tool's schema and metadata. Tool versions are controlled |
| 813 | * at the Composio SDK initialization level through the `toolkitVersions` configuration. |
| 814 | * Experimental local tools are session-scoped; attach them when creating or reusing a |
| 815 | * Tool Router session, then use `session.tools()`, `session.localTools()`, or |
| 816 | * `session.execute()`. |
| 817 | * |
| 818 | * @param {string} slug - The unique identifier of the tool (e.g., 'GITHUB_GET_REPOS') |
| 819 | * @param {GetRawComposioToolBySlugOptions} [options] - Optional configuration for tool retrieval |
| 820 | * @param {TransformToolSchemaModifier} [options.modifySchema] - Function to transform the tool schema |
| 821 | * @returns {Promise<Tool>} The requested tool with its complete schema and metadata |
| 822 | * |
| 823 | * @example |
| 824 | * ```typescript |
| 825 | * // Get a tool by slug |
| 826 | * const tool = await composio.tools.getRawComposioToolBySlug('GITHUB_GET_REPOS'); |
| 827 | * console.log(tool.name, tool.description); |
| 828 | * |
| 829 | * // Get a tool with schema transformation |
| 830 | * const customizedTool = await composio.tools.getRawComposioToolBySlug( |
| 831 | * 'SLACK_SEND_MESSAGE', |
| 832 | * { |
| 833 | * modifySchema: ({ toolSlug, toolkitSlug, schema }) => { |
| 834 | * return { |
| 835 | * ...schema, |
| 836 | * description: `Enhanced ${schema.description} with custom modifications`, |
| 837 | * customMetadata: { |
| 838 | * lastModified: new Date().toISOString(), |
| 839 | * toolkit: toolkitSlug |
| 840 | * } |
| 841 | * }; |
| 842 | * } |
| 843 | * } |
| 844 | * ); |
| 845 | * |
| 846 | * // Access tool properties |
| 847 | * const githubTool = await composio.tools.getRawComposioToolBySlug('GITHUB_CREATE_AN_ISSUE'); |
| 848 | * console.log({ |
| 849 | * slug: githubTool.slug, |
| 850 | * name: githubTool.name, |
| 851 | * toolkit: githubTool.toolkit?.name, |
| 852 | * version: githubTool.version, |
| 853 | * availableVersions: githubTool.availableVersions, |
| 854 | * inputParameters: githubTool.inputParameters |
| 855 | * }); |
| 856 | * ``` |
| 857 | */ |
| 858 | async getRawComposioToolBySlug( |
| 859 | slug: string, |
| 860 | options?: ToolRetrievalOptions, |
| 861 | requestOptions?: ComposioRequestOptions |
| 862 | ): Promise<Tool> { |
| 863 | let tool: ToolRetrieveResponse; |
| 864 | try { |
| 865 | // Build API call parameters based on version source |
| 866 | const retrieveParams = options?.version |
| 867 | ? { version: options.version } // Explicit version → use 'version' param |
| 868 | : { toolkit_versions: this.toolkitVersions }; // SDK config → use 'toolkit_versions' param |
| 869 | |
| 870 | tool = await withCancellation( |
| 871 | () => this.client.tools.retrieve(slug, retrieveParams, requestOptions), |
| 872 | requestOptions?.signal |
| 873 | ); |
| 874 | } catch (error) { |
| 875 | if (error instanceof ComposioRequestCancelledError) { |
| 876 | throw error; |
| 877 | } |
| 878 | if (isRateLimitResponse(error)) { |
| 879 | throw new ComposioToolFetchRateLimitError( |
| 880 | withApiErrorMessage( |
| 881 | `Rate limited while retrieving tool with slug ${slug}`, |
| 882 | error.details |
| 883 | ), |
| 884 | error, |
| 885 | { slug } |
| 886 | ); |
| 887 | } |
| 888 | // The tools endpoint reports an unknown slug as 404 (or 400 for a |
| 889 | // malformed one). Anything else (401, 5xx, network) is not "not found", |
| 890 | // so keep the client error reachable as `cause` under a generic error. |
| 891 | if (error instanceof APIError && (error.status === 404 || error.status === 400)) { |
| 892 | throw new ComposioToolNotFoundError( |
| 893 | withApiErrorMessage(`Tool with slug ${slug} not found`, error.details), |
| 894 | { |
| 895 | meta: { slug }, |
| 896 | cause: error, |
| 897 | possibleFixes: apiErrorSuggestedFixes(error.details), |
| 898 | } |
| 899 | ); |
| 900 | } |
| 901 | const details = error instanceof APIError ? error.details : undefined; |
| 902 | const originalMessage = |
| 903 | error instanceof APIError && error.status !== undefined |
| 904 | ? undefined |
| 905 | : error instanceof Error |
| 906 | ? error.message |
| 907 | : undefined; |
| 908 | throw new ComposioToolFetchError( |
| 909 | withApiErrorMessage(`Unable to retrieve tool with slug ${slug}`, details, originalMessage), |
| 910 | { |
| 911 | meta: { slug }, |
| 912 | cause: error, |
| 913 | possibleFixes: apiErrorSuggestedFixes(details), |
| 914 | } |
| 915 | ); |
| 916 | } |
| 917 | |
| 918 | // change the case of the tool to camel case and apply default modifiers |
| 919 | const transformedTool = this.transformToolCases(tool); |
| 920 | if (transformedTool === undefined) { |
| 921 | // The tool exists; its schema is what could not be parsed. Reporting that |
| 922 | // as TOOL_NOT_FOUND makes a caller that treats the code as "no such tool" |
| 923 | // hide a real one. |
| 924 | throw new ComposioToolSchemaInvalidError( |
| 925 | `Tool with slug ${slug} has an unusable input schema`, |
| 926 | { meta: { slug } } |
| 927 | ); |
| 928 | } |
| 929 | let [modifiedTool] = await this.applyDefaultSchemaModifiers([transformedTool]); |
| 930 | // apply local modifiers if they are provided |
| 931 | if (options?.modifySchema) { |
| 932 | const modifier = options.modifySchema; |
| 933 | if (typeof modifier === 'function') { |
| 934 | modifiedTool = await modifier({ |
| 935 | toolSlug: slug, |
| 936 | toolkitSlug: modifiedTool.toolkit?.slug ?? 'unknown', |
| 937 | schema: modifiedTool, |
| 938 | }); |
| 939 | } else { |
| 940 | throw new ComposioInvalidModifierError('Invalid schema modifier. Not a function.'); |
| 941 | } |
| 942 | } |
| 943 | return modifiedTool; |
| 944 | } |
| 945 | |
| 946 | /** |
| 947 | * Get a list of tools from Composio based on filters. |
| 948 | * This method fetches the tools from the Composio API and wraps them using the provider. |
| 949 | * |
| 950 | * @param {string} userId - The user id to get the tools for |
| 951 | * @param {ToolListParams} filters - The filters to apply when fetching tools |
| 952 | * @param {ProviderOptions<TProvider> & ComposioRequestOptions} [options] - Provider options, modifiers, and/or AbortSignal |
| 953 | * @returns {Promise<ReturnType<T['wrapTools']>>} The wrapped tools collection |
| 954 | * |
| 955 | * @example |
| 956 | * ```typescript |
| 957 | * // Get tools from the GitHub toolkit |
| 958 | * const tools = await composio.tools.get('default', { |
| 959 | * toolkits: ['github'], |
| 960 | * limit: 10 |
| 961 | * }); |
| 962 | * |
| 963 | * // Timeout a slow search after 5s |
| 964 | * const emailTools = await composio.tools.get('default', { |
| 965 | * search: 'send email', |
| 966 | * }, { signal: AbortSignal.timeout(5_000) }); |
| 967 | * ``` |
| 968 | */ |
| 969 | async get<T extends TProvider>( |
| 970 | userId: string, |
| 971 | filters: ToolListParams, |
| 972 | options?: ProviderOptions<TProvider> & ComposioRequestOptions |
| 973 | ): Promise<ReturnType<T['wrapTools']>>; |
| 974 | |
| 975 | /** |
| 976 | * Get a specific tool by its slug. |
| 977 | * This method fetches the tool from the Composio API and wraps it using the provider. |
| 978 | * |
| 979 | * @param {string} userId - The user id to get the tool for |
| 980 | * @param {string} slug - The slug of the tool to fetch |
| 981 | * @param {ProviderOptions<TProvider> & ComposioRequestOptions} [options] - Optional provider options including modifiers and signal |
| 982 | * @returns {Promise<ReturnType<T['wrapTools']>>} The wrapped tool |
| 983 | * |
| 984 | * @example |
| 985 | * ```typescript |
| 986 | * // Get a specific tool by slug |
| 987 | * const hackerNewsUserTool = await composio.tools.get('default', 'HACKERNEWS_GET_USER'); |
| 988 | * |
| 989 | * // Get a tool with schema modifications |
| 990 | * const tool = await composio.tools.get('default', 'GITHUB_GET_REPOS', { |
| 991 | * modifySchema: (toolSlug, toolkitSlug, schema) => { |
| 992 | * // Customize the tool schema |
| 993 | * return {...schema, description: 'Custom description'}; |
| 994 | * } |
| 995 | * }); |
| 996 | * |
| 997 | * // Timeout after 5s |
| 998 | * const tools = await composio.tools.get('user_1', { search: 'email' }, { |
| 999 | * signal: AbortSignal.timeout(5_000) |
| 1000 | * }); |
| 1001 | * ``` |
| 1002 | */ |
| 1003 | async get<T extends TProvider>( |
| 1004 | userId: string, |
| 1005 | slug: string, |
| 1006 | options?: ProviderOptions<TProvider> & ComposioRequestOptions |
| 1007 | ): Promise<ReturnType<T['wrapTools']>>; |
| 1008 | |
| 1009 | async get( |
| 1010 | userId: string, |
| 1011 | arg2: ToolListParams | string, |
| 1012 | arg3?: ProviderOptions<TProvider> & ComposioRequestOptions |
| 1013 | ): Promise<TToolCollection> { |
| 1014 | const options = arg3; |
| 1015 | const requestOptions: ComposioRequestOptions | undefined = |
| 1016 | options?.signal != null ? { signal: options.signal } : undefined; |
| 1017 | // Strip signal so it isn't captured in the provider execution closure — |
| 1018 | // an expired AbortSignal.timeout() would poison every future tool call. |
| 1019 | const { signal: _, ...modifiers } = options ?? {}; |
| 1020 | |
| 1021 | if (typeof arg2 === 'string') { |
| 1022 | const rawTool = await this.getRawComposioToolBySlug(arg2, undefined, requestOptions); |
| 1023 | const [tool] = await this.applySchemaModifiers([rawTool], options?.modifySchema); |
| 1024 | return this.wrapToolsForProvider(userId, [tool], modifiers as ExecuteToolModifiers, [ |
| 1025 | rawTool, |
| 1026 | ]) as TToolCollection; |
| 1027 | } else { |
| 1028 | const rawTools = await this.getRawComposioTools(arg2, undefined, requestOptions); |
| 1029 | const tools = await this.applySchemaModifiers(rawTools, options?.modifySchema); |
| 1030 | return this.wrapToolsForProvider( |
| 1031 | userId, |
| 1032 | tools, |
| 1033 | modifiers as ExecuteToolModifiers, |
| 1034 | rawTools |
| 1035 | ) as TToolCollection; |
| 1036 | } |
| 1037 | } |
| 1038 | |
| 1039 | private async applySchemaModifiers( |
| 1040 | tools: Tool[], |
| 1041 | modifier?: TransformToolSchemaModifier |
| 1042 | ): Promise<Tool[]> { |
| 1043 | if (modifier && typeof modifier !== 'function') { |
| 1044 | throw new ComposioInvalidModifierError('Invalid schema modifier. Not a function.'); |
| 1045 | } |
| 1046 | return Promise.all( |
| 1047 | tools.map(tool => { |
| 1048 | const schema = ToolSchema.parse(tool); |
| 1049 | return modifier |
| 1050 | ? modifier({ |
| 1051 | toolSlug: tool.slug, |
| 1052 | toolkitSlug: tool.toolkit?.slug ?? 'unknown', |
| 1053 | schema, |
| 1054 | }) |
| 1055 | : schema; |
| 1056 | }) |
| 1057 | ); |
| 1058 | } |
| 1059 | |
| 1060 | /** |
| 1061 | * @internal |
| 1062 | * Creates a global execute tool function. |
| 1063 | * This function is used by providers to execute tools. |
| 1064 | * It skips the version check for provider controlled execution. |
| 1065 | * @returns {GlobalExecuteToolFn} The global execute tool function |
| 1066 | */ |
| 1067 | private createExecuteFnForProviders(): GlobalExecuteToolFn { |
| 1068 | return async (slug: string, body: ToolExecuteParams, modifiers?: ExecuteToolModifiers) => { |
| 1069 | return await this.execute( |
| 1070 | slug, |
| 1071 | { ...body, dangerouslySkipVersionCheck: body.dangerouslySkipVersionCheck ?? true }, |
| 1072 | modifiers |
| 1073 | ); |
| 1074 | }; |
| 1075 | } |
| 1076 | |
| 1077 | /** |
| 1078 | * @internal |
| 1079 | * Utility to wrap a given set of tools in the format expected by the provider |
| 1080 | * |
| 1081 | * @param userId - The user id to get the tools for |
| 1082 | * @param tools - The tools to wrap |
| 1083 | * @param modifiers - The modifiers to be applied to the tools |
| 1084 | * @param rawTools - The fetched schemas used during execution |
| 1085 | * @returns The wrapped tools |
| 1086 | */ |
| 1087 | wrapToolsForProvider<T extends TProvider>( |
| 1088 | userId: string, |
| 1089 | tools: Tool[], |
| 1090 | modifiers?: ExecuteToolModifiers, |
| 1091 | rawTools: Tool[] = tools.map(tool => ToolSchema.parse(tool)) |
| 1092 | ): ReturnType<T['wrapTools']> { |
| 1093 | const executeToolFn = this.createExecuteToolFn(userId, modifiers, rawTools); |
| 1094 | return this.provider.wrapTools(tools, executeToolFn) as ReturnType<T['wrapTools']>; |
| 1095 | } |
| 1096 | |
| 1097 | /** |
| 1098 | * @internal |
| 1099 | * Utility to wrap a given set of tools in the format expected by the tool router |
| 1100 | * |
| 1101 | * @param {string} sessionId - The session id to execute the tool for |
| 1102 | * @param {Tool[]} tools - The tools to wrap |
| 1103 | * @param {SessionExecuteMetaModifiers} modifiers - The modifiers to apply to the tool |
| 1104 | * @returns {Tool[]} The wrapped tools |
| 1105 | */ |
| 1106 | wrapToolsForToolRouter( |
| 1107 | sessionId: string, |
| 1108 | tools: Tool[], |
| 1109 | modifiers?: SessionExecuteMetaModifiers, |
| 1110 | rawTools: Tool[] = tools.map(tool => ToolSchema.parse(tool)) |
| 1111 | ): Tool[] { |
| 1112 | const executeToolFn = this.createExecuteToolFnForToolRouter(sessionId, rawTools, modifiers); |
| 1113 | return this.provider.wrapTools(tools, executeToolFn) as Tool[]; |
| 1114 | } |
| 1115 | |
| 1116 | /** |
| 1117 | * @internal |
| 1118 | * @description |
| 1119 | * Creates a function that executes a tool. |
| 1120 | * This function is used by agentic providers to execute the tool |
| 1121 | * |
| 1122 | * @param {string} userId - The user id |
| 1123 | * @param {ExecuteToolModifiers} modifiers - The modifiers to be applied to the tool |
| 1124 | * @param {Tool[]} tools - The fetched tools available to the provider |
| 1125 | * @returns {ExecuteToolFn} The execute tool function |
| 1126 | */ |
| 1127 | private createExecuteToolFn( |
| 1128 | userId: string, |
| 1129 | modifiers: ExecuteToolModifiers | undefined, |
| 1130 | tools: Tool[] |
| 1131 | ): ExecuteToolFn { |
| 1132 | const toolBySlug = new Map(tools.map(tool => [tool.slug.toUpperCase(), tool])); |
| 1133 | const executeToolFn = async (toolSlug: string, input: Record<string, unknown>) => { |
| 1134 | const body: ToolExecuteParams = { |
| 1135 | userId, |
| 1136 | arguments: input, |
| 1137 | // dangerously skip version check for agentic tool execution via providers |
| 1138 | // this can be safe because most agentic flows users fetch latest version and then execute the tool |
| 1139 | dangerouslySkipVersionCheck: true, |
| 1140 | }; |
| 1141 | const tool = toolBySlug.get(toolSlug.toUpperCase()); |
| 1142 | return tool |
| 1143 | ? this.executeWithTool(toolSlug, this.parseToolExecuteParams(body), modifiers, tool) |
| 1144 | : this.execute(toolSlug, body, modifiers); |
| 1145 | }; |
| 1146 | return executeToolFn; |
| 1147 | } |
| 1148 | |
| 1149 | /** |
| 1150 | * @internal |
| 1151 | * Creates a function that executes a tool for a tool router session |
| 1152 | * |
| 1153 | * @param {string} sessionId - The session id to execute the tool for |
| 1154 | * @param {SessionExecuteMetaModifiers} modifiers - The modifiers to apply to the tool |
| 1155 | * @returns {ExecuteToolFn} The execute tool function |
| 1156 | */ |
| 1157 | private createExecuteToolFnForToolRouter( |
| 1158 | sessionId: string, |
| 1159 | tools: Tool[], |
| 1160 | modifiers?: SessionExecuteMetaModifiers |
| 1161 | ): ExecuteToolFn { |
| 1162 | const toolBySlug = new Map(tools.map(tool => [tool.slug.toUpperCase(), tool])); |
| 1163 | const executeToolFn = async ( |
| 1164 | toolSlug: string, |
| 1165 | input: Record<string, unknown> |
| 1166 | ): Promise<ToolExecuteResponse> => { |
| 1167 | return await this.executeSessionTool( |
| 1168 | toolSlug, |
| 1169 | { |
| 1170 | sessionId, |
| 1171 | arguments: input, |
| 1172 | }, |
| 1173 | modifiers, |
| 1174 | toolBySlug.get(toolSlug.toUpperCase()) |
| 1175 | ); |
| 1176 | }; |
| 1177 | return executeToolFn; |
| 1178 | } |
| 1179 | |
| 1180 | /** |
| 1181 | * @internal |
| 1182 | * Executes a composio tool via API without modifiers |
| 1183 | * @param tool - The tool to execute |
| 1184 | * @param body - The body of the tool execution |
| 1185 | * @returns The response from the tool execution |
| 1186 | */ |
| 1187 | private async executeComposioTool( |
| 1188 | tool: Tool, |
| 1189 | body: ToolExecuteParams, |
| 1190 | requestOptions?: ComposioRequestOptions |
| 1191 | ): Promise<ToolExecuteResponse> { |
| 1192 | const toolkitVersion = |
| 1193 | body.version ?? getToolkitVersion(tool.toolkit?.slug ?? 'unknown', this.toolkitVersions); |
| 1194 | // if the version is latest and dangerouslySkipVersionCheck is not true, throw an error |
| 1195 | if (toolkitVersion === 'latest' && !body.dangerouslySkipVersionCheck) { |
| 1196 | throw new ComposioToolVersionRequiredError(); |
| 1197 | } |
| 1198 | try { |
| 1199 | const executeBody: ComposioToolExecuteParams = { |
| 1200 | allow_tracing: body.allowTracing, |
| 1201 | connected_account_id: body.connectedAccountId, |
| 1202 | custom_auth_params: body.customAuthParams |
| 1203 | ? { |
| 1204 | base_url: body.customAuthParams.baseURL, |
| 1205 | body: body.customAuthParams.body, |
| 1206 | parameters: body.customAuthParams.parameters, |
| 1207 | } |
| 1208 | : undefined, |
| 1209 | /** |
| 1210 | * @deprecated The `customConnectionData` execute param is deprecated and will be |
| 1211 | * removed in a future release. Use `customAuthParams` instead. |
| 1212 | */ |
| 1213 | custom_connection_data: body.customConnectionData, |
| 1214 | arguments: body.arguments, |
| 1215 | user_id: body.userId, |
| 1216 | version: toolkitVersion, |
| 1217 | text: body.text, |
| 1218 | }; |
| 1219 | const result = await withCancellation( |
| 1220 | () => this.client.tools.execute(tool.slug, executeBody, withoutRetries(requestOptions)), |
| 1221 | requestOptions?.signal |
| 1222 | ); |
| 1223 | // transform the response to the ToolExecuteResponse format |
| 1224 | return this.transformToolExecuteResponse(result); |
| 1225 | } catch (error) { |
| 1226 | if (error instanceof ComposioRequestCancelledError) { |
| 1227 | throw error; |
| 1228 | } |
| 1229 | const toolError = handleToolExecutionError(tool.slug, error as Error); |
| 1230 | throw toolError; |
| 1231 | } |
| 1232 | } |
| 1233 | |
| 1234 | private async executeWithTool( |
| 1235 | slug: string, |
| 1236 | body: ToolExecuteParams, |
| 1237 | options: (ExecuteToolModifiers & ComposioRequestOptions) | undefined, |
| 1238 | tool: Tool |
| 1239 | ): Promise<ToolExecuteResponse> { |
| 1240 | const requestOptions: ComposioRequestOptions | undefined = |
| 1241 | options?.signal != null ? { signal: options.signal } : undefined; |
| 1242 | const { signal: _, ...modifiers } = options ?? {}; |
| 1243 | const toolkitSlug = tool.toolkit?.slug ?? 'unknown'; |
| 1244 | |
| 1245 | const params = await this.applyBeforeExecuteModifiers( |
| 1246 | tool, |
| 1247 | { |
| 1248 | toolSlug: slug, |
| 1249 | toolkitSlug, |
| 1250 | params: body, |
| 1251 | }, |
| 1252 | modifiers as ExecuteToolModifiers, |
| 1253 | requestOptions |
| 1254 | ); |
| 1255 | |
| 1256 | let result = await this.executeComposioTool(tool, params, requestOptions); |
| 1257 | |
| 1258 | result = await this.applyAfterExecuteModifiers( |
| 1259 | tool, |
| 1260 | { |
| 1261 | toolSlug: slug, |
| 1262 | toolkitSlug, |
| 1263 | result, |
| 1264 | }, |
| 1265 | (modifiers as ExecuteToolModifiers).afterExecute, |
| 1266 | requestOptions |
| 1267 | ); |
| 1268 | |
| 1269 | return result; |
| 1270 | } |
| 1271 | |
| 1272 | private parseToolExecuteParams(body: ToolExecuteParams): ToolExecuteParams { |
| 1273 | const executeParams = ToolExecuteParamsSchema.safeParse(body); |
| 1274 | if (!executeParams.success) { |
| 1275 | throw new ValidationError('Invalid tool execute parameters', { cause: executeParams.error }); |
| 1276 | } |
| 1277 | return executeParams.data; |
| 1278 | } |
| 1279 | |
| 1280 | /** |
| 1281 | * Executes a given tool with the provided parameters. |
| 1282 | * |
| 1283 | * This method calls the Composio API to execute the tool and returns the response. |
| 1284 | * |
| 1285 | * **Version Control:** |
| 1286 | * By default, manual tool execution requires a specific toolkit version. If the version resolves to "latest", |
| 1287 | * the execution will throw a `ComposioToolVersionRequiredError` unless `dangerouslySkipVersionCheck` is set to `true`. |
| 1288 | * This helps prevent unexpected behavior when new toolkit versions are released. |
| 1289 | * |
| 1290 | * @param {string} slug - The slug/ID of the tool to be executed |
| 1291 | * @param {ToolExecuteParams} body - The parameters to be passed to the tool |
| 1292 | * @param {string} [body.version] - The specific version of the tool to execute (e.g., "20250909_00") |
| 1293 | * @param {boolean} [body.dangerouslySkipVersionCheck] - Skip version validation for "latest" version (use with caution) |
| 1294 | * @param {string} [body.userId] - The user ID to execute the tool for |
| 1295 | * @param {string} [body.connectedAccountId] - The connected account ID to use for authenticated tools |
| 1296 | * @param {Record<string, unknown>} [body.arguments] - The arguments to pass to the tool |
| 1297 | * @param {ExecuteToolModifiers & ComposioRequestOptions} [options] - Optional modifiers and request options |
| 1298 | * @returns {Promise<ToolExecuteResponse>} The response from the tool execution |
| 1299 | * |
| 1300 | * @throws {ComposioConnectedAccountNotFoundError} If the connected account is not found |
| 1301 | * @throws {ComposioToolNotFoundError} If the tool with the given slug is not found |
| 1302 | * @throws {ComposioToolVersionRequiredError} If version resolves to "latest" and dangerouslySkipVersionCheck is not true |
| 1303 | * @throws {ComposioToolExecutionError} If there is an error during tool execution |
| 1304 | * |
| 1305 | * @example Execute with a specific version (recommended for production) |
| 1306 | * ```typescript |
| 1307 | * // Look up the tool's current version once, then pin that string in your code or config |
| 1308 | * const { version } = await composio.tools.getRawComposioToolBySlug('GITHUB_GET_REPOS'); |
| 1309 | * console.log(version); // e.g. '20250909_00' |
| 1310 | * |
| 1311 | * const result = await composio.tools.execute('GITHUB_GET_REPOS', { |
| 1312 | * userId: 'default', |
| 1313 | * version: '20250909_00', |
| 1314 | * arguments: { owner: 'composio' } |
| 1315 | * }); |
| 1316 | * ``` |
| 1317 | * |
| 1318 | * @example Execute with dangerouslySkipVersionCheck (not recommended for production) |
| 1319 | * ```typescript |
| 1320 | * const result = await composio.tools.execute('HACKERNEWS_GET_USER', { |
| 1321 | * userId: 'default', |
| 1322 | * arguments: { userId: 'pg' }, |
| 1323 | * dangerouslySkipVersionCheck: true // Allows execution with "latest" version |
| 1324 | * }); |
| 1325 | * ``` |
| 1326 | * |
| 1327 | * @example Execute with SDK-level toolkit versions configuration |
| 1328 | * ```typescript |
| 1329 | * // If toolkitVersions are set during Composio initialization, no need to pass version |
| 1330 | * const composio = new Composio({ toolkitVersions: { github: '20250909_00' } }); |
| 1331 | * const result = await composio.tools.execute('GITHUB_GET_REPOS', { |
| 1332 | * userId: 'default', |
| 1333 | * arguments: { owner: 'composio' } |
| 1334 | * }); |
| 1335 | * ``` |
| 1336 | * |
| 1337 | * @example Execute with modifiers |
| 1338 | * ```typescript |
| 1339 | * const result = await composio.tools.execute('GITHUB_GET_ISSUES', { |
| 1340 | * userId: 'default', |
| 1341 | * version: '20250909_00', |
| 1342 | * arguments: { owner: 'composio', repo: 'sdk' } |
| 1343 | * }, { |
| 1344 | * beforeExecute: ({ toolSlug, toolkitSlug, params }) => { |
| 1345 | * console.log(`Executing ${toolSlug} from ${toolkitSlug}`); |
| 1346 | * return params; |
| 1347 | * }, |
| 1348 | * afterExecute: ({ toolSlug, toolkitSlug, result }) => { |
| 1349 | * console.log(`Completed ${toolSlug}`); |
| 1350 | * return result; |
| 1351 | * } |
| 1352 | * }); |
| 1353 | * ``` |
| 1354 | * |
| 1355 | * @example Execute with timeout |
| 1356 | * ```typescript |
| 1357 | * const result = await composio.tools.execute('HACKERNEWS_GET_FRONTPAGE', { |
| 1358 | * userId: 'default', |
| 1359 | * arguments: {}, |
| 1360 | * dangerouslySkipVersionCheck: true, |
| 1361 | * }, { signal: AbortSignal.timeout(5_000) }); |
| 1362 | * ``` |
| 1363 | */ |
| 1364 | async execute( |
| 1365 | slug: string, |
| 1366 | body: ToolExecuteParams, |
| 1367 | options?: ExecuteToolModifiers & ComposioRequestOptions |
| 1368 | ): Promise<ToolExecuteResponse> { |
| 1369 | const executeParams = this.parseToolExecuteParams(body); |
| 1370 | |
| 1371 | const requestOptions: ComposioRequestOptions | undefined = |
| 1372 | options?.signal != null ? { signal: options.signal } : undefined; |
| 1373 | |
| 1374 | const tool = await this.getToolSchemaForExecute(slug, executeParams.version, requestOptions); |
| 1375 | return this.executeWithTool(slug, executeParams, options, tool); |
| 1376 | } |
| 1377 | |
| 1378 | /** The tool's schema for `execute()`, fetched only if no unexpired copy is cached. Failures aren't cached. */ |
| 1379 | private async getToolSchemaForExecute( |
| 1380 | slug: string, |
| 1381 | version: string | undefined, |
| 1382 | requestOptions: ComposioRequestOptions | undefined |
| 1383 | ): Promise<Tool> { |
| 1384 | const key = `${slug}\0${version ?? ''}`; |
| 1385 | const cached = this.executeToolSchemas.get(key); |
| 1386 | if (cached && cached.expiresAt > Date.now()) { |
| 1387 | return cached.tool; |
| 1388 | } |
| 1389 | |
| 1390 | const tool = await this.getRawComposioToolBySlug(slug, { version }, requestOptions); |
| 1391 | |
| 1392 | const resolvedVersion = |
| 1393 | version ?? getToolkitVersion(tool.toolkit?.slug ?? 'unknown', this.toolkitVersions); |
| 1394 | const ttlMs = |
| 1395 | resolvedVersion === 'latest' ? LATEST_TOOL_SCHEMA_TTL_MS : PINNED_TOOL_SCHEMA_TTL_MS; |
| 1396 | // Re-insert so a refreshed entry counts as the newest. |
| 1397 | this.executeToolSchemas.delete(key); |
| 1398 | if (this.executeToolSchemas.size >= MAX_CACHED_TOOL_SCHEMAS) { |
| 1399 | const oldestKey = this.executeToolSchemas.keys().next().value; |
| 1400 | if (oldestKey !== undefined) { |
| 1401 | this.executeToolSchemas.delete(oldestKey); |
| 1402 | } |
| 1403 | } |
| 1404 | this.executeToolSchemas.set(key, { tool, expiresAt: Date.now() + ttlMs }); |
| 1405 | return tool; |
| 1406 | } |
| 1407 | |
| 1408 | /** |
| 1409 | * Executes a tool based on a tool router session. |
| 1410 | * |
| 1411 | * @param {string} toolSlug - The slug of the tool to execute |
| 1412 | * @param {ToolExecuteMetaParams} body - The execution parameters |
| 1413 | * @param {string} body.sessionId - The session id to execute the tool for |
| 1414 | * @param {Record<string, unknown>} body.arguments - The input to pass to the tool |
| 1415 | * @param {SessionExecuteMetaModifiers} modifiers - The modifiers to apply to the tool |
| 1416 | * @param {Tool} tool - Optional tool schema used to resolve toolkit metadata for modifiers |
| 1417 | * @returns {Promise<ToolExecuteResponse>} The response from the tool execution |
| 1418 | */ |
| 1419 | async executeSessionTool( |
| 1420 | toolSlug: string, |
| 1421 | body: ToolExecuteMetaParams, |
| 1422 | modifiers?: SessionExecuteMetaModifiers, |
| 1423 | tool?: Tool, |
| 1424 | options?: ToolRouterSessionExecuteOptions, |
| 1425 | requestOptions?: ComposioRequestOptions |
| 1426 | ): Promise<ToolExecuteResponse> { |
| 1427 | const executeParams = ToolExecuteMetaParamsSchema.safeParse(body); |
| 1428 | if (!executeParams.success) { |
| 1429 | throw new ValidationError('Invalid tool execute session parameters', { |
| 1430 | cause: executeParams.error, |
| 1431 | }); |
| 1432 | } |
| 1433 | |
| 1434 | let modifiedParams = body.arguments ?? {}; |
| 1435 | const toolkitSlug = tool?.toolkit?.slug ?? 'composio'; |
| 1436 | |
| 1437 | if (tool) { |
| 1438 | const fileModifiedParams = await this.applyFileUploadModifiers( |
| 1439 | tool, |
| 1440 | { |
| 1441 | toolSlug, |
| 1442 | toolkitSlug, |
| 1443 | params: { arguments: modifiedParams }, |
| 1444 | }, |
| 1445 | undefined, |
| 1446 | requestOptions |
| 1447 | ); |
| 1448 | modifiedParams = fileModifiedParams.arguments ?? {}; |
| 1449 | } |
| 1450 | |
| 1451 | // Apply beforeExecute modifier after file preprocessing so the hook sees |
| 1452 | // the same arguments that will be sent to the Tool Router. |
| 1453 | if (modifiers?.beforeExecute) { |
| 1454 | modifiedParams = await modifiers.beforeExecute({ |
| 1455 | toolSlug, |
| 1456 | toolkitSlug, |
| 1457 | sessionId: body.sessionId, |
| 1458 | params: modifiedParams, |
| 1459 | }); |
| 1460 | } |
| 1461 | |
| 1462 | const executePayload: SessionExecuteParams = { |
| 1463 | tool_slug: toolSlug, |
| 1464 | arguments: modifiedParams, |
| 1465 | // Provider-wrapped session tools are agentic calls, so they opt into |
| 1466 | // direct tool offload when the backend session workbench allows it. |
| 1467 | enable_auto_workbench_offload: true, |
| 1468 | }; |
| 1469 | if (options?.experimental) { |
| 1470 | executePayload.experimental = options.experimental; |
| 1471 | } |
| 1472 | |
| 1473 | const response = await withCancellation( |
| 1474 | () => |
| 1475 | this.client.toolRouter.session.execute( |
| 1476 | body.sessionId, |
| 1477 | executePayload, |
| 1478 | withoutRetries(requestOptions) |
| 1479 | ), |
| 1480 | requestOptions?.signal |
| 1481 | ).catch((error: unknown) => { |
| 1482 | throw handleToolExecutionError(toolSlug, error as Error); |
| 1483 | }); |
| 1484 | |
| 1485 | const { data, error, logId, resultType, instantCharge } = transformExecuteResponse( |
| 1486 | response, |
| 1487 | toolSlug |
| 1488 | ); |
| 1489 | let result: ToolExecuteResponse = { |
| 1490 | data, |
| 1491 | error, |
| 1492 | successful: isExecutionSuccessful({ resultType }), |
| 1493 | logId, |
| 1494 | ...(instantCharge !== undefined && { instantCharge }), |
| 1495 | }; |
| 1496 | |
| 1497 | // Apply afterExecute modifier if provided |
| 1498 | if (modifiers?.afterExecute) { |
| 1499 | result = await modifiers.afterExecute({ |
| 1500 | toolSlug, |
| 1501 | toolkitSlug, |
| 1502 | sessionId: body.sessionId, |
| 1503 | result, |
| 1504 | }); |
| 1505 | } |
| 1506 | |
| 1507 | return result; |
| 1508 | } |
| 1509 | |
| 1510 | /** |
| 1511 | * Fetches the list of all available tools in the Composio SDK. |
| 1512 | * |
| 1513 | * This method is mostly used by the CLI to get the list of tools. |
| 1514 | * No filtering is done on the tools, the list is cached in the backend, no further optimization is required. |
| 1515 | * @returns {Promise<ToolRetrieveEnumResponse>} The complete list of all available tools with their metadata |
| 1516 | * |
| 1517 | * @example |
| 1518 | * ```typescript |
| 1519 | * // Get all available tools as an enum |
| 1520 | * const toolsEnum = await composio.tools.getToolsEnum(); |
| 1521 | * console.log(toolsEnum.items); |
| 1522 | * ``` |
| 1523 | */ |
| 1524 | async getToolsEnum(requestOptions?: ComposioRequestOptions): Promise<ToolRetrieveEnumResponse> { |
| 1525 | return withCancellation( |
| 1526 | () => this.client.tools.retrieveEnum(requestOptions), |
| 1527 | requestOptions?.signal |
| 1528 | ); |
| 1529 | } |
| 1530 | |
| 1531 | /** |
| 1532 | * Generates arguments for a tool from a natural-language description of the task. |
| 1533 | * |
| 1534 | * Composio uses an LLM to fill the tool's input parameters from `text`. Review the |
| 1535 | * generated arguments before passing them to `tools.execute()`. |
| 1536 | * |
| 1537 | * @param {string} slug - The slug of the tool to generate arguments for |
| 1538 | * @param {ToolGetInputParams} body - The generation request |
| 1539 | * @param {string} body.text - What you want the tool to do, in natural language |
| 1540 | * @param {string} [body.custom_description] - Extra context about the tool for the LLM |
| 1541 | * @param {string} [body.system_prompt] - System prompt that steers the LLM |
| 1542 | * @param {string} [body.version] - Tool version to generate arguments for |
| 1543 | * @returns {Promise<ToolGetInputResponse>} The generated `arguments`, or an `error` when generation fails |
| 1544 | * |
| 1545 | * @example |
| 1546 | * ```typescript |
| 1547 | * const { arguments: args, error } = await composio.tools.getInput('GITHUB_CREATE_AN_ISSUE', { |
| 1548 | * text: 'Open an issue in composiohq/composio titled "Docs typo" describing the broken link', |
| 1549 | * version: '20250909_00', |
| 1550 | * }); |
| 1551 | * if (error) throw new Error(error); |
| 1552 | * console.log(args); // { owner: 'composiohq', repo: 'composio', title: 'Docs typo', ... } |
| 1553 | * ``` |
| 1554 | */ |
| 1555 | async getInput( |
| 1556 | slug: string, |
| 1557 | body: ToolGetInputParams, |
| 1558 | requestOptions?: ComposioRequestOptions |
| 1559 | ): Promise<ToolGetInputResponse> { |
| 1560 | return withCancellation( |
| 1561 | () => this.client.tools.getInput(slug, body, requestOptions), |
| 1562 | requestOptions?.signal |
| 1563 | ); |
| 1564 | } |
| 1565 | |
| 1566 | /** |
| 1567 | * Sends an HTTP request to a toolkit's API, authenticated as a connected account. |
| 1568 | * |
| 1569 | * Use it to call an endpoint that no predefined tool covers. Composio injects the |
| 1570 | * connected account's credentials on the server side. |
| 1571 | * |
| 1572 | * A relative `endpoint` is appended to the toolkit's base URL, and that base URL can |
| 1573 | * already include a path. Google Calendar's base URL is |
| 1574 | * `https://www.googleapis.com/calendar/v3`, so pass `/users/me/calendarList`, not |
| 1575 | * `/calendar/v3/users/me/calendarList` (which resolves to `/calendar/v3/calendar/v3/...` |
| 1576 | * and returns a 404 from Google). An absolute URL on the same domain is sent as-is. |
| 1577 | * |
| 1578 | * @param {ToolProxyParams} body - The proxy request |
| 1579 | * @param {string} body.endpoint - Path relative to the toolkit's base URL, or an absolute URL |
| 1580 | * @param {'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'} body.method - HTTP method |
| 1581 | * @param {string} [body.connectedAccountId] - The connected account to authenticate as |
| 1582 | * @param {string} [body.userId] - The user the connected account belongs to. Projects with 2FA enabled check it against the connected account and may require it |
| 1583 | * @param {unknown} [body.body] - JSON request body |
| 1584 | * @param {Array<{ in: 'query' | 'header'; name: string; value: string | number }>} [body.parameters] - Extra query parameters or headers |
| 1585 | * @returns {Promise<ToolProxyResponse>} The upstream status, headers, and parsed body |
| 1586 | * |
| 1587 | * @example |
| 1588 | * ```typescript |
| 1589 | * // Google Calendar's base URL is https://www.googleapis.com/calendar/v3 |
| 1590 | * const { status, data } = await composio.tools.proxyExecute({ |
| 1591 | * endpoint: '/users/me/calendarList', |
| 1592 | * method: 'GET', |
| 1593 | * connectedAccountId: 'ca_...', |
| 1594 | * parameters: [{ in: 'query', name: 'maxResults', value: 10 }], |
| 1595 | * }); |
| 1596 | * console.log(status, data); |
| 1597 | * ``` |
| 1598 | */ |
| 1599 | async proxyExecute( |
| 1600 | body: ToolProxyParams, |
| 1601 | requestOptions?: ComposioRequestOptions |
| 1602 | ): Promise<ToolProxyResponse> { |
| 1603 | const toolProxyParams = ToolProxyParamsSchema.safeParse(body); |
| 1604 | if (!toolProxyParams.success) { |
| 1605 | throw new ValidationError('Invalid tool proxy parameters', { cause: toolProxyParams.error }); |
| 1606 | } |
| 1607 | // convert the headers and query to the composio format |
| 1608 | // { name: string, type: 'header' | 'query', value: string } |
| 1609 | const parameters: NonNullable<ComposioToolProxyParams['parameters']>[number][] = []; |
| 1610 | const parameterTypes = { |
| 1611 | header: 'header', |
| 1612 | query: 'query', |
| 1613 | } as const; |
| 1614 | |
| 1615 | if (toolProxyParams.data.parameters) { |
| 1616 | parameters.push( |
| 1617 | ...(toolProxyParams.data.parameters ?? []).map(value => ({ |
| 1618 | name: value.name, |
| 1619 | type: value.in === 'header' ? parameterTypes.header : parameterTypes.query, |
| 1620 | value: value.value.toString(), |
| 1621 | })) |
| 1622 | ); |
| 1623 | } |
| 1624 | |
| 1625 | const proxyBody = { |
| 1626 | endpoint: toolProxyParams.data.endpoint, |
| 1627 | method: toolProxyParams.data.method, |
| 1628 | body: toolProxyParams.data.body, |
| 1629 | connected_account_id: toolProxyParams.data.connectedAccountId, |
| 1630 | user_id: toolProxyParams.data.userId, |
| 1631 | parameters: parameters, |
| 1632 | /** |
| 1633 | * @deprecated The `customConnectionData` proxy param is deprecated and will be |
| 1634 | * removed in a future release. Use `customAuthParams` instead. |
| 1635 | */ |
| 1636 | custom_connection_data: toolProxyParams.data.customConnectionData, |
| 1637 | } as ComposioToolProxyParams; |
| 1638 | return withCancellation( |
| 1639 | () => this.client.tools.proxy(proxyBody, withoutRetries(requestOptions)), |
| 1640 | requestOptions?.signal |
| 1641 | ); |
| 1642 | } |
| 1643 | } |