@devries-cameron20 / composio Mirror · read-only / commits / 3388afcc9
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.

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 22, 03:15 UTC

refactor(core): address review comments — rename API, add Zod validation

- Rename CustomTool() → createCustomTool() (camelCase convention) - Rename CustomToolHandle type → CustomTool - Rename connectedToolkit → toolkit with clear TSDoc - Add CreateCustomToolBaseSchema (Zod) for string field validation - Remove SessionContextImpl from public exports (internal only) - Export CreateCustomToolParams type Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

Dhawal Upadhyay committed Mar 10, 2026 at 21:03 UTC 3388afcc9b4dbaee044d5305d128f1f6a8caa176
8 files changed +160 -153
ts/e2e-tests/runtimes/node/custom-tools/fixtures/index.mjs
+6 -6
@@ -7,7 +7,7 @@
7 * Requires COMPOSIO_API_KEY in environment.
8 */
9 import { Composio } from '@composio/core';
10 -import { CustomTool } from '@composio/core/experimental';
10 +import { createCustomTool } from '@composio/core/experimental';
11 import { z } from 'zod/v3';
12
13 const apiKey = process.env.COMPOSIO_API_KEY;
@@ -18,7 +18,7 @@ if (!apiKey) {
18
19 // ── Define custom tools ──────────────────────────────────────
20
21 -const getUserContext = CustomTool({
21 +const getUserContext = createCustomTool({
22 slug: 'GET_USER_CONTEXT',
23 name: 'Get user context',
24 description: 'Retrieve user preferences and history',
@@ -30,7 +30,7 @@ const getUserContext = CustomTool({
30 },
31 });
32
33 -const enrichedSearch = CustomTool({
33 +const enrichedSearch = createCustomTool({
34 slug: 'ENRICHED_SEARCH',
35 name: 'Enriched search',
36 description: 'Search and enrich results with user context',
@@ -45,7 +45,7 @@ const enrichedSearch = CustomTool({
45 },
46 });
47
48 -const throwingTool = CustomTool({
48 +const throwingTool = createCustomTool({
49 slug: 'THROWING_TOOL',
50 name: 'Throwing tool',
51 description: 'A tool that always throws an error',
@@ -56,7 +56,7 @@ const throwingTool = CustomTool({
56 });
57
58 // Tool with strict numeric schema — for Zod validation failure test
59 -const strictTool = CustomTool({
59 +const strictTool = createCustomTool({
60 slug: 'STRICT_TOOL',
61 name: 'Strict tool',
62 description: 'Tool with strict numeric input',
@@ -69,7 +69,7 @@ const strictTool = CustomTool({
69 });
70
71 // Tool that chains into a remote tool via SessionContext.execute()
72 -const weatherChain = CustomTool({
72 +const weatherChain = createCustomTool({
73 slug: 'WEATHER_CHAIN',
74 name: 'Weather chain',
75 description: 'Fetches weather via remote tool and enriches with local context',
ts/packages/core/src/experimental/index.ts
+3 -4
@@ -7,11 +7,10 @@
7 */
8
9 // Custom local tools
10 -export { CustomTool } from '../models/CustomTool';
11 -export { SessionContextImpl } from '../models/SessionContext';
10 +export { createCustomTool } from '../models/CustomTool';
11 export type {
13 - CustomToolHandle,
14 - NewCustomToolOptions,
12 + CustomTool,
13 + CreateCustomToolParams,
14 CustomToolExecuteFn,
15 SessionContext,
16 } from '../types/customTool.types';
ts/packages/core/src/index.ts
+1 -2
@@ -12,8 +12,7 @@ export { RemoteFile } from './models/RemoteFile';
12 export { createConnectionRequest } from './models/ConnectionRequest';
13 export { ToolRouterSession } from './models/ToolRouterSession';
14 /** @experimental Create custom local tools — also available from '@composio/core/experimental' */
15 -export { CustomTool } from './models/CustomTool';
16 -export { SessionContextImpl } from './models/SessionContext';
15 +export { createCustomTool } from './models/CustomTool';
16 export * from './types/provider.types';
17 export * from './types/customTool.types';
18 export * from './types/tool.types';
ts/packages/core/src/models/CustomTool.ts
+45 -54
@@ -3,9 +3,9 @@
3 *
4 * Usage:
5 * ```typescript
6 - * import { CustomTool } from '@composio/core/experimental';
6 + * import { createCustomTool } from '@composio/core/experimental';
7 *
8 - * const myTool = CustomTool({
8 + * const myTool = createCustomTool({
9 * slug: 'GET_USER_CONTEXT',
10 * name: 'Get user context',
11 * description: 'Retrieve what we know about a user',
@@ -16,14 +16,15 @@
16 */
17 import * as zodToJsonSchema from 'zod-to-json-schema';
18 import { z } from 'zod/v3';
19 -import type {
20 - NewCustomToolOptions,
21 - CustomToolHandle,
22 - CustomToolExecuteFn,
23 - LocalToolsMap,
24 - LocalToolsMapEntry,
25 - LocalToolDefinition,
26 - InputParamsSchema,
19 +import {
20 + CreateCustomToolBaseSchema,
21 + type CreateCustomToolParams,
22 + type CustomTool,
23 + type CustomToolExecuteFn,
24 + type LocalToolsMap,
25 + type LocalToolsMapEntry,
26 + type LocalToolDefinition,
27 + type InputParamsSchema,
28 } from '../types/customTool.types';
29
30 /** Prefix applied by the backend to local tool slugs for disambiguation. */
@@ -32,7 +33,7 @@ export const LOCAL_TOOL_PREFIX = 'LOCAL_';
33 /**
34 * Create a custom local tool for use in tool router sessions.
35 *
35 - * The returned handle is a lightweight reference containing the tool's metadata
36 + * The returned object is a lightweight reference containing the tool's metadata
37 * and execute function. Pass it to `composio.create(userId, { customTools: [...] })`
38 * to bind it to a session.
39 *
@@ -40,11 +41,11 @@ export const LOCAL_TOOL_PREFIX = 'LOCAL_';
41 * The SDK wraps it into the standard response format internally.
42 *
43 * @param options - Tool definition including slug, schema, and execute function
43 - * @returns A CustomToolHandle to pass to session creation
44 + * @returns A CustomTool to pass to session creation
45 *
46 * @example No-auth tool (no session needed)
47 * ```typescript
47 - * const getUserContext = CustomTool({
48 + * const getUserContext = createCustomTool({
49 * slug: 'GET_USER_CONTEXT',
50 * name: 'Get user context',
51 * description: 'Retrieve user preferences and history',
@@ -56,9 +57,9 @@ export const LOCAL_TOOL_PREFIX = 'LOCAL_';
57 * });
58 * ```
59 *
59 - * @example No-auth tool using session to call other tools
60 + * @example Tool using session to call other tools
61 * ```typescript
61 - * const enrichedSearch = CustomTool({
62 + * const enrichedSearch = createCustomTool({
63 * slug: 'ENRICHED_SEARCH',
64 * name: 'Enriched search',
65 * description: 'Search and enrich results with user context',
@@ -70,13 +71,13 @@ export const LOCAL_TOOL_PREFIX = 'LOCAL_';
71 * });
72 * ```
73 *
73 - * @example Auth tool with connectedToolkit (requires Composio connection)
74 + * @example Auth tool with toolkit (requires Composio connection)
75 * ```typescript
75 - * const getAdAccounts = CustomTool({
76 + * const getAdAccounts = createCustomTool({
77 * slug: 'GET_AD_ACCOUNTS',
78 * name: 'Get ad accounts',
79 * description: 'Get Meta ad account IDs for the authenticated user',
79 - * connectedToolkit: 'meta_ads',
80 + * toolkit: 'meta_ads',
81 * inputParams: z.object({ fields: z.string().default('id,name') }),
82 * execute: async (input, session) => {
83 * const result = await session.execute('META_ADS_GET_AD_ACCOUNTS', {
@@ -87,32 +88,22 @@ export const LOCAL_TOOL_PREFIX = 'LOCAL_';
88 * });
89 * ```
90 */
90 -export function CustomTool<T extends z.ZodType>(
91 - options: NewCustomToolOptions<T>
92 -): CustomToolHandle {
93 - const { slug, name, description, inputParams, execute, connectedToolkit } = options;
91 +export function createCustomTool<T extends z.ZodType>(
92 + options: CreateCustomToolParams<T>
93 +): CustomTool {
94 + // Validate string/scalar fields via Zod schema
95 + const validated = CreateCustomToolBaseSchema.parse(options);
96
95 - if (!slug) {
96 - throw new Error('CustomTool: slug is required');
97 + // Manual checks for fields Zod can't validate
98 + if (!options.inputParams) {
99 + throw new Error('createCustomTool: inputParams is required');
100 }
98 - if (slug.toUpperCase().startsWith(LOCAL_TOOL_PREFIX)) {
99 - throw new Error(
100 - `CustomTool: slug must not start with "${LOCAL_TOOL_PREFIX}" — this prefix is reserved for internal routing.`
101 - );
102 - }
103 - if (!name) {
104 - throw new Error('CustomTool: name is required');
105 - }
106 - if (!description) {
107 - throw new Error('CustomTool: description is required');
108 - }
109 - if (!inputParams) {
110 - throw new Error('CustomTool: inputParams is required');
111 - }
112 - if (typeof execute !== 'function') {
113 - throw new Error('CustomTool: execute must be a function');
101 + if (typeof options.execute !== 'function') {
102 + throw new Error('createCustomTool: execute must be a function');
103 }
104
105 + const { inputParams, execute } = options;
106 +
107 // Convert Zod schema → JSON Schema (reuses same pattern as legacy CustomTools.createTool)
108 const paramsSchema = zodToJsonSchema.default(inputParams, {
109 name: 'input',
@@ -126,10 +117,10 @@ export function CustomTool<T extends z.ZodType>(
117 };
118
119 return {
129 - slug,
130 - name,
131 - description,
132 - connectedToolkit,
120 + slug: validated.slug,
121 + name: validated.name,
122 + description: validated.description,
123 + toolkit: validated.toolkit,
124 inputSchema,
125 inputParams,
126 execute: execute as CustomToolExecuteFn<z.ZodType>,
@@ -137,24 +128,24 @@ export function CustomTool<T extends z.ZodType>(
128 }
129
130 /**
140 - * Build a LocalToolsMap from an array of handles.
131 + * Build a LocalToolsMap from an array of custom tools.
132 * Used internally by ToolRouter.create() to construct the per-session routing map.
133 *
134 * @internal
144 - * @param handles - The custom tool handles to include in the session
135 + * @param tools - The custom tools to include in the session
136 * @returns Maps for O(1) lookup by both prefixed and original slug
137 * @throws If duplicate slugs are detected
138 */
148 -export function buildLocalToolsMap(handles: CustomToolHandle[]): LocalToolsMap {
139 +export function buildLocalToolsMap(tools: CustomTool[]): LocalToolsMap {
140 const byPrefixed = new Map<string, LocalToolsMapEntry>();
141 const byOriginal = new Map<string, LocalToolsMapEntry>();
142
152 - for (const handle of handles) {
143 + for (const handle of tools) {
144 const upperSlug = handle.slug.toUpperCase();
145 const prefixedSlug = `${LOCAL_TOOL_PREFIX}${upperSlug}`;
146
147 if (byOriginal.has(upperSlug)) {
157 - throw new Error(`CustomTool: duplicate slug "${handle.slug}"`);
148 + throw new Error(`createCustomTool: duplicate slug "${handle.slug}"`);
149 }
150
151 const entry: LocalToolsMapEntry = { handle, prefixedSlug };
@@ -166,20 +157,20 @@ export function buildLocalToolsMap(handles: CustomToolHandle[]): LocalToolsMap {
157 }
158
159 /**
169 - * Serialize custom tool handles into the format expected by the backend session creation API.
160 + * Serialize custom tools into the format expected by the backend session creation API.
161 *
162 * @internal
172 - * @param handles - The custom tool handles to serialize
163 + * @param tools - The custom tools to serialize
164 * @returns Array of LocalToolDefinition for the API payload
165 */
166 export function serializeLocalTools(
176 - handles: CustomToolHandle[]
167 + tools: CustomTool[]
168 ): LocalToolDefinition[] {
178 - return handles.map(handle => ({
169 + return tools.map(handle => ({
170 slug: handle.slug,
171 name: handle.name,
172 description: handle.description,
173 input_schema: handle.inputSchema,
183 - ...(handle.connectedToolkit ? { toolkit: handle.connectedToolkit } : {}),
174 + ...(handle.toolkit ? { toolkit: handle.toolkit } : {}),
175 }));
176 }
ts/packages/core/src/types/customTool.types.ts
+38 -22
@@ -59,7 +59,7 @@ export interface ExecuteMetadata {
59 }
60
61 // ────────────────────────────────────────────────────────────────
62 -// New custom tool types (for tool router integration via CustomTool())
62 +// New custom tool types (for tool router integration via createCustomTool())
63 // ────────────────────────────────────────────────────────────────
64
65 /**
@@ -74,7 +74,10 @@ export interface SessionContext {
74 toolSlug: string,
75 arguments_: Record<string, unknown>
76 ): Promise<SdkToolExecuteResponse>;
77 - /** Proxy API calls through Composio's auth layer (resolved from session) */
77 + /**
78 + * Proxy API calls through Composio's auth layer (resolved from session).
79 + * @todo Not yet implemented — pending backend session-scoped proxy endpoint.
80 + */
81 proxyExecute(params: ToolProxyParams): Promise<SdkToolExecuteResponse>;
82 }
83
@@ -91,38 +94,52 @@ export type CustomToolExecuteFn<T extends z.ZodType> = (
94 session: SessionContext
95 ) => Promise<Record<string, unknown>>;
96
94 -/** Options for creating a custom local tool via `CustomTool()`. */
95 -export type NewCustomToolOptions<T extends z.ZodType> = {
96 - /** Unique slug identifier (e.g. 'GET_USER_CONTEXT') */
97 - slug: string;
98 - /** Human-readable name */
99 - name: string;
100 - /** Description — required for search indexing */
101 - description: string;
102 - /** Zod schema for input parameters */
103 - inputParams: T;
97 +/**
98 + * Zod schema for validating the string/scalar fields of createCustomTool() options.
99 + * Used internally for validation — inputParams and execute are checked manually.
100 + */
101 +export const CreateCustomToolBaseSchema = z.object({
102 + slug: z
103 + .string()
104 + .min(1, 'createCustomTool: slug is required')
105 + .refine(s => !s.toUpperCase().startsWith('LOCAL_'), {
106 + message:
107 + 'createCustomTool: slug must not start with "LOCAL_" — this prefix is reserved for internal routing.',
108 + }),
109 + name: z.string().min(1, 'createCustomTool: name is required'),
110 + description: z.string().min(1, 'createCustomTool: description is required'),
111 /**
105 - * Composio toolkit slug requiring an active connection (e.g. 'meta_ads').
106 - * If not provided, the tool does not need Composio auth.
112 + * Composio toolkit slug that this tool requires an active connection for.
113 + * Set this to the toolkit whose auth your tool needs (e.g. `'meta_ads'`, `'gmail'`).
114 + * Leave empty for tools that don't need any Composio-managed authentication.
115 */
108 - connectedToolkit?: string;
116 + toolkit: z.string().optional(),
117 +});
118 +
119 +/** Options for creating a custom local tool via `createCustomTool()`. */
120 +export type CreateCustomToolParams<T extends z.ZodType> = z.infer<
121 + typeof CreateCustomToolBaseSchema
122 +> & {
123 + /** Zod schema for input parameters */
124 + inputParams: T;
125 /** The function that executes the tool */
126 execute: CustomToolExecuteFn<T>;
127 };
128
129 /**
114 - * Handle returned from `CustomTool()`.
130 + * Custom tool definition returned from `createCustomTool()`.
131 * Pass to `composio.create(userId, { customTools: [...] })` to bind to a session.
132 */
117 -export interface CustomToolHandle {
133 +export interface CustomTool {
134 readonly slug: string;
135 readonly name: string;
136 readonly description: string;
137 /**
122 - * Composio toolkit slug requiring an active connection.
123 - * Undefined means the tool does not need Composio auth.
138 + * Composio toolkit slug that this tool requires an active connection for.
139 + * Set this to the toolkit whose auth your tool needs (e.g. `'meta_ads'`, `'gmail'`).
140 + * Undefined means the tool doesn't need any Composio-managed authentication.
141 */
125 - readonly connectedToolkit?: string;
142 + readonly toolkit?: string;
143 readonly inputSchema: Record<string, unknown>;
144 /** @internal Original Zod schema — used for runtime input validation (defaults, coercions, transforms) */
145 readonly inputParams: z.ZodType;
@@ -136,13 +153,12 @@ export interface LocalToolDefinition {
153 name: string;
154 description: string;
155 input_schema: Record<string, unknown>;
139 - /** Maps connectedToolkit → toolkit in the backend payload */
156 toolkit?: string;
157 }
158
159 /** @internal Entry in the per-session local tools routing map. */
160 export type LocalToolsMapEntry = {
145 - handle: CustomToolHandle;
161 + handle: CustomTool;
162 prefixedSlug: string;
163 };
164
ts/packages/core/src/types/toolRouter.types.ts
+4 -2
@@ -3,7 +3,7 @@ import type { BaseComposioProvider } from '../provider/BaseProvider';
3 import { SessionMetaToolOptions } from './modifiers.types';
4 import { ConnectionRequest } from './connectionRequest.types';
5 import type { ToolRouterSessionFilesMount } from '../models/ToolRouterSessionFileMount';
6 -import type { CustomToolHandle } from './customTool.types';
6 +import type { CustomTool } from './customTool.types';
7
8 export const MCPServerTypeSchema = z.enum(['http', 'sse']);
9 export type MCPServerType = z.infer<typeof MCPServerTypeSchema>;
@@ -217,7 +217,7 @@ export const ToolRouterCreateSessionConfigSchema = z
217 .optional()
218 .describe('Experimental features configuration - not stable, may be modified or removed'),
219 customTools: z
220 - .array(z.custom<CustomToolHandle>())
220 + .array(z.custom<CustomTool>())
221 .optional()
222 .describe(
223 'Custom local tools to include in this session. Created via CustomTool() from @composio/core/experimental.'
@@ -440,6 +440,8 @@ export interface Session<
440 search: ToolRouterSessionSearchFn;
441 /** Execute a tool within the session */
442 execute: ToolRouterSessionExecuteFn;
443 + /** Get provider-wrapped local custom tools for MCP flows */
444 + localTools: () => Promise<ReturnType<TProvider['wrapTools']>>;
445 /** Experimental features (files, assistive prompt, etc.) */
446 experimental: SessionExperimental;
447 }
ts/packages/core/test/models/customTool.test.ts
+47 -47
@@ -1,14 +1,14 @@
1 import { describe, it, expect, vi, beforeEach } from 'vitest';
2 import { z } from 'zod/v3';
3 -import { CustomTool, buildLocalToolsMap, serializeLocalTools, LOCAL_TOOL_PREFIX } from '../../src/models/CustomTool';
3 +import { createCustomTool, buildLocalToolsMap, serializeLocalTools, LOCAL_TOOL_PREFIX } from '../../src/models/CustomTool';
4 import { SessionContextImpl } from '../../src/models/SessionContext';
5 -import type { CustomToolHandle, SessionContext } from '../../src/types/customTool.types';
5 +import type { CustomTool, SessionContext } from '../../src/types/customTool.types';
6
7 // ────────────────────────────────────────────────────────────────
8 -// CustomTool() factory
8 +// createCustomTool() factory
9 // ────────────────────────────────────────────────────────────────
10
11 -describe('CustomTool', () => {
11 +describe('createCustomTool', () => {
12 const baseOptions = {
13 slug: 'GET_USER_CONTEXT',
14 name: 'Get user context',
@@ -19,31 +19,31 @@ describe('CustomTool', () => {
19 execute: vi.fn().mockResolvedValue({ result: 'ok' }),
20 };
21
22 - it('should return a valid handle with correct fields', () => {
23 - const handle = CustomTool(baseOptions);
22 + it('should return a valid tool with correct fields', () => {
23 + const tool = createCustomTool(baseOptions);
24
25 - expect(handle.slug).toBe('GET_USER_CONTEXT');
26 - expect(handle.name).toBe('Get user context');
27 - expect(handle.description).toBe('Retrieve what we know about a user');
28 - expect(handle.connectedToolkit).toBeUndefined();
29 - expect(handle.execute).toBe(baseOptions.execute);
30 - expect(handle.inputSchema).toMatchObject({
25 + expect(tool.slug).toBe('GET_USER_CONTEXT');
26 + expect(tool.name).toBe('Get user context');
27 + expect(tool.description).toBe('Retrieve what we know about a user');
28 + expect(tool.toolkit).toBeUndefined();
29 + expect(tool.execute).toBe(baseOptions.execute);
30 + expect(tool.inputSchema).toMatchObject({
31 type: 'object',
32 properties: {
33 category: { type: 'string', description: 'The category' },
34 },
35 required: ['category'],
36 });
37 - expect(handle.inputParams).toBe(baseOptions.inputParams);
37 + expect(tool.inputParams).toBe(baseOptions.inputParams);
38 });
39
40 - it('should include connectedToolkit when provided', () => {
41 - const handle = CustomTool({ ...baseOptions, connectedToolkit: 'meta_ads' });
42 - expect(handle.connectedToolkit).toBe('meta_ads');
40 + it('should include toolkit when provided', () => {
41 + const tool = createCustomTool({ ...baseOptions, toolkit: 'meta_ads' });
42 + expect(tool.toolkit).toBe('meta_ads');
43 });
44
45 it('should convert Zod schema with optional fields correctly', () => {
46 - const handle = CustomTool({
46 + const tool = createCustomTool({
47 ...baseOptions,
48 inputParams: z.object({
49 required_field: z.string(),
@@ -51,7 +51,7 @@ describe('CustomTool', () => {
51 }),
52 });
53
54 - expect(handle.inputSchema).toMatchObject({
54 + expect(tool.inputSchema).toMatchObject({
55 type: 'object',
56 properties: {
57 required_field: { type: 'string' },
@@ -62,14 +62,14 @@ describe('CustomTool', () => {
62 });
63
64 it('should convert Zod schema with defaults correctly', () => {
65 - const handle = CustomTool({
65 + const tool = createCustomTool({
66 ...baseOptions,
67 inputParams: z.object({
68 category: z.string().default('all'),
69 }),
70 });
71
72 - expect(handle.inputSchema).toMatchObject({
72 + expect(tool.inputSchema).toMatchObject({
73 type: 'object',
74 properties: {
75 category: expect.objectContaining({ type: 'string' }),
@@ -79,39 +79,39 @@ describe('CustomTool', () => {
79
80 describe('validation', () => {
81 it('should throw if slug is missing', () => {
82 - expect(() => CustomTool({ ...baseOptions, slug: '' })).toThrow('slug is required');
82 + expect(() => createCustomTool({ ...baseOptions, slug: '' })).toThrow('slug is required');
83 });
84
85 it('should throw if slug starts with LOCAL_ prefix', () => {
86 - expect(() => CustomTool({ ...baseOptions, slug: 'LOCAL_MY_TOOL' })).toThrow(
87 - 'must not start with "LOCAL_"'
86 + expect(() => createCustomTool({ ...baseOptions, slug: 'LOCAL_MY_TOOL' })).toThrow(
87 + /LOCAL_/
88 );
89 });
90
91 it('should throw if slug starts with local_ prefix (case-insensitive)', () => {
92 - expect(() => CustomTool({ ...baseOptions, slug: 'local_something' })).toThrow(
93 - 'must not start with "LOCAL_"'
92 + expect(() => createCustomTool({ ...baseOptions, slug: 'local_something' })).toThrow(
93 + /LOCAL_/
94 );
95 });
96
97 it('should throw if name is missing', () => {
98 - expect(() => CustomTool({ ...baseOptions, name: '' })).toThrow('name is required');
98 + expect(() => createCustomTool({ ...baseOptions, name: '' })).toThrow('name is required');
99 });
100
101 it('should throw if description is missing', () => {
102 - expect(() => CustomTool({ ...baseOptions, description: '' })).toThrow(
102 + expect(() => createCustomTool({ ...baseOptions, description: '' })).toThrow(
103 'description is required'
104 );
105 });
106
107 it('should throw if inputParams is missing', () => {
108 - expect(() => CustomTool({ ...baseOptions, inputParams: null as any })).toThrow(
108 + expect(() => createCustomTool({ ...baseOptions, inputParams: null as any })).toThrow(
109 'inputParams is required'
110 );
111 });
112
113 it('should throw if execute is not a function', () => {
114 - expect(() => CustomTool({ ...baseOptions, execute: 'not-fn' as any })).toThrow(
114 + expect(() => createCustomTool({ ...baseOptions, execute: 'not-fn' as any })).toThrow(
115 'execute must be a function'
116 );
117 });
@@ -121,13 +121,13 @@ describe('CustomTool', () => {
121 it('should allow no-session execute (input only)', async () => {
122 const noSessionExecute = vi.fn().mockResolvedValue({ result: 42 });
123
124 - const handle = CustomTool({
124 + const tool = createCustomTool({
125 ...baseOptions,
126 execute: noSessionExecute,
127 });
128
129 // Call without session — JS ignores extra params
130 - const result = await handle.execute({ category: 'test' } as any);
130 + const result = await tool.execute({ category: 'test' } as any);
131 expect(result.result).toBe(42);
132 expect(noSessionExecute).toHaveBeenCalledWith({ category: 'test' });
133 });
@@ -135,7 +135,7 @@ describe('CustomTool', () => {
135 it('should allow session-based execute (input + session)', async () => {
136 const sessionExecute = vi.fn().mockResolvedValue({ userId: 'u1' });
137
138 - const handle = CustomTool({
138 + const tool = createCustomTool({
139 ...baseOptions,
140 execute: sessionExecute,
141 });
@@ -146,7 +146,7 @@ describe('CustomTool', () => {
146 proxyExecute: vi.fn(),
147 };
148
149 - const result = await handle.execute({ category: 'test' }, mockSession);
149 + const result = await tool.execute({ category: 'test' }, mockSession);
150 expect(result.userId).toBe('u1');
151 expect(sessionExecute).toHaveBeenCalledWith({ category: 'test' }, mockSession);
152 });
@@ -158,7 +158,7 @@ describe('CustomTool', () => {
158 // ────────────────────────────────────────────────────────────────
159
160 describe('buildLocalToolsMap', () => {
161 - const makeHandle = (slug: string): CustomToolHandle => ({
161 + const makeTool = (slug: string): CustomTool => ({
162 slug,
163 name: `Tool ${slug}`,
164 description: `Description for ${slug}`,
@@ -168,8 +168,8 @@ describe('buildLocalToolsMap', () => {
168 });
169
170 it('should create maps with both prefixed and original slug keys', () => {
171 - const handles = [makeHandle('MY_TOOL'), makeHandle('OTHER_TOOL')];
172 - const map = buildLocalToolsMap(handles);
171 + const tools = [makeTool('MY_TOOL'), makeTool('OTHER_TOOL')];
172 + const map = buildLocalToolsMap(tools);
173
174 expect(map.byPrefixed.size).toBe(2);
175 expect(map.byOriginal.size).toBe(2);
@@ -184,16 +184,16 @@ describe('buildLocalToolsMap', () => {
184 });
185
186 it('should handle case-insensitive slugs (uppercased internally)', () => {
187 - const handle = makeHandle('my_tool');
188 - const map = buildLocalToolsMap([handle]);
187 + const tool = makeTool('my_tool');
188 + const map = buildLocalToolsMap([tool]);
189
190 expect(map.byOriginal.has('MY_TOOL')).toBe(true);
191 expect(map.byPrefixed.has('LOCAL_MY_TOOL')).toBe(true);
192 });
193
194 it('should throw on duplicate slugs', () => {
195 - const handles = [makeHandle('DUPE'), makeHandle('DUPE')];
196 - expect(() => buildLocalToolsMap(handles)).toThrow('duplicate slug "DUPE"');
195 + const tools = [makeTool('DUPE'), makeTool('DUPE')];
196 + expect(() => buildLocalToolsMap(tools)).toThrow('duplicate slug "DUPE"');
197 });
198
199 });
@@ -203,18 +203,18 @@ describe('buildLocalToolsMap', () => {
203 // ────────────────────────────────────────────────────────────────
204
205 describe('serializeLocalTools', () => {
206 - it('should serialize handles into backend format', () => {
207 - const handle: CustomToolHandle = {
206 + it('should serialize tools into backend format', () => {
207 + const tool: CustomTool = {
208 slug: 'GET_DATA',
209 name: 'Get Data',
210 description: 'Gets some data',
211 - connectedToolkit: 'my_toolkit',
211 + toolkit: 'my_toolkit',
212 inputSchema: { type: 'object', properties: { id: { type: 'string' } } },
213 inputParams: z.object({ id: z.string() }),
214 execute: vi.fn(),
215 };
216
217 - const result = serializeLocalTools([handle]);
217 + const result = serializeLocalTools([tool]);
218
219 expect(result).toEqual([
220 {
@@ -227,8 +227,8 @@ describe('serializeLocalTools', () => {
227 ]);
228 });
229
230 - it('should omit toolkit when connectedToolkit not provided', () => {
231 - const handle: CustomToolHandle = {
230 + it('should omit toolkit when not provided', () => {
231 + const tool: CustomTool = {
232 slug: 'NO_TOOLKIT',
233 name: 'No Toolkit',
234 description: 'No toolkit tool',
@@ -237,7 +237,7 @@ describe('serializeLocalTools', () => {
237 execute: vi.fn(),
238 };
239
240 - const result = serializeLocalTools([handle]);
240 + const result = serializeLocalTools([tool]);
241 expect(result[0]).not.toHaveProperty('toolkit');
242 });
243 });
ts/packages/core/test/models/customToolRouting.test.ts
+16 -16
@@ -2,11 +2,11 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
2 import { z } from 'zod/v3';
3 import { ToolRouter } from '../../src/models/ToolRouter';
4 import { ToolRouterSession } from '../../src/models/ToolRouterSession';
5 -import { CustomTool, buildLocalToolsMap } from '../../src/models/CustomTool';
5 +import { createCustomTool, buildLocalToolsMap } from '../../src/models/CustomTool';
6 import { MockProvider } from '../utils/mocks/provider.mock';
7 import ComposioClient from '@composio/client';
8 import { Tools } from '../../src/models/Tools';
9 -import type { CustomToolHandle } from '../../src/types/customTool.types';
9 +import type { CustomTool } from '../../src/types/customTool.types';
10
11 // Mock telemetry
12 vi.mock('../../src/telemetry/Telemetry', () => ({
@@ -65,7 +65,7 @@ const createMockClient = () => ({
65 // Execute returns data directly (simplified API)
66 const localExecute = vi.fn().mockResolvedValue({ local_result: true });
67
68 -const customToolHandle = CustomTool({
68 +const customToolHandle = createCustomTool({
69 slug: 'GET_USER_CONTEXT',
70 name: 'Get user context',
71 description: 'Retrieve user preferences',
@@ -77,11 +77,11 @@ const sessionExecute = vi.fn().mockImplementation(async (input: any, session: an
77 userId: session.userId,
78 }));
79
80 -const sessionToolHandle = CustomTool({
80 +const sessionToolHandle = createCustomTool({
81 slug: 'GET_AD_ACCOUNTS',
82 name: 'Get ad accounts',
83 description: 'Get ad account IDs',
84 - connectedToolkit: 'meta_ads',
84 + toolkit: 'meta_ads',
85 inputParams: z.object({ fields: z.string() }),
86 execute: sessionExecute,
87 });
@@ -91,7 +91,7 @@ const sessionToolHandle = CustomTool({
91 const createSessionWithProvider = (
92 client: ReturnType<typeof createMockClient>,
93 provider: MockProvider,
94 - customTools: CustomToolHandle[]
94 + customTools: CustomTool[]
95 ) => {
96 return new ToolRouterSession(
97 client as unknown as ComposioClient,
@@ -146,7 +146,7 @@ describe('ToolRouter.create() with customTools', () => {
146 ]);
147 });
148
149 - it('should include toolkit in local_tools when connectedToolkit is present', async () => {
149 + it('should include toolkit in local_tools when toolkit is present', async () => {
150 await router.create('user_1', {
151 customTools: [sessionToolHandle],
152 });
@@ -182,7 +182,7 @@ describe('ToolRouterSession execution routing', () => {
182
183 const createSession = (
184 client: ReturnType<typeof createMockClient>,
185 - customTools: CustomToolHandle[] = []
185 + customTools: CustomTool[] = []
186 ) => {
187 const localToolsMap = customTools.length ? buildLocalToolsMap(customTools) : undefined;
188
@@ -282,7 +282,7 @@ describe('ToolRouterSession execution routing', () => {
282 return { inner_result: inner.data };
283 });
284
285 - const chainedTool = CustomTool({
285 + const chainedTool = createCustomTool({
286 slug: 'CHAINED_TOOL',
287 name: 'Chained',
288 description: 'Calls another tool',
@@ -303,7 +303,7 @@ describe('ToolRouterSession execution routing', () => {
303
304 describe('session.execute() — error handling', () => {
305 it('should catch errors thrown by execute function and return error response', async () => {
306 - const throwingTool = CustomTool({
306 + const throwingTool = createCustomTool({
307 slug: 'THROWING_TOOL',
308 name: 'Throwing',
309 description: 'Throws an error',
@@ -325,7 +325,7 @@ describe('ToolRouterSession execution routing', () => {
325 category: input.category,
326 }));
327
328 - const toolWithDefaults = CustomTool({
328 + const toolWithDefaults = createCustomTool({
329 slug: 'DEFAULTS_TOOL',
330 name: 'Defaults',
331 description: 'Tool with default values',
@@ -345,7 +345,7 @@ describe('ToolRouterSession execution routing', () => {
345 });
346
347 it('should return validation error for invalid input', async () => {
348 - const strictTool = CustomTool({
348 + const strictTool = createCustomTool({
349 slug: 'STRICT_TOOL',
350 name: 'Strict',
351 description: 'Tool with strict input',
@@ -361,7 +361,7 @@ describe('ToolRouterSession execution routing', () => {
361 });
362
363 it('should handle non-Error throws gracefully', async () => {
364 - const throwingTool = CustomTool({
364 + const throwingTool = createCustomTool({
365 slug: 'STRING_THROW',
366 name: 'String throw',
367 description: 'Throws a string',
@@ -479,7 +479,7 @@ describe('ToolRouterSession execution routing', () => {
479 /** Helper: set up provider + session + capture executeFn + get latest Tools mock */
480 const setupMultiExecute = async (
481 client: ReturnType<typeof createMockClient>,
482 - customTools: CustomToolHandle[]
482 + customTools: CustomTool[]
483 ) => {
484 const provider = new MockProvider();
485 captureExecuteFn(provider);
@@ -585,7 +585,7 @@ describe('ToolRouterSession execution routing', () => {
585 });
586
587 it('should still succeed when one local tool errors in a mixed batch', async () => {
588 - const throwingHandle = CustomTool({
588 + const throwingHandle = createCustomTool({
589 slug: 'MIXED_THROWER',
590 name: 'Throws in batch',
591 description: 'Throws',
@@ -670,7 +670,7 @@ describe('ToolRouterSession execution routing', () => {
670 // Track call timing to verify parallelism
671 const callOrder: string[] = [];
672
673 - const slowLocalHandle = CustomTool({
673 + const slowLocalHandle = createCustomTool({
674 slug: 'SLOW_LOCAL',
675 name: 'Slow local',
676 description: 'Slow',