@devries-cameron20 / composio Mirror · read-only / commits / 27a23ad66
Fork 0

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

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 22, 02:00 UTC

feat(python): add custom tools and toolkits for tool router sessions

Port the TypeScript custom tools feature to the Python SDK, enabling developers to define local tools that run in-process alongside remote Composio tools within a session. Three tool patterns supported: - Standalone tools (no auth) - Extension tools (inherits auth from a Composio toolkit via extends_toolkit) - Custom toolkits (groups related tools under one namespace) Key implementation: - Factory functions: experimental_create_tool() and experimental_create_toolkit() - Pydantic BaseModel for input schema (equivalent of Zod in TS) - SessionContext with execute() for sibling routing and proxy_execute() for auth proxy - COMPOSIO_MULTI_EXECUTE_TOOL routing: splits local/remote, parallel execution via ThreadPoolExecutor (max 5 workers) - Custom tools map built from backend response (authoritative slug mapping) - Bumps composio-client to 1.29.0 for custom_tools/custom_toolkits/proxy_execute types Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

Dhawal Upadhyay committed Mar 20, 2026 at 12:48 UTC 27a23ad66939569587277582f3c2223b78fe16c3
10 files changed +2238 -10
python/composio/__init__.py
+14
@@ -1,4 +1,13 @@
1 from .__version__ import __version__
2 +from .core.models.custom_tool import (
3 + experimental_create_tool,
4 + experimental_create_toolkit,
5 +)
6 +from .core.models.custom_tool_types import (
7 + CustomTool,
8 + CustomToolkit,
9 + SessionContext,
10 +)
11 from .core.models.tool_router_session_files import RemoteFile
12 from .core.models.tools import (
13 after_execute,
@@ -25,7 +34,10 @@ from .sdk import Composio
34
35 __all__ = (
36 "Composio",
37 + "CustomTool",
38 + "CustomToolkit",
39 "RemoteFile",
40 + "SessionContext",
41 "ConnectionExpiredEvent",
42 "ConnectionState",
43 "ConnectionStatusEnum",
@@ -35,6 +47,8 @@ __all__ = (
47 "WebhookEventType",
48 "after_execute",
49 "before_execute",
50 + "experimental_create_tool",
51 + "experimental_create_toolkit",
52 "is_connection_expired_event",
53 "schema_modifier",
54 "__version__",
python/composio/core/models/__init__.py
+17
@@ -1,5 +1,14 @@
1 from .auth_configs import AuthConfigs
2 from .connected_accounts import ConnectedAccounts
3 +from .custom_tool import experimental_create_tool, experimental_create_toolkit
4 +from .custom_tool_types import (
5 + CustomTool,
6 + CustomToolkit,
7 + ProxyExecuteResponse,
8 + RegisteredCustomTool,
9 + RegisteredCustomToolkit,
10 + SessionContext,
11 +)
12 from .mcp import MCP
13 from .tool_router import ToolRouter
14 from .tool_router_session import ToolRouterSession
@@ -24,8 +33,14 @@ __all__ = [
33 "ConnectionExpiredEvent",
34 "ConnectionState",
35 "ConnectionStatusEnum",
36 + "CustomTool",
37 + "CustomToolkit",
38 "MCP",
39 + "ProxyExecuteResponse",
40 + "RegisteredCustomTool",
41 + "RegisteredCustomToolkit",
42 "RemoteFile",
43 + "SessionContext",
44 "SingleConnectedAccountDetailedResponse",
45 "ToolRouter",
46 "ToolRouterSession",
@@ -36,5 +51,7 @@ __all__ = [
51 "WebhookConnectionMetadata",
52 "WebhookEvent",
53 "WebhookEventType",
54 + "experimental_create_tool",
55 + "experimental_create_toolkit",
56 "is_connection_expired_event",
57 ]
python/composio/core/models/custom_tool.py new
+484
@@ -0,0 +1,484 @@
1 +"""Factory functions for creating custom tools and toolkits.
2 +
3 +Usage::
4 +
5 + from composio import experimental_create_tool, experimental_create_toolkit
6 + from pydantic import BaseModel, Field
7 +
8 + class GrepInput(BaseModel):
9 + pattern: str = Field(description="Pattern to search for")
10 +
11 + grep = experimental_create_tool("GREP",
12 + name="Grep Search",
13 + description="Search for patterns in files",
14 + input_params=GrepInput,
15 + execute=lambda input, ctx: {"matches": []},
16 + )
17 +
18 + dev_tools = experimental_create_toolkit("DEV_TOOLS",
19 + name="Dev Tools",
20 + description="Local dev utilities",
21 + tools=[grep],
22 + )
23 +"""
24 +
25 +from __future__ import annotations
26 +
27 +import typing as t
28 +
29 +from pydantic import BaseModel
30 +
31 +from composio.exceptions import ValidationError
32 +
33 +from .custom_tool_types import (
34 + LOCAL_TOOL_PREFIX,
35 + MAX_SLUG_LENGTH,
36 + SLUG_REGEX,
37 + CustomTool,
38 + CustomToolExecuteFn,
39 + CustomToolkit,
40 + CustomToolsMap,
41 + CustomToolsMapEntry,
42 +)
43 +
44 +if t.TYPE_CHECKING:
45 + from composio_client.types.tool_router.session_create_response import (
46 + Experimental as SessionCreateResponseExperimental,
47 + )
48 +
49 +
50 +# ────────────────────────────────────────────────────────────────
51 +# Slug validation helpers
52 +# ────────────────────────────────────────────────────────────────
53 +
54 +
55 +def _validate_slug(slug: str, context: str) -> str:
56 + """Validate a custom tool or toolkit slug."""
57 + if not slug:
58 + raise ValidationError(f"{context}: slug is required")
59 +
60 + if not SLUG_REGEX.match(slug):
61 + raise ValidationError(
62 + f"{context}: slug must only contain alphanumeric characters, "
63 + f"underscores, and hyphens"
64 + )
65 +
66 + upper = slug.upper()
67 + if upper.startswith("LOCAL_"):
68 + raise ValidationError(
69 + f'{context}: slug must not start with "LOCAL_" — '
70 + f"this prefix is reserved for internal routing."
71 + )
72 + if upper.startswith("COMPOSIO_"):
73 + raise ValidationError(
74 + f'{context}: slug must not start with "COMPOSIO_" — '
75 + f"this prefix is reserved for Composio meta tools."
76 + )
77 +
78 + return slug
79 +
80 +
81 +def _compute_final_slug_length(tool_slug: str, toolkit_slug: t.Optional[str]) -> int:
82 + """Compute the final slug length: LOCAL_[TOOLKIT_]SLUG."""
83 + length = len(LOCAL_TOOL_PREFIX) + len(tool_slug)
84 + if toolkit_slug:
85 + length += len(toolkit_slug) + 1 # +1 for underscore separator
86 + return length
87 +
88 +
89 +def _validate_slug_length(
90 + tool_slug: str, toolkit_slug: t.Optional[str], context: str
91 +) -> None:
92 + """Validate that the final slug won't exceed the max length."""
93 + final_length = _compute_final_slug_length(tool_slug, toolkit_slug)
94 + if final_length > MAX_SLUG_LENGTH:
95 + prefix = LOCAL_TOOL_PREFIX + (
96 + f"{toolkit_slug.upper()}_" if toolkit_slug else ""
97 + )
98 + available = MAX_SLUG_LENGTH - len(prefix)
99 + raise ValidationError(
100 + f'{context}: slug "{tool_slug}" is too long. '
101 + f'With prefix "{prefix}", the final slug would be {final_length} '
102 + f"characters (max {MAX_SLUG_LENGTH}). "
103 + f"Shorten the slug to at most {available} characters."
104 + )
105 +
106 +
107 +def _build_final_slug(tool_slug: str, toolkit_slug: t.Optional[str] = None) -> str:
108 + """Build the final slug: LOCAL_[TOOLKIT_]SLUG."""
109 + upper = tool_slug.upper()
110 + if toolkit_slug:
111 + return f"{LOCAL_TOOL_PREFIX}{toolkit_slug.upper()}_{upper}"
112 + return f"{LOCAL_TOOL_PREFIX}{upper}"
113 +
114 +
115 +def _get_input_json_schema(model: t.Type[BaseModel]) -> t.Dict[str, t.Any]:
116 + """Convert a Pydantic model class to a JSON Schema dict suitable for the backend."""
117 + full_schema = model.model_json_schema()
118 + schema: t.Dict[str, t.Any] = {"type": "object"}
119 + if "properties" in full_schema:
120 + schema["properties"] = full_schema["properties"]
121 + if "required" in full_schema:
122 + schema["required"] = full_schema["required"]
123 + # Inline $defs if present (Pydantic puts nested models there)
124 + if "$defs" in full_schema:
125 + schema["$defs"] = full_schema["$defs"]
126 + return schema
127 +
128 +
129 +# ────────────────────────────────────────────────────────────────
130 +# Factory functions
131 +# ────────────────────────────────────────────────────────────────
132 +
133 +
134 +def experimental_create_tool(
135 + slug: str,
136 + *,
137 + name: str,
138 + description: str,
139 + input_params: t.Type[BaseModel],
140 + execute: CustomToolExecuteFn,
141 + extends_toolkit: t.Optional[str] = None,
142 + output_params: t.Optional[t.Type[BaseModel]] = None,
143 +) -> CustomTool:
144 + """Create a custom tool for use in tool router sessions.
145 +
146 + The returned object is a lightweight reference containing the tool's metadata
147 + and execute function. Pass it to
148 + ``composio.create(user_id, experimental={"custom_tools": [...]})``
149 + to bind it to a session.
150 +
151 + Just return the result data from ``execute``, or raise an error.
152 + The SDK wraps it into the standard response format internally.
153 +
154 + :param slug: Unique tool identifier (alphanumeric, underscores, hyphens;
155 + no LOCAL_ or COMPOSIO_ prefix)
156 + :param name: Human-readable display name
157 + :param description: Tool description (used for BM25 search matching)
158 + :param input_params: Pydantic BaseModel class for input parameters
159 + :param execute: Function ``(input, ctx) -> dict`` that executes the tool
160 + :param extends_toolkit: Composio toolkit slug to inherit auth from (e.g. 'gmail')
161 + :param output_params: Optional Pydantic BaseModel class for output documentation
162 + :returns: A CustomTool to pass to session creation
163 +
164 + Example — standalone tool (no auth)::
165 +
166 + class GrepInput(BaseModel):
167 + pattern: str = Field(description="Pattern to search for")
168 + path: str = Field(description="File path")
169 +
170 + grep = experimental_create_tool("GREP",
171 + name="Grep Search",
172 + description="Search for patterns in files",
173 + input_params=GrepInput,
174 + execute=lambda input, ctx: {"matches": []},
175 + )
176 +
177 + Example — tool extending a Composio toolkit (inherits auth)::
178 +
179 + class DraftInput(BaseModel):
180 + to: str = Field(description="Recipient email")
181 + subject: str = Field(description="Subject")
182 + body: str = Field(description="Body")
183 +
184 + create_draft = experimental_create_tool("CREATE_DRAFT",
185 + name="Create Gmail draft",
186 + description="Create a real Gmail draft via the Gmail API",
187 + extends_toolkit="gmail",
188 + input_params=DraftInput,
189 + execute=lambda input, ctx: ctx.proxy_execute(
190 + toolkit="gmail",
191 + endpoint="https://gmail.googleapis.com/gmail/v1/users/me/drafts",
192 + method="POST",
193 + body={"message": {"raw": "..."}},
194 + ),
195 + )
196 + """
197 + context = "experimental_create_tool"
198 +
199 + # Validate slug
200 + _validate_slug(slug, context)
201 +
202 + # Validate required fields
203 + if not name:
204 + raise ValidationError(f"{context}: name is required")
205 + if not description:
206 + raise ValidationError(f"{context}: description is required")
207 +
208 + # Validate input_params is a Pydantic BaseModel subclass (not an instance)
209 + if not isinstance(input_params, type) or not issubclass(input_params, BaseModel):
210 + raise ValidationError(
211 + f"{context}: input_params must be a Pydantic BaseModel subclass. "
212 + f"Tool input parameters are always an object with named properties."
213 + )
214 +
215 + # Validate execute is callable
216 + if not callable(execute):
217 + raise ValidationError(f"{context}: execute must be a callable")
218 +
219 + # Early length validation
220 + _validate_slug_length(slug, extends_toolkit, context)
221 +
222 + # Convert Pydantic model → JSON Schema
223 + input_schema = _get_input_json_schema(input_params)
224 +
225 + # Convert output schema if provided
226 + output_schema: t.Optional[t.Dict[str, t.Any]] = None
227 + if output_params is not None:
228 + if not isinstance(output_params, type) or not issubclass(
229 + output_params, BaseModel
230 + ):
231 + raise ValidationError(
232 + f"{context}: output_params must be a Pydantic BaseModel subclass"
233 + )
234 + output_schema = output_params.model_json_schema()
235 +
236 + return CustomTool(
237 + slug=slug,
238 + name=name,
239 + description=description,
240 + extends_toolkit=extends_toolkit,
241 + input_schema=input_schema,
242 + output_schema=output_schema,
243 + input_params=input_params,
244 + execute=execute,
245 + )
246 +
247 +
248 +def experimental_create_toolkit(
249 + slug: str,
250 + *,
251 + name: str,
252 + description: str,
253 + tools: t.List[CustomTool],
254 +) -> CustomToolkit:
255 + """Create a custom toolkit that groups related tools.
256 +
257 + Tools passed here must NOT have ``extends_toolkit`` set — they inherit the
258 + toolkit identity instead.
259 +
260 + :param slug: Unique toolkit identifier (alphanumeric, underscores, hyphens;
261 + no LOCAL_ or COMPOSIO_ prefix)
262 + :param name: Human-readable display name
263 + :param description: Toolkit description
264 + :param tools: List of CustomTool objects to include in this toolkit
265 + :returns: A CustomToolkit to pass to session creation
266 +
267 + Example::
268 +
269 + dev_tools = experimental_create_toolkit("DEV_TOOLS",
270 + name="Dev Tools",
271 + description="Local dev utilities",
272 + tools=[grep_tool, sed_tool],
273 + )
274 + """
275 + context = "experimental_create_toolkit"
276 +
277 + # Validate slug
278 + _validate_slug(slug, context)
279 +
280 + # Validate required fields
281 + if not name:
282 + raise ValidationError(f"{context}: name is required")
283 + if not description:
284 + raise ValidationError(f"{context}: description is required")
285 +
286 + # Non-empty tools required
287 + if not tools:
288 + raise ValidationError(f"{context}: at least one tool is required")
289 +
290 + # Validate each tool
291 + for tool in tools:
292 + if tool.extends_toolkit:
293 + raise ValidationError(
294 + f'{context}: tool "{tool.slug}" has extends_toolkit set. '
295 + f"Tools in a custom toolkit must not use extends_toolkit — "
296 + f"they inherit the toolkit identity instead."
297 + )
298 + # Early length validation with toolkit slug
299 + _validate_slug_length(
300 + tool.slug, slug, f'{context}("{slug}")'
301 + )
302 +
303 + return CustomToolkit(
304 + slug=slug,
305 + name=name,
306 + description=description,
307 + tools=tuple(tools),
308 + )
309 +
310 +
311 +# ────────────────────────────────────────────────────────────────
312 +# Serialization (for backend API payload)
313 +# ────────────────────────────────────────────────────────────────
314 +
315 +
316 +def serialize_custom_tools(tools: t.List[CustomTool]) -> t.List[t.Dict[str, t.Any]]:
317 + """Serialize custom tools into the format expected by the backend."""
318 + result = []
319 + for tool in tools:
320 + entry: t.Dict[str, t.Any] = {
321 + "slug": tool.slug,
322 + "name": tool.name,
323 + "description": tool.description,
324 + "input_schema": tool.input_schema,
325 + }
326 + if tool.output_schema:
327 + entry["output_schema"] = tool.output_schema
328 + if tool.extends_toolkit:
329 + entry["extends_toolkit"] = tool.extends_toolkit
330 + result.append(entry)
331 + return result
332 +
333 +
334 +def serialize_custom_toolkits(
335 + toolkits: t.List[CustomToolkit],
336 +) -> t.List[t.Dict[str, t.Any]]:
337 + """Serialize custom toolkits into the format expected by the backend."""
338 + result = []
339 + for tk in toolkits:
340 + toolkit_tools = []
341 + for tool in tk.tools:
342 + entry: t.Dict[str, t.Any] = {
343 + "slug": tool.slug,
344 + "name": tool.name,
345 + "description": tool.description,
346 + "input_schema": tool.input_schema,
347 + }
348 + if tool.output_schema:
349 + entry["output_schema"] = tool.output_schema
350 + toolkit_tools.append(entry)
351 + result.append(
352 + {
353 + "slug": tk.slug,
354 + "name": tk.name,
355 + "description": tk.description,
356 + "tools": toolkit_tools,
357 + }
358 + )
359 + return result
360 +
361 +
362 +# ────────────────────────────────────────────────────────────────
363 +# Routing map builders
364 +# ────────────────────────────────────────────────────────────────
365 +
366 +
367 +def build_custom_tools_map(
368 + tools: t.List[CustomTool],
369 + toolkits: t.Optional[t.List[CustomToolkit]] = None,
370 +) -> CustomToolsMap:
371 + """Build a CustomToolsMap from custom tools and toolkits.
372 +
373 + Used internally by ToolRouter.create() to construct the per-session routing map.
374 + """
375 + by_final_slug: t.Dict[str, CustomToolsMapEntry] = {}
376 + by_original_slug: t.Dict[str, CustomToolsMapEntry] = {}
377 +
378 + def add_entry(
379 + handle: CustomTool, final_slug: str, toolkit: t.Optional[str]
380 + ) -> None:
381 + original_slug = handle.slug.upper()
382 +
383 + if len(final_slug) > MAX_SLUG_LENGTH:
384 + raise ValidationError(
385 + f'Custom tool slug "{handle.slug}" produces final slug '
386 + f'"{final_slug}" which exceeds {MAX_SLUG_LENGTH} characters.'
387 + )
388 +
389 + if final_slug in by_final_slug:
390 + raise ValidationError(
391 + f'Custom tool slug collision: "{final_slug}" is already registered.'
392 + )
393 +
394 + if original_slug in by_original_slug:
395 + existing = by_original_slug[original_slug]
396 + raise ValidationError(
397 + f'Custom tool slug collision: original slug "{handle.slug}" '
398 + f"maps to multiple final slugs. "
399 + f'"{existing.final_slug}" and "{final_slug}" both resolve '
400 + f'from "{original_slug}".'
401 + )
402 +
403 + entry = CustomToolsMapEntry(
404 + handle=handle, final_slug=final_slug, toolkit=toolkit
405 + )
406 + by_final_slug[final_slug] = entry
407 + by_original_slug[original_slug] = entry
408 +
409 + # Process standalone tools
410 + for handle in tools:
411 + add_entry(
412 + handle,
413 + _build_final_slug(handle.slug, handle.extends_toolkit),
414 + handle.extends_toolkit,
415 + )
416 +
417 + # Process toolkit tools
418 + if toolkits:
419 + for tk in toolkits:
420 + for handle in tk.tools:
421 + add_entry(
422 + handle, _build_final_slug(handle.slug, tk.slug), tk.slug
423 + )
424 +
425 + return CustomToolsMap(
426 + by_final_slug=by_final_slug,
427 + by_original_slug=by_original_slug,
428 + toolkits=list(toolkits) if toolkits else None,
429 + )
430 +
431 +
432 +def build_custom_tools_map_from_response(
433 + tools: t.List[CustomTool],
434 + toolkits: t.Optional[t.List[CustomToolkit]],
435 + experimental: t.Optional[SessionCreateResponseExperimental],
436 +) -> CustomToolsMap:
437 + """Build a CustomToolsMap using the slug/original_slug mapping from the backend response.
438 +
439 + Uses the backend's authoritative prefixed slugs instead of computing them client-side.
440 + """
441 + by_final_slug: t.Dict[str, CustomToolsMapEntry] = {}
442 + by_original_slug: t.Dict[str, CustomToolsMapEntry] = {}
443 +
444 + # Build lookup from original slug → handle + toolkit
445 + handles_by_original: t.Dict[
446 + str, t.Tuple[CustomTool, t.Optional[str]]
447 + ] = {}
448 + for handle in tools:
449 + handles_by_original[handle.slug.upper()] = (handle, handle.extends_toolkit)
450 + if toolkits:
451 + for tk in toolkits:
452 + for handle in tk.tools:
453 + handles_by_original[handle.slug.upper()] = (handle, tk.slug)
454 +
455 + def add_entry(
456 + final_slug: str, original_slug: str, toolkit: t.Optional[str]
457 + ) -> None:
458 + match = handles_by_original.get(original_slug.upper())
459 + if not match:
460 + return # Response tool not found in our handles
461 + handle, default_toolkit = match
462 + resolved_toolkit = toolkit if toolkit is not None else default_toolkit
463 + entry = CustomToolsMapEntry(
464 + handle=handle, final_slug=final_slug, toolkit=resolved_toolkit
465 + )
466 + by_final_slug[final_slug] = entry
467 + by_original_slug[original_slug.upper()] = entry
468 +
469 + # Map standalone custom tools from response
470 + if experimental and experimental.custom_tools:
471 + for ct in experimental.custom_tools:
472 + add_entry(ct.slug, ct.original_slug, ct.extends_toolkit)
473 +
474 + # Map toolkit custom tools from response
475 + if experimental and experimental.custom_toolkits:
476 + for ctk in experimental.custom_toolkits:
477 + for ct in ctk.tools:
478 + add_entry(ct.slug, ct.original_slug, ctk.slug)
479 +
480 + return CustomToolsMap(
481 + by_final_slug=by_final_slug,
482 + by_original_slug=by_original_slug,
483 + toolkits=list(toolkits) if toolkits else None,
484 + )
python/composio/core/models/custom_tool_execution.py new
+71
@@ -0,0 +1,71 @@
1 +"""Standalone functions for custom tool lookup and execution.
2 +
3 +Extracted for reuse in SessionContextImpl (sibling routing).
4 +"""
5 +
6 +from __future__ import annotations
7 +
8 +import typing as t
9 +
10 +from pydantic import ValidationError as PydanticValidationError
11 +
12 +from .custom_tool_types import (
13 + CustomToolsMap,
14 + CustomToolsMapEntry,
15 + SessionContext,
16 +)
17 +from .tools import ToolExecutionResponse
18 +
19 +
20 +def find_custom_tool(
21 + map_: t.Optional[CustomToolsMap],
22 + slug: str,
23 +) -> t.Optional[CustomToolsMapEntry]:
24 + """Find a custom tool entry by slug.
25 +
26 + Checks both the final slug map (LOCAL_X — agent/LLM path)
27 + and original slug map (X — programmatic path). Case-insensitive.
28 + """
29 + if map_ is None:
30 + return None
31 + upper = slug.upper()
32 + return map_.by_final_slug.get(upper) or map_.by_original_slug.get(upper)
33 +
34 +
35 +def execute_custom_tool(
36 + entry: CustomToolsMapEntry,
37 + arguments: t.Dict[str, t.Any],
38 + session_context: SessionContext,
39 +) -> ToolExecutionResponse:
40 + """Execute a custom tool in-process.
41 +
42 + Validates input via the Pydantic model, calls the user's execute function,
43 + and wraps the result into the standard response format.
44 + """
45 + handle = entry.handle
46 +
47 + # Validate and transform input using the Pydantic model.
48 + # This applies defaults, coercions, and validators.
49 + try:
50 + validated = handle.input_params.model_validate(arguments)
51 + except PydanticValidationError as e:
52 + return {
53 + "data": {},
54 + "error": f"Input validation failed: {e}",
55 + "successful": False,
56 + }
57 +
58 + try:
59 + # User's execute returns data directly — we wrap into {data, error, successful}
60 + data = handle.execute(validated, session_context)
61 + return {
62 + "data": data if data is not None else {},
63 + "error": None,
64 + "successful": True,
65 + }
66 + except Exception as e:
67 + return {
68 + "data": {},
69 + "error": str(e),
70 + "successful": False,
71 + }
python/composio/core/models/custom_tool_types.py new
+180
@@ -0,0 +1,180 @@
1 +"""Type definitions for custom tools in tool router sessions.
2 +
3 +Mirrors the TypeScript types in ts/packages/core/src/types/customTool.types.ts
4 +"""
5 +
6 +from __future__ import annotations
7 +
8 +import re
9 +import typing as t
10 +from dataclasses import dataclass, field
11 +
12 +import typing_extensions as te
13 +from pydantic import BaseModel
14 +
15 +from composio.core.models.tools import ToolExecutionResponse
16 +
17 +# ────────────────────────────────────────────────────────────────
18 +# Constants
19 +# ────────────────────────────────────────────────────────────────
20 +
21 +LOCAL_TOOL_PREFIX = "LOCAL_"
22 +MAX_SLUG_LENGTH = 60
23 +SLUG_REGEX = re.compile(r"^[A-Za-z0-9_-]+$")
24 +
25 +# ────────────────────────────────────────────────────────────────
26 +# Execute function type
27 +# ────────────────────────────────────────────────────────────────
28 +
29 +CustomToolExecuteFn = t.Callable[
30 + [t.Any, "SessionContext"],
31 + t.Dict[str, t.Any],
32 +]
33 +"""
34 +Execute function for custom tools.
35 +
36 +Signature: (input: BaseModel, ctx: SessionContext) -> dict
37 +
38 +Just return the result data, or raise an error. The SDK wraps it internally
39 +into {data, error, successful}.
40 +"""
41 +
42 +# ────────────────────────────────────────────────────────────────
43 +# SessionContext protocol
44 +# ────────────────────────────────────────────────────────────────
45 +
46 +
47 +class SessionContext(te.Protocol):
48 + """Session context injected into custom tool execute functions at runtime.
49 +
50 + Provides identity context and methods to call other tools or proxy API requests.
51 + """
52 +
53 + @property
54 + def user_id(self) -> str: ...
55 +
56 + def execute(
57 + self,
58 + tool_slug: str,
59 + arguments: t.Dict[str, t.Any],
60 + ) -> ToolExecutionResponse:
61 + """Execute any Composio tool from within a custom tool."""
62 + ...
63 +
64 + def proxy_execute(
65 + self,
66 + *,
67 + toolkit: str,
68 + endpoint: str,
69 + method: t.Literal["GET", "POST", "PUT", "DELETE", "PATCH"],
70 + body: t.Any = None,
71 + parameters: t.Optional[t.List[t.Dict[str, t.Any]]] = None,
72 + ) -> ProxyExecuteResponse:
73 + """Proxy API calls through Composio's auth layer."""
74 + ...
75 +
76 +
77 +# ────────────────────────────────────────────────────────────────
78 +# Custom tool / toolkit definitions (returned by factory functions)
79 +# ────────────────────────────────────────────────────────────────
80 +
81 +
82 +@dataclass(frozen=True)
83 +class CustomTool:
84 + """Custom tool definition returned from ``experimental_create_tool()``.
85 +
86 + Pass to ``composio.create(user_id, experimental={"custom_tools": [...]})``
87 + to bind to a session.
88 + """
89 +
90 + slug: str
91 + name: str
92 + description: str
93 + input_schema: t.Dict[str, t.Any]
94 + input_params: t.Type[BaseModel]
95 + execute: CustomToolExecuteFn
96 + extends_toolkit: t.Optional[str] = None
97 + output_schema: t.Optional[t.Dict[str, t.Any]] = None
98 +
99 +
100 +@dataclass(frozen=True)
101 +class CustomToolkit:
102 + """Custom toolkit definition returned from ``experimental_create_toolkit()``.
103 +
104 + Pass to ``composio.create(user_id, experimental={"custom_toolkits": [...]})``
105 + to bind to a session.
106 + """
107 +
108 + slug: str
109 + name: str
110 + description: str
111 + tools: t.Tuple[CustomTool, ...]
112 +
113 +
114 +# ────────────────────────────────────────────────────────────────
115 +# Internal routing map types
116 +# ────────────────────────────────────────────────────────────────
117 +
118 +
119 +@dataclass
120 +class CustomToolsMapEntry:
121 + """Entry in the per-session custom tools routing map."""
122 +
123 + handle: CustomTool
124 + final_slug: str
125 + toolkit: t.Optional[str] = None
126 +
127 +
128 +@dataclass
129 +class CustomToolsMap:
130 + """Lookup maps used by ToolRouterSession for routing custom tools."""
131 +
132 + by_final_slug: t.Dict[str, CustomToolsMapEntry] = field(default_factory=dict)
133 + by_original_slug: t.Dict[str, CustomToolsMapEntry] = field(default_factory=dict)
134 + toolkits: t.Optional[t.List[CustomToolkit]] = None
135 +
136 +
137 +# ────────────────────────────────────────────────────────────────
138 +# Registered types (returned by session.custom_tools() / .custom_toolkits())
139 +# ────────────────────────────────────────────────────────────────
140 +
141 +
142 +@dataclass(frozen=True)
143 +class RegisteredCustomTool:
144 + """A custom tool as registered in a session, with its final resolved slug."""
145 +
146 + slug: str
147 + name: str
148 + description: str
149 + input_schema: t.Dict[str, t.Any]
150 + toolkit: t.Optional[str] = None
151 + output_schema: t.Optional[t.Dict[str, t.Any]] = None
152 +
153 +
154 +@dataclass(frozen=True)
155 +class RegisteredCustomToolkit:
156 + """A custom toolkit as registered in a session, with final slugs on nested tools."""
157 +
158 + slug: str
159 + name: str
160 + description: str
161 + tools: t.List[RegisteredCustomTool]
162 +
163 +
164 +# ────────────────────────────────────────────────────────────────
165 +# Proxy execute response types
166 +# ────────────────────────────────────────────────────────────────
167 +
168 +
169 +class ProxyExecuteBinaryData(te.TypedDict, total=False):
170 + content_type: str
171 + size: int
172 + url: str
173 + expires_at: t.Optional[str]
174 +
175 +
176 +class ProxyExecuteResponse(te.TypedDict, total=False):
177 + status: int
178 + data: t.Optional[t.Any]
179 + headers: t.Optional[t.Dict[str, str]]
180 + binary_data: ProxyExecuteBinaryData
python/composio/core/models/session_context.py new
+126
@@ -0,0 +1,126 @@
1 +"""Session context implementation injected into custom tool execute functions.
2 +
3 +One instance is created per session and shared across all custom tool invocations,
4 +including sibling routing (tool A calling tool B without hitting the network).
5 +"""
6 +
7 +from __future__ import annotations
8 +
9 +import typing as t
10 +
11 +from composio.client import HttpClient
12 +from composio.core.models.custom_tool_execution import (
13 + execute_custom_tool,
14 + find_custom_tool,
15 +)
16 +from composio.core.models.custom_tool_types import (
17 + CustomToolsMap,
18 + ProxyExecuteResponse,
19 +)
20 +from composio.core.models.tools import ToolExecutionResponse
21 +
22 +
23 +class SessionContextImpl:
24 + """Concrete implementation of SessionContext.
25 +
26 + One instance is created per session (singleton) and shared across
27 + all custom tool invocations. When ``custom_tools_map`` is provided,
28 + ``execute()`` checks local tools first before falling back to the
29 + backend API (sibling routing).
30 + """
31 +
32 + def __init__(
33 + self,
34 + client: HttpClient,
35 + user_id: str,
36 + session_id: str,
37 + custom_tools_map: t.Optional[CustomToolsMap] = None,
38 + ) -> None:
39 + self._client = client
40 + self._user_id = user_id
41 + self._session_id = session_id
42 + self._custom_tools_map = custom_tools_map
43 +
44 + @property
45 + def user_id(self) -> str:
46 + return self._user_id
47 +
48 + def execute(
49 + self,
50 + tool_slug: str,
51 + arguments: t.Dict[str, t.Any],
52 + ) -> ToolExecutionResponse:
53 + """Execute any tool from within a custom tool.
54 +
55 + Routes to sibling local tools in-process when available,
56 + otherwise delegates to the backend API.
57 + """
58 + # Try local tool first (sibling routing)
59 + entry = find_custom_tool(self._custom_tools_map, tool_slug)
60 + if entry:
61 + return execute_custom_tool(entry, arguments, self)
62 +
63 + # Fall back to remote execution
64 + response = self._client.tool_router.session.execute(
65 + session_id=self._session_id,
66 + tool_slug=tool_slug,
67 + arguments=arguments,
68 + )
69 + return {
70 + "data": response.data if hasattr(response, "data") else {},
71 + "error": response.error if hasattr(response, "error") else None,
72 + "successful": not (hasattr(response, "error") and response.error),
73 + }
74 +
75 + def proxy_execute(
76 + self,
77 + *,
78 + toolkit: str,
79 + endpoint: str,
80 + method: t.Literal["GET", "POST", "PUT", "DELETE", "PATCH"],
81 + body: t.Any = None,
82 + parameters: t.Optional[t.List[t.Dict[str, t.Any]]] = None,
83 + ) -> ProxyExecuteResponse:
84 + """Proxy API calls through Composio's auth layer.
85 +
86 + The backend resolves the connected account from the toolkit
87 + within the session.
88 + """
89 + from composio_client import omit
90 +
91 + # Transform parameters to API format
92 + api_params: t.List[t.Dict[str, t.Any]] = []
93 + if parameters:
94 + for p in parameters:
95 + api_params.append(
96 + {
97 + "name": p["name"],
98 + "type": p.get("in", p.get("type", "header")),
99 + "value": str(p["value"]),
100 + }
101 + )
102 +
103 + response = self._client.tool_router.session.proxy_execute(
104 + session_id=self._session_id,
105 + toolkit_slug=toolkit,
106 + endpoint=endpoint,
107 + method=method,
108 + body=body if body is not None else omit,
109 + parameters=api_params if api_params else omit,
110 + )
111 +
112 + result: ProxyExecuteResponse = {
113 + "status": int(response.status),
114 + "data": response.data,
115 + "headers": response.headers,
116 + }
117 +
118 + if response.binary_data:
119 + result["binary_data"] = {
120 + "content_type": response.binary_data.content_type,
121 + "size": int(response.binary_data.size),
122 + "url": response.binary_data.url,
123 + "expires_at": response.binary_data.expires_at,
124 + }
125 +
126 + return result
python/composio/core/models/tool_router.py
+48 -5
@@ -17,6 +17,16 @@ from composio_client.types.tool_router import session_create_params
17
18 from composio.client import HttpClient
19 from composio.core.models.base import Resource
20 +from composio.core.models.custom_tool import (
21 + build_custom_tools_map_from_response,
22 + serialize_custom_tools,
23 + serialize_custom_toolkits,
24 +)
25 +from composio.core.models.custom_tool_types import (
26 + CustomTool,
27 + CustomToolkit,
28 + CustomToolsMap,
29 +)
30 from composio.core.models.tool_router_session import ToolRouterSession
31 from composio.core.models.tool_router_session_files import ToolRouterSessionFilesMount
32 from composio.core.provider import TTool, TToolCollection
@@ -178,9 +188,13 @@ class ToolRouterExperimentalConfig(te.TypedDict, total=False):
188
189 Attributes:
190 assistive_prompt: Configuration for assistive prompt generation.
191 + custom_tools: Custom tools to include in the session.
192 + custom_toolkits: Custom toolkits with grouped tools.
193 """
194
195 assistive_prompt: ToolRouterAssistivePromptConfig
196 + custom_tools: t.List["CustomTool"]
197 + custom_toolkits: t.List["CustomToolkit"]
198
199
200 @dataclass
@@ -696,18 +710,36 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):
710 # Build experimental config
711 # Map SDK's experimental.assistive_prompt.user_timezone to API's
712 # experimental.assistive_prompt_config.user_timezone
713 + custom_tools: t.Optional[t.List[CustomTool]] = None
714 + custom_toolkits: t.Optional[t.List[CustomToolkit]] = None
715 +
716 if experimental is not None:
717 + experimental_payload: t.Dict[str, t.Any] = {}
718 +
719 assistive_prompt_config = experimental.get("assistive_prompt")
720 if assistive_prompt_config is not None:
721 user_timezone = assistive_prompt_config.get("user_timezone")
703 - # Only include if user_timezone is a non-empty string
722 if user_timezone:
705 - create_params["experimental"] = {
706 - "assistive_prompt_config": {
707 - "user_timezone": user_timezone,
708 - }
723 + experimental_payload["assistive_prompt_config"] = {
724 + "user_timezone": user_timezone,
725 }
726
727 + # Serialize custom tools and toolkits for the backend
728 + custom_tools = experimental.get("custom_tools")
729 + custom_toolkits = experimental.get("custom_toolkits")
730 +
731 + if custom_tools:
732 + experimental_payload["custom_tools"] = serialize_custom_tools(
733 + custom_tools
734 + )
735 + if custom_toolkits:
736 + experimental_payload["custom_toolkits"] = serialize_custom_toolkits(
737 + custom_toolkits
738 + )
739 +
740 + if experimental_payload:
741 + create_params["experimental"] = experimental_payload
742 +
743 if self._provider is None:
744 raise ValueError(
745 "Provider is required for tool router. "
@@ -717,6 +749,15 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):
749 # Make API call to create session
750 session = self._client.tool_router.session.create(**create_params)
751
752 + # Build custom tools routing map from backend response
753 + custom_tools_map: t.Optional[CustomToolsMap] = None
754 + if custom_tools or custom_toolkits:
755 + custom_tools_map = build_custom_tools_map_from_response(
756 + tools=custom_tools or [],
757 + toolkits=custom_toolkits,
758 + experimental=session.experimental,
759 + )
760 +
761 # Transform experimental response:
762 # API's assistive_prompt -> SDK's assistive_prompt
763 # files mount is always present
@@ -739,6 +780,8 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):
780 url=session.mcp.url,
781 ),
782 experimental=experimental_response,
783 + custom_tools_map=custom_tools_map,
784 + user_id=user_id,
785 )
786
787 def use(self, session_id: str) -> ToolRouterSession[TTool, TToolCollection]:
python/composio/core/models/tool_router_session.py
+351 -4
@@ -2,16 +2,32 @@
2 ToolRouterSession class for managing a single tool router session.
3
4 Provides methods for tools, authorize, toolkits, search, execute, and files.
5 +When custom tools are bound to the session, execution is routed: local tools
6 +run in-process, remote tools are sent to the backend.
7 """
8
9 from __future__ import annotations
10
11 import typing as t
12 +from concurrent.futures import ThreadPoolExecutor
13
14 from composio_client import omit
15
16 from composio.client import HttpClient
17 from composio.core.models.connected_accounts import ConnectionRequest
18 +from composio.core.models.custom_tool_execution import (
19 + execute_custom_tool,
20 + find_custom_tool,
21 +)
22 +from composio.core.models.custom_tool_types import (
23 + CustomToolsMap,
24 + CustomToolsMapEntry,
25 + ProxyExecuteResponse,
26 + RegisteredCustomTool,
27 + RegisteredCustomToolkit,
28 +)
29 +from composio.core.models.session_context import SessionContextImpl
30 +from composio.core.models.tools import ToolExecutionResponse
31 from composio.core.provider import TTool, TToolCollection
32 from composio.core.provider.base import BaseProvider
33
@@ -19,6 +35,9 @@ if t.TYPE_CHECKING:
35 from composio.core.models._modifiers import Modifiers
36 from composio.core.models.tool_router import ToolRouterSessionExperimental
37
38 +COMPOSIO_MULTI_EXECUTE_TOOL = "COMPOSIO_MULTI_EXECUTE_TOOL"
39 +MAX_PARALLEL_WORKERS = 5
40 +
41
42 class ToolRouterSession(t.Generic[TTool, TToolCollection]):
43 """
@@ -43,6 +62,8 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
62 session_id: str,
63 mcp: t.Any,
64 experimental: "ToolRouterSessionExperimental",
65 + custom_tools_map: t.Optional[CustomToolsMap] = None,
66 + user_id: t.Optional[str] = None,
67 ) -> None:
68 self._client = client
69 self._provider = provider
@@ -50,6 +71,24 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
71 self.session_id = session_id
72 self.mcp = mcp
73 self.experimental = experimental
74 + self._custom_tools_map = custom_tools_map
75 + self._user_id = user_id
76 +
77 + # Create singleton session context if custom tools are bound
78 + self._session_context: t.Optional[SessionContextImpl] = None
79 + if custom_tools_map and user_id:
80 + self._session_context = SessionContextImpl(
81 + client=client,
82 + user_id=user_id,
83 + session_id=session_id,
84 + custom_tools_map=custom_tools_map,
85 + )
86 +
87 + def _has_custom_tools(self) -> bool:
88 + """Check if this session has any custom tools bound."""
89 + if self._custom_tools_map is None:
90 + return False
91 + return len(self._custom_tools_map.by_final_slug) > 0
92
93 def tools(self, modifiers: t.Optional["Modifiers"] = None) -> TToolCollection:
94 """
@@ -57,6 +96,10 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
96
97 Returns tools configured for this session, wrapped in the format expected
98 by your AI provider (OpenAI, Anthropic, LangChain, etc.).
99 +
100 + When custom tools are bound to the session, execution of
101 + COMPOSIO_MULTI_EXECUTE_TOOL is intercepted: local tools are executed
102 + in-process, remote tools are sent to the backend.
103 """
104 from composio.core.models.tools import Tools as ToolsModel
105 from composio.core.provider import AgenticProvider, NonAgenticProvider
@@ -93,17 +136,183 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
136 ).wrap_tools(tools=router_tools),
137 )
138
139 + # For agentic providers: if custom tools are bound, create a routing
140 + # execute function that intercepts COMPOSIO_MULTI_EXECUTE_TOOL
141 + if self._has_custom_tools():
142 + execute_fn = self._create_routing_execute_fn(tools_model, modifiers)
143 + else:
144 + execute_fn = tools_model._wrap_execute_tool_for_tool_router(
145 + session_id=self.session_id,
146 + modifiers=modifiers,
147 + )
148 +
149 return t.cast(
150 TToolCollection,
98 - t.cast(AgenticProvider[TTool, TToolCollection], self._provider).wrap_tools(
151 + t.cast(
152 + AgenticProvider[TTool, TToolCollection], self._provider
153 + ).wrap_tools(
154 tools=router_tools,
100 - execute_tool=tools_model._wrap_execute_tool_for_tool_router(
155 + execute_tool=execute_fn,
156 + ),
157 + )
158 +
159 + def _create_routing_execute_fn(
160 + self,
161 + tools_model: t.Any,
162 + modifiers: t.Optional["Modifiers"],
163 + ) -> t.Callable[..., t.Any]:
164 + """Create an execute function that routes local/remote tools."""
165 +
166 + def routing_execute(slug: str, arguments: t.Dict) -> t.Dict:
167 + if slug == COMPOSIO_MULTI_EXECUTE_TOOL:
168 + return self._route_multi_execute(
169 + arguments, tools_model, modifiers
170 + )
171 + # Non-multi-execute meta tools always go to backend
172 + return tools_model._wrap_execute_tool_for_tool_router(
173 + session_id=self.session_id,
174 + modifiers=modifiers,
175 + )(slug, arguments)
176 +
177 + return routing_execute
178 +
179 + def _parse_tool_item(
180 + self, item: t.Any
181 + ) -> t.Dict[str, t.Any]:
182 + """Parse an individual tool item from COMPOSIO_MULTI_EXECUTE_TOOL's tools array."""
183 + if not isinstance(item, dict):
184 + return {"tool_slug": "", "arguments": {}}
185 + return {
186 + "tool_slug": str(item.get("tool_slug", "")),
187 + "arguments": item.get("arguments", {}),
188 + }
189 +
190 + def _route_multi_execute(
191 + self,
192 + input_args: t.Dict[str, t.Any],
193 + tools_model: t.Any,
194 + modifiers: t.Optional["Modifiers"],
195 + ) -> t.Dict[str, t.Any]:
196 + """Route a COMPOSIO_MULTI_EXECUTE_TOOL call.
197 +
198 + Splits the tools[] array into local and remote, executes each
199 + appropriately, and merges results preserving original order.
200 + """
201 + tool_items = input_args.get("tools")
202 + if not isinstance(tool_items, list) or len(tool_items) == 0:
203 + # Fallback: send to backend as-is
204 + return tools_model._wrap_execute_tool_for_tool_router(
205 + session_id=self.session_id,
206 + modifiers=modifiers,
207 + )(COMPOSIO_MULTI_EXECUTE_TOOL, input_args)
208 +
209 + parsed = [self._parse_tool_item(item) for item in tool_items]
210 +
211 + # Partition into local (with resolved entry) and remote
212 + local_items: t.List[t.Tuple[int, CustomToolsMapEntry]] = []
213 + remote_indices: t.List[int] = []
214 + for i, p in enumerate(parsed):
215 + entry = find_custom_tool(self._custom_tools_map, p["tool_slug"])
216 + if entry:
217 + local_items.append((i, entry))
218 + else:
219 + remote_indices.append(i)
220 +
221 + # All remote — just forward entire payload
222 + if not local_items:
223 + return tools_model._wrap_execute_tool_for_tool_router(
224 + session_id=self.session_id,
225 + modifiers=modifiers,
226 + )(COMPOSIO_MULTI_EXECUTE_TOOL, input_args)
227 +
228 + ctx = self._session_context
229 + assert ctx is not None
230 +
231 + # Determine worker count (capped at MAX_PARALLEL_WORKERS)
232 + num_tasks = len(local_items) + (1 if remote_indices else 0)
233 + num_workers = min(MAX_PARALLEL_WORKERS, num_tasks)
234 +
235 + with ThreadPoolExecutor(max_workers=num_workers) as pool:
236 + # Submit local tool executions
237 + local_futures = []
238 + for idx, entry in local_items:
239 + future = pool.submit(
240 + execute_custom_tool,
241 + entry,
242 + parsed[idx]["arguments"],
243 + ctx,
244 + )
245 + local_futures.append((idx, future))
246 +
247 + # Submit remote batch (single call) if any
248 + remote_future = None
249 + if remote_indices:
250 + remote_tool_items = [tool_items[i] for i in remote_indices]
251 + remote_input = {**input_args, "tools": remote_tool_items}
252 + execute_fn = tools_model._wrap_execute_tool_for_tool_router(
253 session_id=self.session_id,
254 modifiers=modifiers,
103 - ),
104 - ),
255 + )
256 + remote_future = pool.submit(
257 + execute_fn,
258 + COMPOSIO_MULTI_EXECUTE_TOOL,
259 + remote_input,
260 + )
261 +
262 + # Gather local results
263 + local_results: t.List[t.Tuple[int, ToolExecutionResponse]] = []
264 + for idx, future in local_futures:
265 + local_results.append((idx, future.result()))
266 +
267 + # Gather remote result
268 + remote_result: t.Optional[t.Dict[str, t.Any]] = None
269 + if remote_future:
270 + remote_result = remote_future.result()
271 +
272 + # If only one local tool and no remote, return unwrapped
273 + if not remote_indices and len(local_results) == 1:
274 + return t.cast(t.Dict[str, t.Any], local_results[0][1])
275 +
276 + # Merge results into the backend's results[] format
277 + remote_data = (remote_result or {}).get("data", {})
278 + remote_results_list: t.List[t.Any] = (
279 + remote_data.get("results", [])
280 + if isinstance(remote_data, dict)
281 + else []
282 )
283
284 + # Build local result entries matching backend format
285 + local_entries = []
286 + for idx, result in local_results:
287 + local_entries.append(
288 + {
289 + "response": {
290 + "successful": result["successful"],
291 + "data": result["data"],
292 + **({"error": result["error"]} if result.get("error") else {}),
293 + },
294 + "tool_slug": parsed[idx]["tool_slug"],
295 + **({"error": result["error"]} if result.get("error") else {}),
296 + }
297 + )
298 +
299 + # Merge: local entries + remote results, re-indexed sequentially
300 + merged: t.List[t.Any] = []
301 + remote_iter = iter(remote_results_list)
302 + local_map = {idx: entry for (idx, _), entry in zip(local_items, local_entries)}
303 +
304 + for i in range(len(parsed)):
305 + if i in local_map:
306 + merged.append(local_map[i])
307 + else:
308 + merged.append(next(remote_iter, {}))
309 +
310 + return {
311 + "data": {"results": merged},
312 + "error": None,
313 + "successful": True,
314 + }
315 +
316 def authorize(
317 self,
318 toolkit: str,
@@ -236,9 +445,147 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
445 ) -> t.Any:
446 """
447 Execute a tool within the session.
448 +
449 + For custom tools, accepts the original slug (e.g. "GREP") or the
450 + full slug (e.g. "LOCAL_GREP"). Custom tools are executed in-process;
451 + remote tools are sent to the Composio backend.
452 """
453 + # Check if this is a local tool (by original or final slug)
454 + entry = find_custom_tool(self._custom_tools_map, tool_slug)
455 + if entry and self._session_context:
456 + return execute_custom_tool(
457 + entry, arguments or {}, self._session_context
458 + )
459 +
460 + # Remote execution
461 return self._client.tool_router.session.execute(
462 session_id=self.session_id,
463 tool_slug=tool_slug,
464 arguments=arguments if arguments is not None else omit,
465 )
466 +
467 + def custom_tools(
468 + self, *, toolkit: t.Optional[str] = None
469 + ) -> t.List[RegisteredCustomTool]:
470 + """List all custom tools registered in this session.
471 +
472 + Returns tools with their final slugs, schemas, and resolved toolkit.
473 +
474 + :param toolkit: Filter by toolkit slug (e.g. 'gmail', 'DEV_TOOLS')
475 + :returns: Array of registered custom tools
476 + """
477 + if not self._custom_tools_map:
478 + return []
479 +
480 + entries = list(self._custom_tools_map.by_final_slug.values())
481 + if toolkit:
482 + entries = [
483 + e
484 + for e in entries
485 + if e.toolkit and e.toolkit.lower() == toolkit.lower()
486 + ]
487 +
488 + return [
489 + RegisteredCustomTool(
490 + slug=entry.final_slug,
491 + name=entry.handle.name,
492 + description=entry.handle.description,
493 + toolkit=entry.toolkit,
494 + input_schema=entry.handle.input_schema,
495 + output_schema=entry.handle.output_schema,
496 + )
497 + for entry in entries
498 + ]
499 +
500 + def custom_toolkits(self) -> t.List[RegisteredCustomToolkit]:
501 + """List all custom toolkits registered in this session.
502 +
503 + Returns toolkits with their tools showing final slugs.
504 + """
505 + if not self._custom_tools_map or not self._custom_tools_map.toolkits:
506 + return []
507 +
508 + result = []
509 + for tk in self._custom_tools_map.toolkits:
510 + tools = []
511 + for tool in tk.tools:
512 + entry = self._custom_tools_map.by_original_slug.get(
513 + tool.slug.upper()
514 + )
515 + tools.append(
516 + RegisteredCustomTool(
517 + slug=entry.final_slug if entry else tool.slug,
518 + name=tool.name,
519 + description=tool.description,
520 + toolkit=tk.slug,
521 + input_schema=tool.input_schema,
522 + output_schema=tool.output_schema,
523 + )
524 + )
525 + result.append(
526 + RegisteredCustomToolkit(
527 + slug=tk.slug,
528 + name=tk.name,
529 + description=tk.description,
530 + tools=tools,
531 + )
532 + )
533 + return result
534 +
535 + def proxy_execute(
536 + self,
537 + *,
538 + toolkit: str,
539 + endpoint: str,
540 + method: t.Literal["GET", "POST", "PUT", "DELETE", "PATCH"],
541 + body: t.Any = None,
542 + parameters: t.Optional[t.List[t.Dict[str, t.Any]]] = None,
543 + ) -> ProxyExecuteResponse:
544 + """Proxy an API call through Composio's auth layer.
545 +
546 + The backend resolves the connected account from the toolkit
547 + within the session.
548 +
549 + :param toolkit: Composio toolkit slug (e.g. 'gmail', 'github')
550 + :param endpoint: API endpoint URL
551 + :param method: HTTP method
552 + :param body: Request body (for POST, PUT, PATCH)
553 + :param parameters: Query/header parameters
554 + :returns: Proxied API response
555 + """
556 + # Transform parameters to API format
557 + api_params: t.List[t.Dict[str, t.Any]] = []
558 + if parameters:
559 + for p in parameters:
560 + api_params.append(
561 + {
562 + "name": p["name"],
563 + "type": p.get("in", p.get("type", "header")),
564 + "value": str(p["value"]),
565 + }
566 + )
567 +
568 + response = self._client.tool_router.session.proxy_execute(
569 + session_id=self.session_id,
570 + toolkit_slug=toolkit,
571 + endpoint=endpoint,
572 + method=method,
573 + body=body if body is not None else omit,
574 + parameters=api_params if api_params else omit,
575 + )
576 +
577 + result: ProxyExecuteResponse = {
578 + "status": int(response.status),
579 + "data": response.data,
580 + "headers": response.headers,
581 + }
582 +
583 + if response.binary_data:
584 + result["binary_data"] = {
585 + "content_type": response.binary_data.content_type,
586 + "size": int(response.binary_data.size),
587 + "url": response.binary_data.url,
588 + "expires_at": response.binary_data.expires_at,
589 + }
590 +
591 + return result
python/pyproject.toml
+1 -1
@@ -7,7 +7,7 @@ requires-python = ">=3.10,<4"
7 dependencies = [
8 "pysher>=1.0.8",
9 "pydantic>=2.6.4",
10 - "composio-client==1.28.0",
10 + "composio-client==1.29.0",
11 "typing-extensions>=4.0.0",
12 "openai",
13 "json-schema-to-pydantic>=0.4.8",
python/tests/test_custom_tools.py new
+946
@@ -0,0 +1,946 @@
1 +"""Tests for custom tools in tool router sessions.
2 +
3 +Covers:
4 +- Factory function validation (slug rules, required fields, Pydantic model check)
5 +- Slug prefixing and collision detection
6 +- Serialization to API format
7 +- Custom tool execution (validation, defaults, errors)
8 +- Routing map building and lookup
9 +- SessionContextImpl sibling routing
10 +- ToolRouterSession integration (execute routing, custom_tools(), custom_toolkits())
11 +- Multi-execute routing (all-local, all-remote, mixed, parallel)
12 +"""
13 +
14 +from unittest.mock import MagicMock, patch
15 +
16 +import pytest
17 +from pydantic import BaseModel, Field
18 +
19 +from composio import experimental_create_tool, experimental_create_toolkit
20 +from composio.core.models.custom_tool import (
21 + build_custom_tools_map,
22 + build_custom_tools_map_from_response,
23 + serialize_custom_tools,
24 + serialize_custom_toolkits,
25 +)
26 +from composio.core.models.custom_tool_execution import (
27 + execute_custom_tool,
28 + find_custom_tool,
29 +)
30 +from composio.core.models.custom_tool_types import (
31 + CustomToolsMap,
32 + CustomToolsMapEntry,
33 + RegisteredCustomTool,
34 + RegisteredCustomToolkit,
35 +)
36 +from composio.core.models.session_context import SessionContextImpl
37 +from composio.core.models.tool_router_session import ToolRouterSession
38 +from composio.exceptions import ValidationError
39 +
40 +
41 +# ────────────────────────────────────────────────────────────────
42 +# Fixtures
43 +# ────────────────────────────────────────────────────────────────
44 +
45 +
46 +class GrepInput(BaseModel):
47 + pattern: str = Field(description="Pattern to search for")
48 + path: str = Field(default=".", description="File path")
49 +
50 +
51 +class EmailInput(BaseModel):
52 + to: str = Field(description="Recipient email")
53 + subject: str = Field(description="Subject")
54 +
55 +
56 +class SetRoleInput(BaseModel):
57 + user_id: str = Field(description="User ID")
58 + role: str = Field(default="viewer", description="New role")
59 +
60 +
61 +@pytest.fixture
62 +def grep_tool():
63 + return experimental_create_tool(
64 + "GREP",
65 + name="Grep Search",
66 + description="Search for patterns in files",
67 + input_params=GrepInput,
68 + execute=lambda input, ctx: {"matches": [input.pattern], "path": input.path},
69 + )
70 +
71 +
72 +@pytest.fixture
73 +def email_tool():
74 + return experimental_create_tool(
75 + "GET_EMAILS",
76 + name="Get Emails",
77 + description="Get emails from Gmail",
78 + input_params=EmailInput,
79 + execute=lambda input, ctx: {"emails": []},
80 + extends_toolkit="gmail",
81 + )
82 +
83 +
84 +@pytest.fixture
85 +def set_role_tool():
86 + return experimental_create_tool(
87 + "SET_ROLE",
88 + name="Set role",
89 + description="Set a user's role",
90 + input_params=SetRoleInput,
91 + execute=lambda input, ctx: {
92 + "user_id": input.user_id,
93 + "role": input.role,
94 + "updated": True,
95 + },
96 + )
97 +
98 +
99 +@pytest.fixture
100 +def role_toolkit(set_role_tool):
101 + return experimental_create_toolkit(
102 + "ROLE_MANAGER",
103 + name="Role Manager",
104 + description="Manage user roles",
105 + tools=[set_role_tool],
106 + )
107 +
108 +
109 +class MockSessionContext:
110 + user_id = "test-user"
111 +
112 + def execute(self, tool_slug, arguments):
113 + return {"data": {}, "error": None, "successful": True}
114 +
115 + def proxy_execute(self, **kwargs):
116 + return {"status": 200, "data": {}, "headers": {}}
117 +
118 +
119 +# ────────────────────────────────────────────────────────────────
120 +# Factory validation tests
121 +# ────────────────────────────────────────────────────────────────
122 +
123 +
124 +class TestCreateCustomTool:
125 + def test_creates_tool_with_valid_params(self, grep_tool):
126 + assert grep_tool.slug == "GREP"
127 + assert grep_tool.name == "Grep Search"
128 + assert grep_tool.description == "Search for patterns in files"
129 + assert grep_tool.extends_toolkit is None
130 + assert grep_tool.input_schema["type"] == "object"
131 + assert "pattern" in grep_tool.input_schema["properties"]
132 + assert grep_tool.output_schema is None
133 +
134 + def test_creates_extension_tool(self, email_tool):
135 + assert email_tool.slug == "GET_EMAILS"
136 + assert email_tool.extends_toolkit == "gmail"
137 +
138 + def test_slug_empty(self):
139 + with pytest.raises(ValidationError, match="slug is required"):
140 + experimental_create_tool(
141 + "",
142 + name="Bad",
143 + description="Bad",
144 + input_params=GrepInput,
145 + execute=lambda i, c: {},
146 + )
147 +
148 + def test_slug_invalid_chars(self):
149 + with pytest.raises(ValidationError, match="alphanumeric"):
150 + experimental_create_tool(
151 + "BAD SLUG!",
152 + name="Bad",
153 + description="Bad",
154 + input_params=GrepInput,
155 + execute=lambda i, c: {},
156 + )
157 +
158 + def test_slug_local_prefix(self):
159 + with pytest.raises(ValidationError, match="LOCAL_"):
160 + experimental_create_tool(
161 + "LOCAL_BAD",
162 + name="Bad",
163 + description="Bad",
164 + input_params=GrepInput,
165 + execute=lambda i, c: {},
166 + )
167 +
168 + def test_slug_composio_prefix(self):
169 + with pytest.raises(ValidationError, match="COMPOSIO_"):
170 + experimental_create_tool(
171 + "COMPOSIO_BAD",
172 + name="Bad",
173 + description="Bad",
174 + input_params=GrepInput,
175 + execute=lambda i, c: {},
176 + )
177 +
178 + def test_name_required(self):
179 + with pytest.raises(ValidationError, match="name is required"):
180 + experimental_create_tool(
181 + "GOOD",
182 + name="",
183 + description="Desc",
184 + input_params=GrepInput,
185 + execute=lambda i, c: {},
186 + )
187 +
188 + def test_description_required(self):
189 + with pytest.raises(ValidationError, match="description is required"):
190 + experimental_create_tool(
191 + "GOOD",
192 + name="Name",
193 + description="",
194 + input_params=GrepInput,
195 + execute=lambda i, c: {},
196 + )
197 +
198 + def test_input_params_must_be_basemodel_subclass(self):
199 + with pytest.raises(ValidationError, match="BaseModel subclass"):
200 + experimental_create_tool(
201 + "GOOD",
202 + name="Name",
203 + description="Desc",
204 + input_params=dict, # type: ignore
205 + execute=lambda i, c: {},
206 + )
207 +
208 + def test_input_params_must_not_be_instance(self):
209 + with pytest.raises(ValidationError, match="BaseModel subclass"):
210 + experimental_create_tool(
211 + "GOOD",
212 + name="Name",
213 + description="Desc",
214 + input_params=GrepInput(pattern="x"), # type: ignore
215 + execute=lambda i, c: {},
216 + )
217 +
218 + def test_execute_must_be_callable(self):
219 + with pytest.raises(ValidationError, match="callable"):
220 + experimental_create_tool(
221 + "GOOD",
222 + name="Name",
223 + description="Desc",
224 + input_params=GrepInput,
225 + execute="not a function", # type: ignore
226 + )
227 +
228 + def test_slug_length_validation_standalone(self):
229 + # LOCAL_ + 55 chars = 61 > 60
230 + with pytest.raises(ValidationError, match="too long"):
231 + experimental_create_tool(
232 + "A" * 55,
233 + name="Name",
234 + description="Desc",
235 + input_params=GrepInput,
236 + execute=lambda i, c: {},
237 + )
238 +
239 + def test_slug_length_validation_extension(self):
240 + # LOCAL_ + GMAIL_ + slug must be <= 60
241 + with pytest.raises(ValidationError, match="too long"):
242 + experimental_create_tool(
243 + "A" * 50,
244 + name="Name",
245 + description="Desc",
246 + input_params=GrepInput,
247 + execute=lambda i, c: {},
248 + extends_toolkit="gmail",
249 + )
250 +
251 + def test_output_params(self):
252 + class OutputSchema(BaseModel):
253 + matches: int
254 +
255 + tool = experimental_create_tool(
256 + "TOOL",
257 + name="Tool",
258 + description="Desc",
259 + input_params=GrepInput,
260 + execute=lambda i, c: {},
261 + output_params=OutputSchema,
262 + )
263 + assert tool.output_schema is not None
264 + assert "properties" in tool.output_schema
265 +
266 + def test_input_schema_includes_defaults(self, grep_tool):
267 + # path has default="." - Pydantic won't include it in required
268 + assert "pattern" in grep_tool.input_schema.get("required", [])
269 + assert "path" not in grep_tool.input_schema.get("required", [])
270 +
271 + def test_frozen_dataclass(self, grep_tool):
272 + with pytest.raises(AttributeError):
273 + grep_tool.slug = "NEW" # type: ignore
274 +
275 +
276 +class TestCreateCustomToolkit:
277 + def test_creates_toolkit(self, role_toolkit, set_role_tool):
278 + assert role_toolkit.slug == "ROLE_MANAGER"
279 + assert role_toolkit.name == "Role Manager"
280 + assert len(role_toolkit.tools) == 1
281 + assert role_toolkit.tools[0].slug == "SET_ROLE"
282 +
283 + def test_rejects_empty_tools(self):
284 + with pytest.raises(ValidationError, match="at least one tool"):
285 + experimental_create_toolkit(
286 + "TK",
287 + name="TK",
288 + description="Desc",
289 + tools=[],
290 + )
291 +
292 + def test_rejects_extends_toolkit_in_tools(self, email_tool):
293 + with pytest.raises(ValidationError, match="extends_toolkit"):
294 + experimental_create_toolkit(
295 + "TK",
296 + name="TK",
297 + description="Desc",
298 + tools=[email_tool],
299 + )
300 +
301 + def test_slug_length_validation(self):
302 + tool = experimental_create_tool(
303 + "A" * 45,
304 + name="Name",
305 + description="Desc",
306 + input_params=GrepInput,
307 + execute=lambda i, c: {},
308 + )
309 + # LOCAL_ + LONG_TOOLKIT_ + AAAA... would exceed 60
310 + with pytest.raises(ValidationError, match="too long"):
311 + experimental_create_toolkit(
312 + "LONG_TOOLKIT",
313 + name="TK",
314 + description="Desc",
315 + tools=[tool],
316 + )
317 +
318 + def test_slug_validation(self):
319 + with pytest.raises(ValidationError, match="LOCAL_"):
320 + experimental_create_toolkit(
321 + "LOCAL_BAD",
322 + name="TK",
323 + description="Desc",
324 + tools=[
325 + experimental_create_tool(
326 + "T",
327 + name="T",
328 + description="D",
329 + input_params=GrepInput,
330 + execute=lambda i, c: {},
331 + )
332 + ],
333 + )
334 +
335 +
336 +# ────────────────────────────────────────────────────────────────
337 +# Serialization tests
338 +# ────────────────────────────────────────────────────────────────
339 +
340 +
341 +class TestSerialization:
342 + def test_serialize_standalone_tool(self, grep_tool):
343 + result = serialize_custom_tools([grep_tool])
344 + assert len(result) == 1
345 + assert result[0]["slug"] == "GREP"
346 + assert result[0]["name"] == "Grep Search"
347 + assert result[0]["input_schema"]["type"] == "object"
348 + assert "extends_toolkit" not in result[0]
349 +
350 + def test_serialize_extension_tool(self, email_tool):
351 + result = serialize_custom_tools([email_tool])
352 + assert result[0]["extends_toolkit"] == "gmail"
353 +
354 + def test_serialize_toolkit(self, role_toolkit):
355 + result = serialize_custom_toolkits([role_toolkit])
356 + assert len(result) == 1
357 + assert result[0]["slug"] == "ROLE_MANAGER"
358 + assert len(result[0]["tools"]) == 1
359 + assert result[0]["tools"][0]["slug"] == "SET_ROLE"
360 +
361 +
362 +# ────────────────────────────────────────────────────────────────
363 +# Routing map tests
364 +# ────────────────────────────────────────────────────────────────
365 +
366 +
367 +class TestCustomToolsMap:
368 + def test_build_map_standalone(self, grep_tool):
369 + m = build_custom_tools_map([grep_tool])
370 + assert "LOCAL_GREP" in m.by_final_slug
371 + assert "GREP" in m.by_original_slug
372 +
373 + def test_build_map_extension(self, email_tool):
374 + m = build_custom_tools_map([email_tool])
375 + assert "LOCAL_GMAIL_GET_EMAILS" in m.by_final_slug
376 + assert "GET_EMAILS" in m.by_original_slug
377 +
378 + def test_build_map_toolkit(self, set_role_tool, role_toolkit):
379 + m = build_custom_tools_map([], [role_toolkit])
380 + assert "LOCAL_ROLE_MANAGER_SET_ROLE" in m.by_final_slug
381 + assert "SET_ROLE" in m.by_original_slug
382 +
383 + def test_build_map_mixed(self, grep_tool, email_tool, role_toolkit):
384 + m = build_custom_tools_map([grep_tool, email_tool], [role_toolkit])
385 + assert len(m.by_final_slug) == 3
386 + assert len(m.by_original_slug) == 3
387 +
388 + def test_collision_detection_final_slug(self, grep_tool):
389 + with pytest.raises(ValidationError, match="collision"):
390 + build_custom_tools_map([grep_tool, grep_tool])
391 +
392 + def test_collision_detection_original_slug(self):
393 + tool1 = experimental_create_tool(
394 + "FOO",
395 + name="Foo",
396 + description="Desc",
397 + input_params=GrepInput,
398 + execute=lambda i, c: {},
399 + )
400 + # Same slug in a toolkit produces different final slug but same original
401 + # This would collide on original slug
402 + toolkit = experimental_create_toolkit(
403 + "TK",
404 + name="TK",
405 + description="D",
406 + tools=[
407 + experimental_create_tool(
408 + "FOO",
409 + name="Foo2",
410 + description="Desc2",
411 + input_params=GrepInput,
412 + execute=lambda i, c: {},
413 + )
414 + ],
415 + )
416 + with pytest.raises(ValidationError, match="collision"):
417 + build_custom_tools_map([tool1], [toolkit])
418 +
419 +
420 +class TestFindCustomTool:
421 + def test_find_by_final_slug(self, grep_tool):
422 + m = build_custom_tools_map([grep_tool])
423 + entry = find_custom_tool(m, "LOCAL_GREP")
424 + assert entry is not None
425 + assert entry.final_slug == "LOCAL_GREP"
426 +
427 + def test_find_by_original_slug(self, grep_tool):
428 + m = build_custom_tools_map([grep_tool])
429 + entry = find_custom_tool(m, "GREP")
430 + assert entry is not None
431 + assert entry.final_slug == "LOCAL_GREP"
432 +
433 + def test_find_case_insensitive(self, grep_tool):
434 + m = build_custom_tools_map([grep_tool])
435 + entry = find_custom_tool(m, "grep")
436 + assert entry is not None
437 + assert entry.final_slug == "LOCAL_GREP"
438 +
439 + def test_find_nonexistent(self, grep_tool):
440 + m = build_custom_tools_map([grep_tool])
441 + assert find_custom_tool(m, "NONEXISTENT") is None
442 +
443 + def test_find_none_map(self):
444 + assert find_custom_tool(None, "GREP") is None
445 +
446 +
447 +class TestBuildMapFromResponse:
448 + def test_builds_from_response(self, grep_tool, email_tool, role_toolkit):
449 + # Mock response experimental
450 + mock_exp = MagicMock()
451 +
452 + mock_ct1 = MagicMock()
453 + mock_ct1.slug = "LOCAL_GREP"
454 + mock_ct1.original_slug = "GREP"
455 + mock_ct1.extends_toolkit = None
456 +
457 + mock_ct2 = MagicMock()
458 + mock_ct2.slug = "LOCAL_GMAIL_GET_EMAILS"
459 + mock_ct2.original_slug = "GET_EMAILS"
460 + mock_ct2.extends_toolkit = "gmail"
461 +
462 + mock_exp.custom_tools = [mock_ct1, mock_ct2]
463 +
464 + mock_ctk = MagicMock()
465 + mock_ctk.slug = "ROLE_MANAGER"
466 + mock_ctk_tool = MagicMock()
467 + mock_ctk_tool.slug = "LOCAL_ROLE_MANAGER_SET_ROLE"
468 + mock_ctk_tool.original_slug = "SET_ROLE"
469 + mock_ctk.tools = [mock_ctk_tool]
470 + mock_exp.custom_toolkits = [mock_ctk]
471 +
472 + set_role = role_toolkit.tools[0]
473 + m = build_custom_tools_map_from_response(
474 + [grep_tool, email_tool],
475 + [role_toolkit],
476 + mock_exp,
477 + )
478 +
479 + assert "LOCAL_GREP" in m.by_final_slug
480 + assert "LOCAL_GMAIL_GET_EMAILS" in m.by_final_slug
481 + assert "LOCAL_ROLE_MANAGER_SET_ROLE" in m.by_final_slug
482 + assert m.by_final_slug["LOCAL_GMAIL_GET_EMAILS"].toolkit == "gmail"
483 +
484 +
485 +# ────────────────────────────────────────────────────────────────
486 +# Custom tool execution tests
487 +# ────────────────────────────────────────────────────────────────
488 +
489 +
490 +class TestExecuteCustomTool:
491 + def test_successful_execution(self, grep_tool):
492 + m = build_custom_tools_map([grep_tool])
493 + entry = find_custom_tool(m, "GREP")
494 + result = execute_custom_tool(entry, {"pattern": "hello"}, MockSessionContext()) # type: ignore
495 + assert result["successful"] is True
496 + assert result["data"]["matches"] == ["hello"]
497 + assert result["data"]["path"] == "." # default value
498 + assert result["error"] is None
499 +
500 + def test_applies_pydantic_defaults(self, grep_tool):
501 + m = build_custom_tools_map([grep_tool])
502 + entry = find_custom_tool(m, "GREP")
503 + result = execute_custom_tool(entry, {"pattern": "test"}, MockSessionContext()) # type: ignore
504 + assert result["data"]["path"] == "." # default applied
505 +
506 + def test_validation_failure(self, grep_tool):
507 + m = build_custom_tools_map([grep_tool])
508 + entry = find_custom_tool(m, "GREP")
509 + result = execute_custom_tool(entry, {}, MockSessionContext()) # type: ignore # missing required "pattern"
510 + assert result["successful"] is False
511 + assert "validation" in result["error"].lower()
512 +
513 + def test_execute_function_error(self):
514 + def bad_execute(input, ctx):
515 + raise RuntimeError("Something went wrong")
516 +
517 + tool = experimental_create_tool(
518 + "BAD",
519 + name="Bad",
520 + description="Desc",
521 + input_params=GrepInput,
522 + execute=bad_execute,
523 + )
524 + m = build_custom_tools_map([tool])
525 + entry = find_custom_tool(m, "BAD")
526 + result = execute_custom_tool(entry, {"pattern": "x"}, MockSessionContext()) # type: ignore
527 + assert result["successful"] is False
528 + assert "Something went wrong" in result["error"]
529 +
530 + def test_execute_returns_none(self):
531 + tool = experimental_create_tool(
532 + "NOOP",
533 + name="Noop",
534 + description="Returns None",
535 + input_params=GrepInput,
536 + execute=lambda i, c: None, # type: ignore
537 + )
538 + m = build_custom_tools_map([tool])
539 + entry = find_custom_tool(m, "NOOP")
540 + result = execute_custom_tool(entry, {"pattern": "x"}, MockSessionContext()) # type: ignore
541 + assert result["successful"] is True
542 + assert result["data"] == {}
543 +
544 +
545 +# ────────────────────────────────────────────────────────────────
546 +# SessionContextImpl tests
547 +# ────────────────────────────────────────────────────────────────
548 +
549 +
550 +class TestSessionContextImpl:
551 + def test_user_id(self):
552 + ctx = SessionContextImpl(
553 + client=MagicMock(),
554 + user_id="user-1",
555 + session_id="sess-1",
556 + )
557 + assert ctx.user_id == "user-1"
558 +
559 + def test_execute_routes_to_sibling(self, grep_tool):
560 + m = build_custom_tools_map([grep_tool])
561 + ctx = SessionContextImpl(
562 + client=MagicMock(),
563 + user_id="user-1",
564 + session_id="sess-1",
565 + custom_tools_map=m,
566 + )
567 + result = ctx.execute("GREP", {"pattern": "test"})
568 + assert result["successful"] is True
569 + assert result["data"]["matches"] == ["test"]
570 +
571 + def test_execute_falls_back_to_remote(self, grep_tool):
572 + m = build_custom_tools_map([grep_tool])
573 + mock_client = MagicMock()
574 + mock_response = MagicMock()
575 + mock_response.data = {"remote": True}
576 + mock_response.error = None
577 + mock_client.tool_router.session.execute.return_value = mock_response
578 +
579 + ctx = SessionContextImpl(
580 + client=mock_client,
581 + user_id="user-1",
582 + session_id="sess-1",
583 + custom_tools_map=m,
584 + )
585 + result = ctx.execute("NONEXISTENT_TOOL", {"arg": "val"})
586 + mock_client.tool_router.session.execute.assert_called_once()
587 + assert result["data"] == {"remote": True}
588 +
589 + def test_proxy_execute(self):
590 + mock_client = MagicMock()
591 + mock_response = MagicMock()
592 + mock_response.status = 200
593 + mock_response.data = {"result": "ok"}
594 + mock_response.headers = {"Content-Type": "application/json"}
595 + mock_response.binary_data = None
596 + mock_client.tool_router.session.proxy_execute.return_value = mock_response
597 +
598 + ctx = SessionContextImpl(
599 + client=mock_client,
600 + user_id="user-1",
601 + session_id="sess-1",
602 + )
603 + result = ctx.proxy_execute(
604 + toolkit="gmail",
605 + endpoint="https://gmail.googleapis.com/test",
606 + method="GET",
607 + )
608 + assert result["status"] == 200
609 + assert result["data"] == {"result": "ok"}
610 + mock_client.tool_router.session.proxy_execute.assert_called_once()
611 +
612 +
613 +# ────────────────────────────────────────────────────────────────
614 +# ToolRouterSession integration tests
615 +# ────────────────────────────────────────────────────────────────
616 +
617 +
618 +@pytest.fixture
619 +def mock_session_deps(grep_tool, email_tool, role_toolkit):
620 + """Create mock dependencies for ToolRouterSession with custom tools."""
621 + client = MagicMock()
622 + provider = MagicMock()
623 + experimental = MagicMock()
624 + experimental.files = MagicMock()
625 + experimental.assistive_prompt = None
626 +
627 + # Build tools map
628 + tools_map = build_custom_tools_map([grep_tool, email_tool], [role_toolkit])
629 +
630 + return {
631 + "client": client,
632 + "provider": provider,
633 + "experimental": experimental,
634 + "tools_map": tools_map,
635 + }
636 +
637 +
638 +class TestToolRouterSessionCustomTools:
639 + def test_execute_routes_to_local(self, mock_session_deps, grep_tool):
640 + session = ToolRouterSession(
641 + client=mock_session_deps["client"],
642 + provider=mock_session_deps["provider"],
643 + auto_upload_download_files=True,
644 + session_id="sess-1",
645 + mcp=MagicMock(),
646 + experimental=mock_session_deps["experimental"],
647 + custom_tools_map=mock_session_deps["tools_map"],
648 + user_id="user-1",
649 + )
650 + result = session.execute("GREP", arguments={"pattern": "test"})
651 + assert result["successful"] is True
652 + assert result["data"]["matches"] == ["test"]
653 + # Should NOT have called the backend
654 + mock_session_deps["client"].tool_router.session.execute.assert_not_called()
655 +
656 + def test_execute_routes_to_local_by_final_slug(self, mock_session_deps):
657 + session = ToolRouterSession(
658 + client=mock_session_deps["client"],
659 + provider=mock_session_deps["provider"],
660 + auto_upload_download_files=True,
661 + session_id="sess-1",
662 + mcp=MagicMock(),
663 + experimental=mock_session_deps["experimental"],
664 + custom_tools_map=mock_session_deps["tools_map"],
665 + user_id="user-1",
666 + )
667 + result = session.execute("LOCAL_GREP", arguments={"pattern": "test"})
668 + assert result["successful"] is True
669 +
670 + def test_execute_case_insensitive(self, mock_session_deps):
671 + session = ToolRouterSession(
672 + client=mock_session_deps["client"],
673 + provider=mock_session_deps["provider"],
674 + auto_upload_download_files=True,
675 + session_id="sess-1",
676 + mcp=MagicMock(),
677 + experimental=mock_session_deps["experimental"],
678 + custom_tools_map=mock_session_deps["tools_map"],
679 + user_id="user-1",
680 + )
681 + result = session.execute("grep", arguments={"pattern": "test"})
682 + assert result["successful"] is True
683 +
684 + def test_execute_routes_to_remote(self, mock_session_deps):
685 + mock_response = MagicMock()
686 + mock_session_deps["client"].tool_router.session.execute.return_value = (
687 + mock_response
688 + )
689 +
690 + session = ToolRouterSession(
691 + client=mock_session_deps["client"],
692 + provider=mock_session_deps["provider"],
693 + auto_upload_download_files=True,
694 + session_id="sess-1",
695 + mcp=MagicMock(),
696 + experimental=mock_session_deps["experimental"],
697 + custom_tools_map=mock_session_deps["tools_map"],
698 + user_id="user-1",
699 + )
700 + session.execute("GMAIL_SEND_EMAIL", arguments={"to": "alice@example.com"})
701 + mock_session_deps["client"].tool_router.session.execute.assert_called_once()
702 +
703 + def test_custom_tools_list(self, mock_session_deps):
704 + session = ToolRouterSession(
705 + client=mock_session_deps["client"],
706 + provider=mock_session_deps["provider"],
707 + auto_upload_download_files=True,
708 + session_id="sess-1",
709 + mcp=MagicMock(),
710 + experimental=mock_session_deps["experimental"],
711 + custom_tools_map=mock_session_deps["tools_map"],
712 + user_id="user-1",
713 + )
714 + tools = session.custom_tools()
715 + assert len(tools) == 3
716 + slugs = {t.slug for t in tools}
717 + assert "LOCAL_GREP" in slugs
718 + assert "LOCAL_GMAIL_GET_EMAILS" in slugs
719 + assert "LOCAL_ROLE_MANAGER_SET_ROLE" in slugs
720 +
721 + def test_custom_tools_filter_by_toolkit(self, mock_session_deps):
722 + session = ToolRouterSession(
723 + client=mock_session_deps["client"],
724 + provider=mock_session_deps["provider"],
725 + auto_upload_download_files=True,
726 + session_id="sess-1",
727 + mcp=MagicMock(),
728 + experimental=mock_session_deps["experimental"],
729 + custom_tools_map=mock_session_deps["tools_map"],
730 + user_id="user-1",
731 + )
732 + gmail_tools = session.custom_tools(toolkit="gmail")
733 + assert len(gmail_tools) == 1
734 + assert gmail_tools[0].slug == "LOCAL_GMAIL_GET_EMAILS"
735 +
736 + def test_custom_toolkits_list(self, mock_session_deps):
737 + session = ToolRouterSession(
738 + client=mock_session_deps["client"],
739 + provider=mock_session_deps["provider"],
740 + auto_upload_download_files=True,
741 + session_id="sess-1",
742 + mcp=MagicMock(),
743 + experimental=mock_session_deps["experimental"],
744 + custom_tools_map=mock_session_deps["tools_map"],
745 + user_id="user-1",
746 + )
747 + toolkits = session.custom_toolkits()
748 + assert len(toolkits) == 1
749 + assert toolkits[0].slug == "ROLE_MANAGER"
750 + assert len(toolkits[0].tools) == 1
751 + assert toolkits[0].tools[0].slug == "LOCAL_ROLE_MANAGER_SET_ROLE"
752 +
753 + def test_custom_tools_empty_when_no_map(self):
754 + session = ToolRouterSession(
755 + client=MagicMock(),
756 + provider=MagicMock(),
757 + auto_upload_download_files=True,
758 + session_id="sess-1",
759 + mcp=MagicMock(),
760 + experimental=MagicMock(),
761 + )
762 + assert session.custom_tools() == []
763 + assert session.custom_toolkits() == []
764 +
765 + def test_proxy_execute(self, mock_session_deps):
766 + mock_response = MagicMock()
767 + mock_response.status = 200
768 + mock_response.data = {"result": "ok"}
769 + mock_response.headers = {"Content-Type": "application/json"}
770 + mock_response.binary_data = None
771 + mock_session_deps[
772 + "client"
773 + ].tool_router.session.proxy_execute.return_value = mock_response
774 +
775 + session = ToolRouterSession(
776 + client=mock_session_deps["client"],
777 + provider=mock_session_deps["provider"],
778 + auto_upload_download_files=True,
779 + session_id="sess-1",
780 + mcp=MagicMock(),
781 + experimental=mock_session_deps["experimental"],
782 + )
783 + result = session.proxy_execute(
784 + toolkit="gmail",
785 + endpoint="https://gmail.googleapis.com/test",
786 + method="GET",
787 + )
788 + assert result["status"] == 200
789 + mock_session_deps[
790 + "client"
791 + ].tool_router.session.proxy_execute.assert_called_once()
792 +
793 +
794 +# ────────────────────────────────────────────────────────────────
795 +# Multi-execute routing tests
796 +# ────────────────────────────────────────────────────────────────
797 +
798 +
799 +class TestMultiExecuteRouting:
800 + def _make_session(self, grep_tool, mock_client=None):
801 + m = build_custom_tools_map([grep_tool])
802 + client = mock_client or MagicMock()
803 + session = ToolRouterSession(
804 + client=client,
805 + provider=MagicMock(),
806 + auto_upload_download_files=True,
807 + session_id="sess-1",
808 + mcp=MagicMock(),
809 + experimental=MagicMock(),
810 + custom_tools_map=m,
811 + user_id="user-1",
812 + )
813 + return session
814 +
815 + def test_route_all_local(self, grep_tool):
816 + session = self._make_session(grep_tool)
817 + mock_tools_model = MagicMock()
818 +
819 + result = session._route_multi_execute(
820 + {"tools": [{"tool_slug": "GREP", "arguments": {"pattern": "test"}}]},
821 + mock_tools_model,
822 + None,
823 + )
824 + # Single local tool returns unwrapped
825 + assert result["successful"] is True
826 + assert result["data"]["matches"] == ["test"]
827 +
828 + def test_route_all_remote(self, grep_tool):
829 + session = self._make_session(grep_tool)
830 + mock_tools_model = MagicMock()
831 +
832 + remote_response = {
833 + "data": {"results": [{"tool_slug": "GMAIL_SEND", "response": {"successful": True}}]},
834 + "error": None,
835 + "successful": True,
836 + }
837 + mock_tools_model._wrap_execute_tool_for_tool_router.return_value = (
838 + lambda slug, args: remote_response
839 + )
840 +
841 + result = session._route_multi_execute(
842 + {
843 + "tools": [
844 + {"tool_slug": "GMAIL_SEND", "arguments": {"to": "alice@x.com"}}
845 + ]
846 + },
847 + mock_tools_model,
848 + None,
849 + )
850 + assert result == remote_response
851 +
852 + def test_route_mixed_local_and_remote(self, grep_tool):
853 + session = self._make_session(grep_tool)
854 + mock_tools_model = MagicMock()
855 +
856 + remote_response = {
857 + "data": {
858 + "results": [
859 + {
860 + "tool_slug": "GMAIL_SEND",
861 + "response": {"successful": True, "data": {"sent": True}},
862 + }
863 + ]
864 + },
865 + "error": None,
866 + "successful": True,
867 + }
868 + mock_tools_model._wrap_execute_tool_for_tool_router.return_value = (
869 + lambda slug, args: remote_response
870 + )
871 +
872 + result = session._route_multi_execute(
873 + {
874 + "tools": [
875 + {"tool_slug": "GREP", "arguments": {"pattern": "test"}},
876 + {"tool_slug": "GMAIL_SEND", "arguments": {"to": "alice@x.com"}},
877 + ]
878 + },
879 + mock_tools_model,
880 + None,
881 + )
882 + # Should have merged results
883 + assert result["successful"] is True
884 + results = result["data"]["results"]
885 + assert len(results) == 2
886 + # First should be the local GREP result
887 + assert results[0]["tool_slug"] == "GREP"
888 + assert results[0]["response"]["successful"] is True
889 + # Second should be the remote result
890 + assert results[1]["tool_slug"] == "GMAIL_SEND"
891 +
892 + def test_route_empty_tools(self, grep_tool):
893 + session = self._make_session(grep_tool)
894 + mock_tools_model = MagicMock()
895 + fallback_result = {"data": {}, "error": None, "successful": True}
896 + mock_tools_model._wrap_execute_tool_for_tool_router.return_value = (
897 + lambda slug, args: fallback_result
898 + )
899 +
900 + result = session._route_multi_execute(
901 + {"tools": []}, mock_tools_model, None
902 + )
903 + # Should fall back to remote
904 + assert result == fallback_result
905 +
906 + def test_route_multiple_local_tools(self):
907 + tool1 = experimental_create_tool(
908 + "TOOL_A",
909 + name="A",
910 + description="D",
911 + input_params=GrepInput,
912 + execute=lambda i, c: {"tool": "A", "pattern": i.pattern},
913 + )
914 + tool2 = experimental_create_tool(
915 + "TOOL_B",
916 + name="B",
917 + description="D",
918 + input_params=GrepInput,
919 + execute=lambda i, c: {"tool": "B", "pattern": i.pattern},
920 + )
921 + m = build_custom_tools_map([tool1, tool2])
922 + session = ToolRouterSession(
923 + client=MagicMock(),
924 + provider=MagicMock(),
925 + auto_upload_download_files=True,
926 + session_id="sess-1",
927 + mcp=MagicMock(),
928 + experimental=MagicMock(),
929 + custom_tools_map=m,
930 + user_id="user-1",
931 + )
932 + result = session._route_multi_execute(
933 + {
934 + "tools": [
935 + {"tool_slug": "TOOL_A", "arguments": {"pattern": "x"}},
936 + {"tool_slug": "TOOL_B", "arguments": {"pattern": "y"}},
937 + ]
938 + },
939 + MagicMock(),
940 + None,
941 + )
942 + assert result["successful"] is True
943 + results = result["data"]["results"]
944 + assert len(results) == 2
945 + assert results[0]["response"]["data"]["tool"] == "A"
946 + assert results[1]["response"]["data"]["tool"] == "B"