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 | /** |
| 2 | * @fileoverview Standalone functions for custom tool lookup and execution. |
| 3 | * Extracted from ToolRouterSession for reuse in SessionContextImpl (sibling routing). |
| 4 | */ |
| 5 | import type { |
| 6 | CustomToolsMap, |
| 7 | CustomToolsMapEntry, |
| 8 | SessionContext, |
| 9 | } from '../types/customTool.types'; |
| 10 | import type { ToolExecuteResponse } from '../types/tool.types'; |
| 11 | import { ValidationError } from '../errors'; |
| 12 | import { ComposioRequestCancelledError, isRequestAbortError } from '../errors/SDKErrors'; |
| 13 | import { ComposioToolInputRequiredError } from '../errors/ToolRouterErrors'; |
| 14 | |
| 15 | /** |
| 16 | * Find a custom tool entry by slug. |
| 17 | * Checks both the final slug map (LOCAL_X — agent/LLM path) and original slug map (X — programmatic path). |
| 18 | */ |
| 19 | export function findCustomTool( |
| 20 | map: CustomToolsMap | undefined, |
| 21 | slug: string |
| 22 | ): CustomToolsMapEntry | undefined { |
| 23 | if (!map) return undefined; |
| 24 | const upper = slug.toUpperCase(); |
| 25 | const finalSlugMatch = map.byFinalSlug.get(upper); |
| 26 | if (finalSlugMatch) return finalSlugMatch; |
| 27 | if (map.ambiguousOriginalSlugs?.has(upper)) return undefined; |
| 28 | return map.byOriginalSlug.get(upper); |
| 29 | } |
| 30 | |
| 31 | /** |
| 32 | * Reject ambiguous bare original slugs before falling through to backend execution. |
| 33 | * Agents receive final slugs (LOCAL_<TOOLKIT>_<TOOL>) from schemas, while bare original |
| 34 | * slugs are only a convenience for manual session.execute() calls when unique. |
| 35 | */ |
| 36 | export function assertUnambiguousCustomToolSlug( |
| 37 | map: CustomToolsMap | undefined, |
| 38 | slug: string |
| 39 | ): void { |
| 40 | if (!map) return; |
| 41 | const upper = slug.toUpperCase(); |
| 42 | if (!map.ambiguousOriginalSlugs?.has(upper)) return; |
| 43 | |
| 44 | const finalSlugs = [...map.byFinalSlug.values()] |
| 45 | .filter(entry => entry.handle.slug.toUpperCase() === upper) |
| 46 | .map(entry => entry.finalSlug) |
| 47 | .sort(); |
| 48 | const hint = finalSlugs.length ? ` Use one of: ${finalSlugs.join(', ')}.` : ''; |
| 49 | |
| 50 | throw new ValidationError( |
| 51 | `Ambiguous custom tool slug "${slug}". Multiple custom toolkit tools share this original slug; ` + |
| 52 | `manual session.execute() by original slug is only supported when the original slug is unique.` + |
| 53 | hint |
| 54 | ); |
| 55 | } |
| 56 | |
| 57 | /** |
| 58 | * Execute a custom tool in-process. |
| 59 | * Validates input via the Zod schema, calls the user's execute function, |
| 60 | * and wraps the result into the standard response format. |
| 61 | * |
| 62 | * Callers provide a pre-built SessionContext (which may include sibling routing). |
| 63 | * |
| 64 | * @throws {ComposioToolInputRequiredError} If a call the tool made through the |
| 65 | * session context needs user input before it can run |
| 66 | */ |
| 67 | export async function executeCustomTool( |
| 68 | entry: CustomToolsMapEntry, |
| 69 | arguments_: Record<string, unknown>, |
| 70 | sessionContext: SessionContext, |
| 71 | options?: { signal?: AbortSignal } |
| 72 | ): Promise<ToolExecuteResponse> { |
| 73 | const { handle } = entry; |
| 74 | |
| 75 | if (options?.signal?.aborted) { |
| 76 | throw new ComposioRequestCancelledError(); |
| 77 | } |
| 78 | |
| 79 | // Validate and transform input using the original Zod schema. |
| 80 | // This applies defaults, coercions, and transforms (e.g. z.string().default('all')). |
| 81 | const parsed = handle.inputParams.safeParse(arguments_); |
| 82 | if (!parsed.success) { |
| 83 | return { |
| 84 | data: {}, |
| 85 | error: `Input validation failed: ${parsed.error.message}`, |
| 86 | successful: false, |
| 87 | }; |
| 88 | } |
| 89 | if (options?.signal?.aborted) { |
| 90 | throw new ComposioRequestCancelledError(); |
| 91 | } |
| 92 | |
| 93 | try { |
| 94 | // Object.create preserves prototype methods (execute, proxyExecute) that spread would drop |
| 95 | const ctxWithSignal: SessionContext = options?.signal |
| 96 | ? Object.assign(Object.create(sessionContext as object) as SessionContext, { |
| 97 | signal: options.signal, |
| 98 | }) |
| 99 | : sessionContext; |
| 100 | const data = await handle.execute(parsed.data, ctxWithSignal); |
| 101 | return { |
| 102 | data: data ?? {}, |
| 103 | error: null, |
| 104 | successful: true, |
| 105 | }; |
| 106 | } catch (err: unknown) { |
| 107 | if (err instanceof ComposioRequestCancelledError) { |
| 108 | throw err; |
| 109 | } |
| 110 | // `ctx.execute()` / `ctx.proxyExecute()` asked for user input: nothing ran. |
| 111 | // Flattening it into a failed result would drop the questions and the |
| 112 | // request state the caller needs to answer them. |
| 113 | if (err instanceof ComposioToolInputRequiredError) { |
| 114 | throw err; |
| 115 | } |
| 116 | if (options?.signal?.aborted && isRequestAbortError(err)) { |
| 117 | throw new ComposioRequestCancelledError(undefined, { |
| 118 | cause: err instanceof Error ? err : undefined, |
| 119 | }); |
| 120 | } |
| 121 | const message = err instanceof Error ? err.message : String(err); |
| 122 | return { |
| 123 | data: {}, |
| 124 | error: message, |
| 125 | successful: false, |
| 126 | }; |
| 127 | } |
| 128 | } |