Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

next
ts 1,031 lines 34.8 KB
Raw
1 import { describe, it, expect, vi, beforeEach } from 'vitest';
2 import ComposioClient, { APIError, Auth } from '@composio/client';
3 import { z as z4 } from 'zod';
4 import { z } from 'zod/v3';
5 import {
6 createCustomTool,
7 createCustomToolkit,
8 buildCustomToolsMap,
9 buildCustomToolsMapFromResponse,
10 serializeCustomTools,
11 serializeCustomToolkits,
12 LOCAL_TOOL_PREFIX,
13 } from '../../src/models/CustomTool';
14 import { SessionContextImpl } from '../../src/models/SessionContext';
15 import { ComposioToolExecutionError } from '../../src/errors/ToolErrors';
16 import type { CustomTool, CustomToolkit, SessionContext } from '../../src/types/customTool.types';
17
18 // ────────────────────────────────────────────────────────────────
19 // createCustomTool() factory
20 // ────────────────────────────────────────────────────────────────
21
22 describe('createCustomTool', () => {
23 const baseOptions = {
24 name: 'Get user context',
25 description: 'Retrieve what we know about a user',
26 inputParams: z.object({
27 category: z.string().describe('The category'),
28 }),
29 execute: vi.fn().mockResolvedValue({ result: 'ok' }),
30 };
31
32 it('should return a valid tool with correct fields', () => {
33 const tool = createCustomTool('GET_USER_CONTEXT', baseOptions);
34
35 expect(tool.slug).toBe('GET_USER_CONTEXT');
36 expect(tool.name).toBe('Get user context');
37 expect(tool.description).toBe('Retrieve what we know about a user');
38 expect(tool.extendsToolkit).toBeUndefined();
39 expect(tool.execute).toBe(baseOptions.execute);
40 expect(tool.inputSchema).toMatchObject({
41 type: 'object',
42 properties: {
43 category: { type: 'string', description: 'The category' },
44 },
45 required: ['category'],
46 });
47 expect(tool.inputParams).toBe(baseOptions.inputParams);
48 });
49
50 it('should include extendsToolkit when provided', () => {
51 const tool = createCustomTool('GET_AD_ACCOUNTS', {
52 ...baseOptions,
53 extendsToolkit: 'meta_ads',
54 });
55 expect(tool.extendsToolkit).toBe('meta_ads');
56 });
57
58 it('should convert outputParams to JSON Schema when provided', () => {
59 const tool = createCustomTool('WITH_OUTPUT', {
60 ...baseOptions,
61 outputParams: z.object({
62 result: z.string(),
63 count: z.number(),
64 }),
65 });
66
67 expect(tool.outputSchema).toMatchObject({
68 type: 'object',
69 properties: {
70 result: { type: 'string' },
71 count: { type: 'number' },
72 },
73 required: ['result', 'count'],
74 });
75 });
76
77 it('should convert Zod v4 input and output schemas correctly', () => {
78 const tool = createCustomTool('ZOD4_TOOL', {
79 name: 'Zod 4 tool',
80 description: 'Tool using Zod 4 schemas',
81 inputParams: z4.object({
82 repository: z4.string().describe('Repository name'),
83 limit: z4.number().optional(),
84 category: z4.string().default('all'),
85 }),
86 outputParams: z4.object({
87 starred: z4.boolean(),
88 }),
89 execute: vi.fn().mockImplementation(async input => ({
90 repository: input.repository.toUpperCase(),
91 })),
92 });
93
94 expect(tool.inputSchema).toMatchObject({
95 type: 'object',
96 properties: {
97 repository: { type: 'string', description: 'Repository name' },
98 limit: { type: 'number' },
99 category: expect.objectContaining({ type: 'string', default: 'all' }),
100 },
101 required: ['repository'],
102 });
103 expect(tool.outputSchema).toMatchObject({
104 type: 'object',
105 properties: {
106 starred: { type: 'boolean' },
107 },
108 required: ['starred'],
109 });
110 });
111
112 it('should keep v3 and v4 input schemas in parity for defaulted fields (input mode)', () => {
113 const v3Tool = createCustomTool('ZOD3_DEFAULT', {
114 ...baseOptions,
115 inputParams: z.object({
116 query: z.string(),
117 category: z.string().default('all'),
118 }),
119 });
120 const v4Tool = createCustomTool('ZOD4_DEFAULT', {
121 ...baseOptions,
122 inputParams: z4.object({
123 query: z4.string(),
124 category: z4.string().default('all'),
125 }),
126 });
127
128 // In input mode a defaulted field is optional in both runtimes: only `query` is required.
129 expect(v3Tool.inputSchema).toMatchObject({ type: 'object', required: ['query'] });
130 expect(v4Tool.inputSchema).toMatchObject({ type: 'object', required: ['query'] });
131 });
132
133 it('should convert a Zod v3 array output schema without misrouting it through the v4 converter', () => {
134 // Regression: a v3 z.array()/z.promise() stores its element schema on `_def.type`, which used
135 // to be mistaken for a v4 schema and crash inside z4.toJSONSchema().
136 const tool = createCustomTool('ZOD3_ARRAY_OUTPUT', {
137 ...baseOptions,
138 outputParams: z.array(z.object({ id: z.string() })),
139 });
140
141 expect(tool.outputSchema).toMatchObject({
142 type: 'array',
143 items: {
144 type: 'object',
145 properties: { id: { type: 'string' } },
146 required: ['id'],
147 },
148 });
149 });
150
151 it('should not have outputSchema when outputParams is not provided', () => {
152 const tool = createCustomTool('NO_OUTPUT', baseOptions);
153 expect(tool.outputSchema).toBeUndefined();
154 });
155
156 it('should convert Zod schema with optional fields correctly', () => {
157 const tool = createCustomTool('OPT_FIELDS', {
158 ...baseOptions,
159 inputParams: z.object({
160 required_field: z.string(),
161 optional_field: z.number().optional(),
162 }),
163 });
164
165 expect(tool.inputSchema).toMatchObject({
166 type: 'object',
167 properties: {
168 required_field: { type: 'string' },
169 optional_field: { type: 'number' },
170 },
171 required: ['required_field'],
172 });
173 });
174
175 it('should convert Zod schema with defaults correctly', () => {
176 const tool = createCustomTool('DEFAULTS', {
177 ...baseOptions,
178 inputParams: z.object({
179 category: z.string().default('all'),
180 }),
181 });
182
183 expect(tool.inputSchema).toMatchObject({
184 type: 'object',
185 properties: {
186 category: expect.objectContaining({ type: 'string' }),
187 },
188 });
189 });
190
191 describe('slug validation', () => {
192 it('should throw if slug is empty', () => {
193 expect(() => createCustomTool('', baseOptions)).toThrow('slug is required');
194 });
195
196 it('should throw if slug starts with LOCAL_ prefix', () => {
197 expect(() => createCustomTool('LOCAL_MY_TOOL', baseOptions)).toThrow(/LOCAL_/);
198 });
199
200 it('should throw if slug starts with local_ prefix (case-insensitive)', () => {
201 expect(() => createCustomTool('local_something', baseOptions)).toThrow(/LOCAL_/);
202 });
203
204 it('should throw if slug contains invalid characters', () => {
205 expect(() => createCustomTool('MY TOOL', baseOptions)).toThrow(/alphanumeric/);
206 expect(() => createCustomTool('MY.TOOL', baseOptions)).toThrow(/alphanumeric/);
207 expect(() => createCustomTool('MY@TOOL', baseOptions)).toThrow(/alphanumeric/);
208 });
209
210 it('should allow underscores and hyphens in slug', () => {
211 const tool1 = createCustomTool('MY_TOOL', baseOptions);
212 expect(tool1.slug).toBe('MY_TOOL');
213
214 const tool2 = createCustomTool('my-tool', baseOptions);
215 expect(tool2.slug).toBe('my-tool');
216 });
217 });
218
219 describe('other validation', () => {
220 it('should throw if name is missing', () => {
221 expect(() => createCustomTool('SLUG', { ...baseOptions, name: '' })).toThrow(
222 'name is required'
223 );
224 });
225
226 it('should throw if description is missing', () => {
227 expect(() => createCustomTool('SLUG', { ...baseOptions, description: '' })).toThrow(
228 'description is required'
229 );
230 });
231
232 it('should throw if inputParams is missing', () => {
233 expect(() =>
234 createCustomTool('SLUG', { ...baseOptions, inputParams: null as unknown })
235 ).toThrow('inputParams is required');
236 });
237
238 it('should throw if execute is not a function', () => {
239 expect(() =>
240 createCustomTool('SLUG', { ...baseOptions, execute: 'not-fn' as unknown })
241 ).toThrow('execute must be a function');
242 });
243
244 it('should throw if a Zod v4 input schema is not an object', () => {
245 expect(() =>
246 createCustomTool('SLUG', { ...baseOptions, inputParams: z4.string() as unknown })
247 ).toThrow('inputParams must be a z.object() schema');
248 });
249 });
250
251 describe('execute function signatures', () => {
252 it('should allow no-session execute (input only)', async () => {
253 const noSessionExecute = vi.fn().mockResolvedValue({ result: 42 });
254
255 const tool = createCustomTool('NO_SESSION', {
256 ...baseOptions,
257 execute: noSessionExecute,
258 });
259
260 const result = await tool.execute({ category: 'test' } as unknown);
261 expect(result.result).toBe(42);
262 expect(noSessionExecute).toHaveBeenCalledWith({ category: 'test' });
263 });
264
265 it('should allow session-based execute (input + session)', async () => {
266 const sessionExecute = vi.fn().mockResolvedValue({ userId: 'u1' });
267
268 const tool = createCustomTool('WITH_SESSION', {
269 ...baseOptions,
270 execute: sessionExecute,
271 });
272
273 const mockSession: SessionContext = {
274 userId: 'user_1',
275 execute: vi.fn(),
276 proxyExecute: vi.fn(),
277 };
278
279 const result = await tool.execute({ category: 'test' }, mockSession);
280 expect(result.userId).toBe('u1');
281 expect(sessionExecute).toHaveBeenCalledWith({ category: 'test' }, mockSession);
282 });
283 });
284 });
285
286 // ────────────────────────────────────────────────────────────────
287 // createCustomToolkit() factory
288 // ────────────────────────────────────────────────────────────────
289
290 describe('createCustomToolkit', () => {
291 const baseTool = createCustomTool('GREP', {
292 name: 'Grep',
293 description: 'Search files',
294 inputParams: z.object({ pattern: z.string() }),
295 execute: vi.fn().mockResolvedValue({}),
296 });
297
298 it('should return a valid toolkit with correct fields', () => {
299 const tk = createCustomToolkit('DEV_TOOLS', {
300 name: 'Dev Tools',
301 description: 'Local dev utilities',
302 tools: [baseTool],
303 });
304
305 expect(tk.slug).toBe('DEV_TOOLS');
306 expect(tk.name).toBe('Dev Tools');
307 expect(tk.description).toBe('Local dev utilities');
308 expect(tk.tools).toHaveLength(1);
309 expect(tk.tools[0].slug).toBe('GREP');
310 });
311
312 it('should throw if slug is empty', () => {
313 expect(() =>
314 createCustomToolkit('', { name: 'X', description: 'X', tools: [baseTool] })
315 ).toThrow('slug is required');
316 });
317
318 it('should throw if slug starts with LOCAL_', () => {
319 expect(() =>
320 createCustomToolkit('LOCAL_TK', { name: 'X', description: 'X', tools: [baseTool] })
321 ).toThrow(/LOCAL_/);
322 });
323
324 it('should throw if slug contains invalid characters', () => {
325 expect(() =>
326 createCustomToolkit('MY TOOLKIT', { name: 'X', description: 'X', tools: [baseTool] })
327 ).toThrow(/alphanumeric/);
328 });
329
330 it('should throw if name is missing', () => {
331 expect(() =>
332 createCustomToolkit('TK', { name: '', description: 'X', tools: [baseTool] })
333 ).toThrow('name is required');
334 });
335
336 it('should throw if description is missing', () => {
337 expect(() =>
338 createCustomToolkit('TK', { name: 'X', description: '', tools: [baseTool] })
339 ).toThrow('description is required');
340 });
341
342 it('should throw if tools array is empty', () => {
343 expect(() => createCustomToolkit('TK', { name: 'X', description: 'X', tools: [] })).toThrow(
344 'at least one tool is required'
345 );
346 });
347
348 it('should reject tools with extendsToolkit set', () => {
349 const extendsTool = createCustomTool('EXTENDS_TOOL', {
350 name: 'Extends',
351 description: 'Has extendsToolkit',
352 extendsToolkit: 'gmail',
353 inputParams: z.object({}),
354 execute: vi.fn().mockResolvedValue({}),
355 });
356
357 expect(() =>
358 createCustomToolkit('TK', { name: 'X', description: 'X', tools: [extendsTool] })
359 ).toThrow('extendsToolkit');
360 });
361 });
362
363 // ────────────────────────────────────────────────────────────────
364 // buildCustomToolsMap()
365 // ────────────────────────────────────────────────────────────────
366
367 describe('buildCustomToolsMap', () => {
368 const makeTool = (slug: string, extendsToolkit?: string): CustomTool => ({
369 slug,
370 name: `Tool ${slug}`,
371 description: `Description for ${slug}`,
372 extendsToolkit,
373 inputSchema: { type: 'object', properties: {} },
374 inputParams: z.object({}),
375 execute: vi.fn(),
376 });
377
378 describe('standalone tools (no extendsToolkit)', () => {
379 it('should prefix as LOCAL_<SLUG>', () => {
380 const map = buildCustomToolsMap([makeTool('MY_TOOL')]);
381
382 expect(map.byFinalSlug.has('LOCAL_MY_TOOL')).toBe(true);
383 expect(map.byOriginalSlug.has('MY_TOOL')).toBe(true);
384 });
385
386 it('should handle case-insensitive slugs (uppercased internally)', () => {
387 const map = buildCustomToolsMap([makeTool('my_tool')]);
388
389 expect(map.byOriginalSlug.has('MY_TOOL')).toBe(true);
390 expect(map.byFinalSlug.has('LOCAL_MY_TOOL')).toBe(true);
391 });
392 });
393
394 describe('tools with extendsToolkit', () => {
395 it('should prefix as LOCAL_<EXTENDS_TOOLKIT>_<SLUG>', () => {
396 const map = buildCustomToolsMap([makeTool('GET_EMAILS', 'gmail')]);
397
398 expect(map.byFinalSlug.has('LOCAL_GMAIL_GET_EMAILS')).toBe(true);
399 expect(map.byOriginalSlug.has('GET_EMAILS')).toBe(true);
400 });
401 });
402
403 describe('toolkit tools', () => {
404 it('should prefix as LOCAL_<TOOLKIT_SLUG>_<TOOL_SLUG>', () => {
405 const sed = makeTool('SED');
406 const tk: CustomToolkit = {
407 slug: 'DEV_TOOLS',
408 name: 'Dev Tools',
409 description: 'Utilities',
410 tools: [sed],
411 };
412
413 const map = buildCustomToolsMap([], [tk]);
414
415 expect(map.byFinalSlug.has('LOCAL_DEV_TOOLS_SED')).toBe(true);
416 expect(map.byOriginalSlug.has('SED')).toBe(true);
417 });
418 });
419
420 describe('mixed tools and toolkits', () => {
421 it('should handle standalone + toolkit tools together', () => {
422 const grep = makeTool('GREP');
423 const sed = makeTool('SED');
424 const tk: CustomToolkit = {
425 slug: 'DEV_TOOLS',
426 name: 'Dev Tools',
427 description: 'Utilities',
428 tools: [sed],
429 };
430
431 const map = buildCustomToolsMap([grep], [tk]);
432
433 expect(map.byFinalSlug.size).toBe(2);
434 expect(map.byFinalSlug.has('LOCAL_GREP')).toBe(true);
435 expect(map.byFinalSlug.has('LOCAL_DEV_TOOLS_SED')).toBe(true);
436 });
437 });
438
439 describe('collision detection', () => {
440 it('should throw on duplicate standalone slugs', () => {
441 expect(() => buildCustomToolsMap([makeTool('DUPE'), makeTool('DUPE')])).toThrow('collision');
442 });
443
444 it('should throw on cross-group collision (standalone vs toolkit same original slug)', () => {
445 const standalone = makeTool('SED');
446 const tkTool = makeTool('SED');
447 const tk: CustomToolkit = {
448 slug: 'DEV_TOOLS',
449 name: 'Dev Tools',
450 description: 'Utilities',
451 tools: [tkTool],
452 };
453
454 expect(() => buildCustomToolsMap([standalone], [tk])).toThrow('collision');
455 });
456
457 it('should allow the same original slug in different toolkits and mark it ambiguous', () => {
458 const alpha: CustomToolkit = {
459 slug: 'ALPHA',
460 name: 'Alpha',
461 description: 'Alpha tools',
462 tools: [makeTool('GREP')],
463 };
464 const beta: CustomToolkit = {
465 slug: 'BETA',
466 name: 'Beta',
467 description: 'Beta tools',
468 tools: [makeTool('GREP')],
469 };
470
471 const map = buildCustomToolsMap([], [alpha, beta]);
472
473 expect([...map.byFinalSlug.keys()].sort()).toEqual(['LOCAL_ALPHA_GREP', 'LOCAL_BETA_GREP']);
474 expect(map.byOriginalSlug.has('GREP')).toBe(false);
475 expect(map.ambiguousOriginalSlugs).toEqual(new Set(['GREP']));
476 });
477 });
478
479 describe('length validation', () => {
480 it('should throw early in createCustomTool when slug is too long (standalone)', () => {
481 const longSlug = 'A'.repeat(56); // LOCAL_ + 56 = 62 > 60
482 expect(() =>
483 createCustomTool(longSlug, {
484 name: 'Long',
485 description: 'Too long',
486 inputParams: z.object({}),
487 execute: vi.fn().mockResolvedValue({}),
488 })
489 ).toThrow('too long');
490 });
491
492 it('should throw early in createCustomTool when slug is too long (extension)', () => {
493 // LOCAL_GMAIL_ = 12 chars, so slug > 48 chars overflows
494 const longSlug = 'A'.repeat(49);
495 expect(() =>
496 createCustomTool(longSlug, {
497 name: 'Long',
498 description: 'Too long',
499 extendsToolkit: 'gmail',
500 inputParams: z.object({}),
501 execute: vi.fn().mockResolvedValue({}),
502 })
503 ).toThrow('too long');
504 });
505
506 it('should throw early in createCustomToolkit when tool slug is too long', () => {
507 const longSlug = 'A'.repeat(50); // LOCAL_DEV_TOOLS_ + 50 = 66 > 60
508 const tool = makeTool(longSlug);
509 expect(() =>
510 createCustomToolkit('DEV_TOOLS', {
511 name: 'Dev Tools',
512 description: 'Utilities',
513 tools: [tool],
514 })
515 ).toThrow('too long');
516 });
517
518 it('should still validate in buildCustomToolsMap as safety net', () => {
519 const longSlug = 'A'.repeat(56);
520 expect(() => buildCustomToolsMap([makeTool(longSlug)])).toThrow('exceeds');
521 });
522
523 it('should accept slugs that fit within 60 chars', () => {
524 const slug = 'A'.repeat(54); // LOCAL_ + 54 = 60 exactly
525 const map = buildCustomToolsMap([makeTool(slug)]);
526 expect(map.byFinalSlug.size).toBe(1);
527 });
528 });
529 });
530
531 // ────────────────────────────────────────────────────────────────
532 // buildCustomToolsMapFromResponse()
533 // ────────────────────────────────────────────────────────────────
534
535 describe('buildCustomToolsMapFromResponse', () => {
536 const makeTool = (slug: string, extendsToolkit?: string): CustomTool => ({
537 slug,
538 name: `Tool ${slug}`,
539 description: `Description for ${slug}`,
540 extendsToolkit,
541 inputSchema: { type: 'object', properties: {} },
542 inputParams: z.object({}),
543 execute: vi.fn(),
544 });
545 const makeToolkit = (slug: string, tools: CustomTool[]): CustomToolkit => ({
546 slug,
547 name: slug,
548 description: `${slug} tools`,
549 tools,
550 });
551 type ResponseExperimental = Parameters<typeof buildCustomToolsMapFromResponse>[2];
552 const response = (value: {
553 custom_tools: Array<{ slug: string; original_slug: string; extends_toolkit?: string }>;
554 custom_toolkits: Array<{ slug: string; tools: Array<{ slug: string; original_slug: string }> }>;
555 }): ResponseExperimental => value as unknown as ResponseExperimental;
556 const alpha = makeToolkit('ALPHA', [makeTool('GREP')]);
557 const beta = makeToolkit('BETA', [makeTool('GREP')]);
558
559 it('maps shared child slugs by toolkit and keeps the bare slug ambiguous', () => {
560 const map = buildCustomToolsMapFromResponse(
561 [],
562 [alpha, beta],
563 response({
564 custom_tools: [],
565 custom_toolkits: [
566 { slug: 'ALPHA', tools: [{ slug: 'LOCAL_ALPHA_GREP', original_slug: 'GREP' }] },
567 { slug: 'BETA', tools: [{ slug: 'LOCAL_BETA_GREP', original_slug: 'GREP' }] },
568 ],
569 })
570 );
571
572 expect(map.byFinalSlug.get('LOCAL_ALPHA_GREP')?.toolkit).toBe('ALPHA');
573 expect(map.byFinalSlug.get('LOCAL_BETA_GREP')?.toolkit).toBe('BETA');
574 expect(map.ambiguousOriginalSlugs).toEqual(new Set(['GREP']));
575 });
576
577 it('rejects a toolkit child without an exact local match', () => {
578 expect(() =>
579 buildCustomToolsMapFromResponse(
580 [],
581 [alpha, beta],
582 response({
583 custom_tools: [],
584 custom_toolkits: [
585 { slug: 'GAMMA', tools: [{ slug: 'LOCAL_GAMMA_GREP', original_slug: 'GREP' }] },
586 ],
587 })
588 )
589 ).toThrow('no exact local match');
590 });
591
592 it('never binds a toolkit child to another toolkit handler', () => {
593 expect(() =>
594 buildCustomToolsMapFromResponse(
595 [],
596 [alpha],
597 response({
598 custom_tools: [],
599 custom_toolkits: [
600 { slug: 'BETA', tools: [{ slug: 'LOCAL_BETA_GREP', original_slug: 'GREP' }] },
601 ],
602 })
603 )
604 ).toThrow('for toolkit "BETA"');
605 });
606
607 it('falls back to a unique bare match for standalone tools without toolkit identity', () => {
608 const map = buildCustomToolsMapFromResponse(
609 [makeTool('GET_EMAILS', 'gmail')],
610 undefined,
611 response({
612 custom_tools: [{ slug: 'LOCAL_GMAIL_GET_EMAILS', original_slug: 'GET_EMAILS' }],
613 custom_toolkits: [],
614 })
615 );
616
617 expect(map.byFinalSlug.get('LOCAL_GMAIL_GET_EMAILS')?.toolkit).toBe('gmail');
618 });
619
620 it('skips response tools that are not defined locally', () => {
621 const map = buildCustomToolsMapFromResponse(
622 [makeTool('GREP')],
623 undefined,
624 response({
625 custom_tools: [
626 { slug: 'LOCAL_GREP', original_slug: 'GREP' },
627 { slug: 'LOCAL_STALE', original_slug: 'STALE' },
628 ],
629 custom_toolkits: [],
630 })
631 );
632
633 expect([...map.byFinalSlug.keys()]).toEqual(['LOCAL_GREP']);
634 });
635
636 it('derives ambiguity from local definitions when the response omits a sibling', () => {
637 const map = buildCustomToolsMapFromResponse(
638 [],
639 [alpha, beta],
640 response({
641 custom_tools: [],
642 custom_toolkits: [
643 { slug: 'ALPHA', tools: [{ slug: 'LOCAL_ALPHA_GREP', original_slug: 'GREP' }] },
644 ],
645 })
646 );
647
648 expect([...map.byFinalSlug.keys()]).toEqual(['LOCAL_ALPHA_GREP']);
649 expect(map.byOriginalSlug.has('GREP')).toBe(false);
650 expect(map.ambiguousOriginalSlugs).toEqual(new Set(['GREP']));
651 });
652
653 it('rejects duplicate qualified response entries', () => {
654 expect(() =>
655 buildCustomToolsMapFromResponse(
656 [],
657 [alpha, beta],
658 response({
659 custom_tools: [],
660 custom_toolkits: [
661 {
662 slug: 'ALPHA',
663 tools: [
664 { slug: 'LOCAL_ALPHA_GREP', original_slug: 'GREP' },
665 { slug: 'LOCAL_ALPHA_GREP_2', original_slug: 'GREP' },
666 ],
667 },
668 ],
669 })
670 )
671 ).toThrow('already registered for toolkit');
672 });
673 });
674
675 // ────────────────────────────────────────────────────────────────
676 // serializeCustomTools()
677 // ────────────────────────────────────────────────────────────────
678
679 describe('serializeCustomTools', () => {
680 it('should serialize tools with extendsToolkit as extends_toolkit', () => {
681 const tool: CustomTool = {
682 slug: 'GET_DATA',
683 name: 'Get Data',
684 description: 'Gets some data',
685 extendsToolkit: 'my_toolkit',
686 inputSchema: { type: 'object', properties: { id: { type: 'string' } } },
687 inputParams: z.object({ id: z.string() }),
688 execute: vi.fn(),
689 };
690
691 const result = serializeCustomTools([tool]);
692
693 expect(result).toEqual([
694 {
695 slug: 'GET_DATA',
696 name: 'Get Data',
697 description: 'Gets some data',
698 extends_toolkit: 'my_toolkit',
699 input_schema: { type: 'object', properties: { id: { type: 'string' } } },
700 },
701 ]);
702 });
703
704 it('should omit extends_toolkit when extendsToolkit is not provided', () => {
705 const tool: CustomTool = {
706 slug: 'NO_TOOLKIT',
707 name: 'No Toolkit',
708 description: 'No toolkit tool',
709 inputSchema: { type: 'object', properties: {} },
710 inputParams: z.object({}),
711 execute: vi.fn(),
712 };
713
714 const result = serializeCustomTools([tool]);
715 expect(result[0]).not.toHaveProperty('extends_toolkit');
716 });
717
718 it('should include output_schema when outputSchema is present', () => {
719 const tool: CustomTool = {
720 slug: 'WITH_OUTPUT',
721 name: 'With Output',
722 description: 'Has output schema',
723 inputSchema: { type: 'object', properties: {} },
724 outputSchema: { type: 'object', properties: { result: { type: 'string' } } },
725 inputParams: z.object({}),
726 execute: vi.fn(),
727 };
728
729 const result = serializeCustomTools([tool]);
730 expect(result[0].output_schema).toEqual({
731 type: 'object',
732 properties: { result: { type: 'string' } },
733 });
734 });
735 });
736
737 // ────────────────────────────────────────────────────────────────
738 // serializeCustomToolkits()
739 // ────────────────────────────────────────────────────────────────
740
741 describe('serializeCustomToolkits', () => {
742 it('should serialize toolkits with their tools', () => {
743 const tool: CustomTool = {
744 slug: 'SED',
745 name: 'Sed Replace',
746 description: 'Find and replace',
747 inputSchema: { type: 'object', properties: { pattern: { type: 'string' } } },
748 inputParams: z.object({ pattern: z.string() }),
749 execute: vi.fn(),
750 };
751 const tk: CustomToolkit = {
752 slug: 'DEV_TOOLS',
753 name: 'Dev Tools',
754 description: 'Dev utilities',
755 tools: [tool],
756 };
757
758 const result = serializeCustomToolkits([tk]);
759
760 expect(result).toEqual([
761 {
762 slug: 'DEV_TOOLS',
763 name: 'Dev Tools',
764 description: 'Dev utilities',
765 tools: [
766 {
767 slug: 'SED',
768 name: 'Sed Replace',
769 description: 'Find and replace',
770 input_schema: { type: 'object', properties: { pattern: { type: 'string' } } },
771 },
772 ],
773 },
774 ]);
775 });
776 });
777
778 // ────────────────────────────────────────────────────────────────
779 // SessionContextImpl
780 // ────────────────────────────────────────────────────────────────
781
782 describe('SessionContextImpl', () => {
783 const client = new ComposioClient({ auth: Auth.project('test-api-key') });
784 const session = Object.assign(client.toolRouter.session, {
785 execute: vi.fn<typeof client.toolRouter.session.execute>(),
786 proxyExecute: vi.fn<typeof client.toolRouter.session.proxyExecute>(),
787 });
788 const toolRouter = Object.assign(client.toolRouter, { session });
789 const mockClient = Object.assign(client, { toolRouter });
790
791 beforeEach(() => {
792 vi.clearAllMocks();
793 });
794
795 it('should expose userId', () => {
796 const ctx = new SessionContextImpl(mockClient, 'user_1', 'sess_1');
797 expect(ctx.userId).toBe('user_1');
798 });
799
800 it('should delegate execute() to client.toolRouter.session.execute()', async () => {
801 mockClient.toolRouter.session.execute.mockResolvedValue({
802 result_type: 'completed',
803 data: { result: 'ok' },
804 error: null,
805 log_id: 'log_1',
806 });
807
808 const ctx = new SessionContextImpl(mockClient, 'user_1', 'sess_1');
809 const result = await ctx.execute('GMAIL_SEND_EMAIL', { to: 'test@test.com' });
810
811 expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith(
812 'sess_1',
813 {
814 tool_slug: 'GMAIL_SEND_EMAIL',
815 arguments: { to: 'test@test.com' },
816 },
817 { maxRetries: 0 }
818 );
819 expect(result).toEqual({
820 data: { result: 'ok' },
821 error: null,
822 logId: 'log_1',
823 resultType: 'completed',
824 });
825 });
826
827 it('keeps the original reason when the backend cannot be reached', async () => {
828 mockClient.toolRouter.session.execute.mockRejectedValue(new Error('socket hang up'));
829
830 const ctx = new SessionContextImpl(mockClient, 'user_1', 'sess_1');
831 const error = await ctx.execute('GMAIL_SEND_EMAIL', {}).catch(e => e);
832
833 expect(error).toBeInstanceOf(ComposioToolExecutionError);
834 expect(error.message).toBe('Error executing the tool GMAIL_SEND_EMAIL: socket hang up');
835 expect(error.cause).toBeInstanceOf(Error);
836 });
837
838 it('surfaces the server details when the backend rejects the execution', async () => {
839 mockClient.toolRouter.session.execute.mockRejectedValue(
840 new APIError(
841 410,
842 {
843 error: {
844 message: 'Toolkit version 20250101_00 is retired',
845 code: 1410,
846 slug: 'TOOLKIT_VERSION_RETIRED',
847 status: 410,
848 suggested_fix: 'Pin 20250909_00',
849 },
850 },
851 undefined,
852 new Headers({ 'x-request-id': 'req_context_410' })
853 )
854 );
855
856 const ctx = new SessionContextImpl(mockClient, 'user_1', 'sess_1');
857 const error = await ctx.execute('GMAIL_SEND_EMAIL', {}).catch(e => e);
858
859 expect(error).toBeInstanceOf(ComposioToolExecutionError);
860 expect(error.message).toBe(
861 'Error executing the tool GMAIL_SEND_EMAIL: Toolkit version 20250101_00 is retired'
862 );
863 expect(error.statusCode).toBe(410);
864 expect(error.apiErrorCode).toBe(1410);
865 expect(error.requestId).toBe('req_context_410');
866 expect(error.possibleFixes).toEqual(['Pin 20250909_00']);
867 });
868
869 it('should pass inline custom tools when delegating execute() to backend', async () => {
870 mockClient.toolRouter.session.execute.mockResolvedValue({
871 result_type: 'completed',
872 data: { result: 'ok' },
873 error: null,
874 log_id: 'log_1',
875 });
876
877 const ctx = new SessionContextImpl(mockClient, 'user_1', 'sess_1', undefined, {
878 custom_tools: [
879 {
880 slug: 'GREP',
881 name: 'Grep',
882 description: 'Search local text',
883 input_schema: { type: 'object', properties: {} },
884 },
885 ],
886 });
887 await ctx.execute('GMAIL_SEND_EMAIL', { to: 'test@test.com' });
888
889 expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith(
890 'sess_1',
891 {
892 tool_slug: 'GMAIL_SEND_EMAIL',
893 arguments: { to: 'test@test.com' },
894 experimental: {
895 custom_tools: [expect.objectContaining({ slug: 'GREP' })],
896 },
897 },
898 { maxRetries: 0 }
899 );
900 });
901
902 it('should preserve logId and error when execute() returns an error', async () => {
903 mockClient.toolRouter.session.execute.mockResolvedValue({
904 result_type: 'failed',
905 data: {},
906 error: 'something went wrong',
907 log_id: 'log_2',
908 });
909
910 const ctx = new SessionContextImpl(mockClient, 'user_1', 'sess_1');
911 const result = await ctx.execute('BAD_TOOL', {});
912
913 expect(result.logId).toBe('log_2');
914 expect(result.error).toBe('something went wrong');
915 });
916
917 it('should call client.toolRouter.session.proxyExecute() via proxyExecute()', async () => {
918 mockClient.toolRouter.session.proxyExecute.mockResolvedValue({
919 status: 200,
920 data: { proxy_result: true },
921 });
922 const ctx = new SessionContextImpl(mockClient, 'user_1', 'sess_1');
923
924 const result = await ctx.proxyExecute({
925 toolkit: 'github',
926 endpoint: 'https://api.github.com/user',
927 method: 'GET',
928 parameters: [{ in: 'header' as const, name: 'X-Custom', value: 'val' }],
929 });
930
931 expect(mockClient.toolRouter.session.proxyExecute).toHaveBeenCalledWith(
932 'sess_1',
933 {
934 toolkit_slug: 'github',
935 endpoint: 'https://api.github.com/user',
936 method: 'GET',
937 parameters: [{ name: 'X-Custom', type: 'header', value: 'val' }],
938 },
939 { maxRetries: 0 }
940 );
941 expect(result).toEqual({
942 resultType: 'completed',
943 status: 200,
944 data: { proxy_result: true },
945 });
946 });
947
948 it('should throw on proxyExecute() with invalid params', async () => {
949 const ctx = new SessionContextImpl(mockClient, 'user_1', 'sess_1');
950 await expect(
951 ctx.proxyExecute({ toolkit: 'github', endpoint: '/test', method: 'INVALID' as unknown })
952 ).rejects.toThrow('Invalid proxy execute parameters');
953 });
954
955 describe('sibling local tool routing', () => {
956 it('should route to local tool when customToolsMap has a match', async () => {
957 const siblingExecute = vi.fn().mockResolvedValue({ local: true });
958 const customToolsMap = buildCustomToolsMap([
959 createCustomTool('SIBLING_TOOL', {
960 name: 'Sibling',
961 description: 'A sibling tool',
962 inputParams: z.object({ key: z.string() }),
963 execute: siblingExecute,
964 }),
965 ]);
966
967 const ctx = new SessionContextImpl(mockClient, 'user_1', 'sess_1', customToolsMap);
968 const result = await ctx.execute('SIBLING_TOOL', { key: 'val' });
969
970 expect(siblingExecute).toHaveBeenCalledWith({ key: 'val' }, ctx);
971 expect(result).toEqual({
972 data: { local: true },
973 error: null,
974 logId: '',
975 resultType: 'completed',
976 });
977 // Should NOT call remote
978 expect(mockClient.toolRouter.session.execute).not.toHaveBeenCalled();
979 });
980
981 it('should fall back to remote when slug not in customToolsMap', async () => {
982 const customToolsMap = buildCustomToolsMap([
983 createCustomTool('OTHER_TOOL', {
984 name: 'Other',
985 description: 'Not the one we call',
986 inputParams: z.object({}),
987 execute: vi.fn().mockResolvedValue({}),
988 }),
989 ]);
990 mockClient.toolRouter.session.execute.mockResolvedValue({
991 result_type: 'completed',
992 data: { remote: true },
993 error: null,
994 log_id: 'log_3',
995 });
996
997 const ctx = new SessionContextImpl(mockClient, 'user_1', 'sess_1', customToolsMap);
998 const result = await ctx.execute('REMOTE_TOOL', { key: 'val' });
999
1000 expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith(
1001 'sess_1',
1002 {
1003 tool_slug: 'REMOTE_TOOL',
1004 arguments: { key: 'val' },
1005 },
1006 { maxRetries: 0 }
1007 );
1008 expect(result).toEqual({
1009 data: { remote: true },
1010 error: null,
1011 logId: 'log_3',
1012 resultType: 'completed',
1013 });
1014 });
1015
1016 it('should delegate to remote when no customToolsMap is provided', async () => {
1017 mockClient.toolRouter.session.execute.mockResolvedValue({
1018 result_type: 'completed',
1019 data: { remote: true },
1020 error: null,
1021 log_id: 'log_4',
1022 });
1023
1024 const ctx = new SessionContextImpl(mockClient, 'user_1', 'sess_1');
1025 const result = await ctx.execute('ANY_TOOL', {});
1026
1027 expect(mockClient.toolRouter.session.execute).toHaveBeenCalled();
1028 expect(result.logId).toBe('log_4');
1029 });
1030 });
1031 });