@devries-cameron20 / composio-1 / commits / b61a0256a
Fork 0

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

refactor: eliminate recursion in SessionContext, use ValidationError

- SessionContextImpl takes customToolsMap directly instead of recursive tryLocalExecute callback — no more per-call context creation, sibling routing does inline lookup and passes `this` (same instance) - Hoist shared SessionContext above multi-execute loop (1 instance per batch instead of N) - Replace all plain Error throws with ValidationError from errors/ - Remove TryLocalExecuteFn type (no longer needed) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

Dhawal Upadhyay committed Mar 17, 2026 at 11:32 UTC b61a0256a955d600efa12ed986a5f8791db9e45e
4 files changed +53 -49
ts/packages/core/src/models/CustomTool.ts
+10 -9
@@ -38,6 +38,7 @@ import {
38 type CustomToolkitDefinition,
39 type InputParamsSchema,
40 } from '../types/customTool.types';
41 +import { ValidationError } from '../errors';
42
43 /** Prefix applied by the backend to local tool slugs for disambiguation. */
44 export const LOCAL_TOOL_PREFIX = 'LOCAL_';
@@ -90,7 +91,7 @@ export function createCustomTool<T extends z.ZodType>(
91 // Validate slug separately
92 const slugResult = CustomToolSlugSchema.safeParse(slug);
93 if (!slugResult.success) {
93 - throw new Error(`createCustomTool: ${slugResult.error.issues[0].message}`);
94 + throw new ValidationError(`createCustomTool: ${slugResult.error.issues[0].message}`, { cause: slugResult.error });
95 }
96
97 // Validate string/scalar fields via Zod schema
@@ -98,10 +99,10 @@ export function createCustomTool<T extends z.ZodType>(
99
100 // Manual checks for fields Zod can't validate
101 if (!options.inputParams) {
101 - throw new Error('createCustomTool: inputParams is required');
102 + throw new ValidationError('createCustomTool: inputParams is required');
103 }
104 if (typeof options.execute !== 'function') {
104 - throw new Error('createCustomTool: execute must be a function');
105 + throw new ValidationError('createCustomTool: execute must be a function');
106 }
107
108 const { inputParams, execute } = options;
@@ -170,7 +171,7 @@ export function createCustomToolkit(
171 // Validate slug
172 const slugResult = CustomToolSlugSchema.safeParse(slug);
173 if (!slugResult.success) {
173 - throw new Error(`createCustomToolkit: ${slugResult.error.issues[0].message}`);
174 + throw new ValidationError(`createCustomToolkit: ${slugResult.error.issues[0].message}`, { cause: slugResult.error });
175 }
176
177 // Validate name/description
@@ -178,13 +179,13 @@ export function createCustomToolkit(
179
180 // Non-empty tools required
181 if (!options.tools?.length) {
181 - throw new Error('createCustomToolkit: at least one tool is required');
182 + throw new ValidationError('createCustomToolkit: at least one tool is required');
183 }
184
185 // Reject tools with extendsToolkit
186 for (const tool of options.tools) {
187 if (tool.extendsToolkit) {
187 - throw new Error(
188 + throw new ValidationError(
189 `createCustomToolkit: tool "${tool.slug}" has extendsToolkit set. ` +
190 `Tools in a custom toolkit must not use extendsToolkit — they inherit the toolkit identity instead.`
191 );
@@ -228,7 +229,7 @@ export function buildCustomToolsMap(
229 if (prefixedSlug.length > MAX_PREFIXED_SLUG_LENGTH) {
230 const prefix = prefixedSlug.substring(0, prefixedSlug.length - originalSlug.length);
231 const available = MAX_PREFIXED_SLUG_LENGTH - prefix.length;
231 - throw new Error(
232 + throw new ValidationError(
233 `Custom tool slug "${handle.slug}" is too long. ` +
234 `With prefix "${prefix}", the final slug "${prefixedSlug}" exceeds ${MAX_PREFIXED_SLUG_LENGTH} characters. ` +
235 `Shorten the slug to at most ${available} characters.`
@@ -237,12 +238,12 @@ export function buildCustomToolsMap(
238
239 // Check cross-group collisions on prefixed slug
240 if (byPrefixed.has(prefixedSlug)) {
240 - throw new Error(`Custom tool slug collision: "${prefixedSlug}" is already registered.`);
241 + throw new ValidationError(`Custom tool slug collision: "${prefixedSlug}" is already registered.`);
242 }
243
244 // Check cross-group collisions on original slug
245 if (byOriginal.has(originalSlug)) {
245 - throw new Error(
246 + throw new ValidationError(
247 `Custom tool slug collision: original slug "${handle.slug}" maps to multiple prefixed slugs. ` +
248 `"${byOriginal.get(originalSlug)!.prefixedSlug}" and "${prefixedSlug}" both resolve from "${originalSlug}".`
249 );
ts/packages/core/src/models/SessionContext.ts
+13 -19
@@ -2,28 +2,22 @@
2 * @fileoverview Session context implementation injected into custom tool execute functions.
3 */
4 import { Composio as ComposioClient } from '@composio/client';
5 -import type { SessionContext } from '../types/customTool.types';
5 +import type { SessionContext, CustomToolsMap } from '../types/customTool.types';
6 import type { ToolExecuteResponse } from '../types/tool.types';
7 import type { SessionProxyExecuteParams } from '../types/toolRouter.types';
8 import { SessionProxyExecuteParamsSchema } from '../types/toolRouter.types';
9 +import { ValidationError } from '../errors';
10 import { transformProxyParams } from './proxyParamsTransform';
10 -
11 -/**
12 - * Callback that attempts local tool execution.
13 - * Returns a Promise if the slug matches a local tool, or undefined to fall back to remote.
14 - */
15 -export type TryLocalExecuteFn = (
16 - slug: string,
17 - args: Record<string, unknown>
18 -) => Promise<ToolExecuteResponse> | undefined;
11 +import { findCustomTool, executeCustomTool } from './customToolExecution';
12
13 /**
14 * Concrete implementation of SessionContext.
22 - * Built per local tool invocation inside ToolRouterSession.
15 + * One instance is created per session (or per multi-execute batch) and shared
16 + * across all custom tool invocations, including sibling routing.
17 *
24 - * When `tryLocalExecute` is provided, `execute()` checks sibling local tools first
25 - * before falling back to the backend API. This allows local tool A to call local
26 - * tool B via `session.execute('B', ...)` without hitting the network.
18 + * When `customToolsMap` is provided, `execute()` checks local tools first
19 + * before falling back to the backend API. This allows tool A to call tool B
20 + * via `session.execute('B', ...)` without hitting the network.
21 */
22 export class SessionContextImpl implements SessionContext {
23 public readonly userId: string;
@@ -32,7 +26,7 @@ export class SessionContextImpl implements SessionContext {
26 private readonly client: ComposioClient,
27 userId: string,
28 private readonly sessionId: string,
35 - private readonly tryLocalExecute?: TryLocalExecuteFn
29 + private readonly customToolsMap?: CustomToolsMap
30 ) {
31 this.userId = userId;
32 }
@@ -47,9 +41,9 @@ export class SessionContextImpl implements SessionContext {
41 arguments_: Record<string, unknown>
42 ): Promise<ToolExecuteResponse> {
43 // Try local tool first (sibling routing)
50 - const localResult = this.tryLocalExecute?.(toolSlug, arguments_);
51 - if (localResult) {
52 - return localResult;
44 + const entry = findCustomTool(this.customToolsMap, toolSlug);
45 + if (entry) {
46 + return executeCustomTool(entry, arguments_, this);
47 }
48
49 // Fall back to remote execution
@@ -74,7 +68,7 @@ export class SessionContextImpl implements SessionContext {
68 async proxyExecute(params: SessionProxyExecuteParams): Promise<ToolExecuteResponse> {
69 const validated = SessionProxyExecuteParamsSchema.safeParse(params);
70 if (!validated.success) {
77 - throw new Error(`Invalid proxy execute parameters: ${validated.error.message}`);
71 + throw new ValidationError('Invalid proxy execute parameters', { cause: validated.error });
72 }
73
74 const body = transformProxyParams(validated.data);
ts/packages/core/src/models/ToolRouterSession.ts
+5 -9
@@ -273,19 +273,14 @@ export class ToolRouterSession<
273
274 /**
275 * Build a SessionContext for local tool execution.
276 - * Includes sibling routing: session.execute() inside a custom tool checks
277 - * local tools first before falling back to the backend API.
276 + * The context holds the custom tools map and routes sibling calls in-process.
277 */
278 private buildSessionContext(): SessionContext {
279 return new SessionContextImpl(
280 this.client,
281 this.userId!,
282 this.sessionId,
284 - (slug, args) => {
285 - const entry = findCustomTool(this.customToolsMap, slug);
286 - if (!entry) return undefined;
287 - return executeCustomTool(entry, args, this.buildSessionContext());
288 - }
283 + this.customToolsMap
284 );
285 }
286
@@ -344,9 +339,10 @@ export class ToolRouterSession<
339 );
340 }
341
347 - // Execute local tools in parallel
342 + // Execute local tools in parallel (shared context for the entire batch)
343 + const ctx = this.buildSessionContext();
344 const localPromises = localItems.map(async ({ index, entry }) => {
349 - const result = await executeCustomTool(entry, parsed[index].arguments, this.buildSessionContext());
345 + const result = await executeCustomTool(entry, parsed[index].arguments, ctx);
346 return { index, result };
347 });
348
ts/packages/core/test/models/customTool.test.ts
+25 -12
@@ -596,31 +596,44 @@ describe('SessionContextImpl', () => {
596 });
597
598 describe('sibling local tool routing', () => {
599 - it('should route to local tool when tryLocalExecute matches', async () => {
600 - const tryLocalExecute = vi.fn().mockReturnValue(
601 - Promise.resolve({ data: { local: true }, error: null, successful: true })
602 - );
603 -
604 - const ctx = new SessionContextImpl(mockClient as any, 'user_1', 'sess_1', tryLocalExecute);
599 + it('should route to local tool when customToolsMap has a match', async () => {
600 + const siblingExecute = vi.fn().mockResolvedValue({ local: true });
601 + const customToolsMap = buildCustomToolsMap([
602 + createCustomTool('SIBLING_TOOL', {
603 + name: 'Sibling',
604 + description: 'A sibling tool',
605 + inputParams: z.object({ key: z.string() }),
606 + execute: siblingExecute,
607 + }),
608 + ]);
609 +
610 + const ctx = new SessionContextImpl(mockClient as any, 'user_1', 'sess_1', customToolsMap);
611 const result = await ctx.execute('SIBLING_TOOL', { key: 'val' });
612
607 - expect(tryLocalExecute).toHaveBeenCalledWith('SIBLING_TOOL', { key: 'val' });
613 + expect(siblingExecute).toHaveBeenCalledWith({ key: 'val' }, ctx);
614 expect(result).toEqual({ data: { local: true }, error: null, successful: true });
615 + // Should NOT call remote
616 expect(mockClient.toolRouter.session.execute).not.toHaveBeenCalled();
617 });
618
612 - it('should fall back to remote when tryLocalExecute returns undefined', async () => {
613 - const tryLocalExecute = vi.fn().mockReturnValue(undefined);
619 + it('should fall back to remote when slug not in customToolsMap', async () => {
620 + const customToolsMap = buildCustomToolsMap([
621 + createCustomTool('OTHER_TOOL', {
622 + name: 'Other',
623 + description: 'Not the one we call',
624 + inputParams: z.object({}),
625 + execute: vi.fn().mockResolvedValue({}),
626 + }),
627 + ]);
628 mockClient.toolRouter.session.execute.mockResolvedValue({
629 data: { remote: true },
630 error: null,
631 log_id: 'log_3',
632 });
633
620 - const ctx = new SessionContextImpl(mockClient as any, 'user_1', 'sess_1', tryLocalExecute);
634 + const ctx = new SessionContextImpl(mockClient as any, 'user_1', 'sess_1', customToolsMap);
635 const result = await ctx.execute('REMOTE_TOOL', { key: 'val' });
636
623 - expect(tryLocalExecute).toHaveBeenCalledWith('REMOTE_TOOL', { key: 'val' });
637 expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith('sess_1', {
638 tool_slug: 'REMOTE_TOOL',
639 arguments: { key: 'val' },
@@ -628,7 +641,7 @@ describe('SessionContextImpl', () => {
641 expect(result).toEqual({ data: { remote: true }, error: null, successful: true });
642 });
643
631 - it('should delegate to remote when no tryLocalExecute is provided', async () => {
644 + it('should delegate to remote when no customToolsMap is provided', async () => {
645 mockClient.toolRouter.session.execute.mockResolvedValue({
646 data: { remote: true },
647 error: null,