Skip to content

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 Upadhyayd97fc8e17d48
diff --git a/python/composio/core/models/session_context.py b/python/composio/core/models/session_context.py
index e0ea91aeb..a23c5591a 100644
--- a/python/composio/core/models/session_context.py
+++ b/python/composio/core/models/session_context.py
@@ -16,13 +16,17 @@ from composio_client.types.tool_router.session_execute_response import (
from composio_client.types.tool_router.session_proxy_execute_response import (
SessionProxyExecuteResponse,
)
+from composio_client.types.tool_router import session_execute_params
from composio.client import HttpClient
from composio.core.models.custom_tool_execution import (
execute_custom_tool,
find_custom_tool,
)
-from composio.core.models.custom_tool_types import CustomToolsMap
+from composio.core.models.custom_tool_types import (
+ CustomToolsMap,
+ InlineCustomToolsWirePayload,
+)
from composio.core.models.tools import _serialize_arguments
from composio.exceptions import ValidationError
@@ -99,11 +103,13 @@ class SessionContextImpl:
user_id: str,
session_id: str,
custom_tools_map: t.Optional[CustomToolsMap] = None,
+ inline_custom_tools_payload: t.Optional[InlineCustomToolsWirePayload] = None,
) -> None:
self._client = client
self._user_id = user_id
self._session_id = session_id
self._custom_tools_map = custom_tools_map
+ self._inline_custom_tools_payload = inline_custom_tools_payload
@property
def user_id(self) -> str:
@@ -136,11 +142,18 @@ class SessionContextImpl:
serialized = _serialize_arguments(arguments)
# Fall back to remote execution
- return self._client.tool_router.session.execute(
- session_id=self._session_id,
- tool_slug=tool_slug,
- arguments=serialized,
- )
+ execute_kwargs: t.Dict[str, t.Any] = {
+ "session_id": self._session_id,
+ "tool_slug": tool_slug,
+ "arguments": serialized,
+ }
+ if self._inline_custom_tools_payload is not None:
+ execute_kwargs["experimental"] = t.cast(
+ session_execute_params.Experimental,
+ self._inline_custom_tools_payload,
+ )
+
+ return self._client.tool_router.session.execute(**execute_kwargs)
def proxy_execute(
self,
diff --git a/python/composio/core/models/tool_router_session.py b/python/composio/core/models/tool_router_session.py
index 6b879a63f..36a3395c8 100644
--- a/python/composio/core/models/tool_router_session.py
+++ b/python/composio/core/models/tool_router_session.py
@@ -28,7 +28,10 @@ from composio_client.types.tool_router.session_proxy_execute_response import (
from composio_client.types.tool_router.session_search_response import (
SessionSearchResponse,
)
-from composio_client.types.tool_router import session_search_params
+from composio_client.types.tool_router import (
+ session_execute_params,
+ session_search_params,
+)
from composio.client import HttpClient
from composio.core.models.connected_accounts import ConnectionRequest
@@ -132,6 +135,7 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
user_id=user_id,
session_id=session_id,
custom_tools_map=custom_tools_map,
+ inline_custom_tools_payload=inline_custom_tools_payload,
)
def _has_custom_tools(self) -> bool:
@@ -149,6 +153,7 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
return tools_model._wrap_execute_tool_for_tool_router(
session_id=self.session_id,
modifiers=modifiers,
+ inline_custom_tools_payload=self._inline_custom_tools_payload,
)
def tools(self, modifiers: t.Optional["Modifiers"] = None) -> TToolCollection:
@@ -698,12 +703,19 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
)
# Remote execution
- return self._client.tool_router.session.execute(
- session_id=self.session_id,
- tool_slug=tool_slug,
- arguments=arguments if arguments is not None else omit,
- account=account if account is not None else omit,
- )
+ execute_kwargs: t.Dict[str, t.Any] = {
+ "session_id": self.session_id,
+ "tool_slug": tool_slug,
+ "arguments": arguments if arguments is not None else omit,
+ "account": account if account is not None else omit,
+ }
+ if self._inline_custom_tools_payload is not None:
+ execute_kwargs["experimental"] = t.cast(
+ session_execute_params.Experimental,
+ self._inline_custom_tools_payload,
+ )
+
+ return self._client.tool_router.session.execute(**execute_kwargs)
def custom_tools(
self, *, toolkit: t.Optional[str] = None
diff --git a/python/composio/core/models/tools.py b/python/composio/core/models/tools.py
index 55d389786..d9808b434 100644
--- a/python/composio/core/models/tools.py
+++ b/python/composio/core/models/tools.py
@@ -15,8 +15,10 @@ from composio.client.types import (
tool_proxy_params,
tool_proxy_response,
)
+from composio_client.types.tool_router import session_execute_params
from composio.core.models._files import FileHelper
from composio.core.models.base import Resource
+from composio.core.models.custom_tool_types import InlineCustomToolsWirePayload
from composio.core.models.custom_tools import CustomTools
from composio.core.provider import TTool, TToolCollection
from composio.core.provider.agentic import AgenticProvider, AgenticProviderExecuteFn
@@ -456,6 +458,7 @@ class Tools(Resource, t.Generic[TTool, TToolCollection]):
self,
session_id: str,
modifiers: t.Optional[Modifiers] = None,
+ inline_custom_tools_payload: t.Optional[InlineCustomToolsWirePayload] = None,
) -> AgenticProviderExecuteFn:
"""
Create an execute function for tool router session tools.
@@ -533,14 +536,21 @@ class Tools(Resource, t.Generic[TTool, TToolCollection]):
# Serialize any Pydantic model instances before sending to the API
processed_arguments = _serialize_arguments(processed_arguments)
- response = self._client.tool_router.session.execute(
- session_id=session_id,
- tool_slug=slug,
- arguments=processed_arguments,
+ execute_kwargs: t.Dict[str, t.Any] = {
+ "session_id": session_id,
+ "tool_slug": slug,
+ "arguments": processed_arguments,
# Provider-wrapped session tools are agentic calls, so they opt into
# direct tool offload when the backend session workbench allows it.
- enable_auto_workbench_offload=True,
- )
+ "enable_auto_workbench_offload": True,
+ }
+ if inline_custom_tools_payload is not None:
+ execute_kwargs["experimental"] = t.cast(
+ session_execute_params.Experimental,
+ inline_custom_tools_payload,
+ )
+
+ response = self._client.tool_router.session.execute(**execute_kwargs)
# Convert response to standard format
result: ToolExecutionResponse = {
diff --git a/python/tests/test_custom_tools.py b/python/tests/test_custom_tools.py
index ebb315b4e..de13718fa 100644
--- a/python/tests/test_custom_tools.py
+++ b/python/tests/test_custom_tools.py
@@ -571,6 +571,35 @@ class TestSessionContextImpl:
arguments={"arg": "val"},
)
+ def test_remote_fallback_passes_inline_custom_tools(self):
+ mock_client = MagicMock()
+ mock_client.tool_router.session.execute.return_value = SessionExecuteResponse(
+ data={"remote": True}, error=None, log_id="log_123"
+ )
+ inline_payload = {
+ "custom_tools": [
+ {
+ "slug": "GREP",
+ "name": "Grep",
+ "description": "Search local text",
+ "input_schema": {"type": "object", "properties": {}},
+ }
+ ]
+ }
+ ctx = SessionContextImpl(
+ client=mock_client,
+ user_id="u",
+ session_id="s",
+ inline_custom_tools_payload=inline_payload,
+ )
+ ctx.execute("GMAIL_SEND_EMAIL", {"to": "[email protected]"})
+ mock_client.tool_router.session.execute.assert_called_once_with(
+ session_id="s",
+ tool_slug="GMAIL_SEND_EMAIL",
+ arguments={"to": "[email protected]"},
+ experimental=inline_payload,
+ )
+
def test_proxy_execute(self):
mock_client = MagicMock()
mock_client.tool_router.session.proxy_execute.return_value = (
@@ -648,6 +677,29 @@ class TestToolRouterSessionCustomTools:
assert result.data == {"sent": True}
assert result.log_id == "log_123"
+ def test_execute_remote_passes_inline_custom_tools(self, mock_session_deps):
+ mock_response = SessionExecuteResponse(
+ data={"sent": True}, error=None, log_id="log_123"
+ )
+ mock_session_deps[
+ "client"
+ ].tool_router.session.execute.return_value = mock_response
+ inline_payload = {
+ "custom_tools": [
+ {
+ "slug": "GREP",
+ "name": "Grep",
+ "description": "Search local text",
+ "input_schema": {"type": "object", "properties": {}},
+ }
+ ]
+ }
+ s = _session(mock_session_deps, inline_custom_tools_payload=inline_payload)
+ s.execute("GMAIL_SEND_EMAIL", arguments={"to": "[email protected]"})
+
+ call_args = mock_session_deps["client"].tool_router.session.execute.call_args
+ assert call_args.kwargs["experimental"] == inline_payload
+
def test_proxy_execute(self, mock_session_deps):
mock_session_deps[
"client"
@@ -693,7 +745,7 @@ class TestToolRouterSessionCustomTools:
class TestMultiExecuteRouting:
- def _make_session(self, *tools):
+ def _make_session(self, *tools, inline_custom_tools_payload=None):
m = build_custom_tools_map(list(tools))
return ToolRouterSession(
client=MagicMock(),
@@ -704,6 +756,7 @@ class TestMultiExecuteRouting:
experimental=MagicMock(),
custom_tools_map=m,
user_id="u",
+ inline_custom_tools_payload=inline_custom_tools_payload,
)
def test_single_local(self, grep_tool):
@@ -725,6 +778,31 @@ class TestMultiExecuteRouting:
)
assert result == remote
+ def test_all_remote_passes_inline_custom_tools(self, grep_tool):
+ inline_payload = {
+ "custom_tools": [
+ {
+ "slug": "GREP",
+ "name": "Grep",
+ "description": "Search local text",
+ "input_schema": {"type": "object", "properties": {}},
+ }
+ ]
+ }
+ s = self._make_session(grep_tool, inline_custom_tools_payload=inline_payload)
+ tm = MagicMock()
+ remote = {"data": {"results": []}, "error": None, "successful": True}
+ tm._wrap_execute_tool_for_tool_router.return_value = lambda slug, args: remote
+ s._route_multi_execute(
+ {"tools": [{"tool_slug": "REMOTE", "arguments": {}}]}, tm
+ )
+
+ tm._wrap_execute_tool_for_tool_router.assert_called_once_with(
+ session_id="s",
+ modifiers=None,
+ inline_custom_tools_payload=inline_payload,
+ )
+
def test_mixed(self, grep_tool):
s = self._make_session(grep_tool)
tm = MagicMock()
diff --git a/python/tests/test_tool_router.py b/python/tests/test_tool_router.py
index c6a91414d..b0a9c1d4a 100644
--- a/python/tests/test_tool_router.py
+++ b/python/tests/test_tool_router.py
@@ -1583,6 +1583,47 @@ class TestToolRouterExecution:
assert result["error"] is None
assert result["successful"] is True
+ def test_execute_endpoint_passes_inline_custom_tools(
+ self, tool_router, mock_client, mock_provider
+ ):
+ """Provider-wrapped session tools pass inline custom definitions."""
+ mock_execute_response = MagicMock()
+ mock_execute_response.data = {"result": "success"}
+ mock_execute_response.error = None
+ mock_client.tool_router.session.execute.return_value = mock_execute_response
+
+ from composio.core.models.tools import Tools as RealTools
+
+ inline_payload = {
+ "custom_tools": [
+ {
+ "slug": "GREP",
+ "name": "Grep",
+ "description": "Search local text",
+ "input_schema": {"type": "object", "properties": {}},
+ }
+ ]
+ }
+ real_tools = RealTools(
+ client=mock_client,
+ provider=mock_provider,
+ dangerously_allow_auto_upload_download_files=False,
+ )
+ execute_fn = real_tools._wrap_execute_tool_for_tool_router(
+ session_id="session_123",
+ inline_custom_tools_payload=inline_payload,
+ )
+
+ execute_fn("GMAIL_SEND_EMAIL", {"to": "[email protected]"})
+
+ mock_client.tool_router.session.execute.assert_called_once_with(
+ session_id="session_123",
+ tool_slug="GMAIL_SEND_EMAIL",
+ arguments={"to": "[email protected]"},
+ enable_auto_workbench_offload=True,
+ experimental=inline_payload,
+ )
+
def test_modifiers_applied_in_tool_router_execution(
self, tool_router, mock_client, mock_provider
):
diff --git a/ts/packages/core/src/models/SessionContext.ts b/ts/packages/core/src/models/SessionContext.ts
index cf21cca7f..92bbca1fe 100644
--- a/ts/packages/core/src/models/SessionContext.ts
+++ b/ts/packages/core/src/models/SessionContext.ts
@@ -2,7 +2,11 @@
* @fileoverview Session context implementation injected into custom tool execute functions.
*/
import { Composio as ComposioClient } from '@composio/client';
-import type { SessionContext, CustomToolsMap } from '../types/customTool.types';
+import type {
+ SessionContext,
+ CustomToolsMap,
+ InlineCustomToolsWirePayload,
+} from '../types/customTool.types';
import type {
SessionProxyExecuteParams,
ToolRouterSessionExecuteResponse,
@@ -16,6 +20,7 @@ import { ValidationError } from '../errors';
import { transformProxyParams } from './proxyParamsTransform';
import { findCustomTool, executeCustomTool } from './customToolExecution';
import { transformExecuteResponse } from '../utils/transformers/toolRouterResponseTransform';
+import type { SessionExecuteParams } from '@composio/client/resources/tool-router/session/session.mjs';
/**
* Concrete implementation of SessionContext.
@@ -33,7 +38,8 @@ export class SessionContextImpl implements SessionContext {
private readonly client: ComposioClient,
userId: string,
private readonly sessionId: string,
- private readonly customToolsMap?: CustomToolsMap
+ private readonly customToolsMap?: CustomToolsMap,
+ private readonly inlineCustomToolsPayload?: InlineCustomToolsWirePayload
) {
this.userId = userId;
}
@@ -61,13 +67,23 @@ export class SessionContextImpl implements SessionContext {
}
// Fall back to remote execution
- const response = await this.client.toolRouter.session.execute(this.sessionId, {
+ const executeParams: SessionExecuteParams = {
tool_slug: toolSlug,
arguments: arguments_,
- });
+ };
+ const experimental = this.inlineExecuteExperimental();
+ if (experimental) {
+ executeParams.experimental = experimental;
+ }
+
+ const response = await this.client.toolRouter.session.execute(this.sessionId, executeParams);
return ToolRouterSessionExecuteResponseSchema.parse(transformExecuteResponse(response));
}
+ private inlineExecuteExperimental(): SessionExecuteParams.Experimental | undefined {
+ return this.inlineCustomToolsPayload as SessionExecuteParams.Experimental | undefined;
+ }
+
/**
* Proxy API calls through Composio's auth layer.
* The backend resolves the connected account from the toolkit within the session.
diff --git a/ts/packages/core/src/models/ToolRouterSession.ts b/ts/packages/core/src/models/ToolRouterSession.ts
index fbae11581..93b0b71cf 100644
--- a/ts/packages/core/src/models/ToolRouterSession.ts
+++ b/ts/packages/core/src/models/ToolRouterSession.ts
@@ -39,7 +39,10 @@ import type {
} from '../types/customTool.types';
import type { Tool, ToolExecuteResponse } from '../types/tool.types';
import type { SessionProxyExecuteParams } from '../types/toolRouter.types';
-import type { SessionExecuteParams } from '@composio/client/resources/tool-router/session/session.mjs';
+import type {
+ SessionExecuteParams,
+ SessionSearchParams,
+} from '@composio/client/resources/tool-router/session/session.mjs';
import { SessionProxyExecuteParamsSchema } from '../types/toolRouter.types';
import { SessionContextImpl } from './SessionContext';
import { findCustomTool, executeCustomTool } from './customToolExecution';
@@ -94,7 +97,13 @@ export class ToolRouterSession<
// Create singleton session context if custom tools are bound
if (customToolsMap && userId) {
- this.sessionContext = new SessionContextImpl(client, userId, sessionId, customToolsMap);
+ this.sessionContext = new SessionContextImpl(
+ client,
+ userId,
+ sessionId,
+ customToolsMap,
+ this.inlineCustomToolsPayload
+ );
}
telemetry.instrument(this, 'ToolRouterSession');
@@ -133,7 +142,8 @@ export class ToolRouterSession<
toolSlug,
{ sessionId: this.sessionId, arguments: input },
modifiers,
- toolBySlug.get(toolSlug.toUpperCase())
+ toolBySlug.get(toolSlug.toUpperCase()),
+ { experimental: this.inlineExecuteExperimental() }
);
};
@@ -360,10 +370,11 @@ export class ToolRouterSession<
query: string;
toolkits?: string[];
}): Promise<ToolRouterSessionSearchResponse> {
+ const experimental = this.inlineSearchExperimental();
const searchParams = {
queries: [{ use_case: params.query }],
...(params.toolkits?.length ? { toolkits: params.toolkits } : {}),
- ...(this.inlineCustomToolsPayload ? { experimental: this.inlineCustomToolsPayload } : {}),
+ ...(experimental ? { experimental } : {}),
};
const response = await this.client.toolRouter.session.search(this.sessionId, searchParams);
const transformed = transformSearchResponse(response);
@@ -407,6 +418,10 @@ export class ToolRouterSession<
if (options?.account) {
executeParams.account = options.account;
}
+ const experimental = this.inlineExecuteExperimental();
+ if (experimental) {
+ executeParams.experimental = experimental;
+ }
const response = await this.client.toolRouter.session.execute(this.sessionId, executeParams);
const transformed = transformExecuteResponse(response);
@@ -458,6 +473,24 @@ export class ToolRouterSession<
return (this.customToolsMap?.byFinalSlug.size ?? 0) > 0;
}
+ private withInlineCustomToolsExperimental<T extends object>(experimental?: T): T | undefined {
+ if (!this.inlineCustomToolsPayload) {
+ return experimental;
+ }
+ return {
+ ...(experimental ?? {}),
+ ...this.inlineCustomToolsPayload,
+ } as T;
+ }
+
+ private inlineExecuteExperimental(): SessionExecuteParams.Experimental | undefined {
+ return this.withInlineCustomToolsExperimental<SessionExecuteParams.Experimental>();
+ }
+
+ private inlineSearchExperimental(): SessionSearchParams.Experimental | undefined {
+ return this.withInlineCustomToolsExperimental<SessionSearchParams.Experimental>();
+ }
+
/** Parse an individual tool item from COMPOSIO_MULTI_EXECUTE_TOOL's tools array */
private parseToolItem(item: unknown): { tool_slug: string; arguments: Record<string, unknown> } {
if (typeof item !== 'object' || item === null) {
@@ -489,7 +522,8 @@ export class ToolRouterSession<
COMPOSIO_MULTI_EXECUTE_TOOL,
{ sessionId: this.sessionId, arguments: input },
modifiers,
- multiExecuteTool
+ multiExecuteTool,
+ { experimental: this.inlineExecuteExperimental() }
);
}
@@ -513,7 +547,8 @@ export class ToolRouterSession<
COMPOSIO_MULTI_EXECUTE_TOOL,
{ sessionId: this.sessionId, arguments: input },
modifiers,
- multiExecuteTool
+ multiExecuteTool,
+ { experimental: this.inlineExecuteExperimental() }
);
}
@@ -533,7 +568,8 @@ export class ToolRouterSession<
COMPOSIO_MULTI_EXECUTE_TOOL,
{ sessionId: this.sessionId, arguments: remoteInput },
modifiers,
- multiExecuteTool
+ multiExecuteTool,
+ { experimental: this.inlineExecuteExperimental() }
);
}
diff --git a/ts/packages/core/src/models/Tools.ts b/ts/packages/core/src/models/Tools.ts
index 2a41261f2..86fc579c0 100644
--- a/ts/packages/core/src/models/Tools.ts
+++ b/ts/packages/core/src/models/Tools.ts
@@ -54,13 +54,17 @@ import { telemetry } from '../telemetry/Telemetry';
import { ComposioConfig } from '../composio';
import { getToolkitVersion } from '../utils/toolkitVersion';
import { handleToolExecutionError } from '../errors/ToolErrors';
-import type { SessionExecuteParams } from '@composio/client/resources/tool-router.mjs';
+import type { SessionExecuteParams } from '@composio/client/resources/tool-router/session/session.mjs';
import { CONFIG_DEFAULTS } from '../utils/config-defaults';
import { resolveEffectiveUploadAllowlist } from '../utils/fileDirs';
import { schemaHasFileUploadable } from '../utils/modifiers/FileToolModifier.utils.neutral';
const TOOL_ROUTER_SESSION_TOOLS_PAGE_LIMIT = 500;
+type ToolRouterSessionExecuteOptions = {
+ experimental?: SessionExecuteParams.Experimental;
+};
+
/**
* This class is used to manage tools in the Composio SDK.
* It provides methods to list, get, and execute tools.
@@ -1028,7 +1032,8 @@ export class Tools<
toolSlug: string,
body: ToolExecuteMetaParams,
modifiers?: SessionExecuteMetaModifiers,
- tool?: Tool
+ tool?: Tool,
+ options?: ToolRouterSessionExecuteOptions
): Promise<ToolExecuteResponse> {
const executeParams = ToolExecuteMetaParamsSchema.safeParse(body);
if (!executeParams.success) {
@@ -1056,6 +1061,9 @@ export class Tools<
// direct tool offload when the backend session workbench allows it.
enable_auto_workbench_offload: true,
};
+ if (options?.experimental) {
+ executePayload.experimental = options.experimental;
+ }
const response = await this.client.toolRouter.session.execute(body.sessionId, executePayload);
diff --git a/ts/packages/core/test/models/customTool.test.ts b/ts/packages/core/test/models/customTool.test.ts
index 498c80c92..7ed05edca 100644
--- a/ts/packages/core/test/models/customTool.test.ts
+++ b/ts/packages/core/test/models/customTool.test.ts
@@ -570,6 +570,34 @@ describe('SessionContextImpl', () => {
});
});
+ it('should pass inline custom tools when delegating execute() to backend', async () => {
+ mockClient.toolRouter.session.execute.mockResolvedValue({
+ data: { result: 'ok' },
+ error: null,
+ log_id: 'log_1',
+ });
+
+ const ctx = new SessionContextImpl(mockClient as any, 'user_1', 'sess_1', undefined, {
+ custom_tools: [
+ {
+ slug: 'GREP',
+ name: 'Grep',
+ description: 'Search local text',
+ input_schema: { type: 'object', properties: {} },
+ },
+ ],
+ });
+ await ctx.execute('GMAIL_SEND_EMAIL', { to: '[email protected]' });
+
+ expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith('sess_1', {
+ tool_slug: 'GMAIL_SEND_EMAIL',
+ arguments: { to: '[email protected]' },
+ experimental: {
+ custom_tools: [expect.objectContaining({ slug: 'GREP' })],
+ },
+ });
+ });
+
it('should preserve logId and error when execute() returns an error', async () => {
mockClient.toolRouter.session.execute.mockResolvedValue({
data: {},
diff --git a/ts/packages/core/test/models/toolRouter.test.ts b/ts/packages/core/test/models/toolRouter.test.ts
index 1799de267..f42826247 100644
--- a/ts/packages/core/test/models/toolRouter.test.ts
+++ b/ts/packages/core/test/models/toolRouter.test.ts
@@ -2332,6 +2332,41 @@ describe('ToolRouter', () => {
account: 'work',
});
});
+
+ it('should pass inline custom tools to remote execute when custom tools are bound', async () => {
+ const grepTool = createCustomTool('GREP', {
+ name: 'Grep',
+ description: 'Search local text',
+ inputParams: z.object({ pattern: z.string() }),
+ execute: vi.fn(async () => ({ matches: [] })),
+ });
+ mockClient.toolRouter.session.create.mockResolvedValueOnce({
+ ...mockSessionCreateResponse,
+ experimental: {
+ custom_tools: [
+ {
+ slug: 'LOCAL_GREP',
+ original_slug: 'GREP',
+ extends_toolkit: null,
+ },
+ ],
+ },
+ });
+ mockClient.toolRouter.session.execute.mockResolvedValueOnce(mockExecuteResponse);
+
+ const session = await toolRouter.create(userId, {
+ experimental: { customTools: [grepTool] },
+ });
+ await session.execute('GMAIL_SEND_EMAIL', { to: '[email protected]' });
+
+ expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith(sessionId, {
+ tool_slug: 'GMAIL_SEND_EMAIL',
+ arguments: { to: '[email protected]' },
+ experimental: {
+ custom_tools: [expect.objectContaining({ slug: 'GREP' })],
+ },
+ });
+ });
});
describe('tools function', () => {
@@ -2495,6 +2530,121 @@ describe('ToolRouter', () => {
expect(mockClient.toolRouter.session.execute).not.toHaveBeenCalled();
});
+ it('should pass inline custom tools when routing remote provider executions', async () => {
+ const grepTool = createCustomTool('GREP', {
+ name: 'Grep',
+ description: 'Search local text',
+ inputParams: z.object({ pattern: z.string() }),
+ execute: vi.fn(async () => ({ matches: [] })),
+ });
+ const executeSessionTool = vi.fn().mockResolvedValue({
+ data: { ok: true },
+ error: null,
+ successful: true,
+ });
+ (Tools as any).mockImplementation(() => ({
+ getRawToolRouterSessionTools: vi
+ .fn()
+ .mockResolvedValue([
+ { slug: 'COMPOSIO_SEARCH_TOOLS' },
+ { slug: 'GMAIL_SEND_EMAIL', toolkit: { slug: 'gmail', name: 'Gmail' } },
+ ]),
+ executeSessionTool,
+ }));
+ mockClient.toolRouter.session.create.mockResolvedValueOnce({
+ ...mockSessionCreateResponse,
+ experimental: {
+ custom_tools: [
+ {
+ slug: 'LOCAL_GREP',
+ original_slug: 'GREP',
+ extends_toolkit: null,
+ },
+ ],
+ },
+ });
+ mockProvider.wrapTools.mockReturnValue('mocked-custom-tools');
+
+ const session = await toolRouter.create(userId, {
+ experimental: { customTools: [grepTool] },
+ });
+ await session.tools();
+ const routingExecute = mockProvider.wrapTools.mock.calls[0][1] as (
+ toolSlug: string,
+ input: Record<string, unknown>
+ ) => Promise<unknown>;
+ await routingExecute('GMAIL_SEND_EMAIL', { to: '[email protected]' });
+
+ expect(executeSessionTool).toHaveBeenCalledWith(
+ 'GMAIL_SEND_EMAIL',
+ { sessionId, arguments: { to: '[email protected]' } },
+ undefined,
+ { slug: 'GMAIL_SEND_EMAIL', toolkit: { slug: 'gmail', name: 'Gmail' } },
+ {
+ experimental: {
+ custom_tools: [expect.objectContaining({ slug: 'GREP' })],
+ },
+ }
+ );
+ });
+
+ it('should pass inline custom tools when routing remote multi-execute batches', async () => {
+ const grepTool = createCustomTool('GREP', {
+ name: 'Grep',
+ description: 'Search local text',
+ inputParams: z.object({ pattern: z.string() }),
+ execute: vi.fn(async () => ({ matches: [] })),
+ });
+ const executeSessionTool = vi.fn().mockResolvedValue({
+ data: { results: [] },
+ error: null,
+ successful: true,
+ });
+ const multiExecuteTool = { slug: 'COMPOSIO_MULTI_EXECUTE_TOOL' };
+ (Tools as any).mockImplementation(() => ({
+ getRawToolRouterSessionTools: vi
+ .fn()
+ .mockResolvedValue([{ slug: 'COMPOSIO_SEARCH_TOOLS' }, multiExecuteTool]),
+ executeSessionTool,
+ }));
+ mockClient.toolRouter.session.create.mockResolvedValueOnce({
+ ...mockSessionCreateResponse,
+ experimental: {
+ custom_tools: [
+ {
+ slug: 'LOCAL_GREP',
+ original_slug: 'GREP',
+ extends_toolkit: null,
+ },
+ ],
+ },
+ });
+ mockProvider.wrapTools.mockReturnValue('mocked-custom-tools');
+
+ const session = await toolRouter.create(userId, {
+ experimental: { customTools: [grepTool] },
+ });
+ await session.tools();
+ const routingExecute = mockProvider.wrapTools.mock.calls[0][1] as (
+ toolSlug: string,
+ input: Record<string, unknown>
+ ) => Promise<unknown>;
+ const input = { tools: [{ tool_slug: 'GMAIL_SEND_EMAIL', arguments: { to: '[email protected]' } }] };
+ await routingExecute('COMPOSIO_MULTI_EXECUTE_TOOL', input);
+
+ expect(executeSessionTool).toHaveBeenCalledWith(
+ 'COMPOSIO_MULTI_EXECUTE_TOOL',
+ { sessionId, arguments: input },
+ undefined,
+ multiExecuteTool,
+ {
+ experimental: {
+ custom_tools: [expect.objectContaining({ slug: 'GREP' })],
+ },
+ }
+ );
+ });
+
it('should not expose custom tools unless SDK preload selects them', async () => {
const grepTool = createCustomTool('GREP', {
name: 'Grep',
diff --git a/ts/packages/core/test/tools/tools.test.ts b/ts/packages/core/test/tools/tools.test.ts
index 24f77cb2e..0b5c015e1 100644
--- a/ts/packages/core/test/tools/tools.test.ts
+++ b/ts/packages/core/test/tools/tools.test.ts
@@ -1073,6 +1073,42 @@ describe('Tools', () => {
});
});
+ it('should pass inline custom tools to tool router session execute', async () => {
+ const toolSlug = 'COMPOSIO_TOOL';
+ const body = {
+ sessionId,
+ arguments: { query: 'test' },
+ };
+
+ mockClient.toolRouter.session.execute.mockResolvedValueOnce({
+ data: { results: true },
+ error: null,
+ log_id: '123',
+ });
+
+ await context.tools.executeSessionTool(toolSlug, body, undefined, undefined, {
+ experimental: {
+ custom_tools: [
+ {
+ slug: 'GREP',
+ name: 'Grep',
+ description: 'Search local text',
+ input_schema: { type: 'object', properties: {} },
+ },
+ ],
+ },
+ });
+
+ expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith(sessionId, {
+ tool_slug: toolSlug,
+ arguments: body.arguments,
+ enable_auto_workbench_offload: true,
+ experimental: {
+ custom_tools: [expect.objectContaining({ slug: 'GREP' })],
+ },
+ });
+ });
+
it('should throw validation error for invalid parameters', async () => {
const invalidBody = {
// missing sessionId