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
feat(python): add custom tools and toolkits for tool router sessions
Dhawal Upadhyay27a23ad66939
diff --git a/python/composio/__init__.py b/python/composio/__init__.pyindex e31cfd28c..143e25b44 100644--- a/python/composio/__init__.py+++ b/python/composio/__init__.py@@ -1,4 +1,13 @@from .__version__ import __version__+from .core.models.custom_tool import (+ experimental_create_tool,+ experimental_create_toolkit,+)+from .core.models.custom_tool_types import (+ CustomTool,+ CustomToolkit,+ SessionContext,+)from .core.models.tool_router_session_files import RemoteFilefrom .core.models.tools import (after_execute,@@ -25,7 +34,10 @@ from .sdk import Composio__all__ = ("Composio",+ "CustomTool",+ "CustomToolkit","RemoteFile",+ "SessionContext","ConnectionExpiredEvent","ConnectionState","ConnectionStatusEnum",@@ -35,6 +47,8 @@ __all__ = ("WebhookEventType","after_execute","before_execute",+ "experimental_create_tool",+ "experimental_create_toolkit","is_connection_expired_event","schema_modifier","__version__",diff --git a/python/composio/core/models/__init__.py b/python/composio/core/models/__init__.pyindex fb11a1314..9770a0612 100644--- a/python/composio/core/models/__init__.py+++ b/python/composio/core/models/__init__.py@@ -1,5 +1,14 @@from .auth_configs import AuthConfigsfrom .connected_accounts import ConnectedAccounts+from .custom_tool import experimental_create_tool, experimental_create_toolkit+from .custom_tool_types import (+ CustomTool,+ CustomToolkit,+ ProxyExecuteResponse,+ RegisteredCustomTool,+ RegisteredCustomToolkit,+ SessionContext,+)from .mcp import MCPfrom .tool_router import ToolRouterfrom .tool_router_session import ToolRouterSession@@ -24,8 +33,14 @@ __all__ = ["ConnectionExpiredEvent","ConnectionState","ConnectionStatusEnum",+ "CustomTool",+ "CustomToolkit","MCP",+ "ProxyExecuteResponse",+ "RegisteredCustomTool",+ "RegisteredCustomToolkit","RemoteFile",+ "SessionContext","SingleConnectedAccountDetailedResponse","ToolRouter","ToolRouterSession",@@ -36,5 +51,7 @@ __all__ = ["WebhookConnectionMetadata","WebhookEvent","WebhookEventType",+ "experimental_create_tool",+ "experimental_create_toolkit","is_connection_expired_event",]diff --git a/python/composio/core/models/custom_tool.py b/python/composio/core/models/custom_tool.pynew file mode 100644index 000000000..7cb3cee62--- /dev/null+++ b/python/composio/core/models/custom_tool.py@@ -0,0 +1,484 @@+"""Factory functions for creating custom tools and toolkits.++Usage::++ from composio import experimental_create_tool, experimental_create_toolkit+ from pydantic import BaseModel, Field++ class GrepInput(BaseModel):+ pattern: str = Field(description="Pattern to search for")++ grep = experimental_create_tool("GREP",+ name="Grep Search",+ description="Search for patterns in files",+ input_params=GrepInput,+ execute=lambda input, ctx: {"matches": []},+ )++ dev_tools = experimental_create_toolkit("DEV_TOOLS",+ name="Dev Tools",+ description="Local dev utilities",+ tools=[grep],+ )+"""++from __future__ import annotations++import typing as t++from pydantic import BaseModel++from composio.exceptions import ValidationError++from .custom_tool_types import (+ LOCAL_TOOL_PREFIX,+ MAX_SLUG_LENGTH,+ SLUG_REGEX,+ CustomTool,+ CustomToolExecuteFn,+ CustomToolkit,+ CustomToolsMap,+ CustomToolsMapEntry,+)++if t.TYPE_CHECKING:+ from composio_client.types.tool_router.session_create_response import (+ Experimental as SessionCreateResponseExperimental,+ )+++# ────────────────────────────────────────────────────────────────+# Slug validation helpers+# ────────────────────────────────────────────────────────────────+++def _validate_slug(slug: str, context: str) -> str:+ """Validate a custom tool or toolkit slug."""+ if not slug:+ raise ValidationError(f"{context}: slug is required")++ if not SLUG_REGEX.match(slug):+ raise ValidationError(+ f"{context}: slug must only contain alphanumeric characters, "+ f"underscores, and hyphens"+ )++ upper = slug.upper()+ if upper.startswith("LOCAL_"):+ raise ValidationError(+ f'{context}: slug must not start with "LOCAL_" — '+ f"this prefix is reserved for internal routing."+ )+ if upper.startswith("COMPOSIO_"):+ raise ValidationError(+ f'{context}: slug must not start with "COMPOSIO_" — '+ f"this prefix is reserved for Composio meta tools."+ )++ return slug+++def _compute_final_slug_length(tool_slug: str, toolkit_slug: t.Optional[str]) -> int:+ """Compute the final slug length: LOCAL_[TOOLKIT_]SLUG."""+ length = len(LOCAL_TOOL_PREFIX) + len(tool_slug)+ if toolkit_slug:+ length += len(toolkit_slug) + 1 # +1 for underscore separator+ return length+++def _validate_slug_length(+ tool_slug: str, toolkit_slug: t.Optional[str], context: str+) -> None:+ """Validate that the final slug won't exceed the max length."""+ final_length = _compute_final_slug_length(tool_slug, toolkit_slug)+ if final_length > MAX_SLUG_LENGTH:+ prefix = LOCAL_TOOL_PREFIX + (+ f"{toolkit_slug.upper()}_" if toolkit_slug else ""+ )+ available = MAX_SLUG_LENGTH - len(prefix)+ raise ValidationError(+ f'{context}: slug "{tool_slug}" is too long. '+ f'With prefix "{prefix}", the final slug would be {final_length} '+ f"characters (max {MAX_SLUG_LENGTH}). "+ f"Shorten the slug to at most {available} characters."+ )+++def _build_final_slug(tool_slug: str, toolkit_slug: t.Optional[str] = None) -> str:+ """Build the final slug: LOCAL_[TOOLKIT_]SLUG."""+ upper = tool_slug.upper()+ if toolkit_slug:+ return f"{LOCAL_TOOL_PREFIX}{toolkit_slug.upper()}_{upper}"+ return f"{LOCAL_TOOL_PREFIX}{upper}"+++def _get_input_json_schema(model: t.Type[BaseModel]) -> t.Dict[str, t.Any]:+ """Convert a Pydantic model class to a JSON Schema dict suitable for the backend."""+ full_schema = model.model_json_schema()+ schema: t.Dict[str, t.Any] = {"type": "object"}+ if "properties" in full_schema:+ schema["properties"] = full_schema["properties"]+ if "required" in full_schema:+ schema["required"] = full_schema["required"]+ # Inline $defs if present (Pydantic puts nested models there)+ if "$defs" in full_schema:+ schema["$defs"] = full_schema["$defs"]+ return schema+++# ────────────────────────────────────────────────────────────────+# Factory functions+# ────────────────────────────────────────────────────────────────+++def experimental_create_tool(+ slug: str,+ *,+ name: str,+ description: str,+ input_params: t.Type[BaseModel],+ execute: CustomToolExecuteFn,+ extends_toolkit: t.Optional[str] = None,+ output_params: t.Optional[t.Type[BaseModel]] = None,+) -> CustomTool:+ """Create a custom tool for use in tool router sessions.++ The returned object is a lightweight reference containing the tool's metadata+ and execute function. Pass it to+ ``composio.create(user_id, experimental={"custom_tools": [...]})``+ to bind it to a session.++ Just return the result data from ``execute``, or raise an error.+ The SDK wraps it into the standard response format internally.++ :param slug: Unique tool identifier (alphanumeric, underscores, hyphens;+ no LOCAL_ or COMPOSIO_ prefix)+ :param name: Human-readable display name+ :param description: Tool description (used for BM25 search matching)+ :param input_params: Pydantic BaseModel class for input parameters+ :param execute: Function ``(input, ctx) -> dict`` that executes the tool+ :param extends_toolkit: Composio toolkit slug to inherit auth from (e.g. 'gmail')+ :param output_params: Optional Pydantic BaseModel class for output documentation+ :returns: A CustomTool to pass to session creation++ Example — standalone tool (no auth)::++ class GrepInput(BaseModel):+ pattern: str = Field(description="Pattern to search for")+ path: str = Field(description="File path")++ grep = experimental_create_tool("GREP",+ name="Grep Search",+ description="Search for patterns in files",+ input_params=GrepInput,+ execute=lambda input, ctx: {"matches": []},+ )++ Example — tool extending a Composio toolkit (inherits auth)::++ class DraftInput(BaseModel):+ to: str = Field(description="Recipient email")+ subject: str = Field(description="Subject")+ body: str = Field(description="Body")++ create_draft = experimental_create_tool("CREATE_DRAFT",+ name="Create Gmail draft",+ description="Create a real Gmail draft via the Gmail API",+ extends_toolkit="gmail",+ input_params=DraftInput,+ execute=lambda input, ctx: ctx.proxy_execute(+ toolkit="gmail",+ endpoint="https://gmail.googleapis.com/gmail/v1/users/me/drafts",+ method="POST",+ body={"message": {"raw": "..."}},+ ),+ )+ """+ context = "experimental_create_tool"++ # Validate slug+ _validate_slug(slug, context)++ # Validate required fields+ if not name:+ raise ValidationError(f"{context}: name is required")+ if not description:+ raise ValidationError(f"{context}: description is required")++ # Validate input_params is a Pydantic BaseModel subclass (not an instance)+ if not isinstance(input_params, type) or not issubclass(input_params, BaseModel):+ raise ValidationError(+ f"{context}: input_params must be a Pydantic BaseModel subclass. "+ f"Tool input parameters are always an object with named properties."+ )++ # Validate execute is callable+ if not callable(execute):+ raise ValidationError(f"{context}: execute must be a callable")++ # Early length validation+ _validate_slug_length(slug, extends_toolkit, context)++ # Convert Pydantic model → JSON Schema+ input_schema = _get_input_json_schema(input_params)++ # Convert output schema if provided+ output_schema: t.Optional[t.Dict[str, t.Any]] = None+ if output_params is not None:+ if not isinstance(output_params, type) or not issubclass(+ output_params, BaseModel+ ):+ raise ValidationError(+ f"{context}: output_params must be a Pydantic BaseModel subclass"+ )+ output_schema = output_params.model_json_schema()++ return CustomTool(+ slug=slug,+ name=name,+ description=description,+ extends_toolkit=extends_toolkit,+ input_schema=input_schema,+ output_schema=output_schema,+ input_params=input_params,+ execute=execute,+ )+++def experimental_create_toolkit(+ slug: str,+ *,+ name: str,+ description: str,+ tools: t.List[CustomTool],+) -> CustomToolkit:+ """Create a custom toolkit that groups related tools.++ Tools passed here must NOT have ``extends_toolkit`` set — they inherit the+ toolkit identity instead.++ :param slug: Unique toolkit identifier (alphanumeric, underscores, hyphens;+ no LOCAL_ or COMPOSIO_ prefix)+ :param name: Human-readable display name+ :param description: Toolkit description+ :param tools: List of CustomTool objects to include in this toolkit+ :returns: A CustomToolkit to pass to session creation++ Example::++ dev_tools = experimental_create_toolkit("DEV_TOOLS",+ name="Dev Tools",+ description="Local dev utilities",+ tools=[grep_tool, sed_tool],+ )+ """+ context = "experimental_create_toolkit"++ # Validate slug+ _validate_slug(slug, context)++ # Validate required fields+ if not name:+ raise ValidationError(f"{context}: name is required")+ if not description:+ raise ValidationError(f"{context}: description is required")++ # Non-empty tools required+ if not tools:+ raise ValidationError(f"{context}: at least one tool is required")++ # Validate each tool+ for tool in tools:+ if tool.extends_toolkit:+ raise ValidationError(+ f'{context}: tool "{tool.slug}" has extends_toolkit set. '+ f"Tools in a custom toolkit must not use extends_toolkit — "+ f"they inherit the toolkit identity instead."+ )+ # Early length validation with toolkit slug+ _validate_slug_length(+ tool.slug, slug, f'{context}("{slug}")'+ )++ return CustomToolkit(+ slug=slug,+ name=name,+ description=description,+ tools=tuple(tools),+ )+++# ────────────────────────────────────────────────────────────────+# Serialization (for backend API payload)+# ────────────────────────────────────────────────────────────────+++def serialize_custom_tools(tools: t.List[CustomTool]) -> t.List[t.Dict[str, t.Any]]:+ """Serialize custom tools into the format expected by the backend."""+ result = []+ for tool in tools:+ entry: t.Dict[str, t.Any] = {+ "slug": tool.slug,+ "name": tool.name,+ "description": tool.description,+ "input_schema": tool.input_schema,+ }+ if tool.output_schema:+ entry["output_schema"] = tool.output_schema+ if tool.extends_toolkit:+ entry["extends_toolkit"] = tool.extends_toolkit+ result.append(entry)+ return result+++def serialize_custom_toolkits(+ toolkits: t.List[CustomToolkit],+) -> t.List[t.Dict[str, t.Any]]:+ """Serialize custom toolkits into the format expected by the backend."""+ result = []+ for tk in toolkits:+ toolkit_tools = []+ for tool in tk.tools:+ entry: t.Dict[str, t.Any] = {+ "slug": tool.slug,+ "name": tool.name,+ "description": tool.description,+ "input_schema": tool.input_schema,+ }+ if tool.output_schema:+ entry["output_schema"] = tool.output_schema+ toolkit_tools.append(entry)+ result.append(+ {+ "slug": tk.slug,+ "name": tk.name,+ "description": tk.description,+ "tools": toolkit_tools,+ }+ )+ return result+++# ────────────────────────────────────────────────────────────────+# Routing map builders+# ────────────────────────────────────────────────────────────────+++def build_custom_tools_map(+ tools: t.List[CustomTool],+ toolkits: t.Optional[t.List[CustomToolkit]] = None,+) -> CustomToolsMap:+ """Build a CustomToolsMap from custom tools and toolkits.++ Used internally by ToolRouter.create() to construct the per-session routing map.+ """+ by_final_slug: t.Dict[str, CustomToolsMapEntry] = {}+ by_original_slug: t.Dict[str, CustomToolsMapEntry] = {}++ def add_entry(+ handle: CustomTool, final_slug: str, toolkit: t.Optional[str]+ ) -> None:+ original_slug = handle.slug.upper()++ if len(final_slug) > MAX_SLUG_LENGTH:+ raise ValidationError(+ f'Custom tool slug "{handle.slug}" produces final slug '+ f'"{final_slug}" which exceeds {MAX_SLUG_LENGTH} characters.'+ )++ if final_slug in by_final_slug:+ raise ValidationError(+ f'Custom tool slug collision: "{final_slug}" is already registered.'+ )++ if original_slug in by_original_slug:+ existing = by_original_slug[original_slug]+ raise ValidationError(+ f'Custom tool slug collision: original slug "{handle.slug}" '+ f"maps to multiple final slugs. "+ f'"{existing.final_slug}" and "{final_slug}" both resolve '+ f'from "{original_slug}".'+ )++ entry = CustomToolsMapEntry(+ handle=handle, final_slug=final_slug, toolkit=toolkit+ )+ by_final_slug[final_slug] = entry+ by_original_slug[original_slug] = entry++ # Process standalone tools+ for handle in tools:+ add_entry(+ handle,+ _build_final_slug(handle.slug, handle.extends_toolkit),+ handle.extends_toolkit,+ )++ # Process toolkit tools+ if toolkits:+ for tk in toolkits:+ for handle in tk.tools:+ add_entry(+ handle, _build_final_slug(handle.slug, tk.slug), tk.slug+ )++ return CustomToolsMap(+ by_final_slug=by_final_slug,+ by_original_slug=by_original_slug,+ toolkits=list(toolkits) if toolkits else None,+ )+++def build_custom_tools_map_from_response(+ tools: t.List[CustomTool],+ toolkits: t.Optional[t.List[CustomToolkit]],+ experimental: t.Optional[SessionCreateResponseExperimental],+) -> CustomToolsMap:+ """Build a CustomToolsMap using the slug/original_slug mapping from the backend response.++ Uses the backend's authoritative prefixed slugs instead of computing them client-side.+ """+ by_final_slug: t.Dict[str, CustomToolsMapEntry] = {}+ by_original_slug: t.Dict[str, CustomToolsMapEntry] = {}++ # Build lookup from original slug → handle + toolkit+ handles_by_original: t.Dict[+ str, t.Tuple[CustomTool, t.Optional[str]]+ ] = {}+ for handle in tools:+ handles_by_original[handle.slug.upper()] = (handle, handle.extends_toolkit)+ if toolkits:+ for tk in toolkits:+ for handle in tk.tools:+ handles_by_original[handle.slug.upper()] = (handle, tk.slug)++ def add_entry(+ final_slug: str, original_slug: str, toolkit: t.Optional[str]+ ) -> None:+ match = handles_by_original.get(original_slug.upper())+ if not match:+ return # Response tool not found in our handles+ handle, default_toolkit = match+ resolved_toolkit = toolkit if toolkit is not None else default_toolkit+ entry = CustomToolsMapEntry(+ handle=handle, final_slug=final_slug, toolkit=resolved_toolkit+ )+ by_final_slug[final_slug] = entry+ by_original_slug[original_slug.upper()] = entry++ # Map standalone custom tools from response+ if experimental and experimental.custom_tools:+ for ct in experimental.custom_tools:+ add_entry(ct.slug, ct.original_slug, ct.extends_toolkit)++ # Map toolkit custom tools from response+ if experimental and experimental.custom_toolkits:+ for ctk in experimental.custom_toolkits:+ for ct in ctk.tools:+ add_entry(ct.slug, ct.original_slug, ctk.slug)++ return CustomToolsMap(+ by_final_slug=by_final_slug,+ by_original_slug=by_original_slug,+ toolkits=list(toolkits) if toolkits else None,+ )diff --git a/python/composio/core/models/custom_tool_execution.py b/python/composio/core/models/custom_tool_execution.pynew file mode 100644index 000000000..3454ae5db--- /dev/null+++ b/python/composio/core/models/custom_tool_execution.py@@ -0,0 +1,71 @@+"""Standalone functions for custom tool lookup and execution.++Extracted for reuse in SessionContextImpl (sibling routing).+"""++from __future__ import annotations++import typing as t++from pydantic import ValidationError as PydanticValidationError++from .custom_tool_types import (+ CustomToolsMap,+ CustomToolsMapEntry,+ SessionContext,+)+from .tools import ToolExecutionResponse+++def find_custom_tool(+ map_: t.Optional[CustomToolsMap],+ slug: str,+) -> t.Optional[CustomToolsMapEntry]:+ """Find a custom tool entry by slug.++ Checks both the final slug map (LOCAL_X — agent/LLM path)+ and original slug map (X — programmatic path). Case-insensitive.+ """+ if map_ is None:+ return None+ upper = slug.upper()+ return map_.by_final_slug.get(upper) or map_.by_original_slug.get(upper)+++def execute_custom_tool(+ entry: CustomToolsMapEntry,+ arguments: t.Dict[str, t.Any],+ session_context: SessionContext,+) -> ToolExecutionResponse:+ """Execute a custom tool in-process.++ Validates input via the Pydantic model, calls the user's execute function,+ and wraps the result into the standard response format.+ """+ handle = entry.handle++ # Validate and transform input using the Pydantic model.+ # This applies defaults, coercions, and validators.+ try:+ validated = handle.input_params.model_validate(arguments)+ except PydanticValidationError as e:+ return {+ "data": {},+ "error": f"Input validation failed: {e}",+ "successful": False,+ }++ try:+ # User's execute returns data directly — we wrap into {data, error, successful}+ data = handle.execute(validated, session_context)+ return {+ "data": data if data is not None else {},+ "error": None,+ "successful": True,+ }+ except Exception as e:+ return {+ "data": {},+ "error": str(e),+ "successful": False,+ }diff --git a/python/composio/core/models/custom_tool_types.py b/python/composio/core/models/custom_tool_types.pynew file mode 100644index 000000000..ae01df870--- /dev/null+++ b/python/composio/core/models/custom_tool_types.py@@ -0,0 +1,180 @@+"""Type definitions for custom tools in tool router sessions.++Mirrors the TypeScript types in ts/packages/core/src/types/customTool.types.ts+"""++from __future__ import annotations++import re+import typing as t+from dataclasses import dataclass, field++import typing_extensions as te+from pydantic import BaseModel++from composio.core.models.tools import ToolExecutionResponse++# ────────────────────────────────────────────────────────────────+# Constants+# ────────────────────────────────────────────────────────────────++LOCAL_TOOL_PREFIX = "LOCAL_"+MAX_SLUG_LENGTH = 60+SLUG_REGEX = re.compile(r"^[A-Za-z0-9_-]+$")++# ────────────────────────────────────────────────────────────────+# Execute function type+# ────────────────────────────────────────────────────────────────++CustomToolExecuteFn = t.Callable[+ [t.Any, "SessionContext"],+ t.Dict[str, t.Any],+]+"""+Execute function for custom tools.++Signature: (input: BaseModel, ctx: SessionContext) -> dict++Just return the result data, or raise an error. The SDK wraps it internally+into {data, error, successful}.+"""++# ────────────────────────────────────────────────────────────────+# SessionContext protocol+# ────────────────────────────────────────────────────────────────+++class SessionContext(te.Protocol):+ """Session context injected into custom tool execute functions at runtime.++ Provides identity context and methods to call other tools or proxy API requests.+ """++ @property+ def user_id(self) -> str: ...++ def execute(+ self,+ tool_slug: str,+ arguments: t.Dict[str, t.Any],+ ) -> ToolExecutionResponse:+ """Execute any Composio tool from within a custom tool."""+ ...++ def proxy_execute(+ self,+ *,+ toolkit: str,+ endpoint: str,+ method: t.Literal["GET", "POST", "PUT", "DELETE", "PATCH"],+ body: t.Any = None,+ parameters: t.Optional[t.List[t.Dict[str, t.Any]]] = None,+ ) -> ProxyExecuteResponse:+ """Proxy API calls through Composio's auth layer."""+ ...+++# ────────────────────────────────────────────────────────────────+# Custom tool / toolkit definitions (returned by factory functions)+# ────────────────────────────────────────────────────────────────+++@dataclass(frozen=True)+class CustomTool:+ """Custom tool definition returned from ``experimental_create_tool()``.++ Pass to ``composio.create(user_id, experimental={"custom_tools": [...]})``+ to bind to a session.+ """++ slug: str+ name: str+ description: str+ input_schema: t.Dict[str, t.Any]+ input_params: t.Type[BaseModel]+ execute: CustomToolExecuteFn+ extends_toolkit: t.Optional[str] = None+ output_schema: t.Optional[t.Dict[str, t.Any]] = None+++@dataclass(frozen=True)+class CustomToolkit:+ """Custom toolkit definition returned from ``experimental_create_toolkit()``.++ Pass to ``composio.create(user_id, experimental={"custom_toolkits": [...]})``+ to bind to a session.+ """++ slug: str+ name: str+ description: str+ tools: t.Tuple[CustomTool, ...]+++# ────────────────────────────────────────────────────────────────+# Internal routing map types+# ────────────────────────────────────────────────────────────────+++@dataclass+class CustomToolsMapEntry:+ """Entry in the per-session custom tools routing map."""++ handle: CustomTool+ final_slug: str+ toolkit: t.Optional[str] = None+++@dataclass+class CustomToolsMap:+ """Lookup maps used by ToolRouterSession for routing custom tools."""++ by_final_slug: t.Dict[str, CustomToolsMapEntry] = field(default_factory=dict)+ by_original_slug: t.Dict[str, CustomToolsMapEntry] = field(default_factory=dict)+ toolkits: t.Optional[t.List[CustomToolkit]] = None+++# ────────────────────────────────────────────────────────────────+# Registered types (returned by session.custom_tools() / .custom_toolkits())+# ────────────────────────────────────────────────────────────────+++@dataclass(frozen=True)+class RegisteredCustomTool:+ """A custom tool as registered in a session, with its final resolved slug."""++ slug: str+ name: str+ description: str+ input_schema: t.Dict[str, t.Any]+ toolkit: t.Optional[str] = None+ output_schema: t.Optional[t.Dict[str, t.Any]] = None+++@dataclass(frozen=True)+class RegisteredCustomToolkit:+ """A custom toolkit as registered in a session, with final slugs on nested tools."""++ slug: str+ name: str+ description: str+ tools: t.List[RegisteredCustomTool]+++# ────────────────────────────────────────────────────────────────+# Proxy execute response types+# ────────────────────────────────────────────────────────────────+++class ProxyExecuteBinaryData(te.TypedDict, total=False):+ content_type: str+ size: int+ url: str+ expires_at: t.Optional[str]+++class ProxyExecuteResponse(te.TypedDict, total=False):+ status: int+ data: t.Optional[t.Any]+ headers: t.Optional[t.Dict[str, str]]+ binary_data: ProxyExecuteBinaryDatadiff --git a/python/composio/core/models/session_context.py b/python/composio/core/models/session_context.pynew file mode 100644index 000000000..d01b91914--- /dev/null+++ b/python/composio/core/models/session_context.py@@ -0,0 +1,126 @@+"""Session context implementation injected into custom tool execute functions.++One instance is created per session and shared across all custom tool invocations,+including sibling routing (tool A calling tool B without hitting the network).+"""++from __future__ import annotations++import typing as t++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,+ ProxyExecuteResponse,+)+from composio.core.models.tools import ToolExecutionResponse+++class SessionContextImpl:+ """Concrete implementation of SessionContext.++ One instance is created per session (singleton) and shared across+ all custom tool invocations. When ``custom_tools_map`` is provided,+ ``execute()`` checks local tools first before falling back to the+ backend API (sibling routing).+ """++ def __init__(+ self,+ client: HttpClient,+ user_id: str,+ session_id: str,+ custom_tools_map: t.Optional[CustomToolsMap] = None,+ ) -> None:+ self._client = client+ self._user_id = user_id+ self._session_id = session_id+ self._custom_tools_map = custom_tools_map++ @property+ def user_id(self) -> str:+ return self._user_id++ def execute(+ self,+ tool_slug: str,+ arguments: t.Dict[str, t.Any],+ ) -> ToolExecutionResponse:+ """Execute any tool from within a custom tool.++ Routes to sibling local tools in-process when available,+ otherwise delegates to the backend API.+ """+ # Try local tool first (sibling routing)+ entry = find_custom_tool(self._custom_tools_map, tool_slug)+ if entry:+ return execute_custom_tool(entry, arguments, self)++ # Fall back to remote execution+ response = self._client.tool_router.session.execute(+ session_id=self._session_id,+ tool_slug=tool_slug,+ arguments=arguments,+ )+ return {+ "data": response.data if hasattr(response, "data") else {},+ "error": response.error if hasattr(response, "error") else None,+ "successful": not (hasattr(response, "error") and response.error),+ }++ def proxy_execute(+ self,+ *,+ toolkit: str,+ endpoint: str,+ method: t.Literal["GET", "POST", "PUT", "DELETE", "PATCH"],+ body: t.Any = None,+ parameters: t.Optional[t.List[t.Dict[str, t.Any]]] = None,+ ) -> ProxyExecuteResponse:+ """Proxy API calls through Composio's auth layer.++ The backend resolves the connected account from the toolkit+ within the session.+ """+ from composio_client import omit++ # Transform parameters to API format+ api_params: t.List[t.Dict[str, t.Any]] = []+ if parameters:+ for p in parameters:+ api_params.append(+ {+ "name": p["name"],+ "type": p.get("in", p.get("type", "header")),+ "value": str(p["value"]),+ }+ )++ response = self._client.tool_router.session.proxy_execute(+ session_id=self._session_id,+ toolkit_slug=toolkit,+ endpoint=endpoint,+ method=method,+ body=body if body is not None else omit,+ parameters=api_params if api_params else omit,+ )++ result: ProxyExecuteResponse = {+ "status": int(response.status),+ "data": response.data,+ "headers": response.headers,+ }++ if response.binary_data:+ result["binary_data"] = {+ "content_type": response.binary_data.content_type,+ "size": int(response.binary_data.size),+ "url": response.binary_data.url,+ "expires_at": response.binary_data.expires_at,+ }++ return resultdiff --git a/python/composio/core/models/tool_router.py b/python/composio/core/models/tool_router.pyindex 3935b8dcf..5409ddd5f 100644--- a/python/composio/core/models/tool_router.py+++ b/python/composio/core/models/tool_router.py@@ -17,6 +17,16 @@ from composio_client.types.tool_router import session_create_paramsfrom composio.client import HttpClientfrom composio.core.models.base import Resource+from composio.core.models.custom_tool import (+ build_custom_tools_map_from_response,+ serialize_custom_tools,+ serialize_custom_toolkits,+)+from composio.core.models.custom_tool_types import (+ CustomTool,+ CustomToolkit,+ CustomToolsMap,+)from composio.core.models.tool_router_session import ToolRouterSessionfrom composio.core.models.tool_router_session_files import ToolRouterSessionFilesMountfrom composio.core.provider import TTool, TToolCollection@@ -178,9 +188,13 @@ class ToolRouterExperimentalConfig(te.TypedDict, total=False):Attributes:assistive_prompt: Configuration for assistive prompt generation.+ custom_tools: Custom tools to include in the session.+ custom_toolkits: Custom toolkits with grouped tools."""assistive_prompt: ToolRouterAssistivePromptConfig+ custom_tools: t.List["CustomTool"]+ custom_toolkits: t.List["CustomToolkit"]@dataclass@@ -696,18 +710,36 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):# Build experimental config# Map SDK's experimental.assistive_prompt.user_timezone to API's# experimental.assistive_prompt_config.user_timezone+ custom_tools: t.Optional[t.List[CustomTool]] = None+ custom_toolkits: t.Optional[t.List[CustomToolkit]] = None+if experimental is not None:+ experimental_payload: t.Dict[str, t.Any] = {}+assistive_prompt_config = experimental.get("assistive_prompt")if assistive_prompt_config is not None:user_timezone = assistive_prompt_config.get("user_timezone")- # Only include if user_timezone is a non-empty stringif user_timezone:- create_params["experimental"] = {- "assistive_prompt_config": {- "user_timezone": user_timezone,- }+ experimental_payload["assistive_prompt_config"] = {+ "user_timezone": user_timezone,}+ # Serialize custom tools and toolkits for the backend+ custom_tools = experimental.get("custom_tools")+ custom_toolkits = experimental.get("custom_toolkits")++ if custom_tools:+ experimental_payload["custom_tools"] = serialize_custom_tools(+ custom_tools+ )+ if custom_toolkits:+ experimental_payload["custom_toolkits"] = serialize_custom_toolkits(+ custom_toolkits+ )++ if experimental_payload:+ create_params["experimental"] = experimental_payload+if self._provider is None:raise ValueError("Provider is required for tool router. "@@ -717,6 +749,15 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):# Make API call to create sessionsession = self._client.tool_router.session.create(**create_params)+ # Build custom tools routing map from backend response+ custom_tools_map: t.Optional[CustomToolsMap] = None+ if custom_tools or custom_toolkits:+ custom_tools_map = build_custom_tools_map_from_response(+ tools=custom_tools or [],+ toolkits=custom_toolkits,+ experimental=session.experimental,+ )+# Transform experimental response:# API's assistive_prompt -> SDK's assistive_prompt# files mount is always present@@ -739,6 +780,8 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):url=session.mcp.url,),experimental=experimental_response,+ custom_tools_map=custom_tools_map,+ user_id=user_id,)def use(self, session_id: str) -> ToolRouterSession[TTool, TToolCollection]:diff --git a/python/composio/core/models/tool_router_session.py b/python/composio/core/models/tool_router_session.pyindex 19299805f..358744cfe 100644--- a/python/composio/core/models/tool_router_session.py+++ b/python/composio/core/models/tool_router_session.py@@ -2,16 +2,32 @@ToolRouterSession class for managing a single tool router session.Provides methods for tools, authorize, toolkits, search, execute, and files.+When custom tools are bound to the session, execution is routed: local tools+run in-process, remote tools are sent to the backend."""from __future__ import annotationsimport typing as t+from concurrent.futures import ThreadPoolExecutorfrom composio_client import omitfrom composio.client import HttpClientfrom composio.core.models.connected_accounts import ConnectionRequest+from composio.core.models.custom_tool_execution import (+ execute_custom_tool,+ find_custom_tool,+)+from composio.core.models.custom_tool_types import (+ CustomToolsMap,+ CustomToolsMapEntry,+ ProxyExecuteResponse,+ RegisteredCustomTool,+ RegisteredCustomToolkit,+)+from composio.core.models.session_context import SessionContextImpl+from composio.core.models.tools import ToolExecutionResponsefrom composio.core.provider import TTool, TToolCollectionfrom composio.core.provider.base import BaseProvider@@ -19,6 +35,9 @@ if t.TYPE_CHECKING:from composio.core.models._modifiers import Modifiersfrom composio.core.models.tool_router import ToolRouterSessionExperimental+COMPOSIO_MULTI_EXECUTE_TOOL = "COMPOSIO_MULTI_EXECUTE_TOOL"+MAX_PARALLEL_WORKERS = 5+class ToolRouterSession(t.Generic[TTool, TToolCollection]):"""@@ -43,6 +62,8 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):session_id: str,mcp: t.Any,experimental: "ToolRouterSessionExperimental",+ custom_tools_map: t.Optional[CustomToolsMap] = None,+ user_id: t.Optional[str] = None,) -> None:self._client = clientself._provider = provider@@ -50,6 +71,24 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):self.session_id = session_idself.mcp = mcpself.experimental = experimental+ self._custom_tools_map = custom_tools_map+ self._user_id = user_id++ # Create singleton session context if custom tools are bound+ self._session_context: t.Optional[SessionContextImpl] = None+ if custom_tools_map and user_id:+ self._session_context = SessionContextImpl(+ client=client,+ user_id=user_id,+ session_id=session_id,+ custom_tools_map=custom_tools_map,+ )++ def _has_custom_tools(self) -> bool:+ """Check if this session has any custom tools bound."""+ if self._custom_tools_map is None:+ return False+ return len(self._custom_tools_map.by_final_slug) > 0def tools(self, modifiers: t.Optional["Modifiers"] = None) -> TToolCollection:"""@@ -57,6 +96,10 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):Returns tools configured for this session, wrapped in the format expectedby your AI provider (OpenAI, Anthropic, LangChain, etc.).++ When custom tools are bound to the session, execution of+ COMPOSIO_MULTI_EXECUTE_TOOL is intercepted: local tools are executed+ in-process, remote tools are sent to the backend."""from composio.core.models.tools import Tools as ToolsModelfrom composio.core.provider import AgenticProvider, NonAgenticProvider@@ -93,17 +136,183 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):).wrap_tools(tools=router_tools),)+ # For agentic providers: if custom tools are bound, create a routing+ # execute function that intercepts COMPOSIO_MULTI_EXECUTE_TOOL+ if self._has_custom_tools():+ execute_fn = self._create_routing_execute_fn(tools_model, modifiers)+ else:+ execute_fn = tools_model._wrap_execute_tool_for_tool_router(+ session_id=self.session_id,+ modifiers=modifiers,+ )+return t.cast(TToolCollection,- t.cast(AgenticProvider[TTool, TToolCollection], self._provider).wrap_tools(+ t.cast(+ AgenticProvider[TTool, TToolCollection], self._provider+ ).wrap_tools(tools=router_tools,- execute_tool=tools_model._wrap_execute_tool_for_tool_router(+ execute_tool=execute_fn,+ ),+ )++ def _create_routing_execute_fn(+ self,+ tools_model: t.Any,+ modifiers: t.Optional["Modifiers"],+ ) -> t.Callable[..., t.Any]:+ """Create an execute function that routes local/remote tools."""++ def routing_execute(slug: str, arguments: t.Dict) -> t.Dict:+ if slug == COMPOSIO_MULTI_EXECUTE_TOOL:+ return self._route_multi_execute(+ arguments, tools_model, modifiers+ )+ # Non-multi-execute meta tools always go to backend+ return tools_model._wrap_execute_tool_for_tool_router(+ session_id=self.session_id,+ modifiers=modifiers,+ )(slug, arguments)++ return routing_execute++ def _parse_tool_item(+ self, item: t.Any+ ) -> t.Dict[str, t.Any]:+ """Parse an individual tool item from COMPOSIO_MULTI_EXECUTE_TOOL's tools array."""+ if not isinstance(item, dict):+ return {"tool_slug": "", "arguments": {}}+ return {+ "tool_slug": str(item.get("tool_slug", "")),+ "arguments": item.get("arguments", {}),+ }++ def _route_multi_execute(+ self,+ input_args: t.Dict[str, t.Any],+ tools_model: t.Any,+ modifiers: t.Optional["Modifiers"],+ ) -> t.Dict[str, t.Any]:+ """Route a COMPOSIO_MULTI_EXECUTE_TOOL call.++ Splits the tools[] array into local and remote, executes each+ appropriately, and merges results preserving original order.+ """+ tool_items = input_args.get("tools")+ if not isinstance(tool_items, list) or len(tool_items) == 0:+ # Fallback: send to backend as-is+ return tools_model._wrap_execute_tool_for_tool_router(+ session_id=self.session_id,+ modifiers=modifiers,+ )(COMPOSIO_MULTI_EXECUTE_TOOL, input_args)++ parsed = [self._parse_tool_item(item) for item in tool_items]++ # Partition into local (with resolved entry) and remote+ local_items: t.List[t.Tuple[int, CustomToolsMapEntry]] = []+ remote_indices: t.List[int] = []+ for i, p in enumerate(parsed):+ entry = find_custom_tool(self._custom_tools_map, p["tool_slug"])+ if entry:+ local_items.append((i, entry))+ else:+ remote_indices.append(i)++ # All remote — just forward entire payload+ if not local_items:+ return tools_model._wrap_execute_tool_for_tool_router(+ session_id=self.session_id,+ modifiers=modifiers,+ )(COMPOSIO_MULTI_EXECUTE_TOOL, input_args)++ ctx = self._session_context+ assert ctx is not None++ # Determine worker count (capped at MAX_PARALLEL_WORKERS)+ num_tasks = len(local_items) + (1 if remote_indices else 0)+ num_workers = min(MAX_PARALLEL_WORKERS, num_tasks)++ with ThreadPoolExecutor(max_workers=num_workers) as pool:+ # Submit local tool executions+ local_futures = []+ for idx, entry in local_items:+ future = pool.submit(+ execute_custom_tool,+ entry,+ parsed[idx]["arguments"],+ ctx,+ )+ local_futures.append((idx, future))++ # Submit remote batch (single call) if any+ remote_future = None+ if remote_indices:+ remote_tool_items = [tool_items[i] for i in remote_indices]+ remote_input = {**input_args, "tools": remote_tool_items}+ execute_fn = tools_model._wrap_execute_tool_for_tool_router(session_id=self.session_id,modifiers=modifiers,- ),- ),+ )+ remote_future = pool.submit(+ execute_fn,+ COMPOSIO_MULTI_EXECUTE_TOOL,+ remote_input,+ )++ # Gather local results+ local_results: t.List[t.Tuple[int, ToolExecutionResponse]] = []+ for idx, future in local_futures:+ local_results.append((idx, future.result()))++ # Gather remote result+ remote_result: t.Optional[t.Dict[str, t.Any]] = None+ if remote_future:+ remote_result = remote_future.result()++ # If only one local tool and no remote, return unwrapped+ if not remote_indices and len(local_results) == 1:+ return t.cast(t.Dict[str, t.Any], local_results[0][1])++ # Merge results into the backend's results[] format+ remote_data = (remote_result or {}).get("data", {})+ remote_results_list: t.List[t.Any] = (+ remote_data.get("results", [])+ if isinstance(remote_data, dict)+ else [])+ # Build local result entries matching backend format+ local_entries = []+ for idx, result in local_results:+ local_entries.append(+ {+ "response": {+ "successful": result["successful"],+ "data": result["data"],+ **({"error": result["error"]} if result.get("error") else {}),+ },+ "tool_slug": parsed[idx]["tool_slug"],+ **({"error": result["error"]} if result.get("error") else {}),+ }+ )++ # Merge: local entries + remote results, re-indexed sequentially+ merged: t.List[t.Any] = []+ remote_iter = iter(remote_results_list)+ local_map = {idx: entry for (idx, _), entry in zip(local_items, local_entries)}++ for i in range(len(parsed)):+ if i in local_map:+ merged.append(local_map[i])+ else:+ merged.append(next(remote_iter, {}))++ return {+ "data": {"results": merged},+ "error": None,+ "successful": True,+ }+def authorize(self,toolkit: str,@@ -236,9 +445,147 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):) -> t.Any:"""Execute a tool within the session.++ For custom tools, accepts the original slug (e.g. "GREP") or the+ full slug (e.g. "LOCAL_GREP"). Custom tools are executed in-process;+ remote tools are sent to the Composio backend."""+ # Check if this is a local tool (by original or final slug)+ entry = find_custom_tool(self._custom_tools_map, tool_slug)+ if entry and self._session_context:+ return execute_custom_tool(+ entry, arguments or {}, self._session_context+ )++ # Remote executionreturn self._client.tool_router.session.execute(session_id=self.session_id,tool_slug=tool_slug,arguments=arguments if arguments is not None else omit,)++ def custom_tools(+ self, *, toolkit: t.Optional[str] = None+ ) -> t.List[RegisteredCustomTool]:+ """List all custom tools registered in this session.++ Returns tools with their final slugs, schemas, and resolved toolkit.++ :param toolkit: Filter by toolkit slug (e.g. 'gmail', 'DEV_TOOLS')+ :returns: Array of registered custom tools+ """+ if not self._custom_tools_map:+ return []++ entries = list(self._custom_tools_map.by_final_slug.values())+ if toolkit:+ entries = [+ e+ for e in entries+ if e.toolkit and e.toolkit.lower() == toolkit.lower()+ ]++ return [+ RegisteredCustomTool(+ slug=entry.final_slug,+ name=entry.handle.name,+ description=entry.handle.description,+ toolkit=entry.toolkit,+ input_schema=entry.handle.input_schema,+ output_schema=entry.handle.output_schema,+ )+ for entry in entries+ ]++ def custom_toolkits(self) -> t.List[RegisteredCustomToolkit]:+ """List all custom toolkits registered in this session.++ Returns toolkits with their tools showing final slugs.+ """+ if not self._custom_tools_map or not self._custom_tools_map.toolkits:+ return []++ result = []+ for tk in self._custom_tools_map.toolkits:+ tools = []+ for tool in tk.tools:+ entry = self._custom_tools_map.by_original_slug.get(+ tool.slug.upper()+ )+ tools.append(+ RegisteredCustomTool(+ slug=entry.final_slug if entry else tool.slug,+ name=tool.name,+ description=tool.description,+ toolkit=tk.slug,+ input_schema=tool.input_schema,+ output_schema=tool.output_schema,+ )+ )+ result.append(+ RegisteredCustomToolkit(+ slug=tk.slug,+ name=tk.name,+ description=tk.description,+ tools=tools,+ )+ )+ return result++ def proxy_execute(+ self,+ *,+ toolkit: str,+ endpoint: str,+ method: t.Literal["GET", "POST", "PUT", "DELETE", "PATCH"],+ body: t.Any = None,+ parameters: t.Optional[t.List[t.Dict[str, t.Any]]] = None,+ ) -> ProxyExecuteResponse:+ """Proxy an API call through Composio's auth layer.++ The backend resolves the connected account from the toolkit+ within the session.++ :param toolkit: Composio toolkit slug (e.g. 'gmail', 'github')+ :param endpoint: API endpoint URL+ :param method: HTTP method+ :param body: Request body (for POST, PUT, PATCH)+ :param parameters: Query/header parameters+ :returns: Proxied API response+ """+ # Transform parameters to API format+ api_params: t.List[t.Dict[str, t.Any]] = []+ if parameters:+ for p in parameters:+ api_params.append(+ {+ "name": p["name"],+ "type": p.get("in", p.get("type", "header")),+ "value": str(p["value"]),+ }+ )++ response = self._client.tool_router.session.proxy_execute(+ session_id=self.session_id,+ toolkit_slug=toolkit,+ endpoint=endpoint,+ method=method,+ body=body if body is not None else omit,+ parameters=api_params if api_params else omit,+ )++ result: ProxyExecuteResponse = {+ "status": int(response.status),+ "data": response.data,+ "headers": response.headers,+ }++ if response.binary_data:+ result["binary_data"] = {+ "content_type": response.binary_data.content_type,+ "size": int(response.binary_data.size),+ "url": response.binary_data.url,+ "expires_at": response.binary_data.expires_at,+ }++ return resultdiff --git a/python/pyproject.toml b/python/pyproject.tomlindex f46676808..285b6bef6 100644--- a/python/pyproject.toml+++ b/python/pyproject.toml@@ -7,7 +7,7 @@ requires-python = ">=3.10,<4"dependencies = ["pysher>=1.0.8","pydantic>=2.6.4",- "composio-client==1.28.0",+ "composio-client==1.29.0","typing-extensions>=4.0.0","openai","json-schema-to-pydantic>=0.4.8",diff --git a/python/tests/test_custom_tools.py b/python/tests/test_custom_tools.pynew file mode 100644index 000000000..d683bb30f--- /dev/null+++ b/python/tests/test_custom_tools.py@@ -0,0 +1,946 @@+"""Tests for custom tools in tool router sessions.++Covers:+- Factory function validation (slug rules, required fields, Pydantic model check)+- Slug prefixing and collision detection+- Serialization to API format+- Custom tool execution (validation, defaults, errors)+- Routing map building and lookup+- SessionContextImpl sibling routing+- ToolRouterSession integration (execute routing, custom_tools(), custom_toolkits())+- Multi-execute routing (all-local, all-remote, mixed, parallel)+"""++from unittest.mock import MagicMock, patch++import pytest+from pydantic import BaseModel, Field++from composio import experimental_create_tool, experimental_create_toolkit+from composio.core.models.custom_tool import (+ build_custom_tools_map,+ build_custom_tools_map_from_response,+ serialize_custom_tools,+ serialize_custom_toolkits,+)+from composio.core.models.custom_tool_execution import (+ execute_custom_tool,+ find_custom_tool,+)+from composio.core.models.custom_tool_types import (+ CustomToolsMap,+ CustomToolsMapEntry,+ RegisteredCustomTool,+ RegisteredCustomToolkit,+)+from composio.core.models.session_context import SessionContextImpl+from composio.core.models.tool_router_session import ToolRouterSession+from composio.exceptions import ValidationError+++# ────────────────────────────────────────────────────────────────+# Fixtures+# ────────────────────────────────────────────────────────────────+++class GrepInput(BaseModel):+ pattern: str = Field(description="Pattern to search for")+ path: str = Field(default=".", description="File path")+++class EmailInput(BaseModel):+ to: str = Field(description="Recipient email")+ subject: str = Field(description="Subject")+++class SetRoleInput(BaseModel):+ user_id: str = Field(description="User ID")+ role: str = Field(default="viewer", description="New role")+++def grep_tool():+ return experimental_create_tool(+ "GREP",+ name="Grep Search",+ description="Search for patterns in files",+ input_params=GrepInput,+ execute=lambda input, ctx: {"matches": [input.pattern], "path": input.path},+ )+++def email_tool():+ return experimental_create_tool(+ "GET_EMAILS",+ name="Get Emails",+ description="Get emails from Gmail",+ input_params=EmailInput,+ execute=lambda input, ctx: {"emails": []},+ extends_toolkit="gmail",+ )+++def set_role_tool():+ return experimental_create_tool(+ "SET_ROLE",+ name="Set role",+ description="Set a user's role",+ input_params=SetRoleInput,+ execute=lambda input, ctx: {+ "user_id": input.user_id,+ "role": input.role,+ "updated": True,+ },+ )+++def role_toolkit(set_role_tool):+ return experimental_create_toolkit(+ "ROLE_MANAGER",+ name="Role Manager",+ description="Manage user roles",+ tools=[set_role_tool],+ )+++class MockSessionContext:+ user_id = "test-user"++ def execute(self, tool_slug, arguments):+ return {"data": {}, "error": None, "successful": True}++ def proxy_execute(self, **kwargs):+ return {"status": 200, "data": {}, "headers": {}}+++# ────────────────────────────────────────────────────────────────+# Factory validation tests+# ────────────────────────────────────────────────────────────────+++class TestCreateCustomTool:+ def test_creates_tool_with_valid_params(self, grep_tool):+ assert grep_tool.slug == "GREP"+ assert grep_tool.name == "Grep Search"+ assert grep_tool.description == "Search for patterns in files"+ assert grep_tool.extends_toolkit is None+ assert grep_tool.input_schema["type"] == "object"+ assert "pattern" in grep_tool.input_schema["properties"]+ assert grep_tool.output_schema is None++ def test_creates_extension_tool(self, email_tool):+ assert email_tool.slug == "GET_EMAILS"+ assert email_tool.extends_toolkit == "gmail"++ def test_slug_empty(self):+ with pytest.raises(ValidationError, match="slug is required"):+ experimental_create_tool(+ "",+ name="Bad",+ description="Bad",+ input_params=GrepInput,+ execute=lambda i, c: {},+ )++ def test_slug_invalid_chars(self):+ with pytest.raises(ValidationError, match="alphanumeric"):+ experimental_create_tool(+ "BAD SLUG!",+ name="Bad",+ description="Bad",+ input_params=GrepInput,+ execute=lambda i, c: {},+ )++ def test_slug_local_prefix(self):+ with pytest.raises(ValidationError, match="LOCAL_"):+ experimental_create_tool(+ "LOCAL_BAD",+ name="Bad",+ description="Bad",+ input_params=GrepInput,+ execute=lambda i, c: {},+ )++ def test_slug_composio_prefix(self):+ with pytest.raises(ValidationError, match="COMPOSIO_"):+ experimental_create_tool(+ "COMPOSIO_BAD",+ name="Bad",+ description="Bad",+ input_params=GrepInput,+ execute=lambda i, c: {},+ )++ def test_name_required(self):+ with pytest.raises(ValidationError, match="name is required"):+ experimental_create_tool(+ "GOOD",+ name="",+ description="Desc",+ input_params=GrepInput,+ execute=lambda i, c: {},+ )++ def test_description_required(self):+ with pytest.raises(ValidationError, match="description is required"):+ experimental_create_tool(+ "GOOD",+ name="Name",+ description="",+ input_params=GrepInput,+ execute=lambda i, c: {},+ )++ def test_input_params_must_be_basemodel_subclass(self):+ with pytest.raises(ValidationError, match="BaseModel subclass"):+ experimental_create_tool(+ "GOOD",+ name="Name",+ description="Desc",+ input_params=dict, # type: ignore+ execute=lambda i, c: {},+ )++ def test_input_params_must_not_be_instance(self):+ with pytest.raises(ValidationError, match="BaseModel subclass"):+ experimental_create_tool(+ "GOOD",+ name="Name",+ description="Desc",+ input_params=GrepInput(pattern="x"), # type: ignore+ execute=lambda i, c: {},+ )++ def test_execute_must_be_callable(self):+ with pytest.raises(ValidationError, match="callable"):+ experimental_create_tool(+ "GOOD",+ name="Name",+ description="Desc",+ input_params=GrepInput,+ execute="not a function", # type: ignore+ )++ def test_slug_length_validation_standalone(self):+ # LOCAL_ + 55 chars = 61 > 60+ with pytest.raises(ValidationError, match="too long"):+ experimental_create_tool(+ "A" * 55,+ name="Name",+ description="Desc",+ input_params=GrepInput,+ execute=lambda i, c: {},+ )++ def test_slug_length_validation_extension(self):+ # LOCAL_ + GMAIL_ + slug must be <= 60+ with pytest.raises(ValidationError, match="too long"):+ experimental_create_tool(+ "A" * 50,+ name="Name",+ description="Desc",+ input_params=GrepInput,+ execute=lambda i, c: {},+ extends_toolkit="gmail",+ )++ def test_output_params(self):+ class OutputSchema(BaseModel):+ matches: int++ tool = experimental_create_tool(+ "TOOL",+ name="Tool",+ description="Desc",+ input_params=GrepInput,+ execute=lambda i, c: {},+ output_params=OutputSchema,+ )+ assert tool.output_schema is not None+ assert "properties" in tool.output_schema++ def test_input_schema_includes_defaults(self, grep_tool):+ # path has default="." - Pydantic won't include it in required+ assert "pattern" in grep_tool.input_schema.get("required", [])+ assert "path" not in grep_tool.input_schema.get("required", [])++ def test_frozen_dataclass(self, grep_tool):+ with pytest.raises(AttributeError):+ grep_tool.slug = "NEW" # type: ignore+++class TestCreateCustomToolkit:+ def test_creates_toolkit(self, role_toolkit, set_role_tool):+ assert role_toolkit.slug == "ROLE_MANAGER"+ assert role_toolkit.name == "Role Manager"+ assert len(role_toolkit.tools) == 1+ assert role_toolkit.tools[0].slug == "SET_ROLE"++ def test_rejects_empty_tools(self):+ with pytest.raises(ValidationError, match="at least one tool"):+ experimental_create_toolkit(+ "TK",+ name="TK",+ description="Desc",+ tools=[],+ )++ def test_rejects_extends_toolkit_in_tools(self, email_tool):+ with pytest.raises(ValidationError, match="extends_toolkit"):+ experimental_create_toolkit(+ "TK",+ name="TK",+ description="Desc",+ tools=[email_tool],+ )++ def test_slug_length_validation(self):+ tool = experimental_create_tool(+ "A" * 45,+ name="Name",+ description="Desc",+ input_params=GrepInput,+ execute=lambda i, c: {},+ )+ # LOCAL_ + LONG_TOOLKIT_ + AAAA... would exceed 60+ with pytest.raises(ValidationError, match="too long"):+ experimental_create_toolkit(+ "LONG_TOOLKIT",+ name="TK",+ description="Desc",+ tools=[tool],+ )++ def test_slug_validation(self):+ with pytest.raises(ValidationError, match="LOCAL_"):+ experimental_create_toolkit(+ "LOCAL_BAD",+ name="TK",+ description="Desc",+ tools=[+ experimental_create_tool(+ "T",+ name="T",+ description="D",+ input_params=GrepInput,+ execute=lambda i, c: {},+ )+ ],+ )+++# ────────────────────────────────────────────────────────────────+# Serialization tests+# ────────────────────────────────────────────────────────────────+++class TestSerialization:+ def test_serialize_standalone_tool(self, grep_tool):+ result = serialize_custom_tools([grep_tool])+ assert len(result) == 1+ assert result[0]["slug"] == "GREP"+ assert result[0]["name"] == "Grep Search"+ assert result[0]["input_schema"]["type"] == "object"+ assert "extends_toolkit" not in result[0]++ def test_serialize_extension_tool(self, email_tool):+ result = serialize_custom_tools([email_tool])+ assert result[0]["extends_toolkit"] == "gmail"++ def test_serialize_toolkit(self, role_toolkit):+ result = serialize_custom_toolkits([role_toolkit])+ assert len(result) == 1+ assert result[0]["slug"] == "ROLE_MANAGER"+ assert len(result[0]["tools"]) == 1+ assert result[0]["tools"][0]["slug"] == "SET_ROLE"+++# ────────────────────────────────────────────────────────────────+# Routing map tests+# ────────────────────────────────────────────────────────────────+++class TestCustomToolsMap:+ def test_build_map_standalone(self, grep_tool):+ m = build_custom_tools_map([grep_tool])+ assert "LOCAL_GREP" in m.by_final_slug+ assert "GREP" in m.by_original_slug++ def test_build_map_extension(self, email_tool):+ m = build_custom_tools_map([email_tool])+ assert "LOCAL_GMAIL_GET_EMAILS" in m.by_final_slug+ assert "GET_EMAILS" in m.by_original_slug++ def test_build_map_toolkit(self, set_role_tool, role_toolkit):+ m = build_custom_tools_map([], [role_toolkit])+ assert "LOCAL_ROLE_MANAGER_SET_ROLE" in m.by_final_slug+ assert "SET_ROLE" in m.by_original_slug++ def test_build_map_mixed(self, grep_tool, email_tool, role_toolkit):+ m = build_custom_tools_map([grep_tool, email_tool], [role_toolkit])+ assert len(m.by_final_slug) == 3+ assert len(m.by_original_slug) == 3++ def test_collision_detection_final_slug(self, grep_tool):+ with pytest.raises(ValidationError, match="collision"):+ build_custom_tools_map([grep_tool, grep_tool])++ def test_collision_detection_original_slug(self):+ tool1 = experimental_create_tool(+ "FOO",+ name="Foo",+ description="Desc",+ input_params=GrepInput,+ execute=lambda i, c: {},+ )+ # Same slug in a toolkit produces different final slug but same original+ # This would collide on original slug+ toolkit = experimental_create_toolkit(+ "TK",+ name="TK",+ description="D",+ tools=[+ experimental_create_tool(+ "FOO",+ name="Foo2",+ description="Desc2",+ input_params=GrepInput,+ execute=lambda i, c: {},+ )+ ],+ )+ with pytest.raises(ValidationError, match="collision"):+ build_custom_tools_map([tool1], [toolkit])+++class TestFindCustomTool:+ def test_find_by_final_slug(self, grep_tool):+ m = build_custom_tools_map([grep_tool])+ entry = find_custom_tool(m, "LOCAL_GREP")+ assert entry is not None+ assert entry.final_slug == "LOCAL_GREP"++ def test_find_by_original_slug(self, grep_tool):+ m = build_custom_tools_map([grep_tool])+ entry = find_custom_tool(m, "GREP")+ assert entry is not None+ assert entry.final_slug == "LOCAL_GREP"++ def test_find_case_insensitive(self, grep_tool):+ m = build_custom_tools_map([grep_tool])+ entry = find_custom_tool(m, "grep")+ assert entry is not None+ assert entry.final_slug == "LOCAL_GREP"++ def test_find_nonexistent(self, grep_tool):+ m = build_custom_tools_map([grep_tool])+ assert find_custom_tool(m, "NONEXISTENT") is None++ def test_find_none_map(self):+ assert find_custom_tool(None, "GREP") is None+++class TestBuildMapFromResponse:+ def test_builds_from_response(self, grep_tool, email_tool, role_toolkit):+ # Mock response experimental+ mock_exp = MagicMock()++ mock_ct1 = MagicMock()+ mock_ct1.slug = "LOCAL_GREP"+ mock_ct1.original_slug = "GREP"+ mock_ct1.extends_toolkit = None++ mock_ct2 = MagicMock()+ mock_ct2.slug = "LOCAL_GMAIL_GET_EMAILS"+ mock_ct2.original_slug = "GET_EMAILS"+ mock_ct2.extends_toolkit = "gmail"++ mock_exp.custom_tools = [mock_ct1, mock_ct2]++ mock_ctk = MagicMock()+ mock_ctk.slug = "ROLE_MANAGER"+ mock_ctk_tool = MagicMock()+ mock_ctk_tool.slug = "LOCAL_ROLE_MANAGER_SET_ROLE"+ mock_ctk_tool.original_slug = "SET_ROLE"+ mock_ctk.tools = [mock_ctk_tool]+ mock_exp.custom_toolkits = [mock_ctk]++ set_role = role_toolkit.tools[0]+ m = build_custom_tools_map_from_response(+ [grep_tool, email_tool],+ [role_toolkit],+ mock_exp,+ )++ assert "LOCAL_GREP" in m.by_final_slug+ assert "LOCAL_GMAIL_GET_EMAILS" in m.by_final_slug+ assert "LOCAL_ROLE_MANAGER_SET_ROLE" in m.by_final_slug+ assert m.by_final_slug["LOCAL_GMAIL_GET_EMAILS"].toolkit == "gmail"+++# ────────────────────────────────────────────────────────────────+# Custom tool execution tests+# ────────────────────────────────────────────────────────────────+++class TestExecuteCustomTool:+ def test_successful_execution(self, grep_tool):+ m = build_custom_tools_map([grep_tool])+ entry = find_custom_tool(m, "GREP")+ result = execute_custom_tool(entry, {"pattern": "hello"}, MockSessionContext()) # type: ignore+ assert result["successful"] is True+ assert result["data"]["matches"] == ["hello"]+ assert result["data"]["path"] == "." # default value+ assert result["error"] is None++ def test_applies_pydantic_defaults(self, grep_tool):+ m = build_custom_tools_map([grep_tool])+ entry = find_custom_tool(m, "GREP")+ result = execute_custom_tool(entry, {"pattern": "test"}, MockSessionContext()) # type: ignore+ assert result["data"]["path"] == "." # default applied++ def test_validation_failure(self, grep_tool):+ m = build_custom_tools_map([grep_tool])+ entry = find_custom_tool(m, "GREP")+ result = execute_custom_tool(entry, {}, MockSessionContext()) # type: ignore # missing required "pattern"+ assert result["successful"] is False+ assert "validation" in result["error"].lower()++ def test_execute_function_error(self):+ def bad_execute(input, ctx):+ raise RuntimeError("Something went wrong")++ tool = experimental_create_tool(+ "BAD",+ name="Bad",+ description="Desc",+ input_params=GrepInput,+ execute=bad_execute,+ )+ m = build_custom_tools_map([tool])+ entry = find_custom_tool(m, "BAD")+ result = execute_custom_tool(entry, {"pattern": "x"}, MockSessionContext()) # type: ignore+ assert result["successful"] is False+ assert "Something went wrong" in result["error"]++ def test_execute_returns_none(self):+ tool = experimental_create_tool(+ "NOOP",+ name="Noop",+ description="Returns None",+ input_params=GrepInput,+ execute=lambda i, c: None, # type: ignore+ )+ m = build_custom_tools_map([tool])+ entry = find_custom_tool(m, "NOOP")+ result = execute_custom_tool(entry, {"pattern": "x"}, MockSessionContext()) # type: ignore+ assert result["successful"] is True+ assert result["data"] == {}+++# ────────────────────────────────────────────────────────────────+# SessionContextImpl tests+# ────────────────────────────────────────────────────────────────+++class TestSessionContextImpl:+ def test_user_id(self):+ ctx = SessionContextImpl(+ client=MagicMock(),+ user_id="user-1",+ session_id="sess-1",+ )+ assert ctx.user_id == "user-1"++ def test_execute_routes_to_sibling(self, grep_tool):+ m = build_custom_tools_map([grep_tool])+ ctx = SessionContextImpl(+ client=MagicMock(),+ user_id="user-1",+ session_id="sess-1",+ custom_tools_map=m,+ )+ result = ctx.execute("GREP", {"pattern": "test"})+ assert result["successful"] is True+ assert result["data"]["matches"] == ["test"]++ def test_execute_falls_back_to_remote(self, grep_tool):+ m = build_custom_tools_map([grep_tool])+ mock_client = MagicMock()+ mock_response = MagicMock()+ mock_response.data = {"remote": True}+ mock_response.error = None+ mock_client.tool_router.session.execute.return_value = mock_response++ ctx = SessionContextImpl(+ client=mock_client,+ user_id="user-1",+ session_id="sess-1",+ custom_tools_map=m,+ )+ result = ctx.execute("NONEXISTENT_TOOL", {"arg": "val"})+ mock_client.tool_router.session.execute.assert_called_once()+ assert result["data"] == {"remote": True}++ def test_proxy_execute(self):+ mock_client = MagicMock()+ mock_response = MagicMock()+ mock_response.status = 200+ mock_response.data = {"result": "ok"}+ mock_response.headers = {"Content-Type": "application/json"}+ mock_response.binary_data = None+ mock_client.tool_router.session.proxy_execute.return_value = mock_response++ ctx = SessionContextImpl(+ client=mock_client,+ user_id="user-1",+ session_id="sess-1",+ )+ result = ctx.proxy_execute(+ toolkit="gmail",+ endpoint="https://gmail.googleapis.com/test",+ method="GET",+ )+ assert result["status"] == 200+ assert result["data"] == {"result": "ok"}+ mock_client.tool_router.session.proxy_execute.assert_called_once()+++# ────────────────────────────────────────────────────────────────+# ToolRouterSession integration tests+# ────────────────────────────────────────────────────────────────+++def mock_session_deps(grep_tool, email_tool, role_toolkit):+ """Create mock dependencies for ToolRouterSession with custom tools."""+ client = MagicMock()+ provider = MagicMock()+ experimental = MagicMock()+ experimental.files = MagicMock()+ experimental.assistive_prompt = None++ # Build tools map+ tools_map = build_custom_tools_map([grep_tool, email_tool], [role_toolkit])++ return {+ "client": client,+ "provider": provider,+ "experimental": experimental,+ "tools_map": tools_map,+ }+++class TestToolRouterSessionCustomTools:+ def test_execute_routes_to_local(self, mock_session_deps, grep_tool):+ session = ToolRouterSession(+ client=mock_session_deps["client"],+ provider=mock_session_deps["provider"],+ auto_upload_download_files=True,+ session_id="sess-1",+ mcp=MagicMock(),+ experimental=mock_session_deps["experimental"],+ custom_tools_map=mock_session_deps["tools_map"],+ user_id="user-1",+ )+ result = session.execute("GREP", arguments={"pattern": "test"})+ assert result["successful"] is True+ assert result["data"]["matches"] == ["test"]+ # Should NOT have called the backend+ mock_session_deps["client"].tool_router.session.execute.assert_not_called()++ def test_execute_routes_to_local_by_final_slug(self, mock_session_deps):+ session = ToolRouterSession(+ client=mock_session_deps["client"],+ provider=mock_session_deps["provider"],+ auto_upload_download_files=True,+ session_id="sess-1",+ mcp=MagicMock(),+ experimental=mock_session_deps["experimental"],+ custom_tools_map=mock_session_deps["tools_map"],+ user_id="user-1",+ )+ result = session.execute("LOCAL_GREP", arguments={"pattern": "test"})+ assert result["successful"] is True++ def test_execute_case_insensitive(self, mock_session_deps):+ session = ToolRouterSession(+ client=mock_session_deps["client"],+ provider=mock_session_deps["provider"],+ auto_upload_download_files=True,+ session_id="sess-1",+ mcp=MagicMock(),+ experimental=mock_session_deps["experimental"],+ custom_tools_map=mock_session_deps["tools_map"],+ user_id="user-1",+ )+ result = session.execute("grep", arguments={"pattern": "test"})+ assert result["successful"] is True++ def test_execute_routes_to_remote(self, mock_session_deps):+ mock_response = MagicMock()+ mock_session_deps["client"].tool_router.session.execute.return_value = (+ mock_response+ )++ session = ToolRouterSession(+ client=mock_session_deps["client"],+ provider=mock_session_deps["provider"],+ auto_upload_download_files=True,+ session_id="sess-1",+ mcp=MagicMock(),+ experimental=mock_session_deps["experimental"],+ custom_tools_map=mock_session_deps["tools_map"],+ user_id="user-1",+ )+ session.execute("GMAIL_SEND_EMAIL", arguments={"to": "[email protected]"})+ mock_session_deps["client"].tool_router.session.execute.assert_called_once()++ def test_custom_tools_list(self, mock_session_deps):+ session = ToolRouterSession(+ client=mock_session_deps["client"],+ provider=mock_session_deps["provider"],+ auto_upload_download_files=True,+ session_id="sess-1",+ mcp=MagicMock(),+ experimental=mock_session_deps["experimental"],+ custom_tools_map=mock_session_deps["tools_map"],+ user_id="user-1",+ )+ tools = session.custom_tools()+ assert len(tools) == 3+ slugs = {t.slug for t in tools}+ assert "LOCAL_GREP" in slugs+ assert "LOCAL_GMAIL_GET_EMAILS" in slugs+ assert "LOCAL_ROLE_MANAGER_SET_ROLE" in slugs++ def test_custom_tools_filter_by_toolkit(self, mock_session_deps):+ session = ToolRouterSession(+ client=mock_session_deps["client"],+ provider=mock_session_deps["provider"],+ auto_upload_download_files=True,+ session_id="sess-1",+ mcp=MagicMock(),+ experimental=mock_session_deps["experimental"],+ custom_tools_map=mock_session_deps["tools_map"],+ user_id="user-1",+ )+ gmail_tools = session.custom_tools(toolkit="gmail")+ assert len(gmail_tools) == 1+ assert gmail_tools[0].slug == "LOCAL_GMAIL_GET_EMAILS"++ def test_custom_toolkits_list(self, mock_session_deps):+ session = ToolRouterSession(+ client=mock_session_deps["client"],+ provider=mock_session_deps["provider"],+ auto_upload_download_files=True,+ session_id="sess-1",+ mcp=MagicMock(),+ experimental=mock_session_deps["experimental"],+ custom_tools_map=mock_session_deps["tools_map"],+ user_id="user-1",+ )+ toolkits = session.custom_toolkits()+ assert len(toolkits) == 1+ assert toolkits[0].slug == "ROLE_MANAGER"+ assert len(toolkits[0].tools) == 1+ assert toolkits[0].tools[0].slug == "LOCAL_ROLE_MANAGER_SET_ROLE"++ def test_custom_tools_empty_when_no_map(self):+ session = ToolRouterSession(+ client=MagicMock(),+ provider=MagicMock(),+ auto_upload_download_files=True,+ session_id="sess-1",+ mcp=MagicMock(),+ experimental=MagicMock(),+ )+ assert session.custom_tools() == []+ assert session.custom_toolkits() == []++ def test_proxy_execute(self, mock_session_deps):+ mock_response = MagicMock()+ mock_response.status = 200+ mock_response.data = {"result": "ok"}+ mock_response.headers = {"Content-Type": "application/json"}+ mock_response.binary_data = None+ mock_session_deps[+ "client"+ ].tool_router.session.proxy_execute.return_value = mock_response++ session = ToolRouterSession(+ client=mock_session_deps["client"],+ provider=mock_session_deps["provider"],+ auto_upload_download_files=True,+ session_id="sess-1",+ mcp=MagicMock(),+ experimental=mock_session_deps["experimental"],+ )+ result = session.proxy_execute(+ toolkit="gmail",+ endpoint="https://gmail.googleapis.com/test",+ method="GET",+ )+ assert result["status"] == 200+ mock_session_deps[+ "client"+ ].tool_router.session.proxy_execute.assert_called_once()+++# ────────────────────────────────────────────────────────────────+# Multi-execute routing tests+# ────────────────────────────────────────────────────────────────+++class TestMultiExecuteRouting:+ def _make_session(self, grep_tool, mock_client=None):+ m = build_custom_tools_map([grep_tool])+ client = mock_client or MagicMock()+ session = ToolRouterSession(+ client=client,+ provider=MagicMock(),+ auto_upload_download_files=True,+ session_id="sess-1",+ mcp=MagicMock(),+ experimental=MagicMock(),+ custom_tools_map=m,+ user_id="user-1",+ )+ return session++ def test_route_all_local(self, grep_tool):+ session = self._make_session(grep_tool)+ mock_tools_model = MagicMock()++ result = session._route_multi_execute(+ {"tools": [{"tool_slug": "GREP", "arguments": {"pattern": "test"}}]},+ mock_tools_model,+ None,+ )+ # Single local tool returns unwrapped+ assert result["successful"] is True+ assert result["data"]["matches"] == ["test"]++ def test_route_all_remote(self, grep_tool):+ session = self._make_session(grep_tool)+ mock_tools_model = MagicMock()++ remote_response = {+ "data": {"results": [{"tool_slug": "GMAIL_SEND", "response": {"successful": True}}]},+ "error": None,+ "successful": True,+ }+ mock_tools_model._wrap_execute_tool_for_tool_router.return_value = (+ lambda slug, args: remote_response+ )++ result = session._route_multi_execute(+ {+ "tools": [+ {"tool_slug": "GMAIL_SEND", "arguments": {"to": "[email protected]"}}+ ]+ },+ mock_tools_model,+ None,+ )+ assert result == remote_response++ def test_route_mixed_local_and_remote(self, grep_tool):+ session = self._make_session(grep_tool)+ mock_tools_model = MagicMock()++ remote_response = {+ "data": {+ "results": [+ {+ "tool_slug": "GMAIL_SEND",+ "response": {"successful": True, "data": {"sent": True}},+ }+ ]+ },+ "error": None,+ "successful": True,+ }+ mock_tools_model._wrap_execute_tool_for_tool_router.return_value = (+ lambda slug, args: remote_response+ )++ result = session._route_multi_execute(+ {+ "tools": [+ {"tool_slug": "GREP", "arguments": {"pattern": "test"}},+ {"tool_slug": "GMAIL_SEND", "arguments": {"to": "[email protected]"}},+ ]+ },+ mock_tools_model,+ None,+ )+ # Should have merged results+ assert result["successful"] is True+ results = result["data"]["results"]+ assert len(results) == 2+ # First should be the local GREP result+ assert results[0]["tool_slug"] == "GREP"+ assert results[0]["response"]["successful"] is True+ # Second should be the remote result+ assert results[1]["tool_slug"] == "GMAIL_SEND"++ def test_route_empty_tools(self, grep_tool):+ session = self._make_session(grep_tool)+ mock_tools_model = MagicMock()+ fallback_result = {"data": {}, "error": None, "successful": True}+ mock_tools_model._wrap_execute_tool_for_tool_router.return_value = (+ lambda slug, args: fallback_result+ )++ result = session._route_multi_execute(+ {"tools": []}, mock_tools_model, None+ )+ # Should fall back to remote+ assert result == fallback_result++ def test_route_multiple_local_tools(self):+ tool1 = experimental_create_tool(+ "TOOL_A",+ name="A",+ description="D",+ input_params=GrepInput,+ execute=lambda i, c: {"tool": "A", "pattern": i.pattern},+ )+ tool2 = experimental_create_tool(+ "TOOL_B",+ name="B",+ description="D",+ input_params=GrepInput,+ execute=lambda i, c: {"tool": "B", "pattern": i.pattern},+ )+ m = build_custom_tools_map([tool1, tool2])+ session = ToolRouterSession(+ client=MagicMock(),+ provider=MagicMock(),+ auto_upload_download_files=True,+ session_id="sess-1",+ mcp=MagicMock(),+ experimental=MagicMock(),+ custom_tools_map=m,+ user_id="user-1",+ )+ result = session._route_multi_execute(+ {+ "tools": [+ {"tool_slug": "TOOL_A", "arguments": {"pattern": "x"}},+ {"tool_slug": "TOOL_B", "arguments": {"pattern": "y"}},+ ]+ },+ MagicMock(),+ None,+ )+ assert result["successful"] is True+ results = result["data"]["results"]+ assert len(results) == 2+ assert results[0]["response"]["data"]["tool"] == "A"+ assert results[1]["response"]["data"]["tool"] == "B"