Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
| 1 | import { describe, it, expect, vi, beforeEach, assert } from 'vitest'; |
| 2 | import { z } from 'zod/v3'; |
| 3 | import { ToolRouter } from '../../src/models/ToolRouter'; |
| 4 | import { ToolRouterSession } from '../../src/models/ToolRouterSession'; |
| 5 | import { |
| 6 | createCustomTool, |
| 7 | createCustomToolkit, |
| 8 | buildCustomToolsMap, |
| 9 | } from '../../src/models/CustomTool'; |
| 10 | import { ComposioToolInputRequiredError, ValidationError } from '../../src/errors'; |
| 11 | import { MockProvider } from '../utils/mocks/provider.mock'; |
| 12 | import ComposioClient from '@composio/client'; |
| 13 | import type { CustomTool, SessionContext } from '../../src/types/customTool.types'; |
| 14 | import type { ComposioConfig } from '../../src/composio'; |
| 15 | |
| 16 | type MultiExecuteResultItem = { |
| 17 | tool_slug: string; |
| 18 | index?: number; |
| 19 | response: { |
| 20 | successful: boolean; |
| 21 | data?: unknown; |
| 22 | error?: string; |
| 23 | }; |
| 24 | error?: string; |
| 25 | }; |
| 26 | |
| 27 | // Single-tool passthrough responses do not use the results array. |
| 28 | type MultiExecuteResponse = { |
| 29 | data: { |
| 30 | results: MultiExecuteResultItem[]; |
| 31 | total_count?: number; |
| 32 | success_count?: number; |
| 33 | error_count?: number; |
| 34 | [key: string]: unknown; |
| 35 | }; |
| 36 | error: string | null; |
| 37 | successful: boolean; |
| 38 | }; |
| 39 | |
| 40 | type CapturedExecuteFn = ( |
| 41 | toolSlug: string, |
| 42 | input: Record<string, unknown> |
| 43 | ) => Promise<MultiExecuteResponse>; |
| 44 | |
| 45 | type MockedToolsInstance = { |
| 46 | executeSessionTool: ReturnType<typeof vi.fn>; |
| 47 | }; |
| 48 | |
| 49 | const toolsMockState = vi.hoisted(() => ({ |
| 50 | latestInstance: undefined as MockedToolsInstance | undefined, |
| 51 | })); |
| 52 | |
| 53 | // Mock telemetry |
| 54 | vi.mock('../../src/telemetry/Telemetry', () => ({ |
| 55 | telemetry: { instrument: vi.fn() }, |
| 56 | })); |
| 57 | |
| 58 | // Mock Tools class |
| 59 | vi.mock('../../src/models/Tools', () => ({ |
| 60 | Tools: vi.fn().mockImplementation(function () { |
| 61 | const instance = { |
| 62 | getRawToolRouterSessionTools: vi.fn().mockResolvedValue([ |
| 63 | { slug: 'COMPOSIO_SEARCH_TOOLS', name: 'Search Tools' }, |
| 64 | { slug: 'COMPOSIO_MULTI_EXECUTE_TOOL', name: 'Multi Execute' }, |
| 65 | ]), |
| 66 | wrapToolsForToolRouter: vi.fn().mockReturnValue('wrapped-tools'), |
| 67 | executeSessionTool: vi.fn().mockResolvedValue({ |
| 68 | data: { remote: true }, |
| 69 | error: null, |
| 70 | successful: true, |
| 71 | }), |
| 72 | }; |
| 73 | |
| 74 | toolsMockState.latestInstance = instance; |
| 75 | return instance; |
| 76 | }), |
| 77 | })); |
| 78 | |
| 79 | const getLatestToolsInstance = (): MockedToolsInstance => { |
| 80 | const instance = toolsMockState.latestInstance; |
| 81 | if (!instance) { |
| 82 | throw new Error('Expected the Tools mock to have been instantiated'); |
| 83 | } |
| 84 | return instance; |
| 85 | }; |
| 86 | |
| 87 | beforeEach(() => { |
| 88 | toolsMockState.latestInstance = undefined; |
| 89 | }); |
| 90 | |
| 91 | // ── Fixtures ───────────────────────────────────────────────────── |
| 92 | |
| 93 | const sessionCreateResponse = { |
| 94 | session_id: 'sess_123', |
| 95 | config: { |
| 96 | preload: { tools: [] }, |
| 97 | user_id: 'user_1', |
| 98 | }, |
| 99 | config_version: 1, |
| 100 | mcp: { type: 'http', url: 'https://api.composio.dev/api/v3/tool_router/session/sess_123' }, |
| 101 | tool_router_tools: [], |
| 102 | }; |
| 103 | |
| 104 | const createMockClient = () => ({ |
| 105 | baseURL: 'https://api.composio.dev', |
| 106 | apiKey: 'test-api-key', |
| 107 | toolRouter: { |
| 108 | session: { |
| 109 | create: vi.fn().mockResolvedValue(sessionCreateResponse), |
| 110 | retrieve: vi.fn(), |
| 111 | link: vi.fn(), |
| 112 | toolkits: vi.fn(), |
| 113 | search: vi.fn(), |
| 114 | proxyExecute: vi.fn().mockResolvedValue({ |
| 115 | status: 200, |
| 116 | data: { ok: true }, |
| 117 | headers: { 'x-test': '1' }, |
| 118 | }), |
| 119 | execute: vi.fn().mockResolvedValue({ |
| 120 | result_type: 'completed', |
| 121 | data: { remote_result: true }, |
| 122 | error: null, |
| 123 | log_id: 'log_remote', |
| 124 | }), |
| 125 | tools: vi.fn(), |
| 126 | }, |
| 127 | }, |
| 128 | tools: { |
| 129 | list: vi.fn(), |
| 130 | retrieve: vi.fn(), |
| 131 | execute: vi.fn(), |
| 132 | proxy: vi.fn(), |
| 133 | }, |
| 134 | }); |
| 135 | |
| 136 | // Execute returns data directly (simplified API) |
| 137 | const localExecute = vi.fn().mockResolvedValue({ local_result: true }); |
| 138 | |
| 139 | const customToolHandle = createCustomTool('GET_USER_CONTEXT', { |
| 140 | name: 'Get user context', |
| 141 | description: 'Retrieve user preferences', |
| 142 | inputParams: z.object({ category: z.string() }), |
| 143 | execute: localExecute, |
| 144 | }); |
| 145 | |
| 146 | const sessionExecute = vi.fn().mockImplementation(async (input: unknown, ctx: SessionContext) => ({ |
| 147 | userId: ctx.userId, |
| 148 | })); |
| 149 | |
| 150 | const sessionToolHandle = createCustomTool('GET_AD_ACCOUNTS', { |
| 151 | name: 'Get ad accounts', |
| 152 | description: 'Get ad account IDs', |
| 153 | extendsToolkit: 'meta_ads', |
| 154 | inputParams: z.object({ fields: z.string() }), |
| 155 | execute: sessionExecute, |
| 156 | }); |
| 157 | |
| 158 | // ── Shared helpers for provider-aware session tests ──────────── |
| 159 | |
| 160 | const createSessionWithProvider = ( |
| 161 | client: ReturnType<typeof createMockClient>, |
| 162 | provider: MockProvider, |
| 163 | customTools: CustomTool[] |
| 164 | ) => { |
| 165 | return new ToolRouterSession( |
| 166 | client as unknown as ComposioClient, |
| 167 | { apiKey: 'key', provider }, |
| 168 | 'sess_123', |
| 169 | { type: 'http' as const, url: 'https://api.composio.dev/api/v3/tool_router/session/sess_123' }, |
| 170 | undefined, |
| 171 | buildCustomToolsMap(customTools), |
| 172 | 'user_1' |
| 173 | ); |
| 174 | }; |
| 175 | |
| 176 | const captureExecuteFn = (provider: MockProvider) => { |
| 177 | let executeFn: CapturedExecuteFn; |
| 178 | provider.wrapTools.mockImplementation((_tools: unknown, capturedExecuteFn: unknown) => { |
| 179 | executeFn = capturedExecuteFn as CapturedExecuteFn; |
| 180 | return 'wrapped-tools-with-routing'; |
| 181 | }); |
| 182 | return () => executeFn; |
| 183 | }; |
| 184 | |
| 185 | // ──────────────────────────────────────────────────────────────── |
| 186 | // ToolRouter.create() with customTools under experimental |
| 187 | // ──────────────────────────────────────────────────────────────── |
| 188 | |
| 189 | describe('ToolRouter.create() with customTools', () => { |
| 190 | let mockClient: ReturnType<typeof createMockClient>; |
| 191 | let router: ToolRouter<unknown, unknown, MockProvider>; |
| 192 | |
| 193 | beforeEach(() => { |
| 194 | vi.clearAllMocks(); |
| 195 | mockClient = createMockClient(); |
| 196 | router = new ToolRouter(mockClient as unknown as ComposioClient, { |
| 197 | apiKey: 'test-key', |
| 198 | provider: new MockProvider(), |
| 199 | }); |
| 200 | }); |
| 201 | |
| 202 | it('should send custom_tools under experimental in the create payload', async () => { |
| 203 | await router.create('user_1', { |
| 204 | toolkits: ['gmail'], |
| 205 | experimental: { |
| 206 | customTools: [customToolHandle], |
| 207 | }, |
| 208 | }); |
| 209 | |
| 210 | const payload = mockClient.toolRouter.session.create.mock.calls[0][0]; |
| 211 | expect(payload.experimental.custom_tools).toEqual([ |
| 212 | { |
| 213 | slug: 'GET_USER_CONTEXT', |
| 214 | name: 'Get user context', |
| 215 | description: 'Retrieve user preferences', |
| 216 | input_schema: customToolHandle.inputSchema, |
| 217 | }, |
| 218 | ]); |
| 219 | }); |
| 220 | |
| 221 | it('should include extendsToolkit as extends_toolkit in serialized custom_tools', async () => { |
| 222 | await router.create('user_1', { |
| 223 | experimental: { |
| 224 | customTools: [sessionToolHandle], |
| 225 | }, |
| 226 | }); |
| 227 | |
| 228 | const payload = mockClient.toolRouter.session.create.mock.calls[0][0]; |
| 229 | expect(payload.experimental.custom_tools[0].extends_toolkit).toBe('meta_ads'); |
| 230 | }); |
| 231 | |
| 232 | it('should send custom tool preload hints under experimental', async () => { |
| 233 | const preloadedTool = createCustomTool('PINNED_CONTEXT', { |
| 234 | name: 'Pinned context', |
| 235 | description: 'Retrieve pinned user context', |
| 236 | preload: true, |
| 237 | inputParams: z.object({}), |
| 238 | execute: localExecute, |
| 239 | }); |
| 240 | |
| 241 | await router.create('user_1', { |
| 242 | experimental: { |
| 243 | customTools: [preloadedTool], |
| 244 | }, |
| 245 | }); |
| 246 | |
| 247 | const payload = mockClient.toolRouter.session.create.mock.calls[0][0]; |
| 248 | expect(payload.experimental.custom_tools[0].preload).toBe(true); |
| 249 | }); |
| 250 | |
| 251 | it('should omit redundant custom tool preload false', async () => { |
| 252 | const searchOnlyTool = createCustomTool('SEARCH_ONLY_CONTEXT', { |
| 253 | name: 'Search-only context', |
| 254 | description: 'Retrieve context through search', |
| 255 | preload: false, |
| 256 | inputParams: z.object({}), |
| 257 | execute: localExecute, |
| 258 | }); |
| 259 | |
| 260 | await router.create('user_1', { |
| 261 | experimental: { |
| 262 | customTools: [searchOnlyTool], |
| 263 | }, |
| 264 | }); |
| 265 | |
| 266 | const payload = mockClient.toolRouter.session.create.mock.calls[0][0]; |
| 267 | expect(payload.experimental.custom_tools[0]).not.toHaveProperty('preload'); |
| 268 | }); |
| 269 | |
| 270 | it('should not send experimental.custom_tools when customTools is omitted or empty', async () => { |
| 271 | await router.create('user_1', { toolkits: ['gmail'] }); |
| 272 | const payload1 = mockClient.toolRouter.session.create.mock.calls[0][0]; |
| 273 | expect(payload1.experimental).toBeUndefined(); |
| 274 | |
| 275 | vi.clearAllMocks(); |
| 276 | await router.create('user_1', { experimental: { customTools: [] } }); |
| 277 | const payload2 = mockClient.toolRouter.session.create.mock.calls[0][0]; |
| 278 | expect(payload2.experimental).toBeUndefined(); |
| 279 | }); |
| 280 | |
| 281 | it('should return a session with the correct sessionId', async () => { |
| 282 | const session = await router.create('user_1', { |
| 283 | experimental: { |
| 284 | customTools: [customToolHandle], |
| 285 | }, |
| 286 | }); |
| 287 | |
| 288 | expect(session.sessionId).toBe('sess_123'); |
| 289 | }); |
| 290 | }); |
| 291 | |
| 292 | describe('ToolRouter.create() with localTools', () => { |
| 293 | let mockClient: ReturnType<typeof createMockClient>; |
| 294 | let router: ToolRouter<unknown, unknown, MockProvider>; |
| 295 | |
| 296 | const devToolkit = createCustomToolkit('DEV_TOOLS', { |
| 297 | name: 'Dev Tools', |
| 298 | description: 'Local dev utilities', |
| 299 | tools: [ |
| 300 | createCustomTool('GREP', { |
| 301 | name: 'Grep', |
| 302 | description: 'Search local text', |
| 303 | inputParams: z.object({ pattern: z.string() }), |
| 304 | execute: async () => ({ matches: [] }), |
| 305 | }), |
| 306 | ], |
| 307 | }); |
| 308 | |
| 309 | beforeEach(() => { |
| 310 | vi.clearAllMocks(); |
| 311 | mockClient = createMockClient(); |
| 312 | mockClient.toolRouter.session.create.mockResolvedValue({ |
| 313 | ...sessionCreateResponse, |
| 314 | experimental: { |
| 315 | custom_tools: [{ slug: 'LOCAL_GET_USER_CONTEXT', original_slug: 'GET_USER_CONTEXT' }], |
| 316 | custom_toolkits: [ |
| 317 | { slug: 'DEV_TOOLS', tools: [{ slug: 'LOCAL_DEV_TOOLS_GREP', original_slug: 'GREP' }] }, |
| 318 | ], |
| 319 | }, |
| 320 | }); |
| 321 | router = new ToolRouter(mockClient as unknown as ComposioClient, { |
| 322 | apiKey: 'test-key', |
| 323 | provider: new MockProvider(), |
| 324 | }); |
| 325 | }); |
| 326 | |
| 327 | it('sends the same custom_tools/custom_toolkits wire payload as the deprecated names', async () => { |
| 328 | await router.create('user_1', { |
| 329 | experimental: { localTools: [customToolHandle], localToolkits: [devToolkit] }, |
| 330 | }); |
| 331 | await router.create('user_1', { |
| 332 | experimental: { customTools: [customToolHandle], customToolkits: [devToolkit] }, |
| 333 | }); |
| 334 | |
| 335 | const [[localPayload], [customPayload]] = mockClient.toolRouter.session.create.mock.calls; |
| 336 | expect(localPayload.experimental).toEqual({ |
| 337 | custom_tools: [expect.objectContaining({ slug: 'GET_USER_CONTEXT' })], |
| 338 | custom_toolkits: [expect.objectContaining({ slug: 'DEV_TOOLS' })], |
| 339 | }); |
| 340 | expect(customPayload).toEqual(localPayload); |
| 341 | }); |
| 342 | |
| 343 | it('routes local tools passed via localTools in-process', async () => { |
| 344 | const session = await router.create('user_1', { |
| 345 | experimental: { localTools: [customToolHandle] }, |
| 346 | }); |
| 347 | |
| 348 | const result = await session.execute('GET_USER_CONTEXT', { category: 'all' }); |
| 349 | |
| 350 | expect(result.error).toBeNull(); |
| 351 | expect(localExecute).toHaveBeenCalled(); |
| 352 | expect(mockClient.toolRouter.session.execute).not.toHaveBeenCalled(); |
| 353 | }); |
| 354 | |
| 355 | it.each([ |
| 356 | [ |
| 357 | 'experimental.localTools or experimental.customTools', |
| 358 | { localTools: [customToolHandle], customTools: [customToolHandle] }, |
| 359 | ], |
| 360 | [ |
| 361 | 'experimental.localToolkits or experimental.customToolkits', |
| 362 | { localToolkits: [devToolkit], customToolkits: [] }, |
| 363 | ], |
| 364 | ])('rejects passing both %s without calling the API', async (fields, experimental) => { |
| 365 | const error = await router.create('user_1', { experimental }).catch(e => e); |
| 366 | |
| 367 | expect(error).toBeInstanceOf(ValidationError); |
| 368 | expect(error.message).toContain(`Pass either ${fields}, not both`); |
| 369 | expect(mockClient.toolRouter.session.create).not.toHaveBeenCalled(); |
| 370 | }); |
| 371 | |
| 372 | it('returns the same registrations from localTools()/localToolkits() and the deprecated methods', async () => { |
| 373 | const session = await router.create('user_1', { |
| 374 | experimental: { localTools: [customToolHandle], localToolkits: [devToolkit] }, |
| 375 | }); |
| 376 | |
| 377 | expect(session.localTools()).toEqual([ |
| 378 | expect.objectContaining({ slug: 'LOCAL_GET_USER_CONTEXT' }), |
| 379 | expect.objectContaining({ slug: 'LOCAL_DEV_TOOLS_GREP', toolkit: 'DEV_TOOLS' }), |
| 380 | ]); |
| 381 | expect(session.customTools()).toEqual(session.localTools()); |
| 382 | expect(session.customTools({ toolkit: 'dev_tools' })).toEqual( |
| 383 | session.localTools({ toolkit: 'dev_tools' }) |
| 384 | ); |
| 385 | expect(session.localToolkits()).toEqual([ |
| 386 | expect.objectContaining({ |
| 387 | slug: 'DEV_TOOLS', |
| 388 | tools: [expect.objectContaining({ slug: 'LOCAL_DEV_TOOLS_GREP' })], |
| 389 | }), |
| 390 | ]); |
| 391 | expect(session.customToolkits()).toEqual(session.localToolkits()); |
| 392 | }); |
| 393 | }); |
| 394 | |
| 395 | // ──────────────────────────────────────────────────────────────── |
| 396 | // ToolRouterSession — execution routing |
| 397 | // ──────────────────────────────────────────────────────────────── |
| 398 | |
| 399 | describe('ToolRouterSession execution routing', () => { |
| 400 | let mockClient: ReturnType<typeof createMockClient>; |
| 401 | |
| 402 | const createSession = ( |
| 403 | client: ReturnType<typeof createMockClient>, |
| 404 | customTools: CustomTool[] = [] |
| 405 | ) => { |
| 406 | const customToolsMap = customTools.length ? buildCustomToolsMap(customTools) : undefined; |
| 407 | |
| 408 | return new ToolRouterSession( |
| 409 | client as unknown as ComposioClient, |
| 410 | { apiKey: 'key', provider: new MockProvider() }, |
| 411 | 'sess_123', |
| 412 | { |
| 413 | type: 'http' as const, |
| 414 | url: 'https://api.composio.dev/api/v3/tool_router/session/sess_123', |
| 415 | }, |
| 416 | undefined, |
| 417 | customToolsMap, |
| 418 | 'user_1' |
| 419 | ); |
| 420 | }; |
| 421 | |
| 422 | beforeEach(() => { |
| 423 | vi.clearAllMocks(); |
| 424 | mockClient = createMockClient(); |
| 425 | localExecute.mockClear(); |
| 426 | sessionExecute.mockClear(); |
| 427 | }); |
| 428 | |
| 429 | describe('session.execute() routing', () => { |
| 430 | it('should route local tool by original slug to in-process execution', async () => { |
| 431 | const session = createSession(mockClient, [customToolHandle]); |
| 432 | |
| 433 | const result = await session.execute('GET_USER_CONTEXT', { category: 'prefs' }); |
| 434 | |
| 435 | expect(result.data).toEqual({ local_result: true }); |
| 436 | expect(result.logId).toBe(''); |
| 437 | expect(result.resultType).toBe('completed'); |
| 438 | expect(localExecute).toHaveBeenCalledWith( |
| 439 | { category: 'prefs' }, |
| 440 | expect.objectContaining({ userId: 'user_1' }) |
| 441 | ); |
| 442 | expect(mockClient.toolRouter.session.execute).not.toHaveBeenCalled(); |
| 443 | }); |
| 444 | |
| 445 | it('should route local tool by prefixed slug to in-process execution', async () => { |
| 446 | const session = createSession(mockClient, [customToolHandle]); |
| 447 | |
| 448 | const result = await session.execute('LOCAL_GET_USER_CONTEXT', { category: 'all' }); |
| 449 | |
| 450 | expect(result.data).toEqual({ local_result: true }); |
| 451 | expect(localExecute).toHaveBeenCalled(); |
| 452 | expect(mockClient.toolRouter.session.execute).not.toHaveBeenCalled(); |
| 453 | }); |
| 454 | |
| 455 | it('should route extendsToolkit tool by prefixed slug', async () => { |
| 456 | const session = createSession(mockClient, [sessionToolHandle]); |
| 457 | |
| 458 | // sessionToolHandle has extendsToolkit: 'meta_ads' → LOCAL_META_ADS_GET_AD_ACCOUNTS |
| 459 | const result = await session.execute('LOCAL_META_ADS_GET_AD_ACCOUNTS', { fields: 'id' }); |
| 460 | |
| 461 | expect(result.data).toEqual({ userId: 'user_1' }); |
| 462 | expect(sessionExecute).toHaveBeenCalled(); |
| 463 | expect(mockClient.toolRouter.session.execute).not.toHaveBeenCalled(); |
| 464 | }); |
| 465 | |
| 466 | it('should be case-insensitive for local tool lookup', async () => { |
| 467 | const session = createSession(mockClient, [customToolHandle]); |
| 468 | |
| 469 | const result = await session.execute('get_user_context', { category: 'test' }); |
| 470 | |
| 471 | expect(result.data).toEqual({ local_result: true }); |
| 472 | }); |
| 473 | |
| 474 | it('should route non-local tool to remote execution', async () => { |
| 475 | const session = createSession(mockClient, [customToolHandle]); |
| 476 | |
| 477 | await session.execute('GMAIL_SEND_EMAIL', { to: 'test@test.com' }); |
| 478 | |
| 479 | expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith( |
| 480 | 'sess_123', |
| 481 | { |
| 482 | tool_slug: 'GMAIL_SEND_EMAIL', |
| 483 | arguments: { to: 'test@test.com' }, |
| 484 | }, |
| 485 | { maxRetries: 0 } |
| 486 | ); |
| 487 | expect(localExecute).not.toHaveBeenCalled(); |
| 488 | }); |
| 489 | |
| 490 | it('should route all tools to remote when no customTools are bound', async () => { |
| 491 | const session = createSession(mockClient); |
| 492 | |
| 493 | await session.execute('GET_USER_CONTEXT', { category: 'test' }); |
| 494 | |
| 495 | expect(mockClient.toolRouter.session.execute).toHaveBeenCalled(); |
| 496 | expect(localExecute).not.toHaveBeenCalled(); |
| 497 | }); |
| 498 | }); |
| 499 | |
| 500 | describe('session.proxyExecute()', () => { |
| 501 | it('should expose the same proxy response shape used by SessionContext', async () => { |
| 502 | const session = createSession(mockClient, [customToolHandle]); |
| 503 | |
| 504 | const result = await session.proxyExecute({ |
| 505 | toolkit: 'github', |
| 506 | endpoint: 'https://api.github.com/user', |
| 507 | method: 'GET', |
| 508 | parameters: [{ in: 'header', name: 'X-Test', value: '1' }], |
| 509 | }); |
| 510 | |
| 511 | expect(mockClient.toolRouter.session.proxyExecute).toHaveBeenCalledWith( |
| 512 | 'sess_123', |
| 513 | { |
| 514 | toolkit_slug: 'github', |
| 515 | endpoint: 'https://api.github.com/user', |
| 516 | method: 'GET', |
| 517 | parameters: [{ name: 'X-Test', type: 'header', value: '1' }], |
| 518 | }, |
| 519 | { maxRetries: 0 } |
| 520 | ); |
| 521 | expect(result).toEqual({ |
| 522 | resultType: 'completed', |
| 523 | status: 200, |
| 524 | data: { ok: true }, |
| 525 | headers: { 'x-test': '1' }, |
| 526 | }); |
| 527 | }); |
| 528 | }); |
| 529 | |
| 530 | describe('session.execute() — SessionContext injection', () => { |
| 531 | it('should inject SessionContext with correct userId', async () => { |
| 532 | const session = createSession(mockClient, [sessionToolHandle]); |
| 533 | |
| 534 | await session.execute('GET_AD_ACCOUNTS', { fields: 'id' }); |
| 535 | |
| 536 | expect(sessionExecute).toHaveBeenCalledWith( |
| 537 | { fields: 'id' }, |
| 538 | expect.objectContaining({ |
| 539 | userId: 'user_1', |
| 540 | }) |
| 541 | ); |
| 542 | }); |
| 543 | |
| 544 | it('should provide a working execute() on SessionContext for remote tools', async () => { |
| 545 | const chainedExecute = vi |
| 546 | .fn() |
| 547 | .mockImplementation(async (input: Record<string, unknown>, ctx: SessionContext) => { |
| 548 | const inner = await ctx.execute('GMAIL_SEND_EMAIL', { to: input.to }); |
| 549 | return { inner_result: inner.data }; |
| 550 | }); |
| 551 | |
| 552 | const chainedTool = createCustomTool('CHAINED_TOOL', { |
| 553 | name: 'Chained', |
| 554 | description: 'Calls another tool', |
| 555 | inputParams: z.object({ to: z.string() }), |
| 556 | execute: chainedExecute, |
| 557 | }); |
| 558 | |
| 559 | const session = createSession(mockClient, [chainedTool]); |
| 560 | await session.execute('CHAINED_TOOL', { to: 'test@test.com' }); |
| 561 | |
| 562 | expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith( |
| 563 | 'sess_123', |
| 564 | { |
| 565 | tool_slug: 'GMAIL_SEND_EMAIL', |
| 566 | arguments: { to: 'test@test.com' }, |
| 567 | }, |
| 568 | { maxRetries: 0 } |
| 569 | ); |
| 570 | }); |
| 571 | |
| 572 | it('should route sibling local tools in-process without hitting the API', async () => { |
| 573 | const siblingExecute = vi.fn().mockResolvedValue({ siblingData: 'from-B' }); |
| 574 | const toolB = createCustomTool('TOOL_B', { |
| 575 | name: 'Tool B', |
| 576 | description: 'Sibling tool', |
| 577 | inputParams: z.object({ key: z.string() }), |
| 578 | execute: siblingExecute, |
| 579 | }); |
| 580 | |
| 581 | const toolAExecute = vi |
| 582 | .fn() |
| 583 | .mockImplementation(async (input: Record<string, unknown>, ctx: SessionContext) => { |
| 584 | const inner = await ctx.execute('TOOL_B', { key: input.value }); |
| 585 | return { fromA: true, fromB: inner.data }; |
| 586 | }); |
| 587 | const toolA = createCustomTool('TOOL_A', { |
| 588 | name: 'Tool A', |
| 589 | description: 'Calls sibling tool B', |
| 590 | inputParams: z.object({ value: z.string() }), |
| 591 | execute: toolAExecute, |
| 592 | }); |
| 593 | |
| 594 | const session = createSession(mockClient, [toolA, toolB]); |
| 595 | const result = await session.execute('TOOL_A', { value: 'hello' }); |
| 596 | |
| 597 | expect(siblingExecute).toHaveBeenCalledWith( |
| 598 | { key: 'hello' }, |
| 599 | expect.objectContaining({ userId: 'user_1' }) |
| 600 | ); |
| 601 | expect(result.data).toEqual({ |
| 602 | fromA: true, |
| 603 | fromB: { siblingData: 'from-B' }, |
| 604 | }); |
| 605 | expect(mockClient.toolRouter.session.execute).not.toHaveBeenCalled(); |
| 606 | }); |
| 607 | }); |
| 608 | |
| 609 | describe('session.execute() — error handling', () => { |
| 610 | it('should catch errors thrown by execute function and return error response', async () => { |
| 611 | const throwingTool = createCustomTool('THROWING_TOOL', { |
| 612 | name: 'Throwing', |
| 613 | description: 'Throws an error', |
| 614 | inputParams: z.object({}), |
| 615 | execute: async () => { |
| 616 | throw new Error('boom'); |
| 617 | }, |
| 618 | }); |
| 619 | |
| 620 | const session = createSession(mockClient, [throwingTool]); |
| 621 | const result = await session.execute('THROWING_TOOL', {}); |
| 622 | |
| 623 | expect(result.error).toBe('boom'); |
| 624 | expect(result.data).toEqual({}); |
| 625 | expect(result.resultType).toBe('failed'); |
| 626 | }); |
| 627 | |
| 628 | it('should mark a local tool that throws an empty message as failed', async () => { |
| 629 | const throwingTool = createCustomTool('SILENT_THROW', { |
| 630 | name: 'Silent throw', |
| 631 | description: 'Throws an error with no message', |
| 632 | inputParams: z.object({}), |
| 633 | execute: async () => { |
| 634 | throw new Error(''); |
| 635 | }, |
| 636 | }); |
| 637 | |
| 638 | const session = createSession(mockClient, [throwingTool]); |
| 639 | const result = await session.execute('SILENT_THROW', {}); |
| 640 | |
| 641 | expect(result.error).toBe(''); |
| 642 | expect(result.resultType).toBe('failed'); |
| 643 | }); |
| 644 | |
| 645 | it('should apply Zod defaults when input is missing optional fields', async () => { |
| 646 | const defaultExecute = vi.fn().mockImplementation(async (input: Record<string, unknown>) => ({ |
| 647 | category: input.category, |
| 648 | })); |
| 649 | |
| 650 | const toolWithDefaults = createCustomTool('DEFAULTS_TOOL', { |
| 651 | name: 'Defaults', |
| 652 | description: 'Tool with default values', |
| 653 | inputParams: z.object({ category: z.string().default('all') }), |
| 654 | execute: defaultExecute, |
| 655 | }); |
| 656 | |
| 657 | const session = createSession(mockClient, [toolWithDefaults]); |
| 658 | const result = await session.execute('DEFAULTS_TOOL', {}); |
| 659 | |
| 660 | expect(defaultExecute).toHaveBeenCalledWith({ category: 'all' }, expect.anything()); |
| 661 | expect(result.data).toEqual({ category: 'all' }); |
| 662 | }); |
| 663 | |
| 664 | it('should return validation error for invalid input', async () => { |
| 665 | const strictTool = createCustomTool('STRICT_TOOL', { |
| 666 | name: 'Strict', |
| 667 | description: 'Tool with strict input', |
| 668 | inputParams: z.object({ count: z.number() }), |
| 669 | execute: vi.fn(), |
| 670 | }); |
| 671 | |
| 672 | const session = createSession(mockClient, [strictTool]); |
| 673 | const result = await session.execute('STRICT_TOOL', { count: 'not-a-number' }); |
| 674 | |
| 675 | expect(result.error).toContain('Input validation failed'); |
| 676 | expect(result.data).toEqual({}); |
| 677 | }); |
| 678 | |
| 679 | it('should handle non-Error throws gracefully', async () => { |
| 680 | const throwingTool = createCustomTool('STRING_THROW', { |
| 681 | name: 'String throw', |
| 682 | description: 'Throws a string', |
| 683 | inputParams: z.object({}), |
| 684 | execute: async () => { |
| 685 | throw 'string error'; |
| 686 | }, |
| 687 | }); |
| 688 | |
| 689 | const session = createSession(mockClient, [throwingTool]); |
| 690 | const result = await session.execute('STRING_THROW', {}); |
| 691 | |
| 692 | expect(result.error).toBe('string error'); |
| 693 | }); |
| 694 | }); |
| 695 | |
| 696 | describe('session.tools() — COMPOSIO_MULTI_EXECUTE_TOOL routing with tools[] array', () => { |
| 697 | it('should route all-local tools[] to in-process execution', async () => { |
| 698 | const provider = new MockProvider(); |
| 699 | const getExecuteFn = captureExecuteFn(provider); |
| 700 | const session = createSessionWithProvider(mockClient, provider, [customToolHandle]); |
| 701 | |
| 702 | await session.tools(); |
| 703 | const executeFn = getExecuteFn(); |
| 704 | |
| 705 | const result = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', { |
| 706 | tools: [{ tool_slug: 'LOCAL_GET_USER_CONTEXT', arguments: { category: 'test' } }], |
| 707 | sync_response_to_workbench: false, |
| 708 | }); |
| 709 | |
| 710 | expect(result.data).toEqual({ local_result: true }); |
| 711 | expect(localExecute).toHaveBeenCalledWith( |
| 712 | { category: 'test' }, |
| 713 | expect.objectContaining({ userId: 'user_1' }) |
| 714 | ); |
| 715 | }); |
| 716 | |
| 717 | it('should route local tool by non-prefixed slug in multi-execute', async () => { |
| 718 | const provider = new MockProvider(); |
| 719 | const getExecuteFn = captureExecuteFn(provider); |
| 720 | const session = createSessionWithProvider(mockClient, provider, [customToolHandle]); |
| 721 | |
| 722 | await session.tools(); |
| 723 | const executeFn = getExecuteFn(); |
| 724 | |
| 725 | const result = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', { |
| 726 | tools: [{ tool_slug: 'GET_USER_CONTEXT', arguments: { category: 'no-prefix' } }], |
| 727 | sync_response_to_workbench: false, |
| 728 | }); |
| 729 | |
| 730 | expect(result.data).toEqual({ local_result: true }); |
| 731 | expect(localExecute).toHaveBeenCalledWith( |
| 732 | { category: 'no-prefix' }, |
| 733 | expect.objectContaining({ userId: 'user_1' }) |
| 734 | ); |
| 735 | }); |
| 736 | |
| 737 | it('should route all-remote tools[] to backend', async () => { |
| 738 | const provider = new MockProvider(); |
| 739 | const getExecuteFn = captureExecuteFn(provider); |
| 740 | const session = createSessionWithProvider(mockClient, provider, [customToolHandle]); |
| 741 | |
| 742 | await session.tools(); |
| 743 | const executeFn = getExecuteFn(); |
| 744 | |
| 745 | const result = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', { |
| 746 | tools: [{ tool_slug: 'GMAIL_SEND_EMAIL', arguments: { to: 'test@test.com' } }], |
| 747 | sync_response_to_workbench: false, |
| 748 | }); |
| 749 | |
| 750 | expect(result.data).toEqual({ remote: true }); |
| 751 | expect(localExecute).not.toHaveBeenCalled(); |
| 752 | }); |
| 753 | |
| 754 | it('should route non-MULTI_EXECUTE session tools to backend', async () => { |
| 755 | const provider = new MockProvider(); |
| 756 | const getExecuteFn = captureExecuteFn(provider); |
| 757 | const session = createSessionWithProvider(mockClient, provider, [customToolHandle]); |
| 758 | |
| 759 | await session.tools(); |
| 760 | const executeFn = getExecuteFn(); |
| 761 | |
| 762 | const result = await executeFn('COMPOSIO_SEARCH_TOOLS', { |
| 763 | queries: [{ use_case: 'send email' }], |
| 764 | }); |
| 765 | |
| 766 | expect(result.data).toEqual({ remote: true }); |
| 767 | }); |
| 768 | |
| 769 | it('should use standard wrapToolsForToolRouter when no local tools', async () => { |
| 770 | const session = new ToolRouterSession( |
| 771 | mockClient as unknown as ComposioClient, |
| 772 | { apiKey: 'key', provider: new MockProvider() }, |
| 773 | 'sess_123', |
| 774 | { |
| 775 | type: 'http' as const, |
| 776 | url: 'https://api.composio.dev/api/v3/tool_router/session/sess_123', |
| 777 | } |
| 778 | ); |
| 779 | |
| 780 | const result = await session.tools(); |
| 781 | |
| 782 | expect(result).toBe('wrapped-tools'); |
| 783 | }); |
| 784 | }); |
| 785 | |
| 786 | describe('COMPOSIO_MULTI_EXECUTE_TOOL — detailed split/merge behavior', () => { |
| 787 | const setupMultiExecute = async ( |
| 788 | client: ReturnType<typeof createMockClient>, |
| 789 | customTools: CustomTool[] |
| 790 | ) => { |
| 791 | const provider = new MockProvider(); |
| 792 | const getExecuteFn = captureExecuteFn(provider); |
| 793 | const session = createSessionWithProvider(client, provider, customTools); |
| 794 | await session.tools(); |
| 795 | const executeFn = getExecuteFn(); |
| 796 | const toolsInstance = getLatestToolsInstance(); |
| 797 | return { executeFn, toolsInstance, provider, session }; |
| 798 | }; |
| 799 | |
| 800 | const backendResponse = ( |
| 801 | results: Array<{ tool_slug: string; data: unknown; error?: string }> |
| 802 | ) => { |
| 803 | const items = results.map((r, i) => ({ |
| 804 | response: { |
| 805 | successful: !r.error, |
| 806 | data: r.data, |
| 807 | ...(r.error ? { error: r.error } : {}), |
| 808 | }, |
| 809 | tool_slug: r.tool_slug, |
| 810 | index: i, |
| 811 | ...(r.error ? { error: r.error } : {}), |
| 812 | })); |
| 813 | const errorCount = results.filter(r => r.error).length; |
| 814 | return { |
| 815 | data: { |
| 816 | results: items, |
| 817 | total_count: results.length, |
| 818 | success_count: results.length - errorCount, |
| 819 | error_count: errorCount, |
| 820 | }, |
| 821 | error: errorCount > 0 ? `${errorCount} out of ${results.length} tools failed` : null, |
| 822 | successful: errorCount === 0, |
| 823 | }; |
| 824 | }; |
| 825 | |
| 826 | const findResult = (results: MultiExecuteResultItem[], slug: string) => |
| 827 | results.find(r => r.tool_slug === slug); |
| 828 | |
| 829 | it('should append local results to remote results array', async () => { |
| 830 | const { executeFn, toolsInstance } = await setupMultiExecute(mockClient, [customToolHandle]); |
| 831 | |
| 832 | toolsInstance.executeSessionTool.mockResolvedValueOnce( |
| 833 | backendResponse([{ tool_slug: 'GMAIL_SEND_EMAIL', data: { sent: true } }]) |
| 834 | ); |
| 835 | |
| 836 | const result = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', { |
| 837 | tools: [ |
| 838 | { tool_slug: 'LOCAL_GET_USER_CONTEXT', arguments: { category: 'a' } }, |
| 839 | { tool_slug: 'GMAIL_SEND_EMAIL', arguments: { to: 'x@y.com' } }, |
| 840 | ], |
| 841 | sync_response_to_workbench: false, |
| 842 | }); |
| 843 | |
| 844 | const { results } = result.data; |
| 845 | expect(results).toHaveLength(2); |
| 846 | |
| 847 | const remote = findResult(results, 'GMAIL_SEND_EMAIL')!; |
| 848 | const local = findResult(results, 'LOCAL_GET_USER_CONTEXT')!; |
| 849 | expect(remote.response.data).toEqual({ sent: true }); |
| 850 | expect(local.response.data).toEqual({ local_result: true }); |
| 851 | expect(local.response.successful).toBe(true); |
| 852 | }); |
| 853 | |
| 854 | it('should handle multiple local tools in same batch', async () => { |
| 855 | const { executeFn } = await setupMultiExecute(mockClient, [ |
| 856 | customToolHandle, |
| 857 | sessionToolHandle, |
| 858 | ]); |
| 859 | |
| 860 | const result = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', { |
| 861 | tools: [ |
| 862 | { tool_slug: 'LOCAL_GET_USER_CONTEXT', arguments: { category: 'batch' } }, |
| 863 | { tool_slug: 'LOCAL_META_ADS_GET_AD_ACCOUNTS', arguments: { fields: 'id,name' } }, |
| 864 | ], |
| 865 | sync_response_to_workbench: false, |
| 866 | }); |
| 867 | |
| 868 | expect(localExecute).toHaveBeenCalledWith( |
| 869 | { category: 'batch' }, |
| 870 | expect.objectContaining({ userId: 'user_1' }) |
| 871 | ); |
| 872 | expect(sessionExecute).toHaveBeenCalledWith( |
| 873 | { fields: 'id,name' }, |
| 874 | expect.objectContaining({ userId: 'user_1' }) |
| 875 | ); |
| 876 | |
| 877 | const { results } = result.data; |
| 878 | expect(results).toHaveLength(2); |
| 879 | expect(findResult(results, 'LOCAL_GET_USER_CONTEXT')).toBeDefined(); |
| 880 | expect(findResult(results, 'LOCAL_META_ADS_GET_AD_ACCOUNTS')).toBeDefined(); |
| 881 | }); |
| 882 | |
| 883 | it('should handle mixed batch with multiple locals + multiple remotes', async () => { |
| 884 | const { executeFn, toolsInstance } = await setupMultiExecute(mockClient, [ |
| 885 | customToolHandle, |
| 886 | sessionToolHandle, |
| 887 | ]); |
| 888 | |
| 889 | toolsInstance.executeSessionTool.mockResolvedValueOnce( |
| 890 | backendResponse([ |
| 891 | { tool_slug: 'GMAIL_SEND_EMAIL', data: { sent: true } }, |
| 892 | { tool_slug: 'SLACK_POST_MESSAGE', data: { ts: '999' } }, |
| 893 | ]) |
| 894 | ); |
| 895 | |
| 896 | const result = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', { |
| 897 | tools: [ |
| 898 | { tool_slug: 'LOCAL_GET_USER_CONTEXT', arguments: { category: 'x' } }, |
| 899 | { tool_slug: 'GMAIL_SEND_EMAIL', arguments: { to: 'a@b.com' } }, |
| 900 | { tool_slug: 'LOCAL_META_ADS_GET_AD_ACCOUNTS', arguments: { fields: 'id' } }, |
| 901 | { tool_slug: 'SLACK_POST_MESSAGE', arguments: { channel: '#dev' } }, |
| 902 | ], |
| 903 | sync_response_to_workbench: false, |
| 904 | }); |
| 905 | |
| 906 | const { results } = result.data; |
| 907 | expect(results).toHaveLength(4); |
| 908 | expect(findResult(results, 'LOCAL_GET_USER_CONTEXT')).toBeDefined(); |
| 909 | expect(findResult(results, 'LOCAL_META_ADS_GET_AD_ACCOUNTS')).toBeDefined(); |
| 910 | expect(findResult(results, 'GMAIL_SEND_EMAIL')).toBeDefined(); |
| 911 | expect(findResult(results, 'SLACK_POST_MESSAGE')).toBeDefined(); |
| 912 | expect(results.map(entry => entry.tool_slug)).toEqual([ |
| 913 | 'LOCAL_GET_USER_CONTEXT', |
| 914 | 'GMAIL_SEND_EMAIL', |
| 915 | 'LOCAL_META_ADS_GET_AD_ACCOUNTS', |
| 916 | 'SLACK_POST_MESSAGE', |
| 917 | ]); |
| 918 | |
| 919 | const backendTools = toolsInstance.executeSessionTool.mock.calls[0][1].arguments.tools; |
| 920 | expect(backendTools).toHaveLength(2); |
| 921 | expect(backendTools.map((t: { tool_slug: string }) => t.tool_slug)).toEqual([ |
| 922 | 'GMAIL_SEND_EMAIL', |
| 923 | 'SLACK_POST_MESSAGE', |
| 924 | ]); |
| 925 | |
| 926 | expect(localExecute).toHaveBeenCalled(); |
| 927 | expect(sessionExecute).toHaveBeenCalled(); |
| 928 | expect(result.successful).toBe(true); |
| 929 | }); |
| 930 | |
| 931 | it('should preserve successful local results when remote transport fails', async () => { |
| 932 | const { executeFn, toolsInstance } = await setupMultiExecute(mockClient, [customToolHandle]); |
| 933 | |
| 934 | toolsInstance.executeSessionTool.mockRejectedValueOnce(new Error('remote unavailable')); |
| 935 | |
| 936 | const result = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', { |
| 937 | tools: [ |
| 938 | { tool_slug: 'LOCAL_GET_USER_CONTEXT', arguments: { category: 'safe-retry' } }, |
| 939 | { tool_slug: 'GMAIL_SEND_EMAIL', arguments: { to: 'a@b.com' } }, |
| 940 | ], |
| 941 | sync_response_to_workbench: false, |
| 942 | }); |
| 943 | |
| 944 | expect(result.successful).toBe(false); |
| 945 | expect(localExecute).toHaveBeenCalledTimes(1); |
| 946 | expect(findResult(result.data.results, 'LOCAL_GET_USER_CONTEXT')).toMatchObject({ |
| 947 | response: { successful: true, data: { local_result: true } }, |
| 948 | }); |
| 949 | expect(findResult(result.data.results, 'GMAIL_SEND_EMAIL')).toMatchObject({ |
| 950 | response: { successful: false, error: 'remote unavailable' }, |
| 951 | error: 'remote unavailable', |
| 952 | }); |
| 953 | }); |
| 954 | |
| 955 | it('should rethrow an input request from the remote half of a mixed batch', async () => { |
| 956 | const { executeFn, toolsInstance } = await setupMultiExecute(mockClient, [customToolHandle]); |
| 957 | |
| 958 | // What `executeSessionTool` throws when the API answers `input_required`. |
| 959 | const inputRequired = new ComposioToolInputRequiredError('Tool COMPOSIO_MULTI_EXECUTE_TOOL', { |
| 960 | inputRequests: { |
| 961 | approval_1: { |
| 962 | type: 'elicitation', |
| 963 | mode: 'form', |
| 964 | message: 'Allow GMAIL_SEND_EMAIL to send this email?', |
| 965 | requestedSchema: { type: 'object' }, |
| 966 | }, |
| 967 | }, |
| 968 | requestState: 'opaque-state-token', |
| 969 | }); |
| 970 | toolsInstance.executeSessionTool.mockRejectedValueOnce(inputRequired); |
| 971 | |
| 972 | const error = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', { |
| 973 | tools: [ |
| 974 | { tool_slug: 'LOCAL_GET_USER_CONTEXT', arguments: { category: 'approval' } }, |
| 975 | { tool_slug: 'GMAIL_SEND_EMAIL', arguments: { to: 'a@b.com' } }, |
| 976 | ], |
| 977 | sync_response_to_workbench: false, |
| 978 | }).catch((caught: unknown) => caught); |
| 979 | |
| 980 | // The caller gets the questions and the state, not per-tool failure strings. |
| 981 | expect(error).toBe(inputRequired); |
| 982 | assert(error instanceof ComposioToolInputRequiredError); |
| 983 | expect(Object.keys(error.inputRequests)).toEqual(['approval_1']); |
| 984 | expect(error.requestState).toBe('opaque-state-token'); |
| 985 | // The local tool had already run; its result is discarded by the throw. |
| 986 | expect(localExecute).toHaveBeenCalledTimes(1); |
| 987 | }); |
| 988 | |
| 989 | it('should recompute remote counters when local results are merged', async () => { |
| 990 | const { executeFn, toolsInstance } = await setupMultiExecute(mockClient, [customToolHandle]); |
| 991 | |
| 992 | toolsInstance.executeSessionTool.mockResolvedValueOnce( |
| 993 | backendResponse([{ tool_slug: 'GMAIL_SEND_EMAIL', data: { sent: true } }]) |
| 994 | ); |
| 995 | |
| 996 | const result = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', { |
| 997 | tools: [ |
| 998 | { tool_slug: 'LOCAL_GET_USER_CONTEXT', arguments: { category: 'counts' } }, |
| 999 | { tool_slug: 'GMAIL_SEND_EMAIL', arguments: { to: 'a@b.com' } }, |
| 1000 | ], |
| 1001 | sync_response_to_workbench: false, |
| 1002 | }); |
| 1003 | |
| 1004 | expect(result.data.total_count).toBe(2); |
| 1005 | expect(result.data.success_count).toBe(2); |
| 1006 | expect(result.data.error_count).toBe(0); |
| 1007 | }); |
| 1008 | |
| 1009 | it('should handle remote null data without crashing', async () => { |
| 1010 | const { executeFn, toolsInstance } = await setupMultiExecute(mockClient, [customToolHandle]); |
| 1011 | |
| 1012 | toolsInstance.executeSessionTool.mockResolvedValueOnce({ |
| 1013 | data: null, |
| 1014 | error: null, |
| 1015 | successful: true, |
| 1016 | }); |
| 1017 | |
| 1018 | const result = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', { |
| 1019 | tools: [ |
| 1020 | { tool_slug: 'LOCAL_GET_USER_CONTEXT', arguments: { category: 'x' } }, |
| 1021 | { tool_slug: 'GMAIL_SEND_EMAIL', arguments: { to: 'a@b.com' } }, |
| 1022 | ], |
| 1023 | sync_response_to_workbench: false, |
| 1024 | }); |
| 1025 | |
| 1026 | expect(result.successful).toBe(true); |
| 1027 | expect(result.data.results).toHaveLength(1); |
| 1028 | expect(findResult(result.data.results, 'LOCAL_GET_USER_CONTEXT')).toBeDefined(); |
| 1029 | }); |
| 1030 | |
| 1031 | it('should surface errors from both local and remote tools', async () => { |
| 1032 | const throwingHandle = createCustomTool('MIXED_THROWER', { |
| 1033 | name: 'Throws in batch', |
| 1034 | description: 'Throws', |
| 1035 | inputParams: z.object({}), |
| 1036 | execute: async () => { |
| 1037 | throw new Error('batch-boom'); |
| 1038 | }, |
| 1039 | }); |
| 1040 | |
| 1041 | const { executeFn, toolsInstance } = await setupMultiExecute(mockClient, [ |
| 1042 | customToolHandle, |
| 1043 | throwingHandle, |
| 1044 | ]); |
| 1045 | |
| 1046 | toolsInstance.executeSessionTool.mockResolvedValueOnce( |
| 1047 | backendResponse([ |
| 1048 | { tool_slug: 'GMAIL_SEND_EMAIL', data: { sent: true } }, |
| 1049 | { |
| 1050 | tool_slug: 'SLACK_POST_MESSAGE', |
| 1051 | data: { message: 'auth failed' }, |
| 1052 | error: 'auth failed', |
| 1053 | }, |
| 1054 | ]) |
| 1055 | ); |
| 1056 | |
| 1057 | const result = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', { |
| 1058 | tools: [ |
| 1059 | { tool_slug: 'LOCAL_GET_USER_CONTEXT', arguments: { category: 'ok' } }, |
| 1060 | { tool_slug: 'LOCAL_MIXED_THROWER', arguments: {} }, |
| 1061 | { tool_slug: 'GMAIL_SEND_EMAIL', arguments: { to: 'a@b.com' } }, |
| 1062 | { tool_slug: 'SLACK_POST_MESSAGE', arguments: { channel: '#dev' } }, |
| 1063 | ], |
| 1064 | sync_response_to_workbench: false, |
| 1065 | }); |
| 1066 | |
| 1067 | const { results } = result.data; |
| 1068 | expect(results).toHaveLength(4); |
| 1069 | |
| 1070 | const localOk = findResult(results, 'LOCAL_GET_USER_CONTEXT')!; |
| 1071 | expect(localOk.response.successful).toBe(true); |
| 1072 | |
| 1073 | const localErr = findResult(results, 'LOCAL_MIXED_THROWER')!; |
| 1074 | expect(localErr.response.successful).toBe(false); |
| 1075 | expect(localErr.response.error).toBe('batch-boom'); |
| 1076 | expect(localErr.error).toBe('batch-boom'); |
| 1077 | |
| 1078 | const remoteErr = findResult(results, 'SLACK_POST_MESSAGE')!; |
| 1079 | expect(remoteErr.response.error).toBe('auth failed'); |
| 1080 | |
| 1081 | expect(result.successful).toBe(false); |
| 1082 | expect(result.error).toContain('2 out of 4'); |
| 1083 | }); |
| 1084 | |
| 1085 | it('should preserve batch-level remote errors when no per-tool remote results exist', async () => { |
| 1086 | const { executeFn, toolsInstance } = await setupMultiExecute(mockClient, [customToolHandle]); |
| 1087 | |
| 1088 | toolsInstance.executeSessionTool.mockResolvedValueOnce({ |
| 1089 | data: null, |
| 1090 | error: 'Remote batch failed before per-tool results were produced', |
| 1091 | successful: false, |
| 1092 | }); |
| 1093 | |
| 1094 | const result = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', { |
| 1095 | tools: [ |
| 1096 | { tool_slug: 'LOCAL_GET_USER_CONTEXT', arguments: { category: 'x' } }, |
| 1097 | { tool_slug: 'GMAIL_SEND_EMAIL', arguments: { to: 'a@b.com' } }, |
| 1098 | ], |
| 1099 | sync_response_to_workbench: false, |
| 1100 | }); |
| 1101 | |
| 1102 | expect(result.successful).toBe(false); |
| 1103 | expect(result.error).toBe('Remote batch failed before per-tool results were produced'); |
| 1104 | }); |
| 1105 | |
| 1106 | it('should report a failed remote batch that carries no error text as unsuccessful', async () => { |
| 1107 | const { executeFn, toolsInstance } = await setupMultiExecute(mockClient, [customToolHandle]); |
| 1108 | |
| 1109 | toolsInstance.executeSessionTool.mockResolvedValueOnce({ |
| 1110 | data: {}, |
| 1111 | error: null, |
| 1112 | successful: false, |
| 1113 | }); |
| 1114 | |
| 1115 | const result = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', { |
| 1116 | tools: [ |
| 1117 | { tool_slug: 'LOCAL_GET_USER_CONTEXT', arguments: { category: 'x' } }, |
| 1118 | { tool_slug: 'GMAIL_SEND_EMAIL', arguments: { to: 'a@b.com' } }, |
| 1119 | ], |
| 1120 | sync_response_to_workbench: false, |
| 1121 | }); |
| 1122 | |
| 1123 | expect(result.successful).toBe(false); |
| 1124 | expect(result.error).toBeNull(); |
| 1125 | }); |
| 1126 | |
| 1127 | it('should forward to backend when tools array is empty', async () => { |
| 1128 | const { executeFn, toolsInstance } = await setupMultiExecute(mockClient, [customToolHandle]); |
| 1129 | |
| 1130 | await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', { |
| 1131 | tools: [], |
| 1132 | sync_response_to_workbench: false, |
| 1133 | }); |
| 1134 | |
| 1135 | expect(toolsInstance.executeSessionTool).toHaveBeenCalledWith( |
| 1136 | 'COMPOSIO_MULTI_EXECUTE_TOOL', |
| 1137 | expect.objectContaining({ |
| 1138 | sessionId: 'sess_123', |
| 1139 | arguments: expect.objectContaining({ tools: [] }), |
| 1140 | }), |
| 1141 | undefined, |
| 1142 | expect.objectContaining({ slug: 'COMPOSIO_MULTI_EXECUTE_TOOL' }) |
| 1143 | ); |
| 1144 | }); |
| 1145 | |
| 1146 | it('should handle non-object items in tools array gracefully', async () => { |
| 1147 | const { executeFn, toolsInstance } = await setupMultiExecute(mockClient, [customToolHandle]); |
| 1148 | |
| 1149 | toolsInstance.executeSessionTool.mockResolvedValueOnce(backendResponse([])); |
| 1150 | |
| 1151 | const result = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', { |
| 1152 | tools: [ |
| 1153 | 'not-an-object', |
| 1154 | null, |
| 1155 | { tool_slug: 'LOCAL_GET_USER_CONTEXT', arguments: { category: 'ok' } }, |
| 1156 | ], |
| 1157 | sync_response_to_workbench: false, |
| 1158 | }); |
| 1159 | |
| 1160 | expect(localExecute).toHaveBeenCalledWith( |
| 1161 | { category: 'ok' }, |
| 1162 | expect.objectContaining({ userId: 'user_1' }) |
| 1163 | ); |
| 1164 | const { results } = result.data; |
| 1165 | expect(findResult(results, 'LOCAL_GET_USER_CONTEXT')).toBeDefined(); |
| 1166 | }); |
| 1167 | |
| 1168 | it('should execute local and remote in parallel (not sequentially)', async () => { |
| 1169 | const callOrder: string[] = []; |
| 1170 | |
| 1171 | const slowLocalHandle = createCustomTool('SLOW_LOCAL', { |
| 1172 | name: 'Slow local', |
| 1173 | description: 'Slow', |
| 1174 | inputParams: z.object({}), |
| 1175 | execute: async () => { |
| 1176 | callOrder.push('local-start'); |
| 1177 | await new Promise(r => setTimeout(r, 50)); |
| 1178 | callOrder.push('local-end'); |
| 1179 | return { slow: true }; |
| 1180 | }, |
| 1181 | }); |
| 1182 | |
| 1183 | const provider = new MockProvider(); |
| 1184 | const getExecuteFn = captureExecuteFn(provider); |
| 1185 | const session = createSessionWithProvider(mockClient, provider, [slowLocalHandle]); |
| 1186 | await session.tools(); |
| 1187 | const executeFn = getExecuteFn(); |
| 1188 | const toolsInstance = getLatestToolsInstance(); |
| 1189 | |
| 1190 | toolsInstance.executeSessionTool.mockImplementation(async () => { |
| 1191 | callOrder.push('remote-start'); |
| 1192 | await new Promise(r => setTimeout(r, 50)); |
| 1193 | callOrder.push('remote-end'); |
| 1194 | return backendResponse([{ tool_slug: 'GMAIL_SEND_EMAIL', data: { sent: true } }]); |
| 1195 | }); |
| 1196 | |
| 1197 | await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', { |
| 1198 | tools: [ |
| 1199 | { tool_slug: 'LOCAL_SLOW_LOCAL', arguments: {} }, |
| 1200 | { tool_slug: 'GMAIL_SEND_EMAIL', arguments: { to: 'x@y.com' } }, |
| 1201 | ], |
| 1202 | sync_response_to_workbench: false, |
| 1203 | }); |
| 1204 | |
| 1205 | const localStartIdx = callOrder.indexOf('local-start'); |
| 1206 | const remoteStartIdx = callOrder.indexOf('remote-start'); |
| 1207 | const localEndIdx = callOrder.indexOf('local-end'); |
| 1208 | const remoteEndIdx = callOrder.indexOf('remote-end'); |
| 1209 | |
| 1210 | expect(localStartIdx).toBeGreaterThanOrEqual(0); |
| 1211 | expect(remoteStartIdx).toBeGreaterThanOrEqual(0); |
| 1212 | expect(Math.max(localStartIdx, remoteStartIdx)).toBeLessThan( |
| 1213 | Math.min(localEndIdx, remoteEndIdx) |
| 1214 | ); |
| 1215 | }); |
| 1216 | }); |
| 1217 | |
| 1218 | describe('multiple custom tools', () => { |
| 1219 | it('should route each tool to its correct execute function', async () => { |
| 1220 | const session = createSession(mockClient, [customToolHandle, sessionToolHandle]); |
| 1221 | |
| 1222 | await session.execute('GET_USER_CONTEXT', { category: 'prefs' }); |
| 1223 | expect(localExecute).toHaveBeenCalled(); |
| 1224 | expect(sessionExecute).not.toHaveBeenCalled(); |
| 1225 | |
| 1226 | localExecute.mockClear(); |
| 1227 | |
| 1228 | await session.execute('GET_AD_ACCOUNTS', { fields: 'id' }); |
| 1229 | expect(sessionExecute).toHaveBeenCalled(); |
| 1230 | expect(localExecute).not.toHaveBeenCalled(); |
| 1231 | }); |
| 1232 | }); |
| 1233 | |
| 1234 | describe('per-tool results — each tool gets its own entry in results[]', () => { |
| 1235 | it('should return per-tool results for mixed local+remote batch', async () => { |
| 1236 | const provider = new MockProvider(); |
| 1237 | const getExecuteFn = captureExecuteFn(provider); |
| 1238 | const session = createSessionWithProvider(mockClient, provider, [customToolHandle]); |
| 1239 | |
| 1240 | await session.tools(); |
| 1241 | |
| 1242 | const latestToolsInstance = getLatestToolsInstance(); |
| 1243 | latestToolsInstance.executeSessionTool.mockResolvedValueOnce({ |
| 1244 | data: { |
| 1245 | results: [ |
| 1246 | { |
| 1247 | response: { successful: true, data: { message_id: 'msg_1' } }, |
| 1248 | tool_slug: 'GMAIL_SEND_EMAIL', |
| 1249 | index: 0, |
| 1250 | }, |
| 1251 | { |
| 1252 | response: { successful: true, data: { ts: '123456' } }, |
| 1253 | tool_slug: 'SLACK_POST_MESSAGE', |
| 1254 | index: 1, |
| 1255 | }, |
| 1256 | ], |
| 1257 | total_count: 2, |
| 1258 | success_count: 2, |
| 1259 | error_count: 0, |
| 1260 | }, |
| 1261 | error: null, |
| 1262 | successful: true, |
| 1263 | }); |
| 1264 | |
| 1265 | const executeFn = getExecuteFn(); |
| 1266 | |
| 1267 | const result = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', { |
| 1268 | tools: [ |
| 1269 | { tool_slug: 'LOCAL_GET_USER_CONTEXT', arguments: { category: 'prefs' } }, |
| 1270 | { tool_slug: 'GMAIL_SEND_EMAIL', arguments: { to: 'a@b.com' } }, |
| 1271 | { tool_slug: 'SLACK_POST_MESSAGE', arguments: { channel: '#general' } }, |
| 1272 | ], |
| 1273 | sync_response_to_workbench: false, |
| 1274 | }); |
| 1275 | |
| 1276 | const { results } = result.data; |
| 1277 | expect(results).toHaveLength(3); |
| 1278 | |
| 1279 | const local = results.find(r => r.tool_slug === 'LOCAL_GET_USER_CONTEXT')!; |
| 1280 | const gmail = results.find(r => r.tool_slug === 'GMAIL_SEND_EMAIL')!; |
| 1281 | const slack = results.find(r => r.tool_slug === 'SLACK_POST_MESSAGE')!; |
| 1282 | |
| 1283 | expect(local.response.data).toEqual({ local_result: true }); |
| 1284 | expect(gmail.response.data).toEqual({ message_id: 'msg_1' }); |
| 1285 | expect(slack.response.data).toEqual({ ts: '123456' }); |
| 1286 | }); |
| 1287 | }); |
| 1288 | |
| 1289 | describe('provider guard — session.tools() throws without provider', () => { |
| 1290 | it('should throw when provider is not configured but local tools exist', async () => { |
| 1291 | const customToolsMap = buildCustomToolsMap([customToolHandle]); |
| 1292 | |
| 1293 | const session = new ToolRouterSession( |
| 1294 | mockClient as unknown as ComposioClient, |
| 1295 | { apiKey: 'key' } as unknown as ComposioConfig<MockProvider>, |
| 1296 | 'sess_123', |
| 1297 | { |
| 1298 | type: 'http' as const, |
| 1299 | url: 'https://api.composio.dev/api/v3/tool_router/session/sess_123', |
| 1300 | }, |
| 1301 | undefined, |
| 1302 | customToolsMap, |
| 1303 | 'user_1' |
| 1304 | ); |
| 1305 | |
| 1306 | await expect(session.tools()).rejects.toThrow( |
| 1307 | 'A provider is required when using custom tools with session.tools()' |
| 1308 | ); |
| 1309 | }); |
| 1310 | }); |
| 1311 | }); |