1
+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';
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';
10
+
11
+// Mock telemetry
12
+vi.mock('../../src/telemetry/Telemetry', () => ({
13
+ telemetry: { instrument: vi.fn() },
14
+}));
15
+
16
+// Mock Tools class
17
+vi.mock('../../src/models/Tools', () => ({
18
+ Tools: vi.fn().mockImplementation(() => ({
19
+ getRawToolRouterMetaTools: vi.fn().mockResolvedValue([
20
+ { slug: 'COMPOSIO_SEARCH_TOOLS', name: 'Search Tools' },
21
+ { slug: 'COMPOSIO_MULTI_EXECUTE_TOOL', name: 'Multi Execute' },
22
+ ]),
23
+ wrapToolsForToolRouter: vi.fn().mockReturnValue('wrapped-tools'),
24
+ executeMetaTool: vi.fn().mockResolvedValue({
25
+ data: { remote: true },
26
+ error: null,
27
+ successful: true,
28
+ }),
29
+ })),
30
+}));
31
+
32
+// ── Fixtures ─────────────────────────────────────────────────────
33
+
34
+const createMockClient = () => ({
35
+ baseURL: 'https://api.composio.dev',
36
+ apiKey: 'test-api-key',
37
+ toolRouter: {
38
+ session: {
39
+ create: vi.fn().mockResolvedValue({
40
+ session_id: 'sess_123',
41
+ mcp: { type: 'http', url: 'https://mcp.example.com/sess_123' },
42
+ tool_router_tools: [],
43
+ }),
44
+ retrieve: vi.fn(),
45
+ link: vi.fn(),
46
+ toolkits: vi.fn(),
47
+ executeMeta: vi.fn(),
48
+ search: vi.fn(),
49
+ execute: vi.fn().mockResolvedValue({
50
+ data: { remote_result: true },
51
+ error: null,
52
+ log_id: 'log_remote',
53
+ }),
54
+ tools: vi.fn(),
55
+ },
56
+ },
57
+ tools: {
58
+ list: vi.fn(),
59
+ retrieve: vi.fn(),
60
+ execute: vi.fn(),
61
+ proxy: vi.fn(),
62
+ },
63
+});
64
+
65
+const localExecute = vi.fn().mockResolvedValue({
66
+ data: { local_result: true },
67
+ error: null,
68
+ successful: true,
69
+});
70
+
71
+const customToolHandle = CustomTool({
72
+ slug: 'GET_USER_CONTEXT',
73
+ name: 'Get user context',
74
+ description: 'Retrieve user preferences',
75
+ inputParams: z.object({ category: z.string() }),
76
+ execute: localExecute,
77
+});
78
+
79
+const sessionExecute = vi.fn().mockImplementation(async (input: any, session: any) => ({
80
+ data: { userId: session.userId },
81
+ error: null,
82
+ successful: true,
83
+}));
84
+
85
+const sessionToolHandle = CustomTool({
86
+ slug: 'GET_AD_ACCOUNTS',
87
+ name: 'Get ad accounts',
88
+ description: 'Get ad account IDs',
89
+ toolkit: 'meta_ads',
90
+ inputParams: z.object({ fields: z.string() }),
91
+ execute: sessionExecute,
92
+});
93
+
94
+// ────────────────────────────────────────────────────────────────
95
+// ToolRouter.create() with customTools
96
+// ────────────────────────────────────────────────────────────────
97
+
98
+describe('ToolRouter.create() with customTools', () => {
99
+ let mockClient: ReturnType<typeof createMockClient>;
100
+ let router: ToolRouter<unknown, unknown, MockProvider>;
101
+
102
+ beforeEach(() => {
103
+ vi.clearAllMocks();
104
+ mockClient = createMockClient();
105
+ router = new ToolRouter(mockClient as unknown as ComposioClient, {
106
+ apiKey: 'test-key',
107
+ provider: new MockProvider(),
108
+ });
109
+ });
110
+
111
+ it('should send local_tools in the create payload', async () => {
112
+ await router.create('user_1', {
113
+ toolkits: ['gmail'],
114
+ customTools: [customToolHandle],
115
+ });
116
+
117
+ const payload = mockClient.toolRouter.session.create.mock.calls[0][0];
118
+ expect(payload.local_tools).toEqual([
119
+ {
120
+ slug: 'GET_USER_CONTEXT',
121
+ name: 'Get user context',
122
+ description: 'Retrieve user preferences',
123
+ input_schema: customToolHandle.inputSchema,
124
+ },
125
+ ]);
126
+ });
127
+
128
+ it('should include toolkit in local_tools when present', async () => {
129
+ await router.create('user_1', {
130
+ customTools: [sessionToolHandle],
131
+ });
132
+
133
+ const payload = mockClient.toolRouter.session.create.mock.calls[0][0];
134
+ expect(payload.local_tools[0].toolkit).toBe('meta_ads');
135
+ });
136
+
137
+ it('should not send local_tools when customTools is omitted', async () => {
138
+ await router.create('user_1', { toolkits: ['gmail'] });
139
+
140
+ const payload = mockClient.toolRouter.session.create.mock.calls[0][0];
141
+ expect(payload.local_tools).toBeUndefined();
142
+ });
143
+
144
+ it('should not send local_tools when customTools is empty', async () => {
145
+ await router.create('user_1', { customTools: [] });
146
+
147
+ const payload = mockClient.toolRouter.session.create.mock.calls[0][0];
148
+ expect(payload.local_tools).toBeUndefined();
149
+ });
150
+
151
+ it('should return a session with the correct sessionId', async () => {
152
+ const session = await router.create('user_1', {
153
+ customTools: [customToolHandle],
154
+ });
155
+
156
+ expect(session.sessionId).toBe('sess_123');
157
+ });
158
+});
159
+
160
+// ────────────────────────────────────────────────────────────────
161
+// ToolRouterSession — execution routing
162
+// ────────────────────────────────────────────────────────────────
163
+
164
+describe('ToolRouterSession execution routing', () => {
165
+ let mockClient: ReturnType<typeof createMockClient>;
166
+
167
+ const createSession = (
168
+ client: ReturnType<typeof createMockClient>,
169
+ customTools: CustomToolHandle[] = []
170
+ ) => {
171
+ const localToolsMap = customTools.length ? buildLocalToolsMap(customTools) : undefined;
172
+
173
+ return new ToolRouterSession(
174
+ client as unknown as ComposioClient,
175
+ { apiKey: 'key', provider: new MockProvider() },
176
+ 'sess_123',
177
+ { type: 'http' as const, url: 'https://mcp.example.com/sess_123' },
178
+ undefined,
179
+ localToolsMap,
180
+ 'user_1'
181
+ );
182
+ };
183
+
184
+ beforeEach(() => {
185
+ vi.clearAllMocks();
186
+ mockClient = createMockClient();
187
+ localExecute.mockClear();
188
+ sessionExecute.mockClear();
189
+ });
190
+
191
+ describe('session.execute() routing', () => {
192
+ it('should route local tool by original slug to in-process execution', async () => {
193
+ const session = createSession(mockClient, [customToolHandle]);
194
+
195
+ const result = await session.execute('GET_USER_CONTEXT', { category: 'prefs' });
196
+
197
+ expect(result.data).toEqual({ local_result: true });
198
+ expect(result.logId).toBe('local');
199
+ expect(localExecute).toHaveBeenCalledWith(
200
+ { category: 'prefs' },
201
+ expect.objectContaining({ userId: 'user_1', sessionId: 'sess_123' })
202
+ );
203
+ // Should NOT call remote
204
+ expect(mockClient.toolRouter.session.execute).not.toHaveBeenCalled();
205
+ });
206
+
207
+ it('should route local tool by prefixed slug to in-process execution', async () => {
208
+ const session = createSession(mockClient, [customToolHandle]);
209
+
210
+ const result = await session.execute('LOCAL_GET_USER_CONTEXT', { category: 'all' });
211
+
212
+ expect(result.data).toEqual({ local_result: true });
213
+ expect(localExecute).toHaveBeenCalled();
214
+ expect(mockClient.toolRouter.session.execute).not.toHaveBeenCalled();
215
+ });
216
+
217
+ it('should be case-insensitive for local tool lookup', async () => {
218
+ const session = createSession(mockClient, [customToolHandle]);
219
+
220
+ const result = await session.execute('get_user_context', { category: 'test' });
221
+
222
+ expect(result.data).toEqual({ local_result: true });
223
+ });
224
+
225
+ it('should route non-local tool to remote execution', async () => {
226
+ const session = createSession(mockClient, [customToolHandle]);
227
+
228
+ await session.execute('GMAIL_SEND_EMAIL', { to: 'test@test.com' });
229
+
230
+ expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith('sess_123', {
231
+ tool_slug: 'GMAIL_SEND_EMAIL',
232
+ arguments: { to: 'test@test.com' },
233
+ });
234
+ expect(localExecute).not.toHaveBeenCalled();
235
+ });
236
+
237
+ it('should route all tools to remote when no customTools are bound', async () => {
238
+ const session = createSession(mockClient);
239
+
240
+ await session.execute('GET_USER_CONTEXT', { category: 'test' });
241
+
242
+ expect(mockClient.toolRouter.session.execute).toHaveBeenCalled();
243
+ expect(localExecute).not.toHaveBeenCalled();
244
+ });
245
+ });
246
+
247
+ describe('session.execute() — SessionContext injection', () => {
248
+ it('should inject SessionContext with correct userId and sessionId', async () => {
249
+ const session = createSession(mockClient, [sessionToolHandle]);
250
+
251
+ await session.execute('GET_AD_ACCOUNTS', { fields: 'id' });
252
+
253
+ expect(sessionExecute).toHaveBeenCalledWith(
254
+ { fields: 'id' },
255
+ expect.objectContaining({
256
+ userId: 'user_1',
257
+ sessionId: 'sess_123',
258
+ })
259
+ );
260
+ });
261
+
262
+ it('should provide a working execute() on SessionContext', async () => {
263
+ // Tool that calls another tool via session.execute()
264
+ const chainedExecute = vi.fn().mockImplementation(async (input: any, session: any) => {
265
+ const inner = await session.execute('GMAIL_SEND_EMAIL', { to: input.to });
266
+ return { data: { inner_result: inner.data }, error: null, successful: true };
267
+ });
268
+
269
+ const chainedTool = CustomTool({
270
+ slug: 'CHAINED_TOOL',
271
+ name: 'Chained',
272
+ description: 'Calls another tool',
273
+ inputParams: z.object({ to: z.string() }),
274
+ execute: chainedExecute,
275
+ });
276
+
277
+ const session = createSession(mockClient, [chainedTool]);
278
+ await session.execute('CHAINED_TOOL', { to: 'test@test.com' });
279
+
280
+ // The chained tool should have called session.execute, which calls the API
281
+ expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith('sess_123', {
282
+ tool_slug: 'GMAIL_SEND_EMAIL',
283
+ arguments: { to: 'test@test.com' },
284
+ });
285
+ });
286
+ });
287
+
288
+ describe('session.execute() — error handling', () => {
289
+ it('should catch errors thrown by execute function and return error response', async () => {
290
+ const throwingTool = CustomTool({
291
+ slug: 'THROWING_TOOL',
292
+ name: 'Throwing',
293
+ description: 'Throws an error',
294
+ inputParams: z.object({}),
295
+ execute: async () => {
296
+ throw new Error('boom');
297
+ },
298
+ });
299
+
300
+ const session = createSession(mockClient, [throwingTool]);
301
+ const result = await session.execute('THROWING_TOOL', {});
302
+
303
+ expect(result.error).toBe('boom');
304
+ expect(result.data).toEqual({});
305
+ });
306
+
307
+ it('should handle non-Error throws gracefully', async () => {
308
+ const throwingTool = CustomTool({
309
+ slug: 'STRING_THROW',
310
+ name: 'String throw',
311
+ description: 'Throws a string',
312
+ inputParams: z.object({}),
313
+ execute: async () => {
314
+ throw 'string error';
315
+ },
316
+ });
317
+
318
+ const session = createSession(mockClient, [throwingTool]);
319
+ const result = await session.execute('STRING_THROW', {});
320
+
321
+ expect(result.error).toBe('string error');
322
+ });
323
+ });
324
+
325
+ describe('session.tools() — COMPOSIO_MULTI_EXECUTE_TOOL routing', () => {
326
+ it('should route local tools via COMPOSIO_MULTI_EXECUTE_TOOL to in-process execution', async () => {
327
+ const provider = new MockProvider();
328
+ // Mock wrapTools to capture the execute function and call it
329
+ provider.wrapTools.mockImplementation((tools: any, executeFn: any) => {
330
+ // Store executeFn so we can call it
331
+ (provider as any)._capturedExecuteFn = executeFn;
332
+ return 'wrapped-tools-with-routing';
333
+ });
334
+
335
+ const session = new ToolRouterSession(
336
+ mockClient as unknown as ComposioClient,
337
+ { apiKey: 'key', provider },
338
+ 'sess_123',
339
+ { type: 'http' as const, url: 'https://mcp.example.com/sess_123' },
340
+ undefined,
341
+ buildLocalToolsMap([customToolHandle]),
342
+ 'user_1'
343
+ );
344
+
345
+ await session.tools();
346
+
347
+ // Now simulate the LLM calling COMPOSIO_MULTI_EXECUTE_TOOL with a local tool
348
+ const executeFn = (provider as any)._capturedExecuteFn;
349
+ expect(executeFn).toBeDefined();
350
+
351
+ const result = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', {
352
+ tool_slug: 'LOCAL_GET_USER_CONTEXT',
353
+ arguments: { category: 'test' },
354
+ });
355
+
356
+ expect(result.data).toEqual({ local_result: true });
357
+ expect(localExecute).toHaveBeenCalledWith(
358
+ { category: 'test' },
359
+ expect.objectContaining({ userId: 'user_1', sessionId: 'sess_123' })
360
+ );
361
+ });
362
+
363
+ it('should route remote tools via COMPOSIO_MULTI_EXECUTE_TOOL to backend', async () => {
364
+ const provider = new MockProvider();
365
+ provider.wrapTools.mockImplementation((tools: any, executeFn: any) => {
366
+ (provider as any)._capturedExecuteFn = executeFn;
367
+ return 'wrapped';
368
+ });
369
+
370
+ const session = new ToolRouterSession(
371
+ mockClient as unknown as ComposioClient,
372
+ { apiKey: 'key', provider },
373
+ 'sess_123',
374
+ { type: 'http' as const, url: 'https://mcp.example.com/sess_123' },
375
+ undefined,
376
+ buildLocalToolsMap([customToolHandle]),
377
+ 'user_1'
378
+ );
379
+
380
+ await session.tools();
381
+
382
+ const executeFn = (provider as any)._capturedExecuteFn;
383
+ const result = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', {
384
+ tool_slug: 'GMAIL_SEND_EMAIL',
385
+ arguments: { to: 'test@test.com' },
386
+ });
387
+
388
+ // Should have gone to remote via executeMetaTool
389
+ expect(result.data).toEqual({ remote: true });
390
+ expect(localExecute).not.toHaveBeenCalled();
391
+ });
392
+
393
+ it('should route non-MULTI_EXECUTE meta tools to backend', async () => {
394
+ const provider = new MockProvider();
395
+ provider.wrapTools.mockImplementation((tools: any, executeFn: any) => {
396
+ (provider as any)._capturedExecuteFn = executeFn;
397
+ return 'wrapped';
398
+ });
399
+
400
+ const session = new ToolRouterSession(
401
+ mockClient as unknown as ComposioClient,
402
+ { apiKey: 'key', provider },
403
+ 'sess_123',
404
+ { type: 'http' as const, url: 'https://mcp.example.com/sess_123' },
405
+ undefined,
406
+ buildLocalToolsMap([customToolHandle]),
407
+ 'user_1'
408
+ );
409
+
410
+ await session.tools();
411
+
412
+ const executeFn = (provider as any)._capturedExecuteFn;
413
+ const result = await executeFn('COMPOSIO_SEARCH_TOOLS', {
414
+ queries: [{ use_case: 'send email' }],
415
+ });
416
+
417
+ // COMPOSIO_SEARCH_TOOLS always goes remote
418
+ expect(result.data).toEqual({ remote: true });
419
+ });
420
+
421
+ it('should use standard wrapToolsForToolRouter when no local tools', async () => {
422
+ const session = new ToolRouterSession(
423
+ mockClient as unknown as ComposioClient,
424
+ { apiKey: 'key', provider: new MockProvider() },
425
+ 'sess_123',
426
+ { type: 'http' as const, url: 'https://mcp.example.com/sess_123' }
427
+ // No localToolsMap, no userId
428
+ );
429
+
430
+ const result = await session.tools();
431
+
432
+ // Should use the standard path
433
+ expect(result).toBe('wrapped-tools');
434
+ });
435
+ });
436
+
437
+ describe('multiple custom tools', () => {
438
+ it('should route each tool to its correct execute function', async () => {
439
+ const session = createSession(mockClient, [customToolHandle, sessionToolHandle]);
440
+
441
+ // First tool
442
+ await session.execute('GET_USER_CONTEXT', { category: 'prefs' });
443
+ expect(localExecute).toHaveBeenCalled();
444
+ expect(sessionExecute).not.toHaveBeenCalled();
445
+
446
+ localExecute.mockClear();
447
+
448
+ // Second tool
449
+ await session.execute('GET_AD_ACCOUNTS', { fields: 'id' });
450
+ expect(sessionExecute).toHaveBeenCalled();
451
+ expect(localExecute).not.toHaveBeenCalled();
452
+ });
453
+ });
454
+});