Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
TypeScript agentic-aiagentsaiai-agentsaiagentsdeveloper-toolsfunction-callinggpt-4javascriptjsllmllmopsmcppythonremote-mcp-serverssetypescript
refactor: eliminate recursion in SessionContext, use ValidationError
Dhawal Upadhyayb61a0256a955
diff --git a/ts/packages/core/src/models/CustomTool.ts b/ts/packages/core/src/models/CustomTool.tsindex e072755aa..08a264cea 100644--- a/ts/packages/core/src/models/CustomTool.ts+++ b/ts/packages/core/src/models/CustomTool.ts@@ -38,6 +38,7 @@ import {type CustomToolkitDefinition,type InputParamsSchema,} from '../types/customTool.types';+import { ValidationError } from '../errors';/** Prefix applied by the backend to local tool slugs for disambiguation. */export const LOCAL_TOOL_PREFIX = 'LOCAL_';@@ -90,7 +91,7 @@ export function createCustomTool<T extends z.ZodType>(// Validate slug separatelyconst slugResult = CustomToolSlugSchema.safeParse(slug);if (!slugResult.success) {- throw new Error(`createCustomTool: ${slugResult.error.issues[0].message}`);+ throw new ValidationError(`createCustomTool: ${slugResult.error.issues[0].message}`, { cause: slugResult.error });}// Validate string/scalar fields via Zod schema@@ -98,10 +99,10 @@ export function createCustomTool<T extends z.ZodType>(// Manual checks for fields Zod can't validateif (!options.inputParams) {- throw new Error('createCustomTool: inputParams is required');+ throw new ValidationError('createCustomTool: inputParams is required');}if (typeof options.execute !== 'function') {- throw new Error('createCustomTool: execute must be a function');+ throw new ValidationError('createCustomTool: execute must be a function');}const { inputParams, execute } = options;@@ -170,7 +171,7 @@ export function createCustomToolkit(// Validate slugconst slugResult = CustomToolSlugSchema.safeParse(slug);if (!slugResult.success) {- throw new Error(`createCustomToolkit: ${slugResult.error.issues[0].message}`);+ throw new ValidationError(`createCustomToolkit: ${slugResult.error.issues[0].message}`, { cause: slugResult.error });}// Validate name/description@@ -178,13 +179,13 @@ export function createCustomToolkit(// Non-empty tools requiredif (!options.tools?.length) {- throw new Error('createCustomToolkit: at least one tool is required');+ throw new ValidationError('createCustomToolkit: at least one tool is required');}// Reject tools with extendsToolkitfor (const tool of options.tools) {if (tool.extendsToolkit) {- throw new Error(+ throw new ValidationError(`createCustomToolkit: tool "${tool.slug}" has extendsToolkit set. ` +`Tools in a custom toolkit must not use extendsToolkit — they inherit the toolkit identity instead.`);@@ -228,7 +229,7 @@ export function buildCustomToolsMap(if (prefixedSlug.length > MAX_PREFIXED_SLUG_LENGTH) {const prefix = prefixedSlug.substring(0, prefixedSlug.length - originalSlug.length);const available = MAX_PREFIXED_SLUG_LENGTH - prefix.length;- throw new Error(+ throw new ValidationError(`Custom tool slug "${handle.slug}" is too long. ` +`With prefix "${prefix}", the final slug "${prefixedSlug}" exceeds ${MAX_PREFIXED_SLUG_LENGTH} characters. ` +`Shorten the slug to at most ${available} characters.`@@ -237,12 +238,12 @@ export function buildCustomToolsMap(// Check cross-group collisions on prefixed slugif (byPrefixed.has(prefixedSlug)) {- throw new Error(`Custom tool slug collision: "${prefixedSlug}" is already registered.`);+ throw new ValidationError(`Custom tool slug collision: "${prefixedSlug}" is already registered.`);}// Check cross-group collisions on original slugif (byOriginal.has(originalSlug)) {- throw new Error(+ throw new ValidationError(`Custom tool slug collision: original slug "${handle.slug}" maps to multiple prefixed slugs. ` +`"${byOriginal.get(originalSlug)!.prefixedSlug}" and "${prefixedSlug}" both resolve from "${originalSlug}".`);diff --git a/ts/packages/core/src/models/SessionContext.ts b/ts/packages/core/src/models/SessionContext.tsindex 9c89f74b2..8f2553119 100644--- a/ts/packages/core/src/models/SessionContext.ts+++ b/ts/packages/core/src/models/SessionContext.ts@@ -2,28 +2,22 @@* @fileoverview Session context implementation injected into custom tool execute functions.*/import { Composio as ComposioClient } from '@composio/client';-import type { SessionContext } from '../types/customTool.types';+import type { SessionContext, CustomToolsMap } from '../types/customTool.types';import type { ToolExecuteResponse } from '../types/tool.types';import type { SessionProxyExecuteParams } from '../types/toolRouter.types';import { SessionProxyExecuteParamsSchema } from '../types/toolRouter.types';+import { ValidationError } from '../errors';import { transformProxyParams } from './proxyParamsTransform';--/**- * Callback that attempts local tool execution.- * Returns a Promise if the slug matches a local tool, or undefined to fall back to remote.- */-export type TryLocalExecuteFn = (- slug: string,- args: Record<string, unknown>-) => Promise<ToolExecuteResponse> | undefined;+import { findCustomTool, executeCustomTool } from './customToolExecution';/*** Concrete implementation of SessionContext.- * Built per local tool invocation inside ToolRouterSession.+ * One instance is created per session (or per multi-execute batch) and shared+ * across all custom tool invocations, including sibling routing.*- * When `tryLocalExecute` is provided, `execute()` checks sibling local tools first- * before falling back to the backend API. This allows local tool A to call local- * tool B via `session.execute('B', ...)` without hitting the network.+ * When `customToolsMap` is provided, `execute()` checks local tools first+ * before falling back to the backend API. This allows tool A to call tool B+ * via `session.execute('B', ...)` without hitting the network.*/export class SessionContextImpl implements SessionContext {public readonly userId: string;@@ -32,7 +26,7 @@ export class SessionContextImpl implements SessionContext {private readonly client: ComposioClient,userId: string,private readonly sessionId: string,- private readonly tryLocalExecute?: TryLocalExecuteFn+ private readonly customToolsMap?: CustomToolsMap) {this.userId = userId;}@@ -47,9 +41,9 @@ export class SessionContextImpl implements SessionContext {arguments_: Record<string, unknown>): Promise<ToolExecuteResponse> {// Try local tool first (sibling routing)- const localResult = this.tryLocalExecute?.(toolSlug, arguments_);- if (localResult) {- return localResult;+ const entry = findCustomTool(this.customToolsMap, toolSlug);+ if (entry) {+ return executeCustomTool(entry, arguments_, this);}// Fall back to remote execution@@ -74,7 +68,7 @@ export class SessionContextImpl implements SessionContext {async proxyExecute(params: SessionProxyExecuteParams): Promise<ToolExecuteResponse> {const validated = SessionProxyExecuteParamsSchema.safeParse(params);if (!validated.success) {- throw new Error(`Invalid proxy execute parameters: ${validated.error.message}`);+ throw new ValidationError('Invalid proxy execute parameters', { cause: validated.error });}const body = transformProxyParams(validated.data);diff --git a/ts/packages/core/src/models/ToolRouterSession.ts b/ts/packages/core/src/models/ToolRouterSession.tsindex 7a69fd228..c3c0cf2c9 100644--- a/ts/packages/core/src/models/ToolRouterSession.ts+++ b/ts/packages/core/src/models/ToolRouterSession.ts@@ -273,19 +273,14 @@ export class ToolRouterSession</*** Build a SessionContext for local tool execution.- * Includes sibling routing: session.execute() inside a custom tool checks- * local tools first before falling back to the backend API.+ * The context holds the custom tools map and routes sibling calls in-process.*/private buildSessionContext(): SessionContext {return new SessionContextImpl(this.client,this.userId!,this.sessionId,- (slug, args) => {- const entry = findCustomTool(this.customToolsMap, slug);- if (!entry) return undefined;- return executeCustomTool(entry, args, this.buildSessionContext());- }+ this.customToolsMap);}@@ -344,9 +339,10 @@ export class ToolRouterSession<);}- // Execute local tools in parallel+ // Execute local tools in parallel (shared context for the entire batch)+ const ctx = this.buildSessionContext();const localPromises = localItems.map(async ({ index, entry }) => {- const result = await executeCustomTool(entry, parsed[index].arguments, this.buildSessionContext());+ const result = await executeCustomTool(entry, parsed[index].arguments, ctx);return { index, result };});diff --git a/ts/packages/core/test/models/customTool.test.ts b/ts/packages/core/test/models/customTool.test.tsindex abb2d2c96..e8d1f39c6 100644--- a/ts/packages/core/test/models/customTool.test.ts+++ b/ts/packages/core/test/models/customTool.test.ts@@ -596,31 +596,44 @@ describe('SessionContextImpl', () => {});describe('sibling local tool routing', () => {- it('should route to local tool when tryLocalExecute matches', async () => {- const tryLocalExecute = vi.fn().mockReturnValue(- Promise.resolve({ data: { local: true }, error: null, successful: true })- );-- const ctx = new SessionContextImpl(mockClient as any, 'user_1', 'sess_1', tryLocalExecute);+ it('should route to local tool when customToolsMap has a match', async () => {+ const siblingExecute = vi.fn().mockResolvedValue({ local: true });+ const customToolsMap = buildCustomToolsMap([+ createCustomTool('SIBLING_TOOL', {+ name: 'Sibling',+ description: 'A sibling tool',+ inputParams: z.object({ key: z.string() }),+ execute: siblingExecute,+ }),+ ]);++ const ctx = new SessionContextImpl(mockClient as any, 'user_1', 'sess_1', customToolsMap);const result = await ctx.execute('SIBLING_TOOL', { key: 'val' });- expect(tryLocalExecute).toHaveBeenCalledWith('SIBLING_TOOL', { key: 'val' });+ expect(siblingExecute).toHaveBeenCalledWith({ key: 'val' }, ctx);expect(result).toEqual({ data: { local: true }, error: null, successful: true });+ // Should NOT call remoteexpect(mockClient.toolRouter.session.execute).not.toHaveBeenCalled();});- it('should fall back to remote when tryLocalExecute returns undefined', async () => {- const tryLocalExecute = vi.fn().mockReturnValue(undefined);+ it('should fall back to remote when slug not in customToolsMap', async () => {+ const customToolsMap = buildCustomToolsMap([+ createCustomTool('OTHER_TOOL', {+ name: 'Other',+ description: 'Not the one we call',+ inputParams: z.object({}),+ execute: vi.fn().mockResolvedValue({}),+ }),+ ]);mockClient.toolRouter.session.execute.mockResolvedValue({data: { remote: true },error: null,log_id: 'log_3',});- const ctx = new SessionContextImpl(mockClient as any, 'user_1', 'sess_1', tryLocalExecute);+ const ctx = new SessionContextImpl(mockClient as any, 'user_1', 'sess_1', customToolsMap);const result = await ctx.execute('REMOTE_TOOL', { key: 'val' });- expect(tryLocalExecute).toHaveBeenCalledWith('REMOTE_TOOL', { key: 'val' });expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith('sess_1', {tool_slug: 'REMOTE_TOOL',arguments: { key: 'val' },@@ -628,7 +641,7 @@ describe('SessionContextImpl', () => {expect(result).toEqual({ data: { remote: true }, error: null, successful: true });});- it('should delegate to remote when no tryLocalExecute is provided', async () => {+ it('should delegate to remote when no customToolsMap is provided', async () => {mockClient.toolRouter.session.execute.mockResolvedValue({data: { remote: true },error: null,