Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

next
ts 704 lines 23.8 KB
Raw
1 /**
2 * @fileoverview Factory functions for creating custom tools and toolkits.
3 *
4 * Usage:
5 * ```typescript
6 * import { experimental_createTool, experimental_createToolkit } from '@composio/core';
7 *
8 * const grep = createCustomTool('GREP', {
9 * name: 'Grep Search',
10 * description: 'Search for patterns in files',
11 * inputParams: z.object({ pattern: z.string() }),
12 * execute: async (input) => ({ matches: [] }),
13 * });
14 *
15 * const devTools = createCustomToolkit('DEV_TOOLS', {
16 * name: 'Dev Tools',
17 * description: 'Local dev utilities',
18 * tools: [grep],
19 * });
20 * ```
21 */
22 import {
23 CreateCustomToolBaseSchema,
24 CreateCustomToolkitBaseSchema,
25 CustomToolSlugSchema,
26 type AnyZodSchema,
27 type CreateLocalToolParams,
28 type CreateLocalToolkitParams,
29 type LocalTool,
30 type LocalToolkit,
31 type LocalToolExecuteFn,
32 type CustomToolsMap,
33 type CustomToolsMapEntry,
34 type CustomToolWireDefinition,
35 type CustomToolkitWireDefinition,
36 } from '../types/customTool.types';
37 import type {
38 SessionCreateResponse,
39 SessionRetrieveResponse,
40 } from '@composio/client/resources/tool-router/session';
41 import { ValidationError } from '../errors';
42 import { PRELOAD_TOOLS_ALL } from '../lib/toolRouterConstants';
43 import {
44 isZodObjectSchema,
45 zodObjectSchemaToJsonSchema,
46 zodSchemaToJsonSchema,
47 } from '../utils/zodSchema';
48
49 /** Prefix applied by the backend to local tool slugs for disambiguation. */
50 export const LOCAL_TOOL_PREFIX = 'LOCAL_';
51
52 /** Maximum allowed length for the final prefixed slug. */
53 const MAX_SLUG_LENGTH = 60;
54
55 type InputParamsSchema = {
56 definitions: {
57 input: {
58 type: string;
59 properties: Record<string, unknown>;
60 required?: string[];
61 };
62 };
63 };
64
65 /**
66 * Compute the final slug length for a tool given its context.
67 * Returns the expected length of LOCAL_[TOOLKIT_]SLUG.
68 */
69 function computeFinalSlugLength(toolSlug: string, toolkitSlug?: string): number {
70 // LOCAL_ + optional TOOLKIT_ + SLUG
71 return (
72 LOCAL_TOOL_PREFIX.length +
73 (toolkitSlug ? toolkitSlug.length + 1 : 0) + // +1 for underscore separator
74 toolSlug.length
75 );
76 }
77
78 /**
79 * Validate that the final slug won't exceed the max length.
80 * Called early in createCustomTool/createCustomToolkit for fast feedback.
81 */
82 function validateSlugLength(
83 toolSlug: string,
84 toolkitSlug: string | undefined,
85 context: string
86 ): void {
87 const finalLength = computeFinalSlugLength(toolSlug, toolkitSlug);
88 if (finalLength > MAX_SLUG_LENGTH) {
89 const prefix = LOCAL_TOOL_PREFIX + (toolkitSlug ? `${toolkitSlug.toUpperCase()}_` : '');
90 const available = MAX_SLUG_LENGTH - prefix.length;
91 throw new ValidationError(
92 `${context}: slug "${toolSlug}" is too long. ` +
93 `With prefix "${prefix}", the final slug would be ${finalLength} characters (max ${MAX_SLUG_LENGTH}). ` +
94 `Shorten the slug to at most ${available} characters.`
95 );
96 }
97 }
98
99 /**
100 * Create a local tool for use in tool router sessions.
101 *
102 * The returned object is a lightweight reference containing the tool's metadata
103 * and execute function. Pass it to `composio.create(userId, { experimental: { localTools: [...] } })`
104 * to bind it to a session.
105 *
106 * Just return the result data from `execute`, or throw an error.
107 * The SDK wraps it into the standard response format internally.
108 *
109 * **Slug naming:** The slug you provide is automatically prefixed with `LOCAL_` when
110 * exposed to the agent (e.g. `'GREP'` becomes `LOCAL_GREP`). If the tool is inside a
111 * custom toolkit, the toolkit slug is also included (e.g. `LOCAL_DEV_TOOLS_GREP`).
112 * The `LOCAL_` prefix is reserved and cannot be used in your slug.
113 *
114 * @param slug - Unique tool identifier (alphanumeric, underscores, hyphens; no LOCAL_ or COMPOSIO_ prefix)
115 * @param options - Tool definition including name, schema, and execute function
116 * @returns A LocalTool to pass to session creation
117 *
118 * @example Standalone tool (no auth)
119 * ```typescript
120 * const grep = createCustomTool('GREP', {
121 * name: 'Grep Search',
122 * description: 'Search for patterns in files',
123 * inputParams: z.object({ pattern: z.string(), path: z.string() }),
124 * execute: async (input) => ({ matches: [] }),
125 * });
126 * ```
127 *
128 * @example Tool extending a Composio toolkit (inherits auth)
129 * ```typescript
130 * const getImportant = createCustomTool('GET_IMPORTANT_EMAILS', {
131 * name: 'Get Important Emails',
132 * description: 'Fetch high-priority emails',
133 * extendsToolkit: 'gmail',
134 * inputParams: z.object({ limit: z.number().default(10) }),
135 * execute: async (input, ctx) => {
136 * // Same response shape as session.execute(): { data, error, logId }
137 * const result = await ctx.execute('GMAIL_SEARCH', { query: 'is:important' });
138 * return { emails: result.data };
139 * },
140 * });
141 * ```
142 */
143 export function createCustomTool<T extends AnyZodSchema>(
144 slug: string,
145 options: CreateLocalToolParams<T>
146 ): LocalTool {
147 // Validate slug separately
148 const slugResult = CustomToolSlugSchema.safeParse(slug);
149 if (!slugResult.success) {
150 throw new ValidationError(`createCustomTool: ${slugResult.error.issues[0].message}`, {
151 cause: slugResult.error,
152 });
153 }
154
155 // Validate string/scalar fields via Zod schema
156 const validated = CreateCustomToolBaseSchema.parse(options);
157
158 // Manual checks for fields Zod can't validate
159 if (!options.inputParams) {
160 throw new ValidationError('createCustomTool: inputParams is required');
161 }
162 if (!isZodObjectSchema(options.inputParams)) {
163 throw new ValidationError(
164 'createCustomTool: inputParams must be a z.object() schema. ' +
165 'Tool input parameters are always an object with named properties.'
166 );
167 }
168 if (typeof options.execute !== 'function') {
169 throw new ValidationError('createCustomTool: execute must be a function');
170 }
171
172 // Early length validation (standalone or extension — we know both parts)
173 validateSlugLength(slug, validated.extendsToolkit, 'createCustomTool');
174
175 const { inputParams, execute } = options;
176
177 // Convert Zod input schema → JSON Schema (inputParams is guaranteed to be z.object)
178 const inputSchema = zodObjectSchemaToJsonSchema(inputParams, 'input');
179
180 // Convert Zod output schema → JSON Schema (if provided, any Zod type allowed)
181 let outputSchema: Record<string, unknown> | undefined;
182 if (options.outputParams) {
183 outputSchema = zodSchemaToJsonSchema(options.outputParams, 'output');
184 }
185
186 return {
187 slug: slugResult.data,
188 name: validated.name,
189 description: validated.description,
190 extendsToolkit: validated.extendsToolkit,
191 preload: validated.preload,
192 inputSchema,
193 outputSchema,
194 inputParams,
195 execute: execute as LocalToolExecuteFn<AnyZodSchema>,
196 };
197 }
198
199 /**
200 * Create a toolkit that groups related local tools. Pass it to
201 * `composio.create(userId, { experimental: { localToolkits: [...] } })`.
202 *
203 * Tools passed here must NOT have `extendsToolkit` set — they inherit the toolkit identity instead.
204 *
205 * **Slug naming:** The toolkit slug becomes part of the final tool slug exposed to the agent.
206 * For example, a toolkit `'DEV_TOOLS'` with a tool `'GREP'` produces `LOCAL_DEV_TOOLS_GREP`.
207 * The `LOCAL_` prefix is reserved and cannot be used in your slug.
208 *
209 * @param slug - Unique toolkit identifier (alphanumeric, underscores, hyphens; no LOCAL_ or COMPOSIO_ prefix)
210 * @param options - Toolkit definition including name, description, and tools
211 * @returns A LocalToolkit to pass to session creation
212 *
213 * @example
214 * ```typescript
215 * const devTools = createCustomToolkit('DEV_TOOLS', {
216 * name: 'Dev Tools',
217 * description: 'Local dev utilities',
218 * tools: [grepTool, sedTool],
219 * });
220 * ```
221 */
222 export function createCustomToolkit(slug: string, options: CreateLocalToolkitParams): LocalToolkit {
223 // Validate slug
224 const slugResult = CustomToolSlugSchema.safeParse(slug);
225 if (!slugResult.success) {
226 throw new ValidationError(`createCustomToolkit: ${slugResult.error.issues[0].message}`, {
227 cause: slugResult.error,
228 });
229 }
230
231 // Validate name/description
232 const validated = CreateCustomToolkitBaseSchema.parse(options);
233
234 // Non-empty tools required
235 if (!options.tools?.length) {
236 throw new ValidationError('createCustomToolkit: at least one tool is required');
237 }
238
239 // Validate each tool
240 for (const tool of options.tools) {
241 // Reject tools with extendsToolkit
242 if (tool.extendsToolkit) {
243 throw new ValidationError(
244 `createCustomToolkit: tool "${tool.slug}" has extendsToolkit set. ` +
245 `Tools in a custom toolkit must not use extendsToolkit — they inherit the toolkit identity instead.`
246 );
247 }
248 // Early length validation — we know both toolkit slug and tool slug
249 validateSlugLength(tool.slug, slug, `createCustomToolkit("${slug}")`);
250 }
251
252 return {
253 slug: slugResult.data,
254 name: validated.name,
255 description: validated.description,
256 preload: validated.preload,
257 tools: options.tools,
258 };
259 }
260
261 /**
262 * Build the final slug for a custom tool given its context.
263 * @internal
264 */
265 function buildFinalSlug(toolSlug: string, toolkitSlug?: string): string {
266 const upper = toolSlug.toUpperCase();
267 return toolkitSlug
268 ? `${LOCAL_TOOL_PREFIX}${toolkitSlug.toUpperCase()}_${upper}`
269 : `${LOCAL_TOOL_PREFIX}${upper}`;
270 }
271
272 const qualifiedOriginalSlugKey = (toolkit: string | undefined, originalSlug: string): string =>
273 `${toolkit?.toUpperCase() ?? ''}::${originalSlug.toUpperCase()}`;
274
275 const canShareOriginalSlug = (existing: CustomToolsMapEntry, next: CustomToolsMapEntry): boolean =>
276 !!existing.toolkit &&
277 !!next.toolkit &&
278 existing.toolkit.toLowerCase() !== next.toolkit.toLowerCase();
279
280 const addOriginalSlugAlias = (params: {
281 byOriginalSlug: Map<string, CustomToolsMapEntry>;
282 ambiguousOriginalSlugs: Set<string>;
283 originalSlug: string;
284 entry: CustomToolsMapEntry;
285 }) => {
286 const originalSlugKey = params.originalSlug.toUpperCase();
287 if (params.ambiguousOriginalSlugs.has(originalSlugKey)) {
288 return;
289 }
290
291 const existing = params.byOriginalSlug.get(originalSlugKey);
292 if (!existing) {
293 params.byOriginalSlug.set(originalSlugKey, params.entry);
294 return;
295 }
296
297 if (existing.finalSlug.toUpperCase() === params.entry.finalSlug.toUpperCase()) {
298 return;
299 }
300
301 if (canShareOriginalSlug(existing, params.entry)) {
302 params.byOriginalSlug.delete(originalSlugKey);
303 params.ambiguousOriginalSlugs.add(originalSlugKey);
304 return;
305 }
306
307 throw new ValidationError(
308 `Custom tool slug collision: original slug "${params.originalSlug}" maps to multiple final slugs. ` +
309 `"${existing.finalSlug}" and "${params.entry.finalSlug}" both resolve from "${originalSlugKey}".`
310 );
311 };
312
313 /**
314 * Build a CustomToolsMap from custom tools and toolkits.
315 * Used internally by ToolRouter.create() to construct the per-session routing map.
316 *
317 * @internal
318 * @param tools - Standalone custom tools
319 * @param toolkits - Custom toolkits containing grouped tools
320 * @returns Maps for O(1) lookup by both final and original slug
321 * @throws If duplicate slugs or cross-group collisions
322 */
323 export function buildCustomToolsMap(tools: LocalTool[], toolkits?: LocalToolkit[]): CustomToolsMap {
324 const byFinalSlug = new Map<string, CustomToolsMapEntry>();
325 const byOriginalSlug = new Map<string, CustomToolsMapEntry>();
326 const byToolkitAndOriginalSlug = new Map<string, CustomToolsMapEntry>();
327 const ambiguousOriginalSlugs = new Set<string>();
328
329 const addEntry = (handle: LocalTool, finalSlug: string, toolkit?: string) => {
330 const originalSlug = handle.slug.toUpperCase();
331 // Custom tool slugs are matched case-insensitively across local and response maps.
332 const finalSlugKey = finalSlug.toUpperCase();
333
334 // Length validated early in createCustomTool/createCustomToolkit, but check as safety net
335 if (finalSlug.length > MAX_SLUG_LENGTH) {
336 throw new ValidationError(
337 `Custom tool slug "${handle.slug}" produces final slug "${finalSlug}" ` +
338 `which exceeds ${MAX_SLUG_LENGTH} characters.`
339 );
340 }
341
342 // Check cross-group collisions on final slug
343 if (byFinalSlug.has(finalSlugKey)) {
344 throw new ValidationError(
345 `Custom tool slug collision: "${finalSlug}" is already registered.`
346 );
347 }
348
349 const qualifiedKey = qualifiedOriginalSlugKey(toolkit, originalSlug);
350 if (byToolkitAndOriginalSlug.has(qualifiedKey)) {
351 throw new ValidationError(
352 `Custom tool slug collision: original slug "${handle.slug}" is already registered for toolkit "${toolkit ?? 'custom'}".`
353 );
354 }
355
356 const entry: CustomToolsMapEntry = { handle, finalSlug, toolkit };
357 byFinalSlug.set(finalSlugKey, entry);
358 byToolkitAndOriginalSlug.set(qualifiedKey, entry);
359 addOriginalSlugAlias({ byOriginalSlug, ambiguousOriginalSlugs, originalSlug, entry });
360 };
361
362 // Process standalone tools
363 for (const handle of tools) {
364 addEntry(handle, buildFinalSlug(handle.slug, handle.extendsToolkit), handle.extendsToolkit);
365 }
366
367 // Process toolkit tools
368 if (toolkits) {
369 for (const toolkit of toolkits) {
370 for (const handle of toolkit.tools) {
371 addEntry(handle, buildFinalSlug(handle.slug, toolkit.slug), toolkit.slug);
372 }
373 }
374 }
375
376 return {
377 byFinalSlug,
378 byOriginalSlug,
379 byToolkitAndOriginalSlug,
380 ...(ambiguousOriginalSlugs.size ? { ambiguousOriginalSlugs } : {}),
381 toolkits,
382 tools: tools.length ? tools : undefined,
383 };
384 }
385
386 /**
387 * Serialize custom tools into the format expected by the backend session creation API.
388 *
389 * Maps `extendsToolkit` → `extends_toolkit` for backend. Omitted for standalone tools.
390 *
391 * @internal
392 * @param tools - The custom tools to serialize
393 * @returns Array of CustomToolDefinition for the API payload
394 */
395 type CustomToolSerializationOptions = {
396 defaultPreload?: boolean;
397 };
398
399 function shouldSerializePreload(
400 preload: boolean | undefined,
401 inheritedPreload: boolean | undefined,
402 defaultPreload: boolean
403 ): boolean | undefined {
404 const inheritedOrDefault = inheritedPreload ?? defaultPreload;
405 if (preload !== undefined) {
406 return preload || inheritedOrDefault ? preload : undefined;
407 }
408 if (inheritedPreload !== undefined) {
409 return inheritedPreload || defaultPreload ? inheritedPreload : undefined;
410 }
411 return defaultPreload ? true : undefined;
412 }
413
414 function preloadWireProperty(
415 preload: boolean | undefined,
416 inheritedPreload: boolean | undefined,
417 defaultPreload: boolean
418 ): { preload?: boolean } {
419 const serializedPreload = shouldSerializePreload(preload, inheritedPreload, defaultPreload);
420 return serializedPreload === undefined ? {} : { preload: serializedPreload };
421 }
422
423 export function serializeCustomTools(
424 tools: LocalTool[],
425 options: CustomToolSerializationOptions = {}
426 ): CustomToolWireDefinition[] {
427 const defaultPreload = options.defaultPreload ?? false;
428 return tools.map(handle => ({
429 slug: handle.slug,
430 name: handle.name,
431 description: handle.description,
432 input_schema: handle.inputSchema,
433 ...(handle.outputSchema ? { output_schema: handle.outputSchema } : {}),
434 ...(handle.extendsToolkit ? { extends_toolkit: handle.extendsToolkit } : {}),
435 ...preloadWireProperty(handle.preload, undefined, defaultPreload),
436 }));
437 }
438
439 /**
440 * Serialize custom toolkits into the format expected by the backend session creation API.
441 *
442 * @internal
443 * @param toolkits - The custom toolkits to serialize
444 * @returns Array of CustomToolkitDefinition for the API payload
445 */
446 export function serializeCustomToolkits(
447 toolkits: LocalToolkit[],
448 options: CustomToolSerializationOptions = {}
449 ): CustomToolkitWireDefinition[] {
450 const defaultPreload = options.defaultPreload ?? false;
451 return toolkits.map(tk => ({
452 slug: tk.slug,
453 name: tk.name,
454 description: tk.description,
455 ...preloadWireProperty(tk.preload, undefined, defaultPreload),
456 tools: tk.tools.map(t => ({
457 slug: t.slug,
458 name: t.name,
459 description: t.description,
460 input_schema: t.inputSchema,
461 ...(t.outputSchema ? { output_schema: t.outputSchema } : {}),
462 ...preloadWireProperty(t.preload, tk.preload, defaultPreload),
463 })),
464 }));
465 }
466
467 /**
468 * Build a CustomToolsMap using the slug/original_slug mapping from the session create response.
469 * This uses the backend's authoritative prefixed slugs instead of computing them client-side.
470 *
471 * @internal
472 * @param tools - The original custom tools passed to session creation
473 * @param toolkits - The original custom toolkits passed to session creation
474 * @param experimental - The experimental section from the session create response
475 * @returns Maps for O(1) lookup by both final and original slug
476 */
477 export function buildCustomToolsMapFromResponse(
478 tools: LocalTool[],
479 toolkits: LocalToolkit[] | undefined,
480 experimental:
481 SessionCreateResponse['experimental'] | SessionRetrieveResponse['experimental'] | undefined
482 ): CustomToolsMap {
483 const byFinalSlug = new Map<string, CustomToolsMapEntry>();
484 const byOriginalSlug = new Map<string, CustomToolsMapEntry>();
485 const byToolkitAndOriginalSlug = new Map<string, CustomToolsMapEntry>();
486 const ambiguousOriginalSlugs = new Set<string>();
487
488 type HandleMatch = { handle: LocalTool; toolkit?: string };
489 const handlesByQualifiedOriginalSlug = new Map<string, HandleMatch>();
490 const handlesByOriginalSlug = new Map<string, HandleMatch[]>();
491
492 const registerHandle = (handle: LocalTool, toolkit?: string) => {
493 const originalSlug = handle.slug.toUpperCase();
494 const match = { handle, toolkit };
495 handlesByQualifiedOriginalSlug.set(qualifiedOriginalSlugKey(toolkit, originalSlug), match);
496 const existing = handlesByOriginalSlug.get(originalSlug) ?? [];
497 existing.push(match);
498 handlesByOriginalSlug.set(originalSlug, existing);
499 };
500
501 for (const handle of tools) {
502 registerHandle(handle, handle.extendsToolkit);
503 }
504 if (toolkits) {
505 for (const tk of toolkits) {
506 for (const handle of tk.tools) {
507 registerHandle(handle, tk.slug);
508 }
509 }
510 }
511
512 const findHandle = (
513 finalSlug: string,
514 originalSlug: string,
515 toolkit?: string
516 ): HandleMatch | undefined => {
517 const originalSlugKey = originalSlug.toUpperCase();
518 const qualifiedMatch = handlesByQualifiedOriginalSlug.get(
519 qualifiedOriginalSlugKey(toolkit, originalSlugKey)
520 );
521 if (qualifiedMatch) return qualifiedMatch;
522
523 const bareMatches = handlesByOriginalSlug.get(originalSlugKey) ?? [];
524 // Response tool not defined locally; nothing to route in-process.
525 if (bareMatches.length === 0) return undefined;
526 // A bare match may only stand in when the response carries no toolkit identity.
527 // Binding a toolkit child to another toolkit's handler would silently execute
528 // the wrong implementation.
529 if (toolkit === undefined && bareMatches.length === 1) return bareMatches[0];
530
531 const registered = [
532 ...new Set(bareMatches.map(m => (m.toolkit ?? 'custom').toUpperCase())),
533 ].sort();
534 throw new ValidationError(
535 `Cannot map custom tool "${finalSlug}": original slug "${originalSlug}" for toolkit ` +
536 `"${toolkit ?? 'custom'}" has no exact local match. Registered for toolkits: ${registered.join(', ')}.`
537 );
538 };
539
540 const addEntry = (finalSlug: string, originalSlug: string, toolkit?: string | null) => {
541 const resolvedToolkit = toolkit ?? undefined;
542 const match = findHandle(finalSlug, originalSlug, resolvedToolkit);
543 if (!match) return;
544
545 const finalSlugKey = finalSlug.toUpperCase();
546 if (byFinalSlug.has(finalSlugKey)) {
547 throw new ValidationError(
548 `Custom tool slug collision: "${finalSlug}" is already registered.`
549 );
550 }
551
552 const entryToolkit = resolvedToolkit ?? match.toolkit;
553 const qualifiedKey = qualifiedOriginalSlugKey(entryToolkit, originalSlug);
554 if (byToolkitAndOriginalSlug.has(qualifiedKey)) {
555 throw new ValidationError(
556 `Custom tool slug collision: original slug "${match.handle.slug}" is already registered for toolkit "${entryToolkit ?? 'custom'}".`
557 );
558 }
559
560 const entry: CustomToolsMapEntry = {
561 handle: match.handle,
562 finalSlug,
563 toolkit: entryToolkit,
564 };
565 byFinalSlug.set(finalSlugKey, entry);
566 byToolkitAndOriginalSlug.set(qualifiedKey, entry);
567 addOriginalSlugAlias({ byOriginalSlug, ambiguousOriginalSlugs, originalSlug, entry });
568 };
569
570 // Map standalone custom tools from response
571 if (experimental?.custom_tools) {
572 for (const ct of experimental.custom_tools) {
573 addEntry(ct.slug, ct.original_slug, ct.extends_toolkit);
574 }
575 }
576
577 // Map toolkit custom tools from response
578 if (experimental?.custom_toolkits) {
579 for (const ctk of experimental.custom_toolkits) {
580 for (const ct of ctk.tools) {
581 addEntry(ct.slug, ct.original_slug, ctk.slug);
582 }
583 }
584 }
585
586 // Ambiguity follows the local definitions, not whichever subset the response
587 // happened to include: a shared child slug must never become callable by its
588 // bare name just because a sibling was omitted.
589 for (const [originalSlugKey, matches] of handlesByOriginalSlug) {
590 if (matches.length > 1) {
591 byOriginalSlug.delete(originalSlugKey);
592 ambiguousOriginalSlugs.add(originalSlugKey);
593 }
594 }
595
596 return {
597 byFinalSlug,
598 byOriginalSlug,
599 byToolkitAndOriginalSlug,
600 ...(ambiguousOriginalSlugs.size ? { ambiguousOriginalSlugs } : {}),
601 toolkits,
602 tools: tools.length ? tools : undefined,
603 };
604 }
605
606 /**
607 * Find a custom tool entry by final slug only.
608 *
609 * @internal
610 */
611 export function findCustomToolMapEntryByFinalSlug(
612 customToolsMap: CustomToolsMap | undefined,
613 slug: string
614 ): CustomToolsMapEntry | undefined {
615 return customToolsMap?.byFinalSlug.get(slug.toUpperCase());
616 }
617
618 /**
619 * Find a custom toolkit tool entry by toolkit slug and original tool slug.
620 *
621 * @internal
622 */
623 export function findCustomToolMapEntryByToolkitAndOriginalSlug(
624 customToolsMap: CustomToolsMap | undefined,
625 toolkit: string | undefined,
626 slug: string
627 ): CustomToolsMapEntry | undefined {
628 return customToolsMap?.byToolkitAndOriginalSlug?.get(qualifiedOriginalSlugKey(toolkit, slug));
629 }
630
631 /**
632 * Reject legacy attempts to preload custom tools through top-level preload.tools.
633 *
634 * Custom tool direct exposure is controlled by LocalTool.preload /
635 * LocalToolkit.preload so it follows the current SDK-provided custom
636 * definitions instead of stale session config.
637 *
638 * @internal
639 */
640 export function assertNoCustomToolSlugsInPreload(
641 preloadTools: readonly string[] | typeof PRELOAD_TOOLS_ALL | undefined,
642 customToolsMap: CustomToolsMap | undefined
643 ): void {
644 if (!preloadTools || preloadTools === PRELOAD_TOOLS_ALL) {
645 return;
646 }
647
648 const customPreloadSlugs = preloadTools.filter(slug => {
649 const normalized = slug.toUpperCase();
650 return (
651 // Top-level preload.tools is only for Composio-managed tool slugs.
652 // Custom tools use `preload: true` on their SDK definitions instead.
653 normalized.startsWith(LOCAL_TOOL_PREFIX) ||
654 customToolsMap?.byOriginalSlug.has(normalized) ||
655 customToolsMap?.ambiguousOriginalSlugs?.has(normalized) ||
656 customToolsMap?.byFinalSlug.has(normalized)
657 );
658 });
659
660 if (customPreloadSlugs.length) {
661 throw new ValidationError(
662 `Custom tool slugs are not supported in preload.tools: ${customPreloadSlugs.join(
663 ', '
664 )}. Set preload: true on the SDK custom tool or custom toolkit definition instead.`
665 );
666 }
667 }
668
669 /**
670 * Resolve custom tools that the SDK should expose directly from session.tools().
671 *
672 * @internal
673 */
674 export function getPreloadedCustomToolSlugs(
675 customToolsMap: CustomToolsMap | undefined,
676 defaultPreload = false
677 ): string[] {
678 if (!customToolsMap) {
679 return [];
680 }
681
682 const seen = new Set<string>();
683 const customToolSlugs: string[] = [];
684
685 for (const entry of customToolsMap.byFinalSlug.values()) {
686 const toolkit = customToolsMap.toolkits?.find(
687 tk => entry.toolkit && tk.slug.toLowerCase() === entry.toolkit.toLowerCase()
688 );
689 const shouldPreload = entry.handle.preload ?? toolkit?.preload ?? defaultPreload;
690 if (!shouldPreload) {
691 continue;
692 }
693
694 const finalSlugKey = entry.finalSlug.toUpperCase();
695 if (seen.has(finalSlugKey)) {
696 continue;
697 }
698
699 seen.add(finalSlugKey);
700 customToolSlugs.push(entry.finalSlug);
701 }
702
703 return customToolSlugs;
704 }