Skip to content

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

fix(python): address codex review findings for custom tools

Dhawal Upadhyay353d000746c2
diff --git a/python/composio/core/models/custom_tool.py b/python/composio/core/models/custom_tool.py
index 7cb3cee62..256667125 100644
--- a/python/composio/core/models/custom_tool.py
+++ b/python/composio/core/models/custom_tool.py
@@ -206,12 +206,27 @@ def experimental_create_tool(
raise ValidationError(f"{context}: description is required")
# Validate input_params is a Pydantic BaseModel subclass (not an instance)
+ # and produces an object-shaped JSON Schema (rejects RootModel[list[...]] etc.)
if not isinstance(input_params, type) or not issubclass(input_params, BaseModel):
raise ValidationError(
f"{context}: input_params must be a Pydantic BaseModel subclass. "
f"Tool input parameters are always an object with named properties."
)
+ # Reject RootModel and other non-object schemas — tool router only passes
+ # named argument objects, so the schema must have named properties.
+ try:
+ from pydantic import RootModel
+
+ if issubclass(input_params, RootModel):
+ raise ValidationError(
+ f"{context}: input_params must be a regular BaseModel with named fields, "
+ f"not a RootModel. Tool input parameters are always an object with "
+ f"named properties."
+ )
+ except ImportError:
+ pass # RootModel not available in older Pydantic
+
# Validate execute is callable
if not callable(execute):
raise ValidationError(f"{context}: execute must be a callable")
@@ -442,15 +457,28 @@ def build_custom_tools_map_from_response(
by_original_slug: t.Dict[str, CustomToolsMapEntry] = {}
# Build lookup from original slug → handle + toolkit
+ # Detect duplicate original slugs across standalone tools and toolkit tools
handles_by_original: t.Dict[
str, t.Tuple[CustomTool, t.Optional[str]]
] = {}
for handle in tools:
- handles_by_original[handle.slug.upper()] = (handle, handle.extends_toolkit)
+ key = handle.slug.upper()
+ if key in handles_by_original:
+ raise ValidationError(
+ f'Duplicate custom tool slug "{handle.slug}" — '
+ f"each tool must have a unique slug across all custom tools and toolkits."
+ )
+ handles_by_original[key] = (handle, handle.extends_toolkit)
if toolkits:
for tk in toolkits:
for handle in tk.tools:
- handles_by_original[handle.slug.upper()] = (handle, tk.slug)
+ key = handle.slug.upper()
+ if key in handles_by_original:
+ raise ValidationError(
+ f'Duplicate custom tool slug "{handle.slug}" — '
+ f"each tool must have a unique slug across all custom tools and toolkits."
+ )
+ handles_by_original[key] = (handle, tk.slug)
def add_entry(
final_slug: str, original_slug: str, toolkit: t.Optional[str]
diff --git a/python/composio/core/models/tool_router_session.py b/python/composio/core/models/tool_router_session.py
index 358744cfe..6e295e8f9 100644
--- a/python/composio/core/models/tool_router_session.py
+++ b/python/composio/core/models/tool_router_session.py
@@ -307,10 +307,26 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
else:
merged.append(next(remote_iter, {}))
+ # Detect failures across local and remote results
+ failed_count = sum(
+ 1
+ for entry in merged
+ if isinstance(entry, dict)
+ and isinstance(entry.get("response"), dict)
+ and not entry["response"].get("successful", True)
+ )
+ has_any_error = failed_count > 0 or (
+ remote_result is not None and not remote_result.get("successful", True)
+ )
+
return {
"data": {"results": merged},
- "error": None,
- "successful": True,
+ "error": (
+ f"{failed_count} out of {len(merged)} tools failed"
+ if has_any_error
+ else None
+ ),
+ "successful": not has_any_error,
}
def authorize(
@@ -453,9 +469,15 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
# Check if this is a local tool (by original or final slug)
entry = find_custom_tool(self._custom_tools_map, tool_slug)
if entry and self._session_context:
- return execute_custom_tool(
+ result = execute_custom_tool(
entry, arguments or {}, self._session_context
)
+ # Normalize to match SessionExecuteResponse shape (data, error, log_id)
+ return {
+ "data": result["data"],
+ "error": result["error"],
+ "log_id": "",
+ }
# Remote execution
return self._client.tool_router.session.execute(
diff --git a/python/tests/test_custom_tools.py b/python/tests/test_custom_tools.py
index d683bb30f..666cf9d91 100644
--- a/python/tests/test_custom_tools.py
+++ b/python/tests/test_custom_tools.py
@@ -263,6 +263,21 @@ class TestCreateCustomTool:
assert tool.output_schema is not None
assert "properties" in tool.output_schema
+ def test_rejects_root_model(self):
+ from pydantic import RootModel
+
+ class ListInput(RootModel[list[int]]):
+ pass
+
+ with pytest.raises(ValidationError, match="RootModel"):
+ experimental_create_tool(
+ "BAD",
+ name="Bad",
+ description="Desc",
+ input_params=ListInput,
+ execute=lambda i, c: {},
+ )
+
def test_input_schema_includes_defaults(self, grep_tool):
# path has default="." - Pydantic won't include it in required
assert "pattern" in grep_tool.input_schema.get("required", [])
@@ -648,8 +663,10 @@ class TestToolRouterSessionCustomTools:
user_id="user-1",
)
result = session.execute("GREP", arguments={"pattern": "test"})
- assert result["successful"] is True
+ # session.execute returns SessionExecuteResponse shape: data, error, log_id
assert result["data"]["matches"] == ["test"]
+ assert result["error"] is None
+ assert result["log_id"] == ""
# Should NOT have called the backend
mock_session_deps["client"].tool_router.session.execute.assert_not_called()
@@ -665,7 +682,7 @@ class TestToolRouterSessionCustomTools:
user_id="user-1",
)
result = session.execute("LOCAL_GREP", arguments={"pattern": "test"})
- assert result["successful"] is True
+ assert result["error"] is None
def test_execute_case_insensitive(self, mock_session_deps):
session = ToolRouterSession(
@@ -679,7 +696,7 @@ class TestToolRouterSessionCustomTools:
user_id="user-1",
)
result = session.execute("grep", arguments={"pattern": "test"})
- assert result["successful"] is True
+ assert result["error"] is None
def test_execute_routes_to_remote(self, mock_session_deps):
mock_response = MagicMock()
@@ -944,3 +961,47 @@ class TestMultiExecuteRouting:
assert len(results) == 2
assert results[0]["response"]["data"]["tool"] == "A"
assert results[1]["response"]["data"]["tool"] == "B"
+
+ def test_route_propagates_local_failure(self):
+ ok_tool = experimental_create_tool(
+ "OK",
+ name="OK",
+ description="D",
+ input_params=GrepInput,
+ execute=lambda i, c: {"ok": True},
+ )
+ bad_tool = experimental_create_tool(
+ "BAD",
+ name="Bad",
+ description="D",
+ input_params=GrepInput,
+ execute=lambda i, c: (_ for _ in ()).throw(RuntimeError("boom")),
+ )
+ m = build_custom_tools_map([ok_tool, bad_tool])
+ session = ToolRouterSession(
+ client=MagicMock(),
+ provider=MagicMock(),
+ auto_upload_download_files=True,
+ session_id="sess-1",
+ mcp=MagicMock(),
+ experimental=MagicMock(),
+ custom_tools_map=m,
+ user_id="user-1",
+ )
+ result = session._route_multi_execute(
+ {
+ "tools": [
+ {"tool_slug": "OK", "arguments": {"pattern": "x"}},
+ {"tool_slug": "BAD", "arguments": {"pattern": "y"}},
+ ]
+ },
+ MagicMock(),
+ None,
+ )
+ # Overall result should report failure
+ assert result["successful"] is False
+ assert "1 out of 2" in result["error"]
+ # Individual results preserved
+ results = result["data"]["results"]
+ assert results[0]["response"]["successful"] is True
+ assert results[1]["response"]["successful"] is False