@devries-cameron20 / composio Mirror · read-only / commits / 353d00074
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

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

- P1: Propagate failure status in multi-execute — merged results now report successful=False and error count when any sub-tool fails - P2: Normalize session.execute() return shape for local tools to match SessionExecuteResponse (data/error/log_id) instead of ToolExecutionResponse - P2: Detect duplicate original slugs in build_custom_tools_map_from_response instead of silently overwriting - P3: Reject RootModel input_params — tool router only passes named argument objects, so non-object schemas are rejected at creation time Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

Dhawal Upadhyay committed Mar 20, 2026 at 13:19 UTC 353d000746c2b81e72186bf87e4b1f9b7ca4e293
3 files changed +119 -8
python/composio/core/models/custom_tool.py
+30 -2
@@ -206,12 +206,27 @@ def experimental_create_tool(
206 raise ValidationError(f"{context}: description is required")
207
208 # Validate input_params is a Pydantic BaseModel subclass (not an instance)
209 + # and produces an object-shaped JSON Schema (rejects RootModel[list[...]] etc.)
210 if not isinstance(input_params, type) or not issubclass(input_params, BaseModel):
211 raise ValidationError(
212 f"{context}: input_params must be a Pydantic BaseModel subclass. "
213 f"Tool input parameters are always an object with named properties."
214 )
215
216 + # Reject RootModel and other non-object schemas — tool router only passes
217 + # named argument objects, so the schema must have named properties.
218 + try:
219 + from pydantic import RootModel
220 +
221 + if issubclass(input_params, RootModel):
222 + raise ValidationError(
223 + f"{context}: input_params must be a regular BaseModel with named fields, "
224 + f"not a RootModel. Tool input parameters are always an object with "
225 + f"named properties."
226 + )
227 + except ImportError:
228 + pass # RootModel not available in older Pydantic
229 +
230 # Validate execute is callable
231 if not callable(execute):
232 raise ValidationError(f"{context}: execute must be a callable")
@@ -442,15 +457,28 @@ def build_custom_tools_map_from_response(
457 by_original_slug: t.Dict[str, CustomToolsMapEntry] = {}
458
459 # Build lookup from original slug → handle + toolkit
460 + # Detect duplicate original slugs across standalone tools and toolkit tools
461 handles_by_original: t.Dict[
462 str, t.Tuple[CustomTool, t.Optional[str]]
463 ] = {}
464 for handle in tools:
449 - handles_by_original[handle.slug.upper()] = (handle, handle.extends_toolkit)
465 + key = handle.slug.upper()
466 + if key in handles_by_original:
467 + raise ValidationError(
468 + f'Duplicate custom tool slug "{handle.slug}" — '
469 + f"each tool must have a unique slug across all custom tools and toolkits."
470 + )
471 + handles_by_original[key] = (handle, handle.extends_toolkit)
472 if toolkits:
473 for tk in toolkits:
474 for handle in tk.tools:
453 - handles_by_original[handle.slug.upper()] = (handle, tk.slug)
475 + key = handle.slug.upper()
476 + if key in handles_by_original:
477 + raise ValidationError(
478 + f'Duplicate custom tool slug "{handle.slug}" — '
479 + f"each tool must have a unique slug across all custom tools and toolkits."
480 + )
481 + handles_by_original[key] = (handle, tk.slug)
482
483 def add_entry(
484 final_slug: str, original_slug: str, toolkit: t.Optional[str]
python/composio/core/models/tool_router_session.py
+25 -3
@@ -307,10 +307,26 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
307 else:
308 merged.append(next(remote_iter, {}))
309
310 + # Detect failures across local and remote results
311 + failed_count = sum(
312 + 1
313 + for entry in merged
314 + if isinstance(entry, dict)
315 + and isinstance(entry.get("response"), dict)
316 + and not entry["response"].get("successful", True)
317 + )
318 + has_any_error = failed_count > 0 or (
319 + remote_result is not None and not remote_result.get("successful", True)
320 + )
321 +
322 return {
323 "data": {"results": merged},
312 - "error": None,
313 - "successful": True,
324 + "error": (
325 + f"{failed_count} out of {len(merged)} tools failed"
326 + if has_any_error
327 + else None
328 + ),
329 + "successful": not has_any_error,
330 }
331
332 def authorize(
@@ -453,9 +469,15 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
469 # Check if this is a local tool (by original or final slug)
470 entry = find_custom_tool(self._custom_tools_map, tool_slug)
471 if entry and self._session_context:
456 - return execute_custom_tool(
472 + result = execute_custom_tool(
473 entry, arguments or {}, self._session_context
474 )
475 + # Normalize to match SessionExecuteResponse shape (data, error, log_id)
476 + return {
477 + "data": result["data"],
478 + "error": result["error"],
479 + "log_id": "",
480 + }
481
482 # Remote execution
483 return self._client.tool_router.session.execute(
python/tests/test_custom_tools.py
+64 -3
@@ -263,6 +263,21 @@ class TestCreateCustomTool:
263 assert tool.output_schema is not None
264 assert "properties" in tool.output_schema
265
266 + def test_rejects_root_model(self):
267 + from pydantic import RootModel
268 +
269 + class ListInput(RootModel[list[int]]):
270 + pass
271 +
272 + with pytest.raises(ValidationError, match="RootModel"):
273 + experimental_create_tool(
274 + "BAD",
275 + name="Bad",
276 + description="Desc",
277 + input_params=ListInput,
278 + execute=lambda i, c: {},
279 + )
280 +
281 def test_input_schema_includes_defaults(self, grep_tool):
282 # path has default="." - Pydantic won't include it in required
283 assert "pattern" in grep_tool.input_schema.get("required", [])
@@ -648,8 +663,10 @@ class TestToolRouterSessionCustomTools:
663 user_id="user-1",
664 )
665 result = session.execute("GREP", arguments={"pattern": "test"})
651 - assert result["successful"] is True
666 + # session.execute returns SessionExecuteResponse shape: data, error, log_id
667 assert result["data"]["matches"] == ["test"]
668 + assert result["error"] is None
669 + assert result["log_id"] == ""
670 # Should NOT have called the backend
671 mock_session_deps["client"].tool_router.session.execute.assert_not_called()
672
@@ -665,7 +682,7 @@ class TestToolRouterSessionCustomTools:
682 user_id="user-1",
683 )
684 result = session.execute("LOCAL_GREP", arguments={"pattern": "test"})
668 - assert result["successful"] is True
685 + assert result["error"] is None
686
687 def test_execute_case_insensitive(self, mock_session_deps):
688 session = ToolRouterSession(
@@ -679,7 +696,7 @@ class TestToolRouterSessionCustomTools:
696 user_id="user-1",
697 )
698 result = session.execute("grep", arguments={"pattern": "test"})
682 - assert result["successful"] is True
699 + assert result["error"] is None
700
701 def test_execute_routes_to_remote(self, mock_session_deps):
702 mock_response = MagicMock()
@@ -944,3 +961,47 @@ class TestMultiExecuteRouting:
961 assert len(results) == 2
962 assert results[0]["response"]["data"]["tool"] == "A"
963 assert results[1]["response"]["data"]["tool"] == "B"
964 +
965 + def test_route_propagates_local_failure(self):
966 + ok_tool = experimental_create_tool(
967 + "OK",
968 + name="OK",
969 + description="D",
970 + input_params=GrepInput,
971 + execute=lambda i, c: {"ok": True},
972 + )
973 + bad_tool = experimental_create_tool(
974 + "BAD",
975 + name="Bad",
976 + description="D",
977 + input_params=GrepInput,
978 + execute=lambda i, c: (_ for _ in ()).throw(RuntimeError("boom")),
979 + )
980 + m = build_custom_tools_map([ok_tool, bad_tool])
981 + session = ToolRouterSession(
982 + client=MagicMock(),
983 + provider=MagicMock(),
984 + auto_upload_download_files=True,
985 + session_id="sess-1",
986 + mcp=MagicMock(),
987 + experimental=MagicMock(),
988 + custom_tools_map=m,
989 + user_id="user-1",
990 + )
991 + result = session._route_multi_execute(
992 + {
993 + "tools": [
994 + {"tool_slug": "OK", "arguments": {"pattern": "x"}},
995 + {"tool_slug": "BAD", "arguments": {"pattern": "y"}},
996 + ]
997 + },
998 + MagicMock(),
999 + None,
1000 + )
1001 + # Overall result should report failure
1002 + assert result["successful"] is False
1003 + assert "1 out of 2" in result["error"]
1004 + # Individual results preserved
1005 + results = result["data"]["results"]
1006 + assert results[0]["response"]["successful"] is True
1007 + assert results[1]["response"]["successful"] is False