Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
TypeScript agentic-aiagentsaiai-agentsaiagentsdeveloper-toolsfunction-callinggpt-4javascriptjsllmllmopsmcppythonremote-mcp-serverssetypescript
Add tool router preload support to Python SDK
Dhawal Upadhyayf846993a4d23
diff --git a/python/composio/core/models/tool_router.py b/python/composio/core/models/tool_router.pyindex 1df028c28..a460ed503 100644--- a/python/composio/core/models/tool_router.py+++ b/python/composio/core/models/tool_router.py@@ -27,7 +27,10 @@ from composio.core.models.custom_tool_types import (CustomTool,CustomToolsMap,)-from composio.core.models.tool_router_session import ToolRouterSession+from composio.core.models.tool_router_session import (+ ToolRouterSession,+ ToolRouterSessionPreloadConfig,+)from composio.core.models.tool_router_session_files import ToolRouterSessionFilesMountfrom composio.core.provider import TTool, TToolCollectionfrom composio.core.provider.base import BaseProvider@@ -206,6 +209,17 @@ class ToolRouterMultiAccountConfig(te.TypedDict, total=False):require_explicit_selection: bool+class ToolRouterPreloadConfig(te.TypedDict, total=False):+ """Configuration for tools preloaded into a tool router session.++ Attributes:+ tools: Tool slugs to expose directly in ``session.tools()`` and MCP+ tool lists without first calling search.+ """++ tools: t.List[str]++class ToolRouterAssistivePromptConfig(te.TypedDict, total=False):"""Configuration for assistive prompt generation.@@ -482,6 +496,7 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):connected_accounts: t.Optional[t.Dict[str, str]] = None,workbench: t.Optional[ToolRouterWorkbenchConfig] = None,multi_account: t.Optional[ToolRouterMultiAccountConfig] = None,+ preload: t.Optional[ToolRouterPreloadConfig] = None,experimental: t.Optional[ToolRouterExperimentalConfig] = None,) -> ToolRouterSession[TTool, TToolCollection]:"""@@ -563,6 +578,10 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):- 'require_explicit_selection' (bool): When True, require explicitaccount selection when multiple accounts are connected.Example: {'enable': True, 'max_accounts_per_toolkit': 3}+ :param preload: Optional preload configuration. Dict with:+ - 'tools' (List[str]): Tool slugs to expose directly in+ session.tools() and MCP tool lists.+ Example: {'tools': ['GMAIL_FETCH_EMAILS']}:param experimental: Optional experimental configuration (ToolRouterExperimentalConfig).Note: These features are experimental and may change.Dict with:@@ -773,6 +792,9 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):if multi_account is not None:create_params["multi_account"] = multi_account+ if preload is not None:+ create_params["preload"] = preload+# Build experimental config# Map SDK's experimental.assistive_prompt.user_timezone to API's# experimental.assistive_prompt_config.user_timezone@@ -851,6 +873,9 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):experimental=experimental_response,custom_tools_map=custom_tools_map,user_id=user_id,+ preload=ToolRouterSessionPreloadConfig(+ tools=list(session.config.preload.tools)+ ),)def use(self, session_id: str) -> ToolRouterSession[TTool, TToolCollection]:@@ -905,6 +930,9 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):url=session.mcp.url,),experimental=experimental_response,+ preload=ToolRouterSessionPreloadConfig(+ tools=list(session.config.preload.tools)+ ),)@@ -925,8 +953,10 @@ __all__ = ["ToolRouterWorkbenchConfig","SandboxSize","ToolRouterMultiAccountConfig",+ "ToolRouterPreloadConfig","ToolRouterExperimentalConfig","ToolRouterAssistivePromptConfig",+ "ToolRouterSessionPreloadConfig","ToolkitConnectionState","ToolkitConnectionsDetails","ToolRouterMCPServerConfig",diff --git a/python/composio/core/models/tool_router_session.py b/python/composio/core/models/tool_router_session.pyindex fca6d9629..720f89e5b 100644--- a/python/composio/core/models/tool_router_session.py+++ b/python/composio/core/models/tool_router_session.py@@ -10,6 +10,7 @@ from __future__ import annotationsimport typing as tfrom concurrent.futures import ThreadPoolExecutor+from dataclasses import dataclassfrom composio_client import omitfrom composio_client.types.tool_router.session_execute_response import (@@ -50,6 +51,13 @@ COMPOSIO_MULTI_EXECUTE_TOOL = "COMPOSIO_MULTI_EXECUTE_TOOL"MAX_PARALLEL_WORKERS = 5+@dataclass+class ToolRouterSessionPreloadConfig:+ """Preloaded tools configured for a tool router session."""++ tools: t.List[str]++class ToolRouterSession(t.Generic[TTool, TToolCollection]):"""Tool router session containing session information and methods.@@ -85,6 +93,7 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):experimental: "ToolRouterSessionExperimental",custom_tools_map: t.Optional[CustomToolsMap] = None,user_id: t.Optional[str] = None,+ preload: t.Optional[ToolRouterSessionPreloadConfig] = None,) -> None:self._client = clientself._provider = provider@@ -95,6 +104,7 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):self.session_id = session_idself.mcp = mcpself.experimental = experimental+ self.preload = preload or ToolRouterSessionPreloadConfig(tools=[])self._custom_tools_map = custom_tools_mapself._user_id = user_id@@ -119,7 +129,7 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):tools_model: t.Any,modifiers: t.Optional["Modifiers"] = None,) -> t.Callable[..., t.Any]:- """Backend execute_meta wrapper with this session's file-upload settings."""+ """Backend execute wrapper with this session's file-upload settings."""return tools_model._wrap_execute_tool_for_tool_router(session_id=self.session_id,modifiers=modifiers,@@ -533,6 +543,7 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):tool_slug: str,*,arguments: t.Optional[t.Dict[str, t.Any]] = None,+ account: t.Optional[str] = None,) -> SessionExecuteResponse:"""Execute a tool within the session.@@ -541,6 +552,10 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):full slug (e.g. "LOCAL_GREP"). Custom tools are executed in-process;remote tools are sent to the Composio backend.+ :param account: Account ID or alias for direct app tool execution in+ multi-account sessions. Helper/meta tools either ignore this+ top-level field or define their own account-selection fields.+Both paths return a ``SessionExecuteResponse`` with ``data``,``error``, and ``log_id`` attributes."""@@ -563,6 +578,7 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):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,)def custom_tools(diff --git a/python/composio/core/models/tools.py b/python/composio/core/models/tools.pyindex b8f8e99fd..a4165e550 100644--- a/python/composio/core/models/tools.py+++ b/python/composio/core/models/tools.py@@ -238,11 +238,11 @@ class Tools(Resource, t.Generic[TTool, TToolCollection]):modifiers: t.Optional["Modifiers"] = None,) -> list[Tool]:"""- Fetches the meta tools for a tool router session.+ Fetches the tools exposed by a tool router session.- This method fetches the meta tools from the Composio API and transforms them to- the expected format. It provides access to the underlying meta tool data without- provider-specific wrapping.+ This method fetches helper/meta tools and any preloaded app tools from the+ Composio API and transforms them to the expected format. It provides access+ to the underlying tool data without provider-specific wrapping.:param session_id: The session ID to get the meta tools for:param modifiers: Optional modifiers to apply to the tool schemas@@ -274,7 +274,7 @@ class Tools(Resource, t.Generic[TTool, TToolCollection]):)```"""- # Fetch meta tools from the API+ # Fetch session tools from the APItools_response = self._client.tool_router.session.tools(session_id=session_id)# Cast to Tool type - session.tools returns compatible Item type from different response schematools_list: t.List[Tool] = [t.cast(Tool, item) for item in tools_response.items]@@ -297,6 +297,10 @@ class Tools(Resource, t.Generic[TTool, TToolCollection]):for tool in tools_list]+ self._tool_schemas.update(+ {tool.slug: tool.model_copy(deep=True) for tool in tools_list}+ )+return tools_listdef _get(@@ -440,10 +444,10 @@ class Tools(Resource, t.Generic[TTool, TToolCollection]):modifiers: t.Optional[Modifiers] = None,) -> AgenticProviderExecuteFn:"""- Create an execute function for tool router that uses the session's execute_meta endpoint.+ Create an execute function for tool router session tools.This method creates a function that executes tools within a tool router session context.- It uses the session's execute_meta endpoint which handles authentication and connection+ It uses the session's execute endpoint which handles authentication and connectionmanagement automatically.:param session_id: The session ID@@ -456,7 +460,7 @@ class Tools(Resource, t.Generic[TTool, TToolCollection]):Execute a tool in the tool router session.This function is used by agentic providers to execute tools within- a tool router session context. It uses the session's execute_meta+ a tool router session context. It uses the session's executeendpoint which handles authentication and connection managementautomatically.@@ -482,7 +486,7 @@ class Tools(Resource, t.Generic[TTool, TToolCollection]):self._tool_schemas[slug] = toolif self._auto_upload_download_files:- meta_tk = tool.toolkit.slug if tool.toolkit else "unknown"+ meta_tk = tool.toolkit.slug if tool.toolkit else "composio"bfu = merge_before_file_upload(modifiers,tool=slug,@@ -494,8 +498,9 @@ class Tools(Resource, t.Generic[TTool, TToolCollection]):before_file_upload=bfu,)+ toolkit_slug = tool.toolkit.slug if tool.toolkit else "composio"+# Apply before_execute modifiers- # Meta tools are always from the 'composio' toolkitprocessed_arguments = argumentsif modifiers is not None:params: ToolExecuteParams = {@@ -504,7 +509,7 @@ class Tools(Resource, t.Generic[TTool, TToolCollection]):type_before: t.Literal["before_execute"] = "before_execute"modified_params = apply_modifier_by_type(modifiers=modifiers,- toolkit="composio",+ toolkit=toolkit_slug,tool=slug,type=type_before,request=params,@@ -514,12 +519,9 @@ class Tools(Resource, t.Generic[TTool, TToolCollection]):# Serialize any Pydantic model instances before sending to the APIprocessed_arguments = _serialize_arguments(processed_arguments)- # Execute the tool via the session's execute_meta endpoint- # Note: execute_meta accepts regular tool slugs at runtime, not just meta tool slugs- # The type signature expects Literal meta tool slugs, but runtime accepts any str- response = self._client.tool_router.session.execute_meta(+ response = self._client.tool_router.session.execute(session_id=session_id,- slug=slug, # type: ignore[arg-type]+ tool_slug=slug,arguments=processed_arguments,)@@ -535,7 +537,7 @@ class Tools(Resource, t.Generic[TTool, TToolCollection]):type_after: t.Literal["after_execute"] = "after_execute"result = apply_modifier_by_type(modifiers=modifiers,- toolkit="composio",+ toolkit=toolkit_slug,tool=slug,type=type_after,response=result,diff --git a/python/tests/test_tool_router.py b/python/tests/test_tool_router.pyindex 971f474b0..d0f6744f5 100644--- a/python/tests/test_tool_router.py+++ b/python/tests/test_tool_router.py@@ -37,6 +37,8 @@ def mock_client():]mock_session_response.config = MagicMock()mock_session_response.config.user_id = "user_123"+ mock_session_response.config.preload = MagicMock()+ mock_session_response.config.preload.tools = []mock_session_response.experimental = None # Default to Noneclient.tool_router.session.create.return_value = mock_session_response@@ -587,6 +589,21 @@ class TestToolRouter:kwargs = mock_client.tool_router.session.create.call_args.kwargsassert "multi_account" not in kwargs+ def test_create_session_with_preload(self, tool_router, mock_client):+ """preload is forwarded and exposed on the session."""+ mock_client.tool_router.session.create.return_value.config.preload.tools = [+ "GMAIL_FETCH_EMAILS"+ ]++ session = tool_router.create(+ user_id="user_123",+ preload={"tools": ["GMAIL_FETCH_EMAILS"]},+ )++ kwargs = mock_client.tool_router.session.create.call_args.kwargs+ assert kwargs["preload"] == {"tools": ["GMAIL_FETCH_EMAILS"]}+ assert session.preload.tools == ["GMAIL_FETCH_EMAILS"]+def test_create_session_complex_config(self, tool_router, mock_client):"""Test creating a session with complex configuration."""session = tool_router.create(@@ -771,6 +788,10 @@ class TestToolRouter:def test_use_session(self, tool_router, mock_client):"""Test retrieving an existing session."""+ mock_client.tool_router.session.retrieve.return_value.config.preload.tools = [+ "GMAIL_FETCH_EMAILS"+ ]+session = tool_router.use(session_id="session_123")# Verify session properties@@ -788,6 +809,7 @@ class TestToolRouter:assert callable(session.tools)assert callable(session.authorize)assert callable(session.toolkits)+ assert session.preload.tools == ["GMAIL_FETCH_EMAILS"]# Verify retrieve was calledmock_client.tool_router.session.retrieve.assert_called_once_with("session_123")@@ -819,6 +841,28 @@ class TestToolRouter:with pytest.raises(Exception, match="Session not found"):tool_router.use(session_id="invalid_session")+ def test_session_execute_with_account(self, tool_router, mock_client):+ """session.execute forwards account for direct app tool execution."""+ mock_execute_response = MagicMock()+ mock_execute_response.data = {"ok": True}+ mock_execute_response.error = None+ mock_execute_response.log_id = "log_123"+ mock_client.tool_router.session.execute.return_value = mock_execute_response++ session = tool_router.create(user_id="user_123")+ session.execute(+ "GMAIL_FETCH_EMAILS",+ arguments={"max_results": 1},+ account="work",+ )++ mock_client.tool_router.session.execute.assert_called_once_with(+ session_id="session_123",+ tool_slug="GMAIL_FETCH_EMAILS",+ arguments={"max_results": 1},+ account="work",+ )+def test_authorize_function(self, tool_router, mock_client):"""Test the authorize function returned by session."""session = tool_router.create(user_id="user_123")@@ -1025,6 +1069,8 @@ class TestToolRouter:# Verify provider's wrap_tools was calledmock_provider.wrap_tools.assert_called_once()+ wrapped_tools = mock_provider.wrap_tools.call_args.kwargs["tools"]+ assert [tool.slug for tool in wrapped_tools] == ["GMAIL_FETCH_EMAILS"]assert result == "mocked-wrapped-tools"@patch("composio.core.models.tools.Tools")@@ -1294,17 +1340,12 @@ class TestToolRouterExecution:call_args = mock_tools_instance._wrap_execute_tool_for_tool_router.call_argsassert call_args.kwargs["session_id"] == "session_123"- def test_execute_meta_endpoint_called(- self, tool_router, mock_client, mock_provider- ):- """Test that execute_meta endpoint is called when executing tools."""- # Setup execute_meta response+ def test_execute_endpoint_called(self, tool_router, mock_client, mock_provider):+ """Test that session execute endpoint is called when executing tools."""mock_execute_response = MagicMock()mock_execute_response.data = {"result": "success"}mock_execute_response.error = None- mock_client.tool_router.session.execute_meta.return_value = (- mock_execute_response- )+ mock_client.tool_router.session.execute.return_value = mock_execute_response# Create a real Tools instance to test the execute functionfrom composio.core.models.tools import Tools as RealTools@@ -1321,10 +1362,10 @@ class TestToolRouterExecution:# Execute the toolresult = execute_fn("GMAIL_SEND_EMAIL", {"to": "[email protected]"})- # Verify execute_meta was called with correct parameters- mock_client.tool_router.session.execute_meta.assert_called_once_with(+ # Verify execute was called with correct parameters+ mock_client.tool_router.session.execute.assert_called_once_with(session_id="session_123",- slug="GMAIL_SEND_EMAIL",+ tool_slug="GMAIL_SEND_EMAIL",arguments={"to": "[email protected]"},)@@ -1337,13 +1378,10 @@ class TestToolRouterExecution:self, tool_router, mock_client, mock_provider):"""Test that modifiers are applied before and after tool execution."""- # Setup execute_meta responsemock_execute_response = MagicMock()mock_execute_response.data = {"result": "success"}mock_execute_response.error = None- mock_client.tool_router.session.execute_meta.return_value = (- mock_execute_response- )+ mock_client.tool_router.session.execute.return_value = mock_execute_response# Create modifier functionsdef before_modifier(tool, toolkit, params):@@ -1382,9 +1420,9 @@ class TestToolRouterExecution:# Execute the toolresult = execute_fn("GMAIL_SEND_EMAIL", {"to": "[email protected]"})- # Verify execute_meta was called with modified arguments- mock_client.tool_router.session.execute_meta.assert_called_once()- call_args = mock_client.tool_router.session.execute_meta.call_args+ # Verify execute was called with modified arguments+ mock_client.tool_router.session.execute.assert_called_once()+ call_args = mock_client.tool_router.session.execute.call_argsassert call_args.kwargs["arguments"] == {"to": "[email protected]"}# Verify result was modified by after_execute@@ -1392,13 +1430,10 @@ class TestToolRouterExecution:def test_execute_tool_error_handling(self, tool_router, mock_client, mock_provider):"""Test that tool execution errors are handled correctly."""- # Setup execute_meta to return an errormock_execute_response = MagicMock()mock_execute_response.data = {}mock_execute_response.error = "Authentication failed"- mock_client.tool_router.session.execute_meta.return_value = (- mock_execute_response- )+ mock_client.tool_router.session.execute.return_value = mock_execute_response# Create a real execute functionfrom composio.core.models.tools import Tools as RealTools