@devries-cameron20 / composio-1 / commits / d97fc8e17
Fork 0

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

Pass inline custom tools on session execute

Dhawal Upadhyay committed May 6, 2026 at 18:17 UTC d97fc8e17d4859953c89efcc1cddf2eb9cee4857
11 files changed +461 -33
python/composio/core/models/session_context.py
+19 -6
@@ -16,13 +16,17 @@ from composio_client.types.tool_router.session_execute_response import (
16 from composio_client.types.tool_router.session_proxy_execute_response import (
17 SessionProxyExecuteResponse,
18 )
19 +from composio_client.types.tool_router import session_execute_params
20
21 from composio.client import HttpClient
22 from composio.core.models.custom_tool_execution import (
23 execute_custom_tool,
24 find_custom_tool,
25 )
25 -from composio.core.models.custom_tool_types import CustomToolsMap
26 +from composio.core.models.custom_tool_types import (
27 + CustomToolsMap,
28 + InlineCustomToolsWirePayload,
29 +)
30 from composio.core.models.tools import _serialize_arguments
31 from composio.exceptions import ValidationError
32
@@ -99,11 +103,13 @@ class SessionContextImpl:
103 user_id: str,
104 session_id: str,
105 custom_tools_map: t.Optional[CustomToolsMap] = None,
106 + inline_custom_tools_payload: t.Optional[InlineCustomToolsWirePayload] = None,
107 ) -> None:
108 self._client = client
109 self._user_id = user_id
110 self._session_id = session_id
111 self._custom_tools_map = custom_tools_map
112 + self._inline_custom_tools_payload = inline_custom_tools_payload
113
114 @property
115 def user_id(self) -> str:
@@ -136,11 +142,18 @@ class SessionContextImpl:
142 serialized = _serialize_arguments(arguments)
143
144 # Fall back to remote execution
139 - return self._client.tool_router.session.execute(
140 - session_id=self._session_id,
141 - tool_slug=tool_slug,
142 - arguments=serialized,
143 - )
145 + execute_kwargs: t.Dict[str, t.Any] = {
146 + "session_id": self._session_id,
147 + "tool_slug": tool_slug,
148 + "arguments": serialized,
149 + }
150 + if self._inline_custom_tools_payload is not None:
151 + execute_kwargs["experimental"] = t.cast(
152 + session_execute_params.Experimental,
153 + self._inline_custom_tools_payload,
154 + )
155 +
156 + return self._client.tool_router.session.execute(**execute_kwargs)
157
158 def proxy_execute(
159 self,
python/composio/core/models/tool_router_session.py
+19 -7
@@ -28,7 +28,10 @@ from composio_client.types.tool_router.session_proxy_execute_response import (
28 from composio_client.types.tool_router.session_search_response import (
29 SessionSearchResponse,
30 )
31 -from composio_client.types.tool_router import session_search_params
31 +from composio_client.types.tool_router import (
32 + session_execute_params,
33 + session_search_params,
34 +)
35
36 from composio.client import HttpClient
37 from composio.core.models.connected_accounts import ConnectionRequest
@@ -132,6 +135,7 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
135 user_id=user_id,
136 session_id=session_id,
137 custom_tools_map=custom_tools_map,
138 + inline_custom_tools_payload=inline_custom_tools_payload,
139 )
140
141 def _has_custom_tools(self) -> bool:
@@ -149,6 +153,7 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
153 return tools_model._wrap_execute_tool_for_tool_router(
154 session_id=self.session_id,
155 modifiers=modifiers,
156 + inline_custom_tools_payload=self._inline_custom_tools_payload,
157 )
158
159 def tools(self, modifiers: t.Optional["Modifiers"] = None) -> TToolCollection:
@@ -698,12 +703,19 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
703 )
704
705 # Remote execution
701 - return self._client.tool_router.session.execute(
702 - session_id=self.session_id,
703 - tool_slug=tool_slug,
704 - arguments=arguments if arguments is not None else omit,
705 - account=account if account is not None else omit,
706 - )
706 + execute_kwargs: t.Dict[str, t.Any] = {
707 + "session_id": self.session_id,
708 + "tool_slug": tool_slug,
709 + "arguments": arguments if arguments is not None else omit,
710 + "account": account if account is not None else omit,
711 + }
712 + if self._inline_custom_tools_payload is not None:
713 + execute_kwargs["experimental"] = t.cast(
714 + session_execute_params.Experimental,
715 + self._inline_custom_tools_payload,
716 + )
717 +
718 + return self._client.tool_router.session.execute(**execute_kwargs)
719
720 def custom_tools(
721 self, *, toolkit: t.Optional[str] = None
python/composio/core/models/tools.py
+16 -6
@@ -15,8 +15,10 @@ from composio.client.types import (
15 tool_proxy_params,
16 tool_proxy_response,
17 )
18 +from composio_client.types.tool_router import session_execute_params
19 from composio.core.models._files import FileHelper
20 from composio.core.models.base import Resource
21 +from composio.core.models.custom_tool_types import InlineCustomToolsWirePayload
22 from composio.core.models.custom_tools import CustomTools
23 from composio.core.provider import TTool, TToolCollection
24 from composio.core.provider.agentic import AgenticProvider, AgenticProviderExecuteFn
@@ -456,6 +458,7 @@ class Tools(Resource, t.Generic[TTool, TToolCollection]):
458 self,
459 session_id: str,
460 modifiers: t.Optional[Modifiers] = None,
461 + inline_custom_tools_payload: t.Optional[InlineCustomToolsWirePayload] = None,
462 ) -> AgenticProviderExecuteFn:
463 """
464 Create an execute function for tool router session tools.
@@ -533,14 +536,21 @@ class Tools(Resource, t.Generic[TTool, TToolCollection]):
536 # Serialize any Pydantic model instances before sending to the API
537 processed_arguments = _serialize_arguments(processed_arguments)
538
536 - response = self._client.tool_router.session.execute(
537 - session_id=session_id,
538 - tool_slug=slug,
539 - arguments=processed_arguments,
539 + execute_kwargs: t.Dict[str, t.Any] = {
540 + "session_id": session_id,
541 + "tool_slug": slug,
542 + "arguments": processed_arguments,
543 # Provider-wrapped session tools are agentic calls, so they opt into
544 # direct tool offload when the backend session workbench allows it.
542 - enable_auto_workbench_offload=True,
543 - )
545 + "enable_auto_workbench_offload": True,
546 + }
547 + if inline_custom_tools_payload is not None:
548 + execute_kwargs["experimental"] = t.cast(
549 + session_execute_params.Experimental,
550 + inline_custom_tools_payload,
551 + )
552 +
553 + response = self._client.tool_router.session.execute(**execute_kwargs)
554
555 # Convert response to standard format
556 result: ToolExecutionResponse = {
python/tests/test_custom_tools.py
+79 -1
@@ -571,6 +571,35 @@ class TestSessionContextImpl:
571 arguments={"arg": "val"},
572 )
573
574 + def test_remote_fallback_passes_inline_custom_tools(self):
575 + mock_client = MagicMock()
576 + mock_client.tool_router.session.execute.return_value = SessionExecuteResponse(
577 + data={"remote": True}, error=None, log_id="log_123"
578 + )
579 + inline_payload = {
580 + "custom_tools": [
581 + {
582 + "slug": "GREP",
583 + "name": "Grep",
584 + "description": "Search local text",
585 + "input_schema": {"type": "object", "properties": {}},
586 + }
587 + ]
588 + }
589 + ctx = SessionContextImpl(
590 + client=mock_client,
591 + user_id="u",
592 + session_id="s",
593 + inline_custom_tools_payload=inline_payload,
594 + )
595 + ctx.execute("GMAIL_SEND_EMAIL", {"to": "a@b.com"})
596 + mock_client.tool_router.session.execute.assert_called_once_with(
597 + session_id="s",
598 + tool_slug="GMAIL_SEND_EMAIL",
599 + arguments={"to": "a@b.com"},
600 + experimental=inline_payload,
601 + )
602 +
603 def test_proxy_execute(self):
604 mock_client = MagicMock()
605 mock_client.tool_router.session.proxy_execute.return_value = (
@@ -648,6 +677,29 @@ class TestToolRouterSessionCustomTools:
677 assert result.data == {"sent": True}
678 assert result.log_id == "log_123"
679
680 + def test_execute_remote_passes_inline_custom_tools(self, mock_session_deps):
681 + mock_response = SessionExecuteResponse(
682 + data={"sent": True}, error=None, log_id="log_123"
683 + )
684 + mock_session_deps[
685 + "client"
686 + ].tool_router.session.execute.return_value = mock_response
687 + inline_payload = {
688 + "custom_tools": [
689 + {
690 + "slug": "GREP",
691 + "name": "Grep",
692 + "description": "Search local text",
693 + "input_schema": {"type": "object", "properties": {}},
694 + }
695 + ]
696 + }
697 + s = _session(mock_session_deps, inline_custom_tools_payload=inline_payload)
698 + s.execute("GMAIL_SEND_EMAIL", arguments={"to": "a@b.com"})
699 +
700 + call_args = mock_session_deps["client"].tool_router.session.execute.call_args
701 + assert call_args.kwargs["experimental"] == inline_payload
702 +
703 def test_proxy_execute(self, mock_session_deps):
704 mock_session_deps[
705 "client"
@@ -693,7 +745,7 @@ class TestToolRouterSessionCustomTools:
745
746
747 class TestMultiExecuteRouting:
696 - def _make_session(self, *tools):
748 + def _make_session(self, *tools, inline_custom_tools_payload=None):
749 m = build_custom_tools_map(list(tools))
750 return ToolRouterSession(
751 client=MagicMock(),
@@ -704,6 +756,7 @@ class TestMultiExecuteRouting:
756 experimental=MagicMock(),
757 custom_tools_map=m,
758 user_id="u",
759 + inline_custom_tools_payload=inline_custom_tools_payload,
760 )
761
762 def test_single_local(self, grep_tool):
@@ -725,6 +778,31 @@ class TestMultiExecuteRouting:
778 )
779 assert result == remote
780
781 + def test_all_remote_passes_inline_custom_tools(self, grep_tool):
782 + inline_payload = {
783 + "custom_tools": [
784 + {
785 + "slug": "GREP",
786 + "name": "Grep",
787 + "description": "Search local text",
788 + "input_schema": {"type": "object", "properties": {}},
789 + }
790 + ]
791 + }
792 + s = self._make_session(grep_tool, inline_custom_tools_payload=inline_payload)
793 + tm = MagicMock()
794 + remote = {"data": {"results": []}, "error": None, "successful": True}
795 + tm._wrap_execute_tool_for_tool_router.return_value = lambda slug, args: remote
796 + s._route_multi_execute(
797 + {"tools": [{"tool_slug": "REMOTE", "arguments": {}}]}, tm
798 + )
799 +
800 + tm._wrap_execute_tool_for_tool_router.assert_called_once_with(
801 + session_id="s",
802 + modifiers=None,
803 + inline_custom_tools_payload=inline_payload,
804 + )
805 +
806 def test_mixed(self, grep_tool):
807 s = self._make_session(grep_tool)
808 tm = MagicMock()
python/tests/test_tool_router.py
+41
@@ -1583,6 +1583,47 @@ class TestToolRouterExecution:
1583 assert result["error"] is None
1584 assert result["successful"] is True
1585
1586 + def test_execute_endpoint_passes_inline_custom_tools(
1587 + self, tool_router, mock_client, mock_provider
1588 + ):
1589 + """Provider-wrapped session tools pass inline custom definitions."""
1590 + mock_execute_response = MagicMock()
1591 + mock_execute_response.data = {"result": "success"}
1592 + mock_execute_response.error = None
1593 + mock_client.tool_router.session.execute.return_value = mock_execute_response
1594 +
1595 + from composio.core.models.tools import Tools as RealTools
1596 +
1597 + inline_payload = {
1598 + "custom_tools": [
1599 + {
1600 + "slug": "GREP",
1601 + "name": "Grep",
1602 + "description": "Search local text",
1603 + "input_schema": {"type": "object", "properties": {}},
1604 + }
1605 + ]
1606 + }
1607 + real_tools = RealTools(
1608 + client=mock_client,
1609 + provider=mock_provider,
1610 + dangerously_allow_auto_upload_download_files=False,
1611 + )
1612 + execute_fn = real_tools._wrap_execute_tool_for_tool_router(
1613 + session_id="session_123",
1614 + inline_custom_tools_payload=inline_payload,
1615 + )
1616 +
1617 + execute_fn("GMAIL_SEND_EMAIL", {"to": "test@example.com"})
1618 +
1619 + mock_client.tool_router.session.execute.assert_called_once_with(
1620 + session_id="session_123",
1621 + tool_slug="GMAIL_SEND_EMAIL",
1622 + arguments={"to": "test@example.com"},
1623 + enable_auto_workbench_offload=True,
1624 + experimental=inline_payload,
1625 + )
1626 +
1627 def test_modifiers_applied_in_tool_router_execution(
1628 self, tool_router, mock_client, mock_provider
1629 ):
ts/packages/core/src/models/SessionContext.ts
+20 -4
@@ -2,7 +2,11 @@
2 * @fileoverview Session context implementation injected into custom tool execute functions.
3 */
4 import { Composio as ComposioClient } from '@composio/client';
5 -import type { SessionContext, CustomToolsMap } from '../types/customTool.types';
5 +import type {
6 + SessionContext,
7 + CustomToolsMap,
8 + InlineCustomToolsWirePayload,
9 +} from '../types/customTool.types';
10 import type {
11 SessionProxyExecuteParams,
12 ToolRouterSessionExecuteResponse,
@@ -16,6 +20,7 @@ import { ValidationError } from '../errors';
20 import { transformProxyParams } from './proxyParamsTransform';
21 import { findCustomTool, executeCustomTool } from './customToolExecution';
22 import { transformExecuteResponse } from '../utils/transformers/toolRouterResponseTransform';
23 +import type { SessionExecuteParams } from '@composio/client/resources/tool-router/session/session.mjs';
24
25 /**
26 * Concrete implementation of SessionContext.
@@ -33,7 +38,8 @@ export class SessionContextImpl implements SessionContext {
38 private readonly client: ComposioClient,
39 userId: string,
40 private readonly sessionId: string,
36 - private readonly customToolsMap?: CustomToolsMap
41 + private readonly customToolsMap?: CustomToolsMap,
42 + private readonly inlineCustomToolsPayload?: InlineCustomToolsWirePayload
43 ) {
44 this.userId = userId;
45 }
@@ -61,13 +67,23 @@ export class SessionContextImpl implements SessionContext {
67 }
68
69 // Fall back to remote execution
64 - const response = await this.client.toolRouter.session.execute(this.sessionId, {
70 + const executeParams: SessionExecuteParams = {
71 tool_slug: toolSlug,
72 arguments: arguments_,
67 - });
73 + };
74 + const experimental = this.inlineExecuteExperimental();
75 + if (experimental) {
76 + executeParams.experimental = experimental;
77 + }
78 +
79 + const response = await this.client.toolRouter.session.execute(this.sessionId, executeParams);
80 return ToolRouterSessionExecuteResponseSchema.parse(transformExecuteResponse(response));
81 }
82
83 + private inlineExecuteExperimental(): SessionExecuteParams.Experimental | undefined {
84 + return this.inlineCustomToolsPayload as SessionExecuteParams.Experimental | undefined;
85 + }
86 +
87 /**
88 * Proxy API calls through Composio's auth layer.
89 * The backend resolves the connected account from the toolkit within the session.
ts/packages/core/src/models/ToolRouterSession.ts
+43 -7
@@ -39,7 +39,10 @@ import type {
39 } from '../types/customTool.types';
40 import type { Tool, ToolExecuteResponse } from '../types/tool.types';
41 import type { SessionProxyExecuteParams } from '../types/toolRouter.types';
42 -import type { SessionExecuteParams } from '@composio/client/resources/tool-router/session/session.mjs';
42 +import type {
43 + SessionExecuteParams,
44 + SessionSearchParams,
45 +} from '@composio/client/resources/tool-router/session/session.mjs';
46 import { SessionProxyExecuteParamsSchema } from '../types/toolRouter.types';
47 import { SessionContextImpl } from './SessionContext';
48 import { findCustomTool, executeCustomTool } from './customToolExecution';
@@ -94,7 +97,13 @@ export class ToolRouterSession<
97
98 // Create singleton session context if custom tools are bound
99 if (customToolsMap && userId) {
97 - this.sessionContext = new SessionContextImpl(client, userId, sessionId, customToolsMap);
100 + this.sessionContext = new SessionContextImpl(
101 + client,
102 + userId,
103 + sessionId,
104 + customToolsMap,
105 + this.inlineCustomToolsPayload
106 + );
107 }
108
109 telemetry.instrument(this, 'ToolRouterSession');
@@ -133,7 +142,8 @@ export class ToolRouterSession<
142 toolSlug,
143 { sessionId: this.sessionId, arguments: input },
144 modifiers,
136 - toolBySlug.get(toolSlug.toUpperCase())
145 + toolBySlug.get(toolSlug.toUpperCase()),
146 + { experimental: this.inlineExecuteExperimental() }
147 );
148 };
149
@@ -360,10 +370,11 @@ export class ToolRouterSession<
370 query: string;
371 toolkits?: string[];
372 }): Promise<ToolRouterSessionSearchResponse> {
373 + const experimental = this.inlineSearchExperimental();
374 const searchParams = {
375 queries: [{ use_case: params.query }],
376 ...(params.toolkits?.length ? { toolkits: params.toolkits } : {}),
366 - ...(this.inlineCustomToolsPayload ? { experimental: this.inlineCustomToolsPayload } : {}),
377 + ...(experimental ? { experimental } : {}),
378 };
379 const response = await this.client.toolRouter.session.search(this.sessionId, searchParams);
380 const transformed = transformSearchResponse(response);
@@ -407,6 +418,10 @@ export class ToolRouterSession<
418 if (options?.account) {
419 executeParams.account = options.account;
420 }
421 + const experimental = this.inlineExecuteExperimental();
422 + if (experimental) {
423 + executeParams.experimental = experimental;
424 + }
425
426 const response = await this.client.toolRouter.session.execute(this.sessionId, executeParams);
427 const transformed = transformExecuteResponse(response);
@@ -458,6 +473,24 @@ export class ToolRouterSession<
473 return (this.customToolsMap?.byFinalSlug.size ?? 0) > 0;
474 }
475
476 + private withInlineCustomToolsExperimental<T extends object>(experimental?: T): T | undefined {
477 + if (!this.inlineCustomToolsPayload) {
478 + return experimental;
479 + }
480 + return {
481 + ...(experimental ?? {}),
482 + ...this.inlineCustomToolsPayload,
483 + } as T;
484 + }
485 +
486 + private inlineExecuteExperimental(): SessionExecuteParams.Experimental | undefined {
487 + return this.withInlineCustomToolsExperimental<SessionExecuteParams.Experimental>();
488 + }
489 +
490 + private inlineSearchExperimental(): SessionSearchParams.Experimental | undefined {
491 + return this.withInlineCustomToolsExperimental<SessionSearchParams.Experimental>();
492 + }
493 +
494 /** Parse an individual tool item from COMPOSIO_MULTI_EXECUTE_TOOL's tools array */
495 private parseToolItem(item: unknown): { tool_slug: string; arguments: Record<string, unknown> } {
496 if (typeof item !== 'object' || item === null) {
@@ -489,7 +522,8 @@ export class ToolRouterSession<
522 COMPOSIO_MULTI_EXECUTE_TOOL,
523 { sessionId: this.sessionId, arguments: input },
524 modifiers,
492 - multiExecuteTool
525 + multiExecuteTool,
526 + { experimental: this.inlineExecuteExperimental() }
527 );
528 }
529
@@ -513,7 +547,8 @@ export class ToolRouterSession<
547 COMPOSIO_MULTI_EXECUTE_TOOL,
548 { sessionId: this.sessionId, arguments: input },
549 modifiers,
516 - multiExecuteTool
550 + multiExecuteTool,
551 + { experimental: this.inlineExecuteExperimental() }
552 );
553 }
554
@@ -533,7 +568,8 @@ export class ToolRouterSession<
568 COMPOSIO_MULTI_EXECUTE_TOOL,
569 { sessionId: this.sessionId, arguments: remoteInput },
570 modifiers,
536 - multiExecuteTool
571 + multiExecuteTool,
572 + { experimental: this.inlineExecuteExperimental() }
573 );
574 }
575
ts/packages/core/src/models/Tools.ts
+10 -2
@@ -54,13 +54,17 @@ import { telemetry } from '../telemetry/Telemetry';
54 import { ComposioConfig } from '../composio';
55 import { getToolkitVersion } from '../utils/toolkitVersion';
56 import { handleToolExecutionError } from '../errors/ToolErrors';
57 -import type { SessionExecuteParams } from '@composio/client/resources/tool-router.mjs';
57 +import type { SessionExecuteParams } from '@composio/client/resources/tool-router/session/session.mjs';
58 import { CONFIG_DEFAULTS } from '../utils/config-defaults';
59 import { resolveEffectiveUploadAllowlist } from '../utils/fileDirs';
60 import { schemaHasFileUploadable } from '../utils/modifiers/FileToolModifier.utils.neutral';
61
62 const TOOL_ROUTER_SESSION_TOOLS_PAGE_LIMIT = 500;
63
64 +type ToolRouterSessionExecuteOptions = {
65 + experimental?: SessionExecuteParams.Experimental;
66 +};
67 +
68 /**
69 * This class is used to manage tools in the Composio SDK.
70 * It provides methods to list, get, and execute tools.
@@ -1028,7 +1032,8 @@ export class Tools<
1032 toolSlug: string,
1033 body: ToolExecuteMetaParams,
1034 modifiers?: SessionExecuteMetaModifiers,
1031 - tool?: Tool
1035 + tool?: Tool,
1036 + options?: ToolRouterSessionExecuteOptions
1037 ): Promise<ToolExecuteResponse> {
1038 const executeParams = ToolExecuteMetaParamsSchema.safeParse(body);
1039 if (!executeParams.success) {
@@ -1056,6 +1061,9 @@ export class Tools<
1061 // direct tool offload when the backend session workbench allows it.
1062 enable_auto_workbench_offload: true,
1063 };
1064 + if (options?.experimental) {
1065 + executePayload.experimental = options.experimental;
1066 + }
1067
1068 const response = await this.client.toolRouter.session.execute(body.sessionId, executePayload);
1069
ts/packages/core/test/models/customTool.test.ts
+28
@@ -570,6 +570,34 @@ describe('SessionContextImpl', () => {
570 });
571 });
572
573 + it('should pass inline custom tools when delegating execute() to backend', async () => {
574 + mockClient.toolRouter.session.execute.mockResolvedValue({
575 + data: { result: 'ok' },
576 + error: null,
577 + log_id: 'log_1',
578 + });
579 +
580 + const ctx = new SessionContextImpl(mockClient as any, 'user_1', 'sess_1', undefined, {
581 + custom_tools: [
582 + {
583 + slug: 'GREP',
584 + name: 'Grep',
585 + description: 'Search local text',
586 + input_schema: { type: 'object', properties: {} },
587 + },
588 + ],
589 + });
590 + await ctx.execute('GMAIL_SEND_EMAIL', { to: 'test@test.com' });
591 +
592 + expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith('sess_1', {
593 + tool_slug: 'GMAIL_SEND_EMAIL',
594 + arguments: { to: 'test@test.com' },
595 + experimental: {
596 + custom_tools: [expect.objectContaining({ slug: 'GREP' })],
597 + },
598 + });
599 + });
600 +
601 it('should preserve logId and error when execute() returns an error', async () => {
602 mockClient.toolRouter.session.execute.mockResolvedValue({
603 data: {},
ts/packages/core/test/models/toolRouter.test.ts
+150
@@ -2332,6 +2332,41 @@ describe('ToolRouter', () => {
2332 account: 'work',
2333 });
2334 });
2335 +
2336 + it('should pass inline custom tools to remote execute when custom tools are bound', async () => {
2337 + const grepTool = createCustomTool('GREP', {
2338 + name: 'Grep',
2339 + description: 'Search local text',
2340 + inputParams: z.object({ pattern: z.string() }),
2341 + execute: vi.fn(async () => ({ matches: [] })),
2342 + });
2343 + mockClient.toolRouter.session.create.mockResolvedValueOnce({
2344 + ...mockSessionCreateResponse,
2345 + experimental: {
2346 + custom_tools: [
2347 + {
2348 + slug: 'LOCAL_GREP',
2349 + original_slug: 'GREP',
2350 + extends_toolkit: null,
2351 + },
2352 + ],
2353 + },
2354 + });
2355 + mockClient.toolRouter.session.execute.mockResolvedValueOnce(mockExecuteResponse);
2356 +
2357 + const session = await toolRouter.create(userId, {
2358 + experimental: { customTools: [grepTool] },
2359 + });
2360 + await session.execute('GMAIL_SEND_EMAIL', { to: 'user@example.com' });
2361 +
2362 + expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith(sessionId, {
2363 + tool_slug: 'GMAIL_SEND_EMAIL',
2364 + arguments: { to: 'user@example.com' },
2365 + experimental: {
2366 + custom_tools: [expect.objectContaining({ slug: 'GREP' })],
2367 + },
2368 + });
2369 + });
2370 });
2371
2372 describe('tools function', () => {
@@ -2495,6 +2530,121 @@ describe('ToolRouter', () => {
2530 expect(mockClient.toolRouter.session.execute).not.toHaveBeenCalled();
2531 });
2532
2533 + it('should pass inline custom tools when routing remote provider executions', async () => {
2534 + const grepTool = createCustomTool('GREP', {
2535 + name: 'Grep',
2536 + description: 'Search local text',
2537 + inputParams: z.object({ pattern: z.string() }),
2538 + execute: vi.fn(async () => ({ matches: [] })),
2539 + });
2540 + const executeSessionTool = vi.fn().mockResolvedValue({
2541 + data: { ok: true },
2542 + error: null,
2543 + successful: true,
2544 + });
2545 + (Tools as any).mockImplementation(() => ({
2546 + getRawToolRouterSessionTools: vi
2547 + .fn()
2548 + .mockResolvedValue([
2549 + { slug: 'COMPOSIO_SEARCH_TOOLS' },
2550 + { slug: 'GMAIL_SEND_EMAIL', toolkit: { slug: 'gmail', name: 'Gmail' } },
2551 + ]),
2552 + executeSessionTool,
2553 + }));
2554 + mockClient.toolRouter.session.create.mockResolvedValueOnce({
2555 + ...mockSessionCreateResponse,
2556 + experimental: {
2557 + custom_tools: [
2558 + {
2559 + slug: 'LOCAL_GREP',
2560 + original_slug: 'GREP',
2561 + extends_toolkit: null,
2562 + },
2563 + ],
2564 + },
2565 + });
2566 + mockProvider.wrapTools.mockReturnValue('mocked-custom-tools');
2567 +
2568 + const session = await toolRouter.create(userId, {
2569 + experimental: { customTools: [grepTool] },
2570 + });
2571 + await session.tools();
2572 + const routingExecute = mockProvider.wrapTools.mock.calls[0][1] as (
2573 + toolSlug: string,
2574 + input: Record<string, unknown>
2575 + ) => Promise<unknown>;
2576 + await routingExecute('GMAIL_SEND_EMAIL', { to: 'user@example.com' });
2577 +
2578 + expect(executeSessionTool).toHaveBeenCalledWith(
2579 + 'GMAIL_SEND_EMAIL',
2580 + { sessionId, arguments: { to: 'user@example.com' } },
2581 + undefined,
2582 + { slug: 'GMAIL_SEND_EMAIL', toolkit: { slug: 'gmail', name: 'Gmail' } },
2583 + {
2584 + experimental: {
2585 + custom_tools: [expect.objectContaining({ slug: 'GREP' })],
2586 + },
2587 + }
2588 + );
2589 + });
2590 +
2591 + it('should pass inline custom tools when routing remote multi-execute batches', async () => {
2592 + const grepTool = createCustomTool('GREP', {
2593 + name: 'Grep',
2594 + description: 'Search local text',
2595 + inputParams: z.object({ pattern: z.string() }),
2596 + execute: vi.fn(async () => ({ matches: [] })),
2597 + });
2598 + const executeSessionTool = vi.fn().mockResolvedValue({
2599 + data: { results: [] },
2600 + error: null,
2601 + successful: true,
2602 + });
2603 + const multiExecuteTool = { slug: 'COMPOSIO_MULTI_EXECUTE_TOOL' };
2604 + (Tools as any).mockImplementation(() => ({
2605 + getRawToolRouterSessionTools: vi
2606 + .fn()
2607 + .mockResolvedValue([{ slug: 'COMPOSIO_SEARCH_TOOLS' }, multiExecuteTool]),
2608 + executeSessionTool,
2609 + }));
2610 + mockClient.toolRouter.session.create.mockResolvedValueOnce({
2611 + ...mockSessionCreateResponse,
2612 + experimental: {
2613 + custom_tools: [
2614 + {
2615 + slug: 'LOCAL_GREP',
2616 + original_slug: 'GREP',
2617 + extends_toolkit: null,
2618 + },
2619 + ],
2620 + },
2621 + });
2622 + mockProvider.wrapTools.mockReturnValue('mocked-custom-tools');
2623 +
2624 + const session = await toolRouter.create(userId, {
2625 + experimental: { customTools: [grepTool] },
2626 + });
2627 + await session.tools();
2628 + const routingExecute = mockProvider.wrapTools.mock.calls[0][1] as (
2629 + toolSlug: string,
2630 + input: Record<string, unknown>
2631 + ) => Promise<unknown>;
2632 + const input = { tools: [{ tool_slug: 'GMAIL_SEND_EMAIL', arguments: { to: 'a@b.com' } }] };
2633 + await routingExecute('COMPOSIO_MULTI_EXECUTE_TOOL', input);
2634 +
2635 + expect(executeSessionTool).toHaveBeenCalledWith(
2636 + 'COMPOSIO_MULTI_EXECUTE_TOOL',
2637 + { sessionId, arguments: input },
2638 + undefined,
2639 + multiExecuteTool,
2640 + {
2641 + experimental: {
2642 + custom_tools: [expect.objectContaining({ slug: 'GREP' })],
2643 + },
2644 + }
2645 + );
2646 + });
2647 +
2648 it('should not expose custom tools unless SDK preload selects them', async () => {
2649 const grepTool = createCustomTool('GREP', {
2650 name: 'Grep',
ts/packages/core/test/tools/tools.test.ts
+36
@@ -1073,6 +1073,42 @@ describe('Tools', () => {
1073 });
1074 });
1075
1076 + it('should pass inline custom tools to tool router session execute', async () => {
1077 + const toolSlug = 'COMPOSIO_TOOL';
1078 + const body = {
1079 + sessionId,
1080 + arguments: { query: 'test' },
1081 + };
1082 +
1083 + mockClient.toolRouter.session.execute.mockResolvedValueOnce({
1084 + data: { results: true },
1085 + error: null,
1086 + log_id: '123',
1087 + });
1088 +
1089 + await context.tools.executeSessionTool(toolSlug, body, undefined, undefined, {
1090 + experimental: {
1091 + custom_tools: [
1092 + {
1093 + slug: 'GREP',
1094 + name: 'Grep',
1095 + description: 'Search local text',
1096 + input_schema: { type: 'object', properties: {} },
1097 + },
1098 + ],
1099 + },
1100 + });
1101 +
1102 + expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith(sessionId, {
1103 + tool_slug: toolSlug,
1104 + arguments: body.arguments,
1105 + enable_auto_workbench_offload: true,
1106 + experimental: {
1107 + custom_tools: [expect.objectContaining({ slug: 'GREP' })],
1108 + },
1109 + });
1110 + });
1111 +
1112 it('should throw validation error for invalid parameters', async () => {
1113 const invalidBody = {
1114 // missing sessionId