@devries-cameron20 / composio Mirror · read-only / commits / 742092718
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 21, 13:30 UTC

fix(sdk): qualify custom toolkit child slug mapping across Python and TypeScript (#4311)

## Summary The Python SDK treated a custom tool's `original_slug` as globally unique, rejecting valid custom toolkits that reuse common child names such as `SEARCH`, `VERSION`, or `GREP` even though the backend-assigned final slugs are toolkit-qualified (`LOCAL_ALPHA_GREP`, `LOCAL_BETA_GREP`). This ports the toolkit-qualified lookup from #3360 to Python, then fixes three response-mapping bugs found in review and applies the same fixes to the TypeScript SDK so both stay in parity. ## Changes ### Python (`composio`) - Scope custom-tool collision detection and response matching by toolkit plus original slug. - Keep bare original-slug aliases only when unambiguous; `session.execute("GREP")` raises with the final slugs to use when the slug is shared. - Preserve toolkit-qualified final slugs in `custom_toolkits()`. - `build_custom_tools_map_from_response`: raise when a response tool has local handles but no exact toolkit match instead of silently dropping it or binding another toolkit's handler; only fall back to a bare match when the response carries no toolkit identity; reject duplicate qualified response entries; derive bare-slug ambiguity from local definitions so omitting a sibling in the response never makes the survivor callable by bare name. - `custom_toolkits()` only reuses a bare alias that belongs to the same toolkit. - Docstring and Python session reference page state that bare-slug execution requires a unique original slug. ### TypeScript (`@composio/core`) - Same four fixes in `buildCustomToolsMapFromResponse` and the same guard in `customToolkits()`. - JSDoc and TypeScript session reference page updated. - Changeset: patch for `@composio/core`. ### Not changed - `COMPOSIO_MULTI_EXECUTE_TOOL` still aborts the whole batch when one item uses an ambiguous bare slug, matching current TS behavior. Switching to per-item errors is a cross-SDK design change left for a follow-up. ## Type of change - [x] Bug fix - [ ] New feature - [ ] Refactor/Chore - [ ] Documentation - [ ] Breaking change ## How Has This Been Tested? Python: - `pytest tests/test_custom_tools.py tests/test_tool_router.py`: 181 passed. - ruff (project config) clean; mypy reports no errors in the touched files. - New tests: sibling routing, multi-execute, preload rejection, listing guard, and five response-mapping cases (no exact match, cross-toolkit binding, standalone bare fallback, unknown response tools skipped, ambiguity from local definitions, duplicate qualified entries). TypeScript: - `vitest run` in `ts/packages/core`: 53 files, 1251 passed, 2 expected failures. - `tsc --noEmit` clean; prettier and oxlint via pre-commit hook. - New tests: cross-toolkit reuse in `buildCustomToolsMap` and a new `buildCustomToolsMapFromResponse` block mirroring the Python cases. Python and TypeScript CI do not run automatically on this fork PR; a maintainer needs to approve the workflow run. ## Checklist - [x] I have read the Code of Conduct and this PR adheres to it - [x] I ran linters/tests locally and they passed - [x] I updated documentation as needed - [x] I added tests or explain why not applicable - [x] I added a changeset if this change affects published packages ## Additional context Reviewed with a second opinion from Codex (gpt-5.6-sol), which flagged the wrong-handler binding and response-derived ambiguity bugs fixed in the follow-up commits. https://claude.ai/code/session_01Y7Ni3QEBDGShSrEtwQS5bA EOF -R ComposioHQ/composio --------- Signed-off-by: CoralGarden52 <2193436736@qq.com> Co-authored-by: jkomyno <alberto@composio.dev> Co-authored-by: Alberto Schiabel <jkomyno@users.noreply.github.com>

CoralGarden52 committed Sep 3, 2026 at 20:08 UTC 7420927183a2905847e352bb0a6e8fba24d6aa9f
12 files changed +807 -46
.changeset/custom-toolkit-slug-mapping.md new
+5
@@ -0,0 +1,5 @@
1 +---
2 +'@composio/core': patch
3 +---
4 +
5 +Fix custom toolkit child slug mapping: reject response tools that have local handles but no exact toolkit match instead of silently dropping them or binding another toolkit's handler, derive bare-slug ambiguity from local definitions, and only reuse a same-toolkit bare alias in customToolkits().
docs/content/reference/sdk-reference/python/session.mdx
+1 -1
@@ -103,7 +103,7 @@ def search(query: str, model: str | None = ...) -> SessionSearchResponse
103
104 ### execute()
105
106 -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.
106 +Execute a tool within the session. For custom tools, accepts the full slug (e.g. "LOCAL_GREP") or the original slug (e.g. "GREP") when that original slug is unique across the session's custom tools and toolkits. Custom tools are executed in-process; remote tools are sent to the Composio backend.
107
108 ```python
109 def execute(tool_slug: str, arguments: Dict[str, Any | None] = ..., account: str | None = ...) -> SessionExecuteResponse
docs/content/reference/sdk-reference/typescript/session.mdx
+4 -3
@@ -114,9 +114,10 @@ async delete(requestOptions?: ComposioRequestOptions): Promise<ToolRouterSession
114
115 Execute a tool within the session.
116
117 -For custom tools, accepts the original slug (e.g. "GREP") or the
118 -full slug (e.g. "LOCAL_GREP"). Custom tools are executed in-process;
119 -remote tools are sent to the Composio backend.
117 +For custom tools, accepts the full slug (e.g. "LOCAL_GREP") or the
118 +original slug (e.g. "GREP") when that original slug is unique across
119 +the session's custom tools and toolkits. Custom tools are executed
120 +in-process; remote tools are sent to the Composio backend.
121
122 ```typescript
123 async execute(toolSlug: string, arguments_?: Record<string, unknown>, options?: ToolRouterSessionExecuteOptions, requestOptions?: ComposioRequestOptions): Promise<ToolRouterSessionExecuteResponse>
python/composio/core/models/custom_tool.py
+156 -26
@@ -138,6 +138,51 @@ def _build_final_slug(tool_slug: str, toolkit_slug: t.Optional[str] = None) -> s
138 return f"{LOCAL_TOOL_PREFIX}{upper}"
139
140
141 +def _qualified_original_slug_key(toolkit: t.Optional[str], original_slug: str) -> str:
142 + return f"{toolkit.upper() if toolkit else ''}::{original_slug.upper()}"
143 +
144 +
145 +def _can_share_original_slug(
146 + existing: CustomToolsMapEntry, next_entry: CustomToolsMapEntry
147 +) -> bool:
148 + return (
149 + existing.toolkit is not None
150 + and next_entry.toolkit is not None
151 + and existing.toolkit.lower() != next_entry.toolkit.lower()
152 + )
153 +
154 +
155 +def _add_original_slug_alias(
156 + *,
157 + by_original_slug: t.Dict[str, CustomToolsMapEntry],
158 + ambiguous_original_slugs: t.Set[str],
159 + original_slug: str,
160 + entry: CustomToolsMapEntry,
161 +) -> None:
162 + original_slug_key = original_slug.upper()
163 + if original_slug_key in ambiguous_original_slugs:
164 + return
165 +
166 + existing = by_original_slug.get(original_slug_key)
167 + if existing is None:
168 + by_original_slug[original_slug_key] = entry
169 + return
170 +
171 + if existing.final_slug.upper() == entry.final_slug.upper():
172 + return
173 +
174 + if _can_share_original_slug(existing, entry):
175 + del by_original_slug[original_slug_key]
176 + ambiguous_original_slugs.add(original_slug_key)
177 + return
178 +
179 + raise ValidationError(
180 + f'Custom tool slug collision: original slug "{original_slug}" '
181 + f'maps to multiple final slugs. "{existing.final_slug}" and '
182 + f'"{entry.final_slug}" both resolve from "{original_slug_key}".'
183 + )
184 +
185 +
186 def _get_input_json_schema(model: t.Type[BaseModel]) -> t.Dict[str, t.Any]:
187 """Convert a Pydantic model class to a JSON Schema dict suitable for the backend."""
188 full_schema = model.model_json_schema()
@@ -578,6 +623,8 @@ def build_custom_tools_map(
623 """Build a CustomToolsMap from custom tools and toolkits."""
624 by_final_slug: t.Dict[str, CustomToolsMapEntry] = {}
625 by_original_slug: t.Dict[str, CustomToolsMapEntry] = {}
626 + by_toolkit_and_original_slug: t.Dict[str, CustomToolsMapEntry] = {}
627 + ambiguous_original_slugs: t.Set[str] = set()
628
629 def add_entry(
630 handle: CustomTool, final_slug: str, toolkit: t.Optional[str]
@@ -597,20 +644,24 @@ def build_custom_tools_map(
644 f'Custom tool slug collision: "{final_slug}" is already registered.'
645 )
646
600 - if original_slug in by_original_slug:
601 - existing = by_original_slug[original_slug]
647 + qualified_key = _qualified_original_slug_key(toolkit, original_slug)
648 + if qualified_key in by_toolkit_and_original_slug:
649 raise ValidationError(
650 f'Custom tool slug collision: original slug "{handle.slug}" '
604 - f"maps to multiple final slugs. "
605 - f'"{existing.final_slug}" and "{final_slug}" both resolve '
606 - f'from "{original_slug}".'
651 + f'is already registered for toolkit "{toolkit or "custom"}".'
652 )
653
654 entry = CustomToolsMapEntry(
655 handle=handle, final_slug=final_slug, toolkit=toolkit
656 )
657 by_final_slug[final_slug_key] = entry
613 - by_original_slug[original_slug] = entry
658 + by_toolkit_and_original_slug[qualified_key] = entry
659 + _add_original_slug_alias(
660 + by_original_slug=by_original_slug,
661 + ambiguous_original_slugs=ambiguous_original_slugs,
662 + original_slug=original_slug,
663 + entry=entry,
664 + )
665
666 # Process standalone tools
667 for handle in tools:
@@ -629,6 +680,8 @@ def build_custom_tools_map(
680 return CustomToolsMap(
681 by_final_slug=by_final_slug,
682 by_original_slug=by_original_slug,
683 + by_toolkit_and_original_slug=by_toolkit_and_original_slug,
684 + ambiguous_original_slugs=ambiguous_original_slugs,
685 toolkits=list(toolkits) if toolkits else None,
686 tools=list(tools) if tools else None,
687 )
@@ -648,41 +701,94 @@ def build_custom_tools_map_from_response(
701 """Build a CustomToolsMap using the slug/original_slug mapping from the backend response."""
702 by_final_slug: t.Dict[str, CustomToolsMapEntry] = {}
703 by_original_slug: t.Dict[str, CustomToolsMapEntry] = {}
704 + by_toolkit_and_original_slug: t.Dict[str, CustomToolsMapEntry] = {}
705 + ambiguous_original_slugs: t.Set[str] = set()
706 +
707 + # Build lookups from toolkit + original slug and from original slug -> matches.
708 + handles_by_qualified_original: t.Dict[
709 + str, t.Tuple[CustomTool, t.Optional[str]]
710 + ] = {}
711 + handles_by_original: t.Dict[str, t.List[t.Tuple[CustomTool, t.Optional[str]]]] = {}
712 +
713 + def register_handle(handle: CustomTool, toolkit: t.Optional[str]) -> None:
714 + original_slug = handle.slug.upper()
715 + match = (handle, toolkit)
716 + handles_by_qualified_original[
717 + _qualified_original_slug_key(toolkit, original_slug)
718 + ] = match
719 + handles_by_original.setdefault(original_slug, []).append(match)
720
652 - # Build lookup from original slug -> handle + toolkit
653 - handles_by_original: t.Dict[str, t.Tuple[CustomTool, t.Optional[str]]] = {}
721 for handle in tools:
655 - key = handle.slug.upper()
656 - if key in handles_by_original:
657 - raise ValidationError(
658 - f'Duplicate custom tool slug "{handle.slug}" — '
659 - f"each tool must have a unique slug across all custom tools and toolkits."
660 - )
661 - handles_by_original[key] = (handle, handle.extends_toolkit)
722 + register_handle(handle, handle.extends_toolkit)
723 if toolkits:
724 for tk in toolkits:
725 for handle in tk.tools:
665 - key = handle.slug.upper()
666 - if key in handles_by_original:
667 - raise ValidationError(
668 - f'Duplicate custom tool slug "{handle.slug}" — '
669 - f"each tool must have a unique slug across all custom tools and toolkits."
670 - )
671 - handles_by_original[key] = (handle, tk.slug)
726 + register_handle(handle, tk.slug)
727 +
728 + def find_handle(
729 + final_slug: str, original_slug: str, toolkit: t.Optional[str]
730 + ) -> t.Optional[t.Tuple[CustomTool, t.Optional[str]]]:
731 + original_slug_key = original_slug.upper()
732 + qualified_match = handles_by_qualified_original.get(
733 + _qualified_original_slug_key(toolkit, original_slug_key)
734 + )
735 + if qualified_match is not None:
736 + return qualified_match
737 +
738 + bare_matches = handles_by_original.get(original_slug_key, [])
739 + if not bare_matches:
740 + # Response tool not defined locally; nothing to route in-process.
741 + return None
742 + # A bare match may only stand in when the response carries no toolkit
743 + # identity. Binding a toolkit child to another toolkit's handler would
744 + # silently execute the wrong implementation.
745 + if toolkit is None and len(bare_matches) == 1:
746 + return bare_matches[0]
747 +
748 + registered = sorted(
749 + {(match_toolkit or "custom").upper() for _, match_toolkit in bare_matches}
750 + )
751 + raise ValidationError(
752 + f'Cannot map custom tool "{final_slug}": original slug '
753 + f'"{original_slug}" for toolkit "{toolkit or "custom"}" has no exact '
754 + f"local match. Registered for toolkits: {', '.join(registered)}."
755 + )
756
757 def add_entry(
758 final_slug: str, original_slug: str, toolkit: t.Optional[str]
759 ) -> None:
676 - match = handles_by_original.get(original_slug.upper())
760 + resolved_toolkit = toolkit
761 + match = find_handle(final_slug, original_slug, resolved_toolkit)
762 if not match:
763 return
764 handle, default_toolkit = match
680 - resolved_toolkit = toolkit if toolkit is not None else default_toolkit
765 + if resolved_toolkit is None:
766 + resolved_toolkit = default_toolkit
767 +
768 + final_slug_key = final_slug.upper()
769 + if final_slug_key in by_final_slug:
770 + raise ValidationError(
771 + f'Custom tool slug collision: "{final_slug}" is already registered.'
772 + )
773 +
774 + qualified_key = _qualified_original_slug_key(resolved_toolkit, original_slug)
775 + if qualified_key in by_toolkit_and_original_slug:
776 + raise ValidationError(
777 + f'Custom tool slug collision: original slug "{handle.slug}" '
778 + f'is already registered for toolkit "{resolved_toolkit or "custom"}".'
779 + )
780 +
781 entry = CustomToolsMapEntry(
782 handle=handle, final_slug=final_slug, toolkit=resolved_toolkit
783 )
684 - by_final_slug[final_slug.upper()] = entry
685 - by_original_slug[original_slug.upper()] = entry
784 + by_final_slug[final_slug_key] = entry
785 + by_toolkit_and_original_slug[qualified_key] = entry
786 + _add_original_slug_alias(
787 + by_original_slug=by_original_slug,
788 + ambiguous_original_slugs=ambiguous_original_slugs,
789 + original_slug=original_slug,
790 + entry=entry,
791 + )
792
793 if experimental and experimental.custom_tools:
794 for ct in experimental.custom_tools:
@@ -693,9 +799,19 @@ def build_custom_tools_map_from_response(
799 for ctk_tool in ctk.tools:
800 add_entry(ctk_tool.slug, ctk_tool.original_slug, ctk.slug)
801
802 + # Ambiguity follows the local definitions, not whichever subset the
803 + # response happened to include: a shared child slug must never become
804 + # callable by its bare name just because a sibling was omitted.
805 + for original_slug_key, matches in handles_by_original.items():
806 + if len(matches) > 1:
807 + by_original_slug.pop(original_slug_key, None)
808 + ambiguous_original_slugs.add(original_slug_key)
809 +
810 return CustomToolsMap(
811 by_final_slug=by_final_slug,
812 by_original_slug=by_original_slug,
813 + by_toolkit_and_original_slug=by_toolkit_and_original_slug,
814 + ambiguous_original_slugs=ambiguous_original_slugs,
815 toolkits=list(toolkits) if toolkits else None,
816 tools=list(tools) if tools else None,
817 )
@@ -711,6 +827,19 @@ def find_custom_tool_map_entry_by_final_slug(
827 return custom_tools_map.by_final_slug.get(slug.upper())
828
829
830 +def find_custom_tool_map_entry_by_toolkit_and_original_slug(
831 + custom_tools_map: t.Optional[CustomToolsMap],
832 + toolkit: t.Optional[str],
833 + slug: str,
834 +) -> t.Optional[CustomToolsMapEntry]:
835 + """Find a custom toolkit tool by toolkit slug and original tool slug."""
836 + if custom_tools_map is None:
837 + return None
838 + return custom_tools_map.by_toolkit_and_original_slug.get(
839 + _qualified_original_slug_key(toolkit, slug)
840 + )
841 +
842 +
843 def assert_no_custom_tool_slugs_in_preload(
844 preload_tools: t.Union[t.Sequence[str], t.Literal["all"], None],
845 custom_tools_map: t.Optional[CustomToolsMap],
@@ -734,6 +863,7 @@ def assert_no_custom_tool_slugs_in_preload(
863 custom_tools_map is not None
864 and (
865 normalized in custom_tools_map.by_original_slug
866 + or normalized in custom_tools_map.ambiguous_original_slugs
867 or normalized in custom_tools_map.by_final_slug
868 )
869 ):
python/composio/core/models/custom_tool_execution.py
+33 -1
@@ -17,6 +17,8 @@ import typing as t
17
18 from pydantic import ValidationError as PydanticValidationError
19
20 +from composio.exceptions import ValidationError
21 +
22 from .custom_tool_types import (
23 CustomToolsMap,
24 CustomToolsMapEntry,
@@ -37,7 +39,37 @@ def find_custom_tool(
39 if map_ is None:
40 return None
41 upper = slug.upper()
40 - return map_.by_final_slug.get(upper) or map_.by_original_slug.get(upper)
42 + final_slug_match = map_.by_final_slug.get(upper)
43 + if final_slug_match is not None:
44 + return final_slug_match
45 + if upper in map_.ambiguous_original_slugs:
46 + return None
47 + return map_.by_original_slug.get(upper)
48 +
49 +
50 +def assert_unambiguous_custom_tool_slug(
51 + map_: t.Optional[CustomToolsMap], slug: str
52 +) -> None:
53 + """Reject ambiguous bare original slugs before remote fallback."""
54 + if map_ is None:
55 + return
56 +
57 + upper = slug.upper()
58 + if upper not in map_.ambiguous_original_slugs:
59 + return
60 +
61 + final_slugs = sorted(
62 + entry.final_slug
63 + for entry in map_.by_final_slug.values()
64 + if entry.handle.slug.upper() == upper
65 + )
66 + hint = f" Use one of: {', '.join(final_slugs)}." if final_slugs else ""
67 + raise ValidationError(
68 + f'Ambiguous custom tool slug "{slug}". Multiple custom toolkit tools '
69 + "share this original slug; manual session.execute() by original slug "
70 + "is only supported when the original slug is unique."
71 + f"{hint}"
72 + )
73
74
75 def execute_custom_tool(
python/composio/core/models/custom_tool_types.py
+7
@@ -175,9 +175,16 @@ class CustomToolsMap:
175 """Lookup maps used by ToolRouterSession for routing custom tools."""
176
177 by_final_slug: t.Dict[str, CustomToolsMapEntry] = field(default_factory=dict)
178 + # Bare original slugs are only stored here when they resolve uniquely.
179 by_original_slug: t.Dict[str, CustomToolsMapEntry] = field(default_factory=dict)
180 toolkits: t.Optional[t.List[t.Any]] = None
181 tools: t.Optional[t.List["CustomTool"]] = None
182 + # Toolkit-qualified lookup allows different custom toolkits to reuse a child slug.
183 + by_toolkit_and_original_slug: t.Dict[str, CustomToolsMapEntry] = field(
184 + default_factory=dict
185 + )
186 + # Bare original slugs in this set must be addressed by their final slug.
187 + ambiguous_original_slugs: t.Set[str] = field(default_factory=set)
188
189
190 # ────────────────────────────────────────────────────────────────
python/composio/core/models/session_context.py
+3
@@ -15,6 +15,7 @@ from composio_client.types.tool_router.session_execute_response import (
15 )
16 from composio.client import HttpClient
17 from composio.core.models.custom_tool_execution import (
18 + assert_unambiguous_custom_tool_slug,
19 execute_custom_tool,
20 find_custom_tool,
21 )
@@ -159,6 +160,8 @@ class SessionContextImpl:
160 log_id="",
161 )
162
163 + assert_unambiguous_custom_tool_slug(self._custom_tools_map, tool_slug)
164 +
165 # Serialize any Pydantic model instances before sending to remote API
166 serialized = _serialize_arguments(arguments)
167
python/composio/core/models/tool_router_session.py
+29 -5
@@ -32,8 +32,12 @@ from composio.client import HttpClient
32 from composio.client.types import Tool
33 from composio.core.models._modifiers import Modifiers, apply_modifier_by_type
34 from composio.core.models.connected_accounts import ConnectionRequest
35 -from composio.core.models.custom_tool import find_custom_tool_map_entry_by_final_slug
35 +from composio.core.models.custom_tool import (
36 + find_custom_tool_map_entry_by_final_slug,
37 + find_custom_tool_map_entry_by_toolkit_and_original_slug,
38 +)
39 from composio.core.models.custom_tool_execution import (
40 + assert_unambiguous_custom_tool_slug,
41 execute_custom_tool,
42 find_custom_tool,
43 )
@@ -388,6 +392,7 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
392 t.cast(SessionContextImpl, self._session_context),
393 ),
394 )
395 + assert_unambiguous_custom_tool_slug(self._custom_tools_map, slug)
396 # Non-multi-execute meta tools always go to backend
397 return backend_execute(slug, arguments)
398
@@ -434,6 +439,9 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
439 if entry:
440 local_items.append((i, entry))
441 else:
442 + assert_unambiguous_custom_tool_slug(
443 + self._custom_tools_map, p["tool_slug"]
444 + )
445 remote_indices.append(i)
446
447 # All remote — just forward entire payload (no modifiers — caller handles them)
@@ -706,9 +714,10 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
714 """
715 Execute a tool within the session.
716
709 - For custom tools, accepts the original slug (e.g. "GREP") or the
710 - full slug (e.g. "LOCAL_GREP"). Custom tools are executed in-process;
711 - remote tools are sent to the Composio backend.
717 + For custom tools, accepts the full slug (e.g. "LOCAL_GREP") or the
718 + original slug (e.g. "GREP") when that original slug is unique across
719 + the session's custom tools and toolkits. Custom tools are executed
720 + in-process; remote tools are sent to the Composio backend.
721
722 :param account: Account ID or alias for direct app tool execution in
723 multi-account sessions. Helper/meta tools either ignore this
@@ -731,6 +740,8 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
740 log_id="",
741 )
742
743 + assert_unambiguous_custom_tool_slug(self._custom_tools_map, tool_slug)
744 +
745 return self._client.tool_router.session.execute(
746 session_id=self.session_id,
747 tool_slug=tool_slug,
@@ -784,7 +795,20 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
795 for tk in self._custom_tools_map.toolkits:
796 tools = []
797 for tool in tk.tools:
787 - entry = self._custom_tools_map.by_original_slug.get(tool.slug.upper())
798 + entry = find_custom_tool_map_entry_by_toolkit_and_original_slug(
799 + self._custom_tools_map, tk.slug, tool.slug
800 + )
801 + if entry is None:
802 + # Only trust a bare alias that belongs to this toolkit.
803 + bare = self._custom_tools_map.by_original_slug.get(
804 + tool.slug.upper()
805 + )
806 + if (
807 + bare is not None
808 + and bare.toolkit is not None
809 + and bare.toolkit.lower() == tk.slug.lower()
810 + ):
811 + entry = bare
812 tools.append(
813 RegisteredCustomTool(
814 slug=entry.final_slug if entry else tool.slug,
python/tests/test_custom_tools.py
+353
@@ -28,12 +28,14 @@ from pydantic import BaseModel, Field
28
29 from composio.core.models.custom_tool import (
30 ExperimentalToolkit,
31 + assert_no_custom_tool_slugs_in_preload,
32 build_custom_tools_map,
33 build_custom_tools_map_from_response,
34 serialize_custom_toolkits,
35 serialize_custom_tools,
36 )
37 from composio.core.models.custom_tool_execution import (
38 + assert_unambiguous_custom_tool_slug,
39 execute_custom_tool,
40 find_custom_tool,
41 )
@@ -74,6 +76,21 @@ def grep_tool():
76 return grep
77
78
79 +@pytest.fixture
80 +def duplicate_slug_tools():
81 + @exp.tool(slug="GREP")
82 + def alpha_grep(input: GrepInput, ctx):
83 + """Search Alpha."""
84 + return {"toolkit": "alpha", "matches": [input.pattern]}
85 +
86 + @exp.tool(slug="GREP")
87 + def beta_grep(input: GrepInput, ctx):
88 + """Search Beta."""
89 + return {"toolkit": "beta", "matches": [input.pattern]}
90 +
91 + return alpha_grep, beta_grep
92 +
93 +
94 @pytest.fixture
95 def email_tool():
96 @exp.tool(extends_toolkit="gmail")
@@ -459,10 +476,62 @@ class TestCustomToolsMap:
476 m = build_custom_tools_map([], [role_toolkit])
477 assert "LOCAL_ROLE_MANAGER_SET_ROLE" in m.by_final_slug
478
479 + def test_allows_same_slug_in_different_toolkits(self, duplicate_slug_tools):
480 + alpha_tool, beta_tool = duplicate_slug_tools
481 + alpha = ExperimentalToolkit(
482 + slug="ALPHA", name="Alpha", description="Alpha tools"
483 + )
484 + alpha._tools.append(alpha_tool)
485 + beta = ExperimentalToolkit(slug="BETA", name="Beta", description="Beta tools")
486 + beta._tools.append(beta_tool)
487 +
488 + m = build_custom_tools_map([], [alpha, beta])
489 +
490 + assert set(m.by_final_slug) == {"LOCAL_ALPHA_GREP", "LOCAL_BETA_GREP"}
491 + assert "GREP" not in m.by_original_slug
492 + assert m.ambiguous_original_slugs == {"GREP"}
493 +
494 + def test_ambiguous_original_slug_requires_final_slug(self, duplicate_slug_tools):
495 + alpha_tool, beta_tool = duplicate_slug_tools
496 + alpha = ExperimentalToolkit(
497 + slug="ALPHA", name="Alpha", description="Alpha tools"
498 + )
499 + alpha._tools.append(alpha_tool)
500 + beta = ExperimentalToolkit(slug="BETA", name="Beta", description="Beta tools")
501 + beta._tools.append(beta_tool)
502 + m = build_custom_tools_map([], [alpha, beta])
503 +
504 + assert find_custom_tool(m, "LOCAL_ALPHA_GREP").toolkit == "ALPHA"
505 + assert find_custom_tool(m, "LOCAL_BETA_GREP").toolkit == "BETA"
506 + assert find_custom_tool(m, "GREP") is None
507 + with pytest.raises(ValidationError, match="Ambiguous custom tool slug"):
508 + assert_unambiguous_custom_tool_slug(m, "GREP")
509 +
510 + def test_preload_rejects_ambiguous_original_slug(self, duplicate_slug_tools):
511 + alpha_tool, beta_tool = duplicate_slug_tools
512 + alpha = ExperimentalToolkit(
513 + slug="ALPHA", name="Alpha", description="Alpha tools"
514 + )
515 + alpha._tools.append(alpha_tool)
516 + beta = ExperimentalToolkit(slug="BETA", name="Beta", description="Beta tools")
517 + beta._tools.append(beta_tool)
518 + m = build_custom_tools_map([], [alpha, beta])
519 +
520 + with pytest.raises(ValidationError, match="not supported in preload.tools"):
521 + assert_no_custom_tool_slugs_in_preload(["grep"], m)
522 +
523 def test_collision_detection(self, grep_tool):
524 with pytest.raises(ValidationError, match="collision"):
525 build_custom_tools_map([grep_tool, grep_tool])
526
527 + def test_rejects_standalone_and_toolkit_same_slug(self, duplicate_slug_tools):
528 + alpha_tool, beta_tool = duplicate_slug_tools
529 + beta = ExperimentalToolkit(slug="BETA", name="Beta", description="Beta tools")
530 + beta._tools.append(beta_tool)
531 +
532 + with pytest.raises(ValidationError, match="collision"):
533 + build_custom_tools_map([alpha_tool], [beta])
534 +
535
536 class TestFindCustomTool:
537 def test_find_by_final_slug(self, grep_tool):
@@ -506,6 +575,138 @@ class TestBuildMapFromResponse:
575 assert "LOCAL_GMAIL_GET_EMAILS" in m.by_final_slug
576 assert "LOCAL_ROLE_MANAGER_SET_ROLE" in m.by_final_slug
577
578 + def test_allows_same_slug_in_different_toolkits(self, duplicate_slug_tools):
579 + alpha_tool, beta_tool = duplicate_slug_tools
580 + alpha = ExperimentalToolkit(
581 + slug="ALPHA", name="Alpha", description="Alpha tools"
582 + )
583 + alpha._tools.append(alpha_tool)
584 + beta = ExperimentalToolkit(slug="BETA", name="Beta", description="Beta tools")
585 + beta._tools.append(beta_tool)
586 + mock_exp = MagicMock()
587 + mock_exp.custom_tools = []
588 + mock_exp.custom_toolkits = [
589 + MagicMock(
590 + slug="ALPHA",
591 + tools=[MagicMock(slug="LOCAL_ALPHA_GREP", original_slug="GREP")],
592 + ),
593 + MagicMock(
594 + slug="BETA",
595 + tools=[MagicMock(slug="LOCAL_BETA_GREP", original_slug="GREP")],
596 + ),
597 + ]
598 +
599 + m = build_custom_tools_map_from_response([], [alpha, beta], mock_exp)
600 +
601 + assert set(m.by_final_slug) == {"LOCAL_ALPHA_GREP", "LOCAL_BETA_GREP"}
602 + assert m.by_final_slug["LOCAL_ALPHA_GREP"].toolkit == "ALPHA"
603 + assert m.by_final_slug["LOCAL_BETA_GREP"].toolkit == "BETA"
604 + assert m.ambiguous_original_slugs == {"GREP"}
605 +
606 + def _duplicate_toolkits(self, duplicate_slug_tools):
607 + alpha_tool, beta_tool = duplicate_slug_tools
608 + alpha = ExperimentalToolkit(
609 + slug="ALPHA", name="Alpha", description="Alpha tools"
610 + )
611 + alpha._tools.append(alpha_tool)
612 + beta = ExperimentalToolkit(slug="BETA", name="Beta", description="Beta tools")
613 + beta._tools.append(beta_tool)
614 + return alpha, beta
615 +
616 + def test_rejects_toolkit_child_without_exact_match(self, duplicate_slug_tools):
617 + alpha, beta = self._duplicate_toolkits(duplicate_slug_tools)
618 + mock_exp = MagicMock()
619 + mock_exp.custom_tools = []
620 + mock_exp.custom_toolkits = [
621 + MagicMock(
622 + slug="GAMMA",
623 + tools=[MagicMock(slug="LOCAL_GAMMA_GREP", original_slug="GREP")],
624 + ),
625 + ]
626 +
627 + with pytest.raises(ValidationError, match="no exact local match"):
628 + build_custom_tools_map_from_response([], [alpha, beta], mock_exp)
629 +
630 + def test_never_binds_toolkit_child_to_another_toolkit(self, duplicate_slug_tools):
631 + alpha_tool, _ = duplicate_slug_tools
632 + alpha = ExperimentalToolkit(
633 + slug="ALPHA", name="Alpha", description="Alpha tools"
634 + )
635 + alpha._tools.append(alpha_tool)
636 + mock_exp = MagicMock()
637 + mock_exp.custom_tools = []
638 + mock_exp.custom_toolkits = [
639 + MagicMock(
640 + slug="BETA",
641 + tools=[MagicMock(slug="LOCAL_BETA_GREP", original_slug="GREP")],
642 + ),
643 + ]
644 +
645 + with pytest.raises(ValidationError, match='for toolkit "BETA"'):
646 + build_custom_tools_map_from_response([], [alpha], mock_exp)
647 +
648 + def test_standalone_falls_back_to_unique_bare_match(self, email_tool):
649 + mock_exp = MagicMock()
650 + mock_exp.custom_tools = [
651 + MagicMock(
652 + slug="LOCAL_GMAIL_GET_EMAILS",
653 + original_slug="GET_EMAILS",
654 + extends_toolkit=None,
655 + )
656 + ]
657 + mock_exp.custom_toolkits = []
658 +
659 + m = build_custom_tools_map_from_response([email_tool], None, mock_exp)
660 +
661 + assert m.by_final_slug["LOCAL_GMAIL_GET_EMAILS"].toolkit == "gmail"
662 +
663 + def test_skips_response_tools_not_defined_locally(self, grep_tool):
664 + mock_exp = MagicMock()
665 + mock_exp.custom_tools = [
666 + MagicMock(slug="LOCAL_GREP", original_slug="GREP", extends_toolkit=None),
667 + MagicMock(slug="LOCAL_STALE", original_slug="STALE", extends_toolkit=None),
668 + ]
669 + mock_exp.custom_toolkits = []
670 +
671 + m = build_custom_tools_map_from_response([grep_tool], None, mock_exp)
672 +
673 + assert set(m.by_final_slug) == {"LOCAL_GREP"}
674 +
675 + def test_ambiguity_follows_local_definitions(self, duplicate_slug_tools):
676 + alpha, beta = self._duplicate_toolkits(duplicate_slug_tools)
677 + mock_exp = MagicMock()
678 + mock_exp.custom_tools = []
679 + mock_exp.custom_toolkits = [
680 + MagicMock(
681 + slug="ALPHA",
682 + tools=[MagicMock(slug="LOCAL_ALPHA_GREP", original_slug="GREP")],
683 + ),
684 + ]
685 +
686 + m = build_custom_tools_map_from_response([], [alpha, beta], mock_exp)
687 +
688 + assert set(m.by_final_slug) == {"LOCAL_ALPHA_GREP"}
689 + assert "GREP" not in m.by_original_slug
690 + assert m.ambiguous_original_slugs == {"GREP"}
691 + assert find_custom_tool(m, "GREP") is None
692 +
693 + def test_rejects_duplicate_qualified_response_entries(self, duplicate_slug_tools):
694 + alpha, beta = self._duplicate_toolkits(duplicate_slug_tools)
695 + mock_exp = MagicMock()
696 + mock_exp.custom_tools = []
697 + mock_exp.custom_toolkits = [
698 + MagicMock(
699 + slug="ALPHA",
700 + tools=[
701 + MagicMock(slug="LOCAL_ALPHA_GREP", original_slug="GREP"),
702 + MagicMock(slug="LOCAL_ALPHA_GREP_2", original_slug="GREP"),
703 + ],
704 + ),
705 + ]
706 +
707 + with pytest.raises(ValidationError, match="already registered for toolkit"):
708 + build_custom_tools_map_from_response([], [alpha, beta], mock_exp)
709 +
710
711 # ────────────────────────────────────────────────────────────────
712 # Execution tests
@@ -556,6 +757,27 @@ class TestSessionContextImpl:
757 assert result.log_id == ""
758 assert result.data["matches"] == ["test"]
759
760 + def test_sibling_routing_rejects_ambiguous_slug(self, duplicate_slug_tools):
761 + alpha_tool, beta_tool = duplicate_slug_tools
762 + alpha = ExperimentalToolkit(
763 + slug="ALPHA", name="Alpha", description="Alpha tools"
764 + )
765 + alpha._tools.append(alpha_tool)
766 + beta = ExperimentalToolkit(slug="BETA", name="Beta", description="Beta tools")
767 + beta._tools.append(beta_tool)
768 + m = build_custom_tools_map([], [alpha, beta])
769 + mock_client = MagicMock()
770 + ctx = SessionContextImpl(
771 + client=mock_client, user_id="u", session_id="s", custom_tools_map=m
772 + )
773 +
774 + with pytest.raises(ValidationError, match="Ambiguous custom tool slug"):
775 + ctx.execute("GREP", {"pattern": "x"})
776 + mock_client.tool_router.session.execute.assert_not_called()
777 +
778 + result = ctx.execute("LOCAL_BETA_GREP", {"pattern": "x"})
779 + assert result.data["toolkit"] == "beta"
780 +
781 def test_remote_fallback(self, grep_tool):
782 m = build_custom_tools_map([grep_tool])
783 mock_client = MagicMock()
@@ -838,6 +1060,100 @@ class TestToolRouterSessionCustomTools:
1060 assert len(tks) == 1
1061 assert tks[0].slug == "ROLE_MANAGER"
1062
1063 + def test_custom_toolkits_list_uses_qualified_slugs(self, duplicate_slug_tools):
1064 + alpha_tool, beta_tool = duplicate_slug_tools
1065 + alpha = ExperimentalToolkit(
1066 + slug="ALPHA", name="Alpha", description="Alpha tools"
1067 + )
1068 + alpha._tools.append(alpha_tool)
1069 + beta = ExperimentalToolkit(slug="BETA", name="Beta", description="Beta tools")
1070 + beta._tools.append(beta_tool)
1071 + custom_tools_map = build_custom_tools_map([], [alpha, beta])
1072 + s = ToolRouterSession(
1073 + client=MagicMock(),
1074 + provider=MagicMock(),
1075 + dangerously_allow_auto_upload_download_files=True,
1076 + session_id="s",
1077 + mcp=MagicMock(),
1078 + experimental=MagicMock(),
1079 + custom_tools_map=custom_tools_map,
1080 + user_id="u",
1081 + )
1082 +
1083 + toolkits = s.custom_toolkits()
1084 +
1085 + assert [tk.tools[0].slug for tk in toolkits] == [
1086 + "LOCAL_ALPHA_GREP",
1087 + "LOCAL_BETA_GREP",
1088 + ]
1089 +
1090 + def test_custom_toolkits_list_never_borrows_other_toolkit_slug(
1091 + self, duplicate_slug_tools
1092 + ):
1093 + alpha_tool, beta_tool = duplicate_slug_tools
1094 + alpha = ExperimentalToolkit(
1095 + slug="ALPHA", name="Alpha", description="Alpha tools"
1096 + )
1097 + alpha._tools.append(alpha_tool)
1098 + beta = ExperimentalToolkit(slug="BETA", name="Beta", description="Beta tools")
1099 + beta._tools.append(beta_tool)
1100 + mock_exp = MagicMock()
1101 + mock_exp.custom_tools = []
1102 + mock_exp.custom_toolkits = [
1103 + MagicMock(
1104 + slug="ALPHA",
1105 + tools=[MagicMock(slug="LOCAL_ALPHA_GREP", original_slug="GREP")],
1106 + ),
1107 + ]
1108 + custom_tools_map = build_custom_tools_map_from_response(
1109 + [], [alpha, beta], mock_exp
1110 + )
1111 + s = ToolRouterSession(
1112 + client=MagicMock(),
1113 + provider=MagicMock(),
1114 + dangerously_allow_auto_upload_download_files=True,
1115 + session_id="s",
1116 + mcp=MagicMock(),
1117 + experimental=MagicMock(),
1118 + custom_tools_map=custom_tools_map,
1119 + user_id="u",
1120 + )
1121 +
1122 + assert [tk.tools[0].slug for tk in s.custom_toolkits()] == [
1123 + "LOCAL_ALPHA_GREP",
1124 + "GREP",
1125 + ]
1126 +
1127 + def test_execute_rejects_ambiguous_original_slug(self, duplicate_slug_tools):
1128 + alpha_tool, beta_tool = duplicate_slug_tools
1129 + alpha = ExperimentalToolkit(
1130 + slug="ALPHA", name="Alpha", description="Alpha tools"
1131 + )
1132 + alpha._tools.append(alpha_tool)
1133 + beta = ExperimentalToolkit(slug="BETA", name="Beta", description="Beta tools")
1134 + beta._tools.append(beta_tool)
1135 + custom_tools_map = build_custom_tools_map([], [alpha, beta])
1136 + client = MagicMock()
1137 + s = ToolRouterSession(
1138 + client=client,
1139 + provider=MagicMock(),
1140 + dangerously_allow_auto_upload_download_files=True,
1141 + session_id="s",
1142 + mcp=MagicMock(),
1143 + experimental=MagicMock(),
1144 + custom_tools_map=custom_tools_map,
1145 + user_id="u",
1146 + )
1147 +
1148 + with pytest.raises(ValidationError, match="Ambiguous custom tool slug"):
1149 + s.execute("GREP", arguments={"pattern": "x"})
1150 + client.tool_router.session.execute.assert_not_called()
1151 +
1152 + alpha_result = s.execute("LOCAL_ALPHA_GREP", arguments={"pattern": "x"})
1153 + beta_result = s.execute("LOCAL_BETA_GREP", arguments={"pattern": "x"})
1154 + assert alpha_result.data["toolkit"] == "alpha"
1155 + assert beta_result.data["toolkit"] == "beta"
1156 +
1157 def test_empty_when_no_map(self):
1158 s = ToolRouterSession(
1159 client=MagicMock(),
@@ -879,6 +1195,43 @@ class TestMultiExecuteRouting:
1195 assert result["successful"] is True
1196 assert result["data"]["matches"] == ["x"]
1197
1198 + def test_rejects_ambiguous_original_slug(self, duplicate_slug_tools):
1199 + alpha_tool, beta_tool = duplicate_slug_tools
1200 + alpha = ExperimentalToolkit(
1201 + slug="ALPHA", name="Alpha", description="Alpha tools"
1202 + )
1203 + alpha._tools.append(alpha_tool)
1204 + beta = ExperimentalToolkit(slug="BETA", name="Beta", description="Beta tools")
1205 + beta._tools.append(beta_tool)
1206 + s = ToolRouterSession(
1207 + client=MagicMock(),
1208 + provider=MagicMock(),
1209 + dangerously_allow_auto_upload_download_files=True,
1210 + session_id="s",
1211 + mcp=MagicMock(),
1212 + experimental=MagicMock(),
1213 + custom_tools_map=build_custom_tools_map([], [alpha, beta]),
1214 + user_id="u",
1215 + )
1216 + tm = MagicMock()
1217 + backend = MagicMock()
1218 + tm._wrap_execute_tool_for_tool_router.return_value = backend
1219 +
1220 + with pytest.raises(ValidationError, match="Ambiguous custom tool slug"):
1221 + s._route_multi_execute(
1222 + {
1223 + "tools": [
1224 + {
1225 + "tool_slug": "LOCAL_ALPHA_GREP",
1226 + "arguments": {"pattern": "x"},
1227 + },
1228 + {"tool_slug": "GREP", "arguments": {"pattern": "x"}},
1229 + ]
1230 + },
1231 + tm,
1232 + )
1233 + backend.assert_not_called()
1234 +
1235 def test_all_remote(self, grep_tool):
1236 s = self._make_session(grep_tool)
1237 tm = MagicMock()
ts/packages/core/src/models/CustomTool.ts
+41 -6
@@ -514,7 +514,11 @@ export function buildCustomToolsMapFromResponse(
514 }
515 }
516
517 - const findHandle = (originalSlug: string, toolkit?: string): HandleMatch | undefined => {
517 + const findHandle = (
518 + finalSlug: string,
519 + originalSlug: string,
520 + toolkit?: string
521 + ): HandleMatch | undefined => {
522 const originalSlugKey = originalSlug.toUpperCase();
523 const qualifiedMatch = handlesByQualifiedOriginalSlug.get(
524 qualifiedOriginalSlugKey(toolkit, originalSlugKey)
@@ -522,13 +526,26 @@ export function buildCustomToolsMapFromResponse(
526 if (qualifiedMatch) return qualifiedMatch;
527
528 const bareMatches = handlesByOriginalSlug.get(originalSlugKey) ?? [];
525 - return bareMatches.length === 1 ? bareMatches[0] : undefined;
529 + // Response tool not defined locally; nothing to route in-process.
530 + if (bareMatches.length === 0) return undefined;
531 + // A bare match may only stand in when the response carries no toolkit identity.
532 + // Binding a toolkit child to another toolkit's handler would silently execute
533 + // the wrong implementation.
534 + if (toolkit === undefined && bareMatches.length === 1) return bareMatches[0];
535 +
536 + const registered = [
537 + ...new Set(bareMatches.map(m => (m.toolkit ?? 'custom').toUpperCase())),
538 + ].sort();
539 + throw new ValidationError(
540 + `Cannot map custom tool "${finalSlug}": original slug "${originalSlug}" for toolkit ` +
541 + `"${toolkit ?? 'custom'}" has no exact local match. Registered for toolkits: ${registered.join(', ')}.`
542 + );
543 };
544
545 const addEntry = (finalSlug: string, originalSlug: string, toolkit?: string | null) => {
546 const resolvedToolkit = toolkit ?? undefined;
530 - const match = findHandle(originalSlug, resolvedToolkit);
531 - if (!match) return; // Response tool not found in our handles (shouldn't happen)
547 + const match = findHandle(finalSlug, originalSlug, resolvedToolkit);
548 + if (!match) return;
549
550 const finalSlugKey = finalSlug.toUpperCase();
551 if (byFinalSlug.has(finalSlugKey)) {
@@ -537,13 +554,21 @@ export function buildCustomToolsMapFromResponse(
554 );
555 }
556
557 + const entryToolkit = resolvedToolkit ?? match.toolkit;
558 + const qualifiedKey = qualifiedOriginalSlugKey(entryToolkit, originalSlug);
559 + if (byToolkitAndOriginalSlug.has(qualifiedKey)) {
560 + throw new ValidationError(
561 + `Custom tool slug collision: original slug "${match.handle.slug}" is already registered for toolkit "${entryToolkit ?? 'custom'}".`
562 + );
563 + }
564 +
565 const entry: CustomToolsMapEntry = {
566 handle: match.handle,
567 finalSlug,
543 - toolkit: resolvedToolkit ?? match.toolkit,
568 + toolkit: entryToolkit,
569 };
570 byFinalSlug.set(finalSlugKey, entry);
546 - byToolkitAndOriginalSlug.set(qualifiedOriginalSlugKey(entry.toolkit, originalSlug), entry);
571 + byToolkitAndOriginalSlug.set(qualifiedKey, entry);
572 addOriginalSlugAlias({ byOriginalSlug, ambiguousOriginalSlugs, originalSlug, entry });
573 };
574
@@ -563,6 +588,16 @@ export function buildCustomToolsMapFromResponse(
588 }
589 }
590
591 + // Ambiguity follows the local definitions, not whichever subset the response
592 + // happened to include: a shared child slug must never become callable by its
593 + // bare name just because a sibling was omitted.
594 + for (const [originalSlugKey, matches] of handlesByOriginalSlug) {
595 + if (matches.length > 1) {
596 + byOriginalSlug.delete(originalSlugKey);
597 + ambiguousOriginalSlugs.add(originalSlugKey);
598 + }
599 + }
600 +
601 return {
602 byFinalSlug,
603 byOriginalSlug,
ts/packages/core/src/models/ToolRouterSession.ts
+9 -4
@@ -375,9 +375,13 @@ export class ToolRouterSession<
375 tools: tk.tools.map(tool => {
376 // Look up by toolkit + original slug so toolkits can safely reuse common names
377 // like VERSION, CLICK, or SEARCH without losing the backend-assigned final slug.
378 + // Only trust a bare alias that belongs to this toolkit.
379 + const bare = this.customToolsMap!.byOriginalSlug.get(tool.slug.toUpperCase());
380 const entry =
381 findCustomToolMapEntryByToolkitAndOriginalSlug(this.customToolsMap, tk.slug, tool.slug) ??
380 - this.customToolsMap!.byOriginalSlug.get(tool.slug.toUpperCase());
382 + (bare?.toolkit && bare.toolkit.toLowerCase() === tk.slug.toLowerCase()
383 + ? bare
384 + : undefined);
385 return {
386 slug: entry?.finalSlug ?? tool.slug,
387 name: tool.name,
@@ -555,9 +559,10 @@ export class ToolRouterSession<
559 /**
560 * Execute a tool within the session.
561 *
558 - * For custom tools, accepts the original slug (e.g. "GREP") or the
559 - * full slug (e.g. "LOCAL_GREP"). Custom tools are executed in-process;
560 - * remote tools are sent to the Composio backend.
562 + * For custom tools, accepts the full slug (e.g. "LOCAL_GREP") or the
563 + * original slug (e.g. "GREP") when that original slug is unique across
564 + * the session's custom tools and toolkits. Custom tools are executed
565 + * in-process; remote tools are sent to the Composio backend.
566 *
567 * @param toolSlug - The tool slug to execute
568 * @param arguments_ - Optional tool arguments
ts/packages/core/test/models/customTool.test.ts
+166
@@ -6,6 +6,7 @@ import {
6 createCustomTool,
7 createCustomToolkit,
8 buildCustomToolsMap,
9 + buildCustomToolsMapFromResponse,
10 serializeCustomTools,
11 serializeCustomToolkits,
12 LOCAL_TOOL_PREFIX,
@@ -451,6 +452,27 @@ describe('buildCustomToolsMap', () => {
452
453 expect(() => buildCustomToolsMap([standalone], [tk])).toThrow('collision');
454 });
455 +
456 + it('should allow the same original slug in different toolkits and mark it ambiguous', () => {
457 + const alpha: CustomToolkit = {
458 + slug: 'ALPHA',
459 + name: 'Alpha',
460 + description: 'Alpha tools',
461 + tools: [makeTool('GREP')],
462 + };
463 + const beta: CustomToolkit = {
464 + slug: 'BETA',
465 + name: 'Beta',
466 + description: 'Beta tools',
467 + tools: [makeTool('GREP')],
468 + };
469 +
470 + const map = buildCustomToolsMap([], [alpha, beta]);
471 +
472 + expect([...map.byFinalSlug.keys()].sort()).toEqual(['LOCAL_ALPHA_GREP', 'LOCAL_BETA_GREP']);
473 + expect(map.byOriginalSlug.has('GREP')).toBe(false);
474 + expect(map.ambiguousOriginalSlugs).toEqual(new Set(['GREP']));
475 + });
476 });
477
478 describe('length validation', () => {
@@ -505,6 +527,150 @@ describe('buildCustomToolsMap', () => {
527 });
528 });
529
530 +// ────────────────────────────────────────────────────────────────
531 +// buildCustomToolsMapFromResponse()
532 +// ────────────────────────────────────────────────────────────────
533 +
534 +describe('buildCustomToolsMapFromResponse', () => {
535 + const makeTool = (slug: string, extendsToolkit?: string): CustomTool => ({
536 + slug,
537 + name: `Tool ${slug}`,
538 + description: `Description for ${slug}`,
539 + extendsToolkit,
540 + inputSchema: { type: 'object', properties: {} },
541 + inputParams: z.object({}),
542 + execute: vi.fn(),
543 + });
544 + const makeToolkit = (slug: string, tools: CustomTool[]): CustomToolkit => ({
545 + slug,
546 + name: slug,
547 + description: `${slug} tools`,
548 + tools,
549 + });
550 + type ResponseExperimental = Parameters<typeof buildCustomToolsMapFromResponse>[2];
551 + const response = (value: {
552 + custom_tools: Array<{ slug: string; original_slug: string; extends_toolkit?: string }>;
553 + custom_toolkits: Array<{ slug: string; tools: Array<{ slug: string; original_slug: string }> }>;
554 + }): ResponseExperimental => value as unknown as ResponseExperimental;
555 + const alpha = makeToolkit('ALPHA', [makeTool('GREP')]);
556 + const beta = makeToolkit('BETA', [makeTool('GREP')]);
557 +
558 + it('maps shared child slugs by toolkit and keeps the bare slug ambiguous', () => {
559 + const map = buildCustomToolsMapFromResponse(
560 + [],
561 + [alpha, beta],
562 + response({
563 + custom_tools: [],
564 + custom_toolkits: [
565 + { slug: 'ALPHA', tools: [{ slug: 'LOCAL_ALPHA_GREP', original_slug: 'GREP' }] },
566 + { slug: 'BETA', tools: [{ slug: 'LOCAL_BETA_GREP', original_slug: 'GREP' }] },
567 + ],
568 + })
569 + );
570 +
571 + expect(map.byFinalSlug.get('LOCAL_ALPHA_GREP')?.toolkit).toBe('ALPHA');
572 + expect(map.byFinalSlug.get('LOCAL_BETA_GREP')?.toolkit).toBe('BETA');
573 + expect(map.ambiguousOriginalSlugs).toEqual(new Set(['GREP']));
574 + });
575 +
576 + it('rejects a toolkit child without an exact local match', () => {
577 + expect(() =>
578 + buildCustomToolsMapFromResponse(
579 + [],
580 + [alpha, beta],
581 + response({
582 + custom_tools: [],
583 + custom_toolkits: [
584 + { slug: 'GAMMA', tools: [{ slug: 'LOCAL_GAMMA_GREP', original_slug: 'GREP' }] },
585 + ],
586 + })
587 + )
588 + ).toThrow('no exact local match');
589 + });
590 +
591 + it('never binds a toolkit child to another toolkit handler', () => {
592 + expect(() =>
593 + buildCustomToolsMapFromResponse(
594 + [],
595 + [alpha],
596 + response({
597 + custom_tools: [],
598 + custom_toolkits: [
599 + { slug: 'BETA', tools: [{ slug: 'LOCAL_BETA_GREP', original_slug: 'GREP' }] },
600 + ],
601 + })
602 + )
603 + ).toThrow('for toolkit "BETA"');
604 + });
605 +
606 + it('falls back to a unique bare match for standalone tools without toolkit identity', () => {
607 + const map = buildCustomToolsMapFromResponse(
608 + [makeTool('GET_EMAILS', 'gmail')],
609 + undefined,
610 + response({
611 + custom_tools: [{ slug: 'LOCAL_GMAIL_GET_EMAILS', original_slug: 'GET_EMAILS' }],
612 + custom_toolkits: [],
613 + })
614 + );
615 +
616 + expect(map.byFinalSlug.get('LOCAL_GMAIL_GET_EMAILS')?.toolkit).toBe('gmail');
617 + });
618 +
619 + it('skips response tools that are not defined locally', () => {
620 + const map = buildCustomToolsMapFromResponse(
621 + [makeTool('GREP')],
622 + undefined,
623 + response({
624 + custom_tools: [
625 + { slug: 'LOCAL_GREP', original_slug: 'GREP' },
626 + { slug: 'LOCAL_STALE', original_slug: 'STALE' },
627 + ],
628 + custom_toolkits: [],
629 + })
630 + );
631 +
632 + expect([...map.byFinalSlug.keys()]).toEqual(['LOCAL_GREP']);
633 + });
634 +
635 + it('derives ambiguity from local definitions when the response omits a sibling', () => {
636 + const map = buildCustomToolsMapFromResponse(
637 + [],
638 + [alpha, beta],
639 + response({
640 + custom_tools: [],
641 + custom_toolkits: [
642 + { slug: 'ALPHA', tools: [{ slug: 'LOCAL_ALPHA_GREP', original_slug: 'GREP' }] },
643 + ],
644 + })
645 + );
646 +
647 + expect([...map.byFinalSlug.keys()]).toEqual(['LOCAL_ALPHA_GREP']);
648 + expect(map.byOriginalSlug.has('GREP')).toBe(false);
649 + expect(map.ambiguousOriginalSlugs).toEqual(new Set(['GREP']));
650 + });
651 +
652 + it('rejects duplicate qualified response entries', () => {
653 + expect(() =>
654 + buildCustomToolsMapFromResponse(
655 + [],
656 + [alpha, beta],
657 + response({
658 + custom_tools: [],
659 + custom_toolkits: [
660 + {
661 + slug: 'ALPHA',
662 + tools: [
663 + { slug: 'LOCAL_ALPHA_GREP', original_slug: 'GREP' },
664 + { slug: 'LOCAL_ALPHA_GREP_2', original_slug: 'GREP' },
665 + ],
666 + },
667 + ],
668 + })
669 + )
670 + ).toThrow('already registered for toolkit');
671 + });
672 +});
673 +
674 // ────────────────────────────────────────────────────────────────
675 // serializeCustomTools()
676 // ────────────────────────────────────────────────────────────────