65
// Execute returns data directly (simplified API)
66
const localExecute = vi.fn().mockResolvedValue({ local_result: true });
67
68
-const customToolHandle = createCustomTool({
69
- slug: 'GET_USER_CONTEXT',
68
+const customToolHandle = createCustomTool('GET_USER_CONTEXT', {
69
name: 'Get user context',
70
description: 'Retrieve user preferences',
71
inputParams: z.object({ category: z.string() }),
76
userId: session.userId,
77
}));
78
80
-const sessionToolHandle = createCustomTool({
81
- slug: 'GET_AD_ACCOUNTS',
79
+const sessionToolHandle = createCustomTool('GET_AD_ACCOUNTS', {
80
name: 'Get ad accounts',
81
description: 'Get ad account IDs',
84
- toolkit: 'meta_ads',
82
+ extendsToolkit: 'meta_ads',
83
inputParams: z.object({ fields: z.string() }),
84
execute: sessionExecute,
85
});
111
};
112
113
// ────────────────────────────────────────────────────────────────
116
-// ToolRouter.create() with customTools
114
+// ToolRouter.create() with customTools under experimental
115
// ────────────────────────────────────────────────────────────────
116
117
describe('ToolRouter.create() with customTools', () => {
127
});
128
});
129
132
- it('should send custom_tools in the create payload', async () => {
130
+ it('should send custom_tools under experimental in the create payload', async () => {
131
await router.create('user_1', {
132
toolkits: ['gmail'],
135
- customTools: [customToolHandle],
133
+ experimental: {
134
+ customTools: [customToolHandle],
135
+ },
136
});
137
138
const payload = mockClient.toolRouter.session.create.mock.calls[0][0];
139
- expect(payload.custom_tools).toEqual([
139
+ expect(payload.experimental.custom_tools).toEqual([
140
{
141
slug: 'GET_USER_CONTEXT',
142
name: 'Get user context',
146
]);
147
});
148
149
- it('should include toolkit in custom_tools when toolkit is present', async () => {
149
+ it('should include extendsToolkit as extends_toolkit in serialized custom_tools', async () => {
150
await router.create('user_1', {
151
- customTools: [sessionToolHandle],
151
+ experimental: {
152
+ customTools: [sessionToolHandle],
153
+ },
154
});
155
156
const payload = mockClient.toolRouter.session.create.mock.calls[0][0];
155
- expect(payload.custom_tools[0].toolkit).toBe('meta_ads');
157
+ expect(payload.experimental.custom_tools[0].extends_toolkit).toBe('meta_ads');
158
});
159
158
- it('should not send custom_tools when customTools is omitted or empty', async () => {
160
+ it('should not send experimental.custom_tools when customTools is omitted or empty', async () => {
161
await router.create('user_1', { toolkits: ['gmail'] });
160
- expect(mockClient.toolRouter.session.create.mock.calls[0][0].custom_tools).toBeUndefined();
162
+ const payload1 = mockClient.toolRouter.session.create.mock.calls[0][0];
163
+ expect(payload1.experimental).toBeUndefined();
164
165
vi.clearAllMocks();
163
- await router.create('user_1', { customTools: [] });
164
- expect(mockClient.toolRouter.session.create.mock.calls[0][0].custom_tools).toBeUndefined();
166
+ await router.create('user_1', { experimental: { customTools: [] } });
167
+ const payload2 = mockClient.toolRouter.session.create.mock.calls[0][0];
168
+ expect(payload2.experimental).toBeUndefined();
169
});
170
171
it('should return a session with the correct sessionId', async () => {
172
const session = await router.create('user_1', {
169
- customTools: [customToolHandle],
173
+ experimental: {
174
+ customTools: [customToolHandle],
175
+ },
176
});
177
178
expect(session.sessionId).toBe('sess_123');
216
217
const result = await session.execute('GET_USER_CONTEXT', { category: 'prefs' });
218
213
- // User returns data directly, SDK wraps it
219
expect(result.data).toEqual({ local_result: true });
220
expect(result.logId).toBe('local');
221
expect(localExecute).toHaveBeenCalledWith(
222
{ category: 'prefs' },
223
expect.objectContaining({ userId: 'user_1' })
224
);
220
- // Should NOT call remote
225
expect(mockClient.toolRouter.session.execute).not.toHaveBeenCalled();
226
});
227
235
expect(mockClient.toolRouter.session.execute).not.toHaveBeenCalled();
236
});
237
238
+ it('should route extendsToolkit tool by prefixed slug', async () => {
239
+ const session = createSession(mockClient, [sessionToolHandle]);
240
+
241
+ // sessionToolHandle has extendsToolkit: 'meta_ads' → LOCAL_META_ADS_GET_AD_ACCOUNTS
242
+ const result = await session.execute('LOCAL_META_ADS_GET_AD_ACCOUNTS', { fields: 'id' });
243
+
244
+ expect(result.data).toEqual({ userId: 'user_1' });
245
+ expect(sessionExecute).toHaveBeenCalled();
246
+ expect(mockClient.toolRouter.session.execute).not.toHaveBeenCalled();
247
+ });
248
+
249
it('should be case-insensitive for local tool lookup', async () => {
250
const session = createSession(mockClient, [customToolHandle]);
251
291
});
292
293
it('should provide a working execute() on SessionContext for remote tools', async () => {
279
- // Tool that calls a remote tool via session.execute()
294
const chainedExecute = vi.fn().mockImplementation(async (input: any, session: any) => {
295
const inner = await session.execute('GMAIL_SEND_EMAIL', { to: input.to });
296
return { inner_result: inner.data };
297
});
298
285
- const chainedTool = createCustomTool({
286
- slug: 'CHAINED_TOOL',
299
+ const chainedTool = createCustomTool('CHAINED_TOOL', {
300
name: 'Chained',
301
description: 'Calls another tool',
302
inputParams: z.object({ to: z.string() }),
306
const session = createSession(mockClient, [chainedTool]);
307
await session.execute('CHAINED_TOOL', { to: 'test@test.com' });
308
296
- // The chained tool should have called session.execute, which calls the API
309
expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith('sess_123', {
310
tool_slug: 'GMAIL_SEND_EMAIL',
311
arguments: { to: 'test@test.com' },
313
});
314
315
it('should route sibling local tools in-process without hitting the API', async () => {
304
- // Tool B — a sibling local tool
316
const siblingExecute = vi.fn().mockResolvedValue({ siblingData: 'from-B' });
306
- const toolB = createCustomTool({
307
- slug: 'TOOL_B',
317
+ const toolB = createCustomTool('TOOL_B', {
318
name: 'Tool B',
319
description: 'Sibling tool',
320
inputParams: z.object({ key: z.string() }),
321
execute: siblingExecute,
322
});
323
314
- // Tool A — calls Tool B via session.execute()
324
const toolAExecute = vi.fn().mockImplementation(async (input: any, session: any) => {
325
const inner = await session.execute('TOOL_B', { key: input.value });
326
return { fromA: true, fromB: inner.data };
327
});
319
- const toolA = createCustomTool({
320
- slug: 'TOOL_A',
328
+ const toolA = createCustomTool('TOOL_A', {
329
name: 'Tool A',
330
description: 'Calls sibling tool B',
331
inputParams: z.object({ value: z.string() }),
335
const session = createSession(mockClient, [toolA, toolB]);
336
const result = await session.execute('TOOL_A', { value: 'hello' });
337
330
- // Tool B should have been called in-process
338
expect(siblingExecute).toHaveBeenCalledWith(
339
{ key: 'hello' },
340
expect.objectContaining({ userId: 'user_1' })
341
);
335
- // Result should contain data from both tools
342
expect(result.data).toEqual({
343
fromA: true,
344
fromB: { siblingData: 'from-B' },
345
});
340
- // Should NOT have called the remote API for Tool B
346
expect(mockClient.toolRouter.session.execute).not.toHaveBeenCalled();
347
});
348
});
349
350
describe('session.execute() — error handling', () => {
351
it('should catch errors thrown by execute function and return error response', async () => {
347
- const throwingTool = createCustomTool({
348
- slug: 'THROWING_TOOL',
352
+ const throwingTool = createCustomTool('THROWING_TOOL', {
353
name: 'Throwing',
354
description: 'Throws an error',
355
inputParams: z.object({}),
370
category: input.category,
371
}));
372
369
- const toolWithDefaults = createCustomTool({
370
- slug: 'DEFAULTS_TOOL',
373
+ const toolWithDefaults = createCustomTool('DEFAULTS_TOOL', {
374
name: 'Defaults',
375
description: 'Tool with default values',
376
inputParams: z.object({ category: z.string().default('all') }),
380
const session = createSession(mockClient, [toolWithDefaults]);
381
const result = await session.execute('DEFAULTS_TOOL', {});
382
380
- // Zod default should be applied
383
expect(defaultExecute).toHaveBeenCalledWith(
384
{ category: 'all' },
385
expect.anything()
388
});
389
390
it('should return validation error for invalid input', async () => {
389
- const strictTool = createCustomTool({
390
- slug: 'STRICT_TOOL',
391
+ const strictTool = createCustomTool('STRICT_TOOL', {
392
name: 'Strict',
393
description: 'Tool with strict input',
394
inputParams: z.object({ count: z.number() }),
403
});
404
405
it('should handle non-Error throws gracefully', async () => {
405
- const throwingTool = createCustomTool({
406
- slug: 'STRING_THROW',
406
+ const throwingTool = createCustomTool('STRING_THROW', {
407
name: 'String throw',
408
description: 'Throws a string',
409
inputParams: z.object({}),
479
sync_response_to_workbench: false,
480
});
481
482
- // All remote — goes to executeMetaTool
482
expect(result.data).toEqual({ remote: true });
483
expect(localExecute).not.toHaveBeenCalled();
484
});
495
queries: [{ use_case: 'send email' }],
496
});
497
499
- // COMPOSIO_SEARCH_TOOLS always goes remote
498
expect(result.data).toEqual({ remote: true });
499
});
500
504
{ apiKey: 'key', provider: new MockProvider() },
505
'sess_123',
506
{ type: 'http' as const, url: 'https://mcp.example.com/sess_123' }
509
- // No customToolsMap, no userId
507
);
508
509
const result = await session.tools();
510
514
- // Should use the standard path
511
expect(result).toBe('wrapped-tools');
512
});
513
});
514
515
describe('COMPOSIO_MULTI_EXECUTE_TOOL — detailed split/merge behavior', () => {
520
- /** Helper: set up provider + session + capture executeFn + get latest Tools mock */
516
const setupMultiExecute = async (
517
client: ReturnType<typeof createMockClient>,
518
customTools: CustomTool[]
528
return { executeFn, toolsInstance, provider, session };
529
};
530
536
- /** Build a backend-shaped results[] response */
531
const backendResponse = (
532
results: Array<{ tool_slug: string; data: any; error?: string }>,
533
) => {
554
};
555
};
556
563
- /** Find a local tool result in the results[] array by slug */
557
const findResult = (results: any[], slug: string) =>
558
results.find((r: any) => r.tool_slug === slug);
559
572
sync_response_to_workbench: false,
573
});
574
582
- // Results is an array with both remote and local entries
575
const { results } = result.data;
576
expect(results).toHaveLength(2);
577
586
- // Remote result comes first (from backend), local appended after
578
const remote = findResult(results, 'GMAIL_SEND_EMAIL');
579
const local = findResult(results, 'LOCAL_GET_USER_CONTEXT');
580
expect(remote.response.data).toEqual({ sent: true });
588
const result = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', {
589
tools: [
590
{ tool_slug: 'LOCAL_GET_USER_CONTEXT', arguments: { category: 'batch' } },
600
- { tool_slug: 'LOCAL_GET_AD_ACCOUNTS', arguments: { fields: 'id,name' } },
591
+ { tool_slug: 'LOCAL_META_ADS_GET_AD_ACCOUNTS', arguments: { fields: 'id,name' } },
592
],
593
sync_response_to_workbench: false,
594
});
605
const { results } = result.data;
606
expect(results).toHaveLength(2);
607
expect(findResult(results, 'LOCAL_GET_USER_CONTEXT')).toBeDefined();
617
- expect(findResult(results, 'LOCAL_GET_AD_ACCOUNTS')).toBeDefined();
608
+ expect(findResult(results, 'LOCAL_META_ADS_GET_AD_ACCOUNTS')).toBeDefined();
609
});
610
611
it('should handle mixed batch with multiple locals + multiple remotes', async () => {
625
tools: [
626
{ tool_slug: 'LOCAL_GET_USER_CONTEXT', arguments: { category: 'x' } },
627
{ tool_slug: 'GMAIL_SEND_EMAIL', arguments: { to: 'a@b.com' } },
637
- { tool_slug: 'LOCAL_GET_AD_ACCOUNTS', arguments: { fields: 'id' } },
628
+ { tool_slug: 'LOCAL_META_ADS_GET_AD_ACCOUNTS', arguments: { fields: 'id' } },
629
{ tool_slug: 'SLACK_POST_MESSAGE', arguments: { channel: '#dev' } },
630
],
631
sync_response_to_workbench: false,
632
});
633
643
- // All 4 tools should appear in results array
634
const { results } = result.data;
635
expect(results).toHaveLength(4);
636
expect(findResult(results, 'LOCAL_GET_USER_CONTEXT')).toBeDefined();
647
- expect(findResult(results, 'LOCAL_GET_AD_ACCOUNTS')).toBeDefined();
637
+ expect(findResult(results, 'LOCAL_META_ADS_GET_AD_ACCOUNTS')).toBeDefined();
638
expect(findResult(results, 'GMAIL_SEND_EMAIL')).toBeDefined();
639
expect(findResult(results, 'SLACK_POST_MESSAGE')).toBeDefined();
640
651
- // Backend only got the 2 remote tools
641
const backendTools = toolsInstance.executeMetaTool.mock.calls[0][1].arguments.tools;
642
expect(backendTools).toHaveLength(2);
643
expect(backendTools.map((t: any) => t.tool_slug)).toEqual([
645
'SLACK_POST_MESSAGE',
646
]);
647
659
- // Both local execute fns were called
648
expect(localExecute).toHaveBeenCalled();
649
expect(sessionExecute).toHaveBeenCalled();
650
expect(result.successful).toBe(true);
651
});
652
653
it('should surface errors from both local and remote tools', async () => {
666
- const throwingHandle = createCustomTool({
667
- slug: 'MIXED_THROWER',
654
+ const throwingHandle = createCustomTool('MIXED_THROWER', {
655
name: 'Throws in batch',
656
description: 'Throws',
657
inputParams: z.object({}),
663
[customToolHandle, throwingHandle]
664
);
665
679
- // Remote also returns an error for one tool
666
toolsInstance.executeMetaTool.mockResolvedValueOnce(
667
backendResponse([
668
{ tool_slug: 'GMAIL_SEND_EMAIL', data: { sent: true } },
683
const { results } = result.data;
684
expect(results).toHaveLength(4);
685
700
- // Local success
686
const localOk = findResult(results, 'LOCAL_GET_USER_CONTEXT');
687
expect(localOk.response.successful).toBe(true);
688
704
- // Local error — data is empty, error is surfaced
689
const localErr = findResult(results, 'LOCAL_MIXED_THROWER');
690
expect(localErr.response.successful).toBe(false);
691
expect(localErr.response.error).toBe('batch-boom');
692
expect(localErr.error).toBe('batch-boom');
693
710
- // Remote error is also preserved (not dropped!)
694
const remoteErr = findResult(results, 'SLACK_POST_MESSAGE');
695
expect(remoteErr.response.error).toBe('auth failed');
696
714
- // Top-level error reflects total failure count
697
expect(result.successful).toBe(false);
698
expect(result.error).toContain('2 out of 4');
699
});
706
sync_response_to_workbench: false,
707
});
708
727
- // Empty array → fallback to backend with full original input
709
expect(toolsInstance.executeMetaTool).toHaveBeenCalledWith(
710
'COMPOSIO_MULTI_EXECUTE_TOOL',
711
expect.objectContaining({
723
backendResponse([])
724
);
725
745
- // Malformed: string instead of object — should not crash
726
const result = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', {
727
tools: ['not-an-object', null, { tool_slug: 'LOCAL_GET_USER_CONTEXT', arguments: { category: 'ok' } }],
728
sync_response_to_workbench: false,
729
});
730
751
- // The valid local tool should still execute
731
expect(localExecute).toHaveBeenCalledWith(
732
{ category: 'ok' },
733
expect.objectContaining({ userId: 'user_1' })
737
});
738
739
it('should execute local and remote in parallel (not sequentially)', async () => {
761
- // Track call timing to verify parallelism
740
const callOrder: string[] = [];
741
764
- const slowLocalHandle = createCustomTool({
765
- slug: 'SLOW_LOCAL',
742
+ const slowLocalHandle = createCustomTool('SLOW_LOCAL', {
743
name: 'Slow local',
744
description: 'Slow',
745
inputParams: z.object({}),
775
sync_response_to_workbench: false,
776
});
777
801
- // Both should start before either ends (parallel execution)
778
const localStartIdx = callOrder.indexOf('local-start');
779
const remoteStartIdx = callOrder.indexOf('remote-start');
780
const localEndIdx = callOrder.indexOf('local-end');
781
const remoteEndIdx = callOrder.indexOf('remote-end');
782
807
- // Both started
783
expect(localStartIdx).toBeGreaterThanOrEqual(0);
784
expect(remoteStartIdx).toBeGreaterThanOrEqual(0);
810
- // Both started before either finished
785
expect(Math.max(localStartIdx, remoteStartIdx)).toBeLessThan(
786
Math.min(localEndIdx, remoteEndIdx)
787
);
792
it('should route each tool to its correct execute function', async () => {
793
const session = createSession(mockClient, [customToolHandle, sessionToolHandle]);
794
821
- // First tool
795
await session.execute('GET_USER_CONTEXT', { category: 'prefs' });
796
expect(localExecute).toHaveBeenCalled();
797
expect(sessionExecute).not.toHaveBeenCalled();
798
799
localExecute.mockClear();
800
828
- // Second tool
801
await session.execute('GET_AD_ACCOUNTS', { fields: 'id' });
802
expect(sessionExecute).toHaveBeenCalled();
803
expect(localExecute).not.toHaveBeenCalled();
843
const { results } = result.data;
844
expect(results).toHaveLength(3);
845
874
- // Each tool has its own entry
846
const local = results.find((r: any) => r.tool_slug === 'LOCAL_GET_USER_CONTEXT');
847
const gmail = results.find((r: any) => r.tool_slug === 'GMAIL_SEND_EMAIL');
848
const slack = results.find((r: any) => r.tool_slug === 'SLACK_POST_MESSAGE');
859
860
const session = new ToolRouterSession(
861
mockClient as unknown as ComposioClient,
891
- { apiKey: 'key' } as any, // no provider
862
+ { apiKey: 'key' } as any,
863
'sess_123',
864
{ type: 'http' as const, url: 'https://mcp.example.com/sess_123' },
865
undefined,
873
});
874
});
875
905
- describe('localTools() method', () => {
906
- it('should return wrapped tools with COMPOSIO_EXECUTE_LOCAL_TOOL slug', async () => {
907
- const provider = new MockProvider();
908
- captureExecuteFn(provider);
909
- const session = createSessionWithProvider(mockClient, provider, [customToolHandle]);
910
-
911
- const result = await session.localTools();
912
-
913
- expect(result).toBe('wrapped-tools-with-routing');
914
- expect(provider.wrapTools).toHaveBeenCalled();
915
-
916
- const tools = (provider as any)._capturedTools;
917
- expect(tools).toHaveLength(1);
918
- expect(tools[0].slug).toBe('COMPOSIO_EXECUTE_LOCAL_TOOL');
919
- });
920
-
921
- it('should route to local tool correctly when executing via localTools()', async () => {
922
- const provider = new MockProvider();
923
- captureExecuteFn(provider);
924
- const session = createSessionWithProvider(mockClient, provider, [customToolHandle]);
925
-
926
- await session.localTools();
927
- const executeFn = (provider as any)._capturedExecuteFn;
928
-
929
- const result = await executeFn('COMPOSIO_EXECUTE_LOCAL_TOOL', {
930
- tool_slug: 'LOCAL_GET_USER_CONTEXT',
931
- arguments: { category: 'test' },
932
- });
933
-
934
- expect(result.data).toEqual({ local_result: true });
935
- expect(result.successful).toBe(true);
936
- expect(localExecute).toHaveBeenCalledWith(
937
- { category: 'test' },
938
- expect.objectContaining({ userId: 'user_1' })
939
- );
940
- });
941
-
942
- it('should return error when executing with invalid slug via localTools()', async () => {
943
- const provider = new MockProvider();
944
- captureExecuteFn(provider);
945
- const session = createSessionWithProvider(mockClient, provider, [customToolHandle]);
946
-
947
- await session.localTools();
948
- const executeFn = (provider as any)._capturedExecuteFn;
949
-
950
- const result = await executeFn('COMPOSIO_EXECUTE_LOCAL_TOOL', {
951
- tool_slug: 'NON_EXISTENT_TOOL',
952
- arguments: {},
953
- });
954
-
955
- expect(result.successful).toBe(false);
956
- expect(result.error).toContain('Custom tool "NON_EXISTENT_TOOL" not found');
957
- expect(result.data).toEqual({});
958
- });
959
-
960
- it('should throw when calling localTools() without custom tools', async () => {
961
- const session = new ToolRouterSession(
962
- mockClient as unknown as ComposioClient,
963
- { apiKey: 'key', provider: new MockProvider() },
964
- 'sess_123',
965
- { type: 'http' as const, url: 'https://mcp.example.com/sess_123' }
966
- // No customToolsMap, no userId
967
- );
968
-
969
- await expect(session.localTools()).rejects.toThrow(
970
- 'No custom tools are bound to this session.'
971
- );
972
- });
973
- });
974
-
975
- describe('COMPOSIO_EXECUTE_LOCAL_TOOL interception in routing', () => {
976
- it('should route COMPOSIO_EXECUTE_LOCAL_TOOL to the correct local tool via session.tools() routing', async () => {
977
- const provider = new MockProvider();
978
- captureExecuteFn(provider);
979
- const session = createSessionWithProvider(mockClient, provider, [customToolHandle]);
980
-
981
- await session.tools();
982
- const executeFn = (provider as any)._capturedExecuteFn;
983
-
984
- const result = await executeFn('COMPOSIO_EXECUTE_LOCAL_TOOL', {
985
- tool_slug: 'LOCAL_GET_USER_CONTEXT',
986
- arguments: { category: 'routing-test' },
987
- });
988
-
989
- expect(result.data).toEqual({ local_result: true });
990
- expect(result.successful).toBe(true);
991
- expect(localExecute).toHaveBeenCalledWith(
992
- { category: 'routing-test' },
993
- expect.objectContaining({ userId: 'user_1' })
994
- );
995
- // Should NOT call remote
996
- expect(mockClient.toolRouter.session.execute).not.toHaveBeenCalled();
997
- });
998
-
999
- it('should return error for COMPOSIO_EXECUTE_LOCAL_TOOL with unknown slug', async () => {
1000
- const provider = new MockProvider();
1001
- captureExecuteFn(provider);
1002
- const session = createSessionWithProvider(mockClient, provider, [customToolHandle]);
1003
-
1004
- await session.tools();
1005
- const executeFn = (provider as any)._capturedExecuteFn;
1006
-
1007
- const result = await executeFn('COMPOSIO_EXECUTE_LOCAL_TOOL', {
1008
- tool_slug: 'DOES_NOT_EXIST',
1009
- arguments: {},
1010
- });
1011
-
1012
- expect(result.successful).toBe(false);
1013
- expect(result.error).toContain('Custom tool "DOES_NOT_EXIST" not found');
1014
- expect(result.data).toEqual({});
1015
- });
1016
- });
876
});