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: rename local tool internals to custom tool
Dhawal Upadhyay153afd7a4550
diff --git a/ts/packages/core/src/models/CustomTool.ts b/ts/packages/core/src/models/CustomTool.tsindex c13d44431..8b2956261 100644--- a/ts/packages/core/src/models/CustomTool.ts+++ b/ts/packages/core/src/models/CustomTool.ts@@ -21,9 +21,9 @@ import {type CreateCustomToolParams,type CustomTool,type CustomToolExecuteFn,- type LocalToolsMap,- type LocalToolsMapEntry,- type LocalToolDefinition,+ type CustomToolsMap,+ type CustomToolsMapEntry,+ type CustomToolDefinition,type InputParamsSchema,} from '../types/customTool.types';@@ -128,7 +128,7 @@ export function createCustomTool<T extends z.ZodType>(}/**- * Build a LocalToolsMap from an array of custom tools.+ * Build a CustomToolsMap from an array of custom tools.* Used internally by ToolRouter.create() to construct the per-session routing map.** @internal@@ -136,9 +136,9 @@ export function createCustomTool<T extends z.ZodType>(* @returns Maps for O(1) lookup by both prefixed and original slug* @throws If duplicate slugs are detected*/-export function buildLocalToolsMap(tools: CustomTool[]): LocalToolsMap {- const byPrefixed = new Map<string, LocalToolsMapEntry>();- const byOriginal = new Map<string, LocalToolsMapEntry>();+export function buildCustomToolsMap(tools: CustomTool[]): CustomToolsMap {+ const byPrefixed = new Map<string, CustomToolsMapEntry>();+ const byOriginal = new Map<string, CustomToolsMapEntry>();for (const handle of tools) {const upperSlug = handle.slug.toUpperCase();@@ -148,7 +148,7 @@ export function buildLocalToolsMap(tools: CustomTool[]): LocalToolsMap {throw new Error(`createCustomTool: duplicate slug "${handle.slug}"`);}- const entry: LocalToolsMapEntry = { handle, prefixedSlug };+ const entry: CustomToolsMapEntry = { handle, prefixedSlug };byPrefixed.set(prefixedSlug, entry);byOriginal.set(upperSlug, entry);}@@ -161,11 +161,11 @@ export function buildLocalToolsMap(tools: CustomTool[]): LocalToolsMap {** @internal* @param tools - The custom tools to serialize- * @returns Array of LocalToolDefinition for the API payload+ * @returns Array of CustomToolDefinition for the API payload*/-export function serializeLocalTools(+export function serializeCustomTools(tools: CustomTool[]-): LocalToolDefinition[] {+): CustomToolDefinition[] {return tools.map(handle => ({slug: handle.slug,name: handle.name,diff --git a/ts/packages/core/src/models/ToolRouter.ts b/ts/packages/core/src/models/ToolRouter.tsindex 7a812162c..cad4c829e 100644--- a/ts/packages/core/src/models/ToolRouter.ts+++ b/ts/packages/core/src/models/ToolRouter.ts@@ -38,8 +38,8 @@ import {transformToolRouterToolkitsParams,} from '../lib/toolRouterParams';import { ToolRouterSession } from './ToolRouterSession';-import { buildLocalToolsMap, serializeLocalTools } from './CustomTool';-import type { LocalToolsMap, LocalToolDefinition } from '../types/customTool.types';+import { buildCustomToolsMap, serializeCustomTools } from './CustomTool';+import type { CustomToolsMap, CustomToolDefinition } from '../types/customTool.types';export class ToolRouter<TToolCollection,@@ -96,11 +96,11 @@ export class ToolRouter<): Promise<Session<TToolCollection, TTool, TProvider>> {const routerConfig = ToolRouterCreateSessionConfigSchema.parse(config ?? {});- // Build local tools map and backend payload from custom tool handles- let localToolsMap: LocalToolsMap | undefined;+ // Build custom tools map and backend payload from custom tool handles+ let customToolsMap: CustomToolsMap | undefined;const customTools = routerConfig.customTools;- const payload: SessionCreateParams & { local_tools?: LocalToolDefinition[] } = {+ const payload: SessionCreateParams & { custom_tools?: CustomToolDefinition[] } = {user_id: userId,auth_configs: routerConfig.authConfigs,connected_accounts: routerConfig.connectedAccounts,@@ -121,10 +121,10 @@ export class ToolRouter<};if (customTools?.length) {- localToolsMap = buildLocalToolsMap(customTools);- // Send definitions to backend for BM25 search indexing- // Type assertion: @composio/client doesn't have local_tools yet (Hermes PR #8453)- payload.local_tools = serializeLocalTools(customTools);+ customToolsMap = buildCustomToolsMap(customTools);+ // Send definitions to backend for search indexing+ // Type assertion: @composio/client doesn't have custom_tools yet+ payload.custom_tools = serializeCustomTools(customTools);}const session = await this.client.toolRouter.session.create(@@ -140,7 +140,7 @@ export class ToolRouter<session.session_id,this.createMCPServerConfig(session.mcp),{ assistivePrompt },- localToolsMap,+ customToolsMap,userId);}diff --git a/ts/packages/core/src/models/ToolRouterSession.ts b/ts/packages/core/src/models/ToolRouterSession.tsindex 585cc385c..02dea012d 100644--- a/ts/packages/core/src/models/ToolRouterSession.ts+++ b/ts/packages/core/src/models/ToolRouterSession.ts@@ -25,10 +25,10 @@ import { ToolkitConnectionStateSchema } from '../types/toolRouter.types';import { ValidationError } from '../errors';import { Tools } from './Tools';import { ToolRouterSessionFilesMount } from './ToolRouterSessionFileMount';-import type { LocalToolsMap, LocalToolsMapEntry, SessionContext } from '../types/customTool.types';+import type { CustomToolsMap, CustomToolsMapEntry, SessionContext } from '../types/customTool.types';import type { Tool, ToolExecuteResponse } from '../types/tool.types';import { SessionContextImpl } from './SessionContext';-import { findLocalTool, executeLocalTool } from './localToolExecution';+import { findCustomTool, executeCustomTool } from './customToolExecution';const COMPOSIO_MULTI_EXECUTE_TOOL = 'COMPOSIO_MULTI_EXECUTE_TOOL';const COMPOSIO_EXECUTE_LOCAL_TOOL = 'COMPOSIO_EXECUTE_LOCAL_TOOL';@@ -48,10 +48,10 @@ export class ToolRouterSession<sessionId: string,mcp: ToolRouterMCPServerConfig,experimentalOverrides?: Pick<SessionExperimental, 'assistivePrompt'>,- private readonly localToolsMap?: LocalToolsMap,+ private readonly customToolsMap?: CustomToolsMap,private readonly userId?: string) {- if (localToolsMap && !userId) {+ if (customToolsMap && !userId) {throw new Error('userId is required when custom tools are bound to a session.');}this.sessionId = sessionId;@@ -77,7 +77,7 @@ export class ToolRouterSession<modifiers?.modifySchema ? { modifySchema: modifiers.modifySchema } : undefined);- if (this.hasLocalTools()) {+ if (this.hasCustomTools()) {// Create an execute function that splits local/remote tools in COMPOSIO_MULTI_EXECUTE_TOOLconst routingExecuteFn = async (toolSlug: string,@@ -89,15 +89,15 @@ export class ToolRouterSession<if (toolSlug === COMPOSIO_EXECUTE_LOCAL_TOOL) {const slug = String(input.tool_slug ?? '');const args = (input.arguments as Record<string, unknown> | undefined) ?? {};- const entry = findLocalTool(this.localToolsMap, slug);+ const entry = findCustomTool(this.customToolsMap, slug);if (!entry) {return {data: {},- error: `Local tool "${slug}" not found`,+ error: `Custom tool "${slug}" not found. If this is a remote tool, execute it via COMPOSIO_MULTI_EXECUTE_TOOL.`,successful: false,};}- return executeLocalTool(entry, args, this.buildSessionContext());+ return executeCustomTool(entry, args, this.buildSessionContext());}// Non-multi-execute meta tools always go to backendreturn ToolsModel.executeMetaTool(@@ -143,7 +143,7 @@ export class ToolRouterSession<* ```*/async localTools(): Promise<ReturnType<TProvider['wrapTools']>> {- if (!this.hasLocalTools()) {+ if (!this.hasCustomTools()) {throw new Error('No custom tools are bound to this session.');}if (!this.config?.provider) {@@ -154,7 +154,7 @@ export class ToolRouterSession<}// Collect local tool slugs and descriptions for the schema- const toolEntries = Array.from(this.localToolsMap!.byOriginal.entries());+ const toolEntries = Array.from(this.customToolsMap!.byOriginal.entries());const slugDescriptions = toolEntries.map(([slug, entry]) => `- ${entry.prefixedSlug}: ${entry.handle.description}`).join('\n');@@ -190,16 +190,16 @@ export class ToolRouterSession<const slug = String(input.tool_slug ?? '');const args = (input.arguments as Record<string, unknown> | undefined) ?? {};- const entry = findLocalTool(this.localToolsMap, slug);+ const entry = findCustomTool(this.customToolsMap, slug);if (!entry) {return {data: {},- error: `Local tool "${slug}" not found. Available: ${toolEntries.map(([, e]) => e.prefixedSlug).join(', ')}`,+ error: `Custom tool "${slug}" not found. Available: ${toolEntries.map(([, e]) => e.prefixedSlug).join(', ')}. If this is a remote tool, execute it via COMPOSIO_MULTI_EXECUTE_TOOL.`,successful: false,};}- return executeLocalTool(entry, args, this.buildSessionContext());+ return executeCustomTool(entry, args, this.buildSessionContext());};return this.config.provider.wrapTools([tool], executeFn) as ReturnType<@@ -312,9 +312,9 @@ export class ToolRouterSession<arguments_?: Record<string, unknown>): Promise<ToolRouterSessionExecuteResponse> {// Check if this is a local tool (by original or prefixed slug)- const entry = findLocalTool(this.localToolsMap, toolSlug);+ const entry = findCustomTool(this.customToolsMap, toolSlug);if (entry) {- const result = await executeLocalTool(entry, arguments_ ?? {}, this.buildSessionContext());+ const result = await executeCustomTool(entry, arguments_ ?? {}, this.buildSessionContext());return {data: result.data,error: result.error,@@ -333,9 +333,9 @@ export class ToolRouterSession<// ── Private helpers ──────────────────────────────────────────- /** Check if this session has any local tools bound. */- private hasLocalTools(): boolean {- return (this.localToolsMap?.byPrefixed.size ?? 0) > 0;+ /** Check if this session has any custom tools bound. */+ private hasCustomTools(): boolean {+ return (this.customToolsMap?.byPrefixed.size ?? 0) > 0;}/**@@ -349,9 +349,9 @@ export class ToolRouterSession<this.userId!,this.sessionId,(slug, args) => {- const entry = findLocalTool(this.localToolsMap, slug);+ const entry = findCustomTool(this.customToolsMap, slug);if (!entry) return undefined;- return executeLocalTool(entry, args, this.buildSessionContext());+ return executeCustomTool(entry, args, this.buildSessionContext());});}@@ -391,10 +391,10 @@ export class ToolRouterSession<const parsed = toolItems.map(item => this.parseToolItem(item));// Partition into local (with resolved entry) and remote- const localItems: Array<{ index: number; entry: LocalToolsMapEntry }> = [];+ const localItems: Array<{ index: number; entry: CustomToolsMapEntry }> = [];const remoteIndices: number[] = [];for (let i = 0; i < parsed.length; i++) {- const entry = findLocalTool(this.localToolsMap, parsed[i].tool_slug);+ const entry = findCustomTool(this.customToolsMap, parsed[i].tool_slug);if (entry) {localItems.push({ index: i, entry });} else {@@ -413,7 +413,7 @@ export class ToolRouterSession<// Execute local tools in parallelconst localPromises = localItems.map(async ({ index, entry }) => {- const result = await executeLocalTool(entry, parsed[index].arguments, this.buildSessionContext());+ const result = await executeCustomTool(entry, parsed[index].arguments, this.buildSessionContext());return { index, result };});diff --git a/ts/packages/core/src/models/localToolExecution.ts b/ts/packages/core/src/models/customToolExecution.tssimilarity index 77%rename from ts/packages/core/src/models/localToolExecution.tsrename to ts/packages/core/src/models/customToolExecution.tsindex 31944edde..ea6a0764f 100644--- a/ts/packages/core/src/models/localToolExecution.ts+++ b/ts/packages/core/src/models/customToolExecution.ts@@ -1,32 +1,32 @@/**- * @fileoverview Standalone functions for local tool lookup and execution.+ * @fileoverview Standalone functions for custom tool lookup and execution.* Extracted from ToolRouterSession for reuse in SessionContextImpl (sibling routing).*/-import type { LocalToolsMap, LocalToolsMapEntry, SessionContext } from '../types/customTool.types';+import type { CustomToolsMap, CustomToolsMapEntry, SessionContext } from '../types/customTool.types';import type { ToolExecuteResponse } from '../types/tool.types';/**- * Find a local tool entry by slug.+ * Find a custom tool entry by slug.* Checks both the prefixed map (LOCAL_X — agent path) and original map (X — programmatic path).*/-export function findLocalTool(- map: LocalToolsMap | undefined,+export function findCustomTool(+ map: CustomToolsMap | undefined,slug: string-): LocalToolsMapEntry | undefined {+): CustomToolsMapEntry | undefined {if (!map) return undefined;const upper = slug.toUpperCase();return map.byPrefixed.get(upper) ?? map.byOriginal.get(upper);}/**- * Execute a local tool in-process.+ * Execute a custom tool in-process.* Validates input via the Zod schema, calls the user's execute function,* and wraps the result into the standard response format.*- * Callers provide a pre-built SessionContext (which may include sibling local routing).+ * Callers provide a pre-built SessionContext (which may include sibling routing).*/-export async function executeLocalTool(- entry: LocalToolsMapEntry,+export async function executeCustomTool(+ entry: CustomToolsMapEntry,arguments_: Record<string, unknown>,sessionContext: SessionContext): Promise<ToolExecuteResponse> {diff --git a/ts/packages/core/src/types/customTool.types.ts b/ts/packages/core/src/types/customTool.types.tsindex 804401983..dbba13d77 100644--- a/ts/packages/core/src/types/customTool.types.ts+++ b/ts/packages/core/src/types/customTool.types.ts@@ -147,8 +147,8 @@ export interface CustomTool {readonly execute: CustomToolExecuteFn<z.ZodType>;}-/** Serialized tool definition sent to backend for BM25 search indexing. */-export interface LocalToolDefinition {+/** Serialized tool definition sent to backend for search indexing. */+export interface CustomToolDefinition {slug: string;name: string;description: string;@@ -156,16 +156,16 @@ export interface LocalToolDefinition {toolkit?: string;}-/** @internal Entry in the per-session local tools routing map. */-export type LocalToolsMapEntry = {+/** @internal Entry in the per-session custom tools routing map. */+export type CustomToolsMapEntry = {handle: CustomTool;prefixedSlug: string;};-/** @internal Lookup maps used by ToolRouterSession for routing. */-export type LocalToolsMap = {+/** @internal Lookup maps used by ToolRouterSession for routing custom tools. */+export type CustomToolsMap = {/** Lookup by prefixed slug (e.g. LOCAL_GET_USER_CONTEXT) — used for agent execution path */- byPrefixed: Map<string, LocalToolsMapEntry>;+ byPrefixed: Map<string, CustomToolsMapEntry>;/** Lookup by original slug (e.g. GET_USER_CONTEXT) — used for programmatic session.execute() */- byOriginal: Map<string, LocalToolsMapEntry>;+ byOriginal: Map<string, CustomToolsMapEntry>;};diff --git a/ts/packages/core/test/models/customTool.test.ts b/ts/packages/core/test/models/customTool.test.tsindex 73c1308c5..0f6a8ab11 100644--- a/ts/packages/core/test/models/customTool.test.ts+++ b/ts/packages/core/test/models/customTool.test.ts@@ -1,6 +1,6 @@import { describe, it, expect, vi, beforeEach } from 'vitest';import { z } from 'zod/v3';-import { createCustomTool, buildLocalToolsMap, serializeLocalTools, LOCAL_TOOL_PREFIX } from '../../src/models/CustomTool';+import { createCustomTool, buildCustomToolsMap, serializeCustomTools, LOCAL_TOOL_PREFIX } from '../../src/models/CustomTool';import { SessionContextImpl } from '../../src/models/SessionContext';import type { CustomTool, SessionContext } from '../../src/types/customTool.types';@@ -154,10 +154,10 @@ describe('createCustomTool', () => {});// ────────────────────────────────────────────────────────────────-// buildLocalToolsMap()+// buildCustomToolsMap()// ────────────────────────────────────────────────────────────────-describe('buildLocalToolsMap', () => {+describe('buildCustomToolsMap', () => {const makeTool = (slug: string): CustomTool => ({slug,name: `Tool ${slug}`,@@ -169,7 +169,7 @@ describe('buildLocalToolsMap', () => {it('should create maps with both prefixed and original slug keys', () => {const tools = [makeTool('MY_TOOL'), makeTool('OTHER_TOOL')];- const map = buildLocalToolsMap(tools);+ const map = buildCustomToolsMap(tools);expect(map.byPrefixed.size).toBe(2);expect(map.byOriginal.size).toBe(2);@@ -185,7 +185,7 @@ describe('buildLocalToolsMap', () => {it('should handle case-insensitive slugs (uppercased internally)', () => {const tool = makeTool('my_tool');- const map = buildLocalToolsMap([tool]);+ const map = buildCustomToolsMap([tool]);expect(map.byOriginal.has('MY_TOOL')).toBe(true);expect(map.byPrefixed.has('LOCAL_MY_TOOL')).toBe(true);@@ -193,16 +193,16 @@ describe('buildLocalToolsMap', () => {it('should throw on duplicate slugs', () => {const tools = [makeTool('DUPE'), makeTool('DUPE')];- expect(() => buildLocalToolsMap(tools)).toThrow('duplicate slug "DUPE"');+ expect(() => buildCustomToolsMap(tools)).toThrow('duplicate slug "DUPE"');});});// ────────────────────────────────────────────────────────────────-// serializeLocalTools()+// serializeCustomTools()// ────────────────────────────────────────────────────────────────-describe('serializeLocalTools', () => {+describe('serializeCustomTools', () => {it('should serialize tools into backend format', () => {const tool: CustomTool = {slug: 'GET_DATA',@@ -214,7 +214,7 @@ describe('serializeLocalTools', () => {execute: vi.fn(),};- const result = serializeLocalTools([tool]);+ const result = serializeCustomTools([tool]);expect(result).toEqual([{@@ -237,7 +237,7 @@ describe('serializeLocalTools', () => {execute: vi.fn(),};- const result = serializeLocalTools([tool]);+ const result = serializeCustomTools([tool]);expect(result[0]).not.toHaveProperty('toolkit');});});diff --git a/ts/packages/core/test/models/customToolRouting.test.ts b/ts/packages/core/test/models/customToolRouting.test.tsindex 27eff0151..70cb65ad4 100644--- a/ts/packages/core/test/models/customToolRouting.test.ts+++ b/ts/packages/core/test/models/customToolRouting.test.ts@@ -2,7 +2,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';import { z } from 'zod/v3';import { ToolRouter } from '../../src/models/ToolRouter';import { ToolRouterSession } from '../../src/models/ToolRouterSession';-import { createCustomTool, buildLocalToolsMap } from '../../src/models/CustomTool';+import { createCustomTool, buildCustomToolsMap } from '../../src/models/CustomTool';import { MockProvider } from '../utils/mocks/provider.mock';import ComposioClient from '@composio/client';import { Tools } from '../../src/models/Tools';@@ -99,7 +99,7 @@ const createSessionWithProvider = ('sess_123',{ type: 'http' as const, url: 'https://mcp.example.com/sess_123' },undefined,- buildLocalToolsMap(customTools),+ buildCustomToolsMap(customTools),'user_1');};@@ -129,14 +129,14 @@ describe('ToolRouter.create() with customTools', () => {});});- it('should send local_tools in the create payload', async () => {+ it('should send custom_tools in the create payload', async () => {await router.create('user_1', {toolkits: ['gmail'],customTools: [customToolHandle],});const payload = mockClient.toolRouter.session.create.mock.calls[0][0];- expect(payload.local_tools).toEqual([+ expect(payload.custom_tools).toEqual([{slug: 'GET_USER_CONTEXT',name: 'Get user context',@@ -146,22 +146,22 @@ describe('ToolRouter.create() with customTools', () => {]);});- it('should include toolkit in local_tools when toolkit is present', async () => {+ it('should include toolkit in custom_tools when toolkit is present', async () => {await router.create('user_1', {customTools: [sessionToolHandle],});const payload = mockClient.toolRouter.session.create.mock.calls[0][0];- expect(payload.local_tools[0].toolkit).toBe('meta_ads');+ expect(payload.custom_tools[0].toolkit).toBe('meta_ads');});- it('should not send local_tools when customTools is omitted or empty', async () => {+ it('should not send custom_tools when customTools is omitted or empty', async () => {await router.create('user_1', { toolkits: ['gmail'] });- expect(mockClient.toolRouter.session.create.mock.calls[0][0].local_tools).toBeUndefined();+ expect(mockClient.toolRouter.session.create.mock.calls[0][0].custom_tools).toBeUndefined();vi.clearAllMocks();await router.create('user_1', { customTools: [] });- expect(mockClient.toolRouter.session.create.mock.calls[0][0].local_tools).toBeUndefined();+ expect(mockClient.toolRouter.session.create.mock.calls[0][0].custom_tools).toBeUndefined();});it('should return a session with the correct sessionId', async () => {@@ -184,7 +184,7 @@ describe('ToolRouterSession execution routing', () => {client: ReturnType<typeof createMockClient>,customTools: CustomTool[] = []) => {- const localToolsMap = customTools.length ? buildLocalToolsMap(customTools) : undefined;+ const customToolsMap = customTools.length ? buildCustomToolsMap(customTools) : undefined;return new ToolRouterSession(client as unknown as ComposioClient,@@ -192,7 +192,7 @@ describe('ToolRouterSession execution routing', () => {'sess_123',{ type: 'http' as const, url: 'https://mcp.example.com/sess_123' },undefined,- localToolsMap,+ customToolsMap,'user_1');};@@ -506,7 +506,7 @@ describe('ToolRouterSession execution routing', () => {{ apiKey: 'key', provider: new MockProvider() },'sess_123',{ type: 'http' as const, url: 'https://mcp.example.com/sess_123' }- // No localToolsMap, no userId+ // No customToolsMap, no userId);const result = await session.tools();@@ -884,7 +884,7 @@ describe('ToolRouterSession execution routing', () => {describe('provider guard — session.tools() throws without provider', () => {it('should throw when provider is not configured but local tools exist', async () => {- const localToolsMap = buildLocalToolsMap([customToolHandle]);+ const customToolsMap = buildCustomToolsMap([customToolHandle]);const session = new ToolRouterSession(mockClient as unknown as ComposioClient,@@ -892,7 +892,7 @@ describe('ToolRouterSession execution routing', () => {'sess_123',{ type: 'http' as const, url: 'https://mcp.example.com/sess_123' },undefined,- localToolsMap,+ customToolsMap,'user_1');@@ -953,7 +953,7 @@ describe('ToolRouterSession execution routing', () => {});expect(result.successful).toBe(false);- expect(result.error).toContain('Local tool "NON_EXISTENT_TOOL" not found');+ expect(result.error).toContain('Custom tool "NON_EXISTENT_TOOL" not found');expect(result.data).toEqual({});});@@ -963,7 +963,7 @@ describe('ToolRouterSession execution routing', () => {{ apiKey: 'key', provider: new MockProvider() },'sess_123',{ type: 'http' as const, url: 'https://mcp.example.com/sess_123' }- // No localToolsMap, no userId+ // No customToolsMap, no userId);await expect(session.localTools()).rejects.toThrow(@@ -1010,7 +1010,7 @@ describe('ToolRouterSession execution routing', () => {});expect(result.successful).toBe(false);- expect(result.error).toContain('Local tool "DOES_NOT_EXIST" not found');+ expect(result.error).toContain('Custom tool "DOES_NOT_EXIST" not found');expect(result.data).toEqual({});});});