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 code review findings

Dhawal Upadhyaye1a045bc547c
diff --git a/python/composio/core/models/custom_tool.py b/python/composio/core/models/custom_tool.py
index 46980249f..d1cc41b69 100644
--- a/python/composio/core/models/custom_tool.py
+++ b/python/composio/core/models/custom_tool.py
@@ -248,28 +248,42 @@ def _infer_tool_from_function(
f'Add a docstring to "{fn.__name__}" or pass description=...'
)
- # Infer input_params from type annotation
+ # Validate and infer function signature.
+ # Accepted shapes (consistent with TS CustomToolExecuteFn):
+ # (input: BaseModel) — no session context needed
+ # (input: BaseModel, ctx) — with session context
+ # The first param MUST be annotated with a BaseModel subclass.
sig = inspect.signature(fn)
params = list(sig.parameters.values())
- input_params: t.Optional[t.Type[BaseModel]] = None
- for p in params:
- if p.annotation is not inspect.Parameter.empty:
- ann = p.annotation
- if isinstance(ann, type) and issubclass(ann, BaseModel):
- input_params = ann
- break
-
- if input_params is None:
+
+ if not params:
raise ValidationError(
- f'experimental.tool: could not infer input parameters for "{fn.__name__}". '
- f"Annotate a parameter with a Pydantic BaseModel subclass, e.g. "
+ f'experimental.tool: "{fn.__name__}" must accept at least one parameter '
+ f"annotated with a Pydantic BaseModel subclass, e.g. "
f"def {fn.__name__}(input: MyInput, ctx): ..."
)
+ if len(params) > 2:
+ raise ValidationError(
+ f'experimental.tool: "{fn.__name__}" accepts {len(params)} parameters, '
+ f"but custom tools accept at most 2: (input: BaseModel, ctx). "
+ f"Extra parameters will not be populated at runtime."
+ )
+
+ # First param must be the input model
+ first = params[0]
+ if first.annotation is inspect.Parameter.empty or not (
+ isinstance(first.annotation, type) and issubclass(first.annotation, BaseModel)
+ ):
+ raise ValidationError(
+ f'experimental.tool: first parameter of "{fn.__name__}" must be annotated '
+ f"with a Pydantic BaseModel subclass. Got: {first.annotation!r}. "
+ f"Expected: def {fn.__name__}(input: MyInput, ctx): ..."
+ )
+ input_params: t.Type[BaseModel] = first.annotation
+
# Wrap function to match CustomToolExecuteFn: (input, ctx) -> dict
- # Support both (input) and (input, ctx) signatures
- num_params = len(params)
- if num_params <= 1:
+ if len(params) == 1:
def execute(input: t.Any, ctx: t.Any) -> t.Dict[str, t.Any]:
return fn(input)
diff --git a/python/composio/core/models/session_context.py b/python/composio/core/models/session_context.py
index 7abfbf466..9833c8579 100644
--- a/python/composio/core/models/session_context.py
+++ b/python/composio/core/models/session_context.py
@@ -22,6 +22,10 @@ from composio.core.models.custom_tool_types import (
from composio.core.models.tools import ToolExecutionResponse
+_VALID_METHODS = frozenset({"GET", "POST", "PUT", "DELETE", "PATCH"})
+_VALID_PARAM_TYPES = frozenset({"header", "query"})
+
+
def proxy_execute_impl(
client: HttpClient,
session_id: str,
@@ -33,16 +37,38 @@ def proxy_execute_impl(
parameters: t.Optional[t.List[t.Dict[str, t.Any]]] = None,
) -> ProxyExecuteResponse:
"""Shared proxy execute implementation used by SessionContextImpl and ToolRouterSession."""
- # Transform parameters to API format using the composio_client Parameter type
+ from composio.exceptions import ValidationError
+
+ # Client-side validation (matches TS SessionProxyExecuteParamsSchema)
+ if not toolkit:
+ raise ValidationError("proxy_execute: toolkit is required")
+ if not endpoint:
+ raise ValidationError("proxy_execute: endpoint is required")
+ if method not in _VALID_METHODS:
+ raise ValidationError(
+ f"proxy_execute: method must be one of {sorted(_VALID_METHODS)}, got {method!r}"
+ )
+
+ # Transform and validate parameters
from composio_client.types.tool_router.session_proxy_execute_params import Parameter
api_params: t.List[Parameter] = []
if parameters:
- for p in parameters:
+ for i, p in enumerate(parameters):
+ if not isinstance(p, dict) or "name" not in p or "value" not in p:
+ raise ValidationError(
+ f"proxy_execute: parameters[{i}] must be a dict with 'name' and 'value' keys"
+ )
+ param_type = p.get("in", p.get("type", "header"))
+ if param_type not in _VALID_PARAM_TYPES:
+ raise ValidationError(
+ f"proxy_execute: parameters[{i}].type must be 'header' or 'query', "
+ f"got {param_type!r}"
+ )
api_params.append(
Parameter(
name=p["name"],
- type=p.get("in", p.get("type", "header")), # type: ignore[typeddict-item]
+ type=param_type, # type: ignore[typeddict-item]
value=str(p["value"]),
)
)
diff --git a/python/composio/core/models/tool_router_session.py b/python/composio/core/models/tool_router_session.py
index 74cc8d0ef..6ccadc8da 100644
--- a/python/composio/core/models/tool_router_session.py
+++ b/python/composio/core/models/tool_router_session.py
@@ -230,6 +230,10 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
Splits the tools[] array into local and remote, executes each
appropriately, and merges results preserving original order.
+ Note: Results are merged in the original request order (index-based).
+ This intentionally differs from TS which appends locals after remotes —
+ preserving order is more predictable for callers.
+
Note: modifiers are NOT applied here — the caller (routing_execute)
handles before_execute/after_execute to avoid double application.
"""
@@ -510,25 +514,31 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
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.
+
+ Returns a dict with ``data``, ``error``, and ``log_id`` keys for both
+ local and remote execution paths.
"""
# 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:
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 the SessionExecuteResponse model as-is
- # to preserve backward compatibility for callers using attribute access
- return self._client.tool_router.session.execute(
+ # Remote execution — normalize to dict for consistent return type
+ response = self._client.tool_router.session.execute(
session_id=self.session_id,
tool_slug=tool_slug,
arguments=arguments if arguments is not None else omit,
)
+ return {
+ "data": response.data if hasattr(response, "data") else {},
+ "error": response.error if hasattr(response, "error") else None,
+ "log_id": response.log_id if hasattr(response, "log_id") else "",
+ }
def custom_tools(
self, *, toolkit: t.Optional[str] = None
diff --git a/python/tests/test_custom_tools.py b/python/tests/test_custom_tools.py
index 95991ed1b..957e9e34f 100644
--- a/python/tests/test_custom_tools.py
+++ b/python/tests/test_custom_tools.py
@@ -181,6 +181,30 @@ class TestDecoratorTool:
"""Bad tool."""
return {}
+ def test_no_params_rejected(self):
+ with pytest.raises(ValidationError, match="at least one parameter"):
+
+ @exp.tool()
+ def no_params():
+ """No params."""
+ return {}
+
+ def test_too_many_params_rejected(self):
+ with pytest.raises(ValidationError, match="at most 2"):
+
+ @exp.tool()
+ def three_params(input: GrepInput, ctx, extra):
+ """Three params."""
+ return {}
+
+ def test_first_param_must_be_basemodel(self):
+ with pytest.raises(ValidationError, match="first parameter"):
+
+ @exp.tool()
+ def swapped(ctx, input: GrepInput):
+ """Swapped order — ctx first, input second."""
+ return {}
+
def test_async_function_rejected(self):
with pytest.raises(ValidationError, match="synchronous"):
@@ -480,12 +504,20 @@ class TestToolRouterSessionCustomTools:
mock_session_deps["client"].tool_router.session.execute.assert_not_called()
def test_execute_remote(self, mock_session_deps):
+ mock_response = MagicMock()
+ mock_response.data = {"sent": True}
+ mock_response.error = None
+ mock_response.log_id = "log_123"
mock_session_deps[
"client"
- ].tool_router.session.execute.return_value = MagicMock()
+ ].tool_router.session.execute.return_value = mock_response
s = _session(mock_session_deps)
- s.execute("GMAIL_SEND_EMAIL", arguments={"to": "[email protected]"})
+ result = s.execute("GMAIL_SEND_EMAIL", arguments={"to": "[email protected]"})
mock_session_deps["client"].tool_router.session.execute.assert_called_once()
+ # Remote returns same dict shape as local
+ assert isinstance(result, dict)
+ assert result["data"] == {"sent": True}
+ assert result["log_id"] == "log_123"
def test_custom_tools_list(self, mock_session_deps):
s = _session(mock_session_deps)