@devries-cameron20 / composio Mirror · read-only / commits / e1a045bc5
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 code review findings

1. Strict function signature validation in @tool() decorator: enforce (input: BaseModel) or (input: BaseModel, ctx) shape, reject swapped params, >2 params, and missing BaseModel annotation on first param 2. Consistent session.execute() return type: both local and remote paths now return a dict with data/error/log_id keys (no more model vs dict divergence) 3. Client-side validation in proxy_execute: validate toolkit, endpoint, method, and parameter shapes before hitting the API (matches TS SessionProxyExecuteParamsSchema behavior) 4. Document intentional order divergence in multi-execute merge: Python preserves original request order (index-based), TS appends locals after remotes Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

Dhawal Upadhyay committed Mar 23, 2026 at 17:15 UTC e1a045bc547c2bc777e37cab5383bfa62ec730d3
4 files changed +106 -24
python/composio/core/models/custom_tool.py
+29 -15
@@ -248,28 +248,42 @@ def _infer_tool_from_function(
248 f'Add a docstring to "{fn.__name__}" or pass description=...'
249 )
250
251 - # Infer input_params from type annotation
251 + # Validate and infer function signature.
252 + # Accepted shapes (consistent with TS CustomToolExecuteFn):
253 + # (input: BaseModel) — no session context needed
254 + # (input: BaseModel, ctx) — with session context
255 + # The first param MUST be annotated with a BaseModel subclass.
256 sig = inspect.signature(fn)
257 params = list(sig.parameters.values())
254 - input_params: t.Optional[t.Type[BaseModel]] = None
255 - for p in params:
256 - if p.annotation is not inspect.Parameter.empty:
257 - ann = p.annotation
258 - if isinstance(ann, type) and issubclass(ann, BaseModel):
259 - input_params = ann
260 - break
261 -
262 - if input_params is None:
258 +
259 + if not params:
260 raise ValidationError(
264 - f'experimental.tool: could not infer input parameters for "{fn.__name__}". '
265 - f"Annotate a parameter with a Pydantic BaseModel subclass, e.g. "
261 + f'experimental.tool: "{fn.__name__}" must accept at least one parameter '
262 + f"annotated with a Pydantic BaseModel subclass, e.g. "
263 f"def {fn.__name__}(input: MyInput, ctx): ..."
264 )
265
266 + if len(params) > 2:
267 + raise ValidationError(
268 + f'experimental.tool: "{fn.__name__}" accepts {len(params)} parameters, '
269 + f"but custom tools accept at most 2: (input: BaseModel, ctx). "
270 + f"Extra parameters will not be populated at runtime."
271 + )
272 +
273 + # First param must be the input model
274 + first = params[0]
275 + if first.annotation is inspect.Parameter.empty or not (
276 + isinstance(first.annotation, type) and issubclass(first.annotation, BaseModel)
277 + ):
278 + raise ValidationError(
279 + f'experimental.tool: first parameter of "{fn.__name__}" must be annotated '
280 + f"with a Pydantic BaseModel subclass. Got: {first.annotation!r}. "
281 + f"Expected: def {fn.__name__}(input: MyInput, ctx): ..."
282 + )
283 + input_params: t.Type[BaseModel] = first.annotation
284 +
285 # Wrap function to match CustomToolExecuteFn: (input, ctx) -> dict
270 - # Support both (input) and (input, ctx) signatures
271 - num_params = len(params)
272 - if num_params <= 1:
286 + if len(params) == 1:
287
288 def execute(input: t.Any, ctx: t.Any) -> t.Dict[str, t.Any]:
289 return fn(input)
python/composio/core/models/session_context.py
+29 -3
@@ -22,6 +22,10 @@ from composio.core.models.custom_tool_types import (
22 from composio.core.models.tools import ToolExecutionResponse
23
24
25 +_VALID_METHODS = frozenset({"GET", "POST", "PUT", "DELETE", "PATCH"})
26 +_VALID_PARAM_TYPES = frozenset({"header", "query"})
27 +
28 +
29 def proxy_execute_impl(
30 client: HttpClient,
31 session_id: str,
@@ -33,16 +37,38 @@ def proxy_execute_impl(
37 parameters: t.Optional[t.List[t.Dict[str, t.Any]]] = None,
38 ) -> ProxyExecuteResponse:
39 """Shared proxy execute implementation used by SessionContextImpl and ToolRouterSession."""
36 - # Transform parameters to API format using the composio_client Parameter type
40 + from composio.exceptions import ValidationError
41 +
42 + # Client-side validation (matches TS SessionProxyExecuteParamsSchema)
43 + if not toolkit:
44 + raise ValidationError("proxy_execute: toolkit is required")
45 + if not endpoint:
46 + raise ValidationError("proxy_execute: endpoint is required")
47 + if method not in _VALID_METHODS:
48 + raise ValidationError(
49 + f"proxy_execute: method must be one of {sorted(_VALID_METHODS)}, got {method!r}"
50 + )
51 +
52 + # Transform and validate parameters
53 from composio_client.types.tool_router.session_proxy_execute_params import Parameter
54
55 api_params: t.List[Parameter] = []
56 if parameters:
41 - for p in parameters:
57 + for i, p in enumerate(parameters):
58 + if not isinstance(p, dict) or "name" not in p or "value" not in p:
59 + raise ValidationError(
60 + f"proxy_execute: parameters[{i}] must be a dict with 'name' and 'value' keys"
61 + )
62 + param_type = p.get("in", p.get("type", "header"))
63 + if param_type not in _VALID_PARAM_TYPES:
64 + raise ValidationError(
65 + f"proxy_execute: parameters[{i}].type must be 'header' or 'query', "
66 + f"got {param_type!r}"
67 + )
68 api_params.append(
69 Parameter(
70 name=p["name"],
45 - type=p.get("in", p.get("type", "header")), # type: ignore[typeddict-item]
71 + type=param_type, # type: ignore[typeddict-item]
72 value=str(p["value"]),
73 )
74 )
python/composio/core/models/tool_router_session.py
+14 -4
@@ -230,6 +230,10 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
230 Splits the tools[] array into local and remote, executes each
231 appropriately, and merges results preserving original order.
232
233 + Note: Results are merged in the original request order (index-based).
234 + This intentionally differs from TS which appends locals after remotes —
235 + preserving order is more predictable for callers.
236 +
237 Note: modifiers are NOT applied here — the caller (routing_execute)
238 handles before_execute/after_execute to avoid double application.
239 """
@@ -510,25 +514,31 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
514 For custom tools, accepts the original slug (e.g. "GREP") or the
515 full slug (e.g. "LOCAL_GREP"). Custom tools are executed in-process;
516 remote tools are sent to the Composio backend.
517 +
518 + Returns a dict with ``data``, ``error``, and ``log_id`` keys for both
519 + local and remote execution paths.
520 """
521 # Check if this is a local tool (by original or final slug)
522 entry = find_custom_tool(self._custom_tools_map, tool_slug)
523 if entry and self._session_context:
524 result = execute_custom_tool(entry, arguments or {}, self._session_context)
518 - # Normalize to match SessionExecuteResponse shape (data, error, log_id)
525 return {
526 "data": result["data"],
527 "error": result["error"],
528 "log_id": "",
529 }
530
525 - # Remote execution — return the SessionExecuteResponse model as-is
526 - # to preserve backward compatibility for callers using attribute access
527 - return self._client.tool_router.session.execute(
531 + # Remote execution — normalize to dict for consistent return type
532 + response = self._client.tool_router.session.execute(
533 session_id=self.session_id,
534 tool_slug=tool_slug,
535 arguments=arguments if arguments is not None else omit,
536 )
537 + return {
538 + "data": response.data if hasattr(response, "data") else {},
539 + "error": response.error if hasattr(response, "error") else None,
540 + "log_id": response.log_id if hasattr(response, "log_id") else "",
541 + }
542
543 def custom_tools(
544 self, *, toolkit: t.Optional[str] = None
python/tests/test_custom_tools.py
+34 -2
@@ -181,6 +181,30 @@ class TestDecoratorTool:
181 """Bad tool."""
182 return {}
183
184 + def test_no_params_rejected(self):
185 + with pytest.raises(ValidationError, match="at least one parameter"):
186 +
187 + @exp.tool()
188 + def no_params():
189 + """No params."""
190 + return {}
191 +
192 + def test_too_many_params_rejected(self):
193 + with pytest.raises(ValidationError, match="at most 2"):
194 +
195 + @exp.tool()
196 + def three_params(input: GrepInput, ctx, extra):
197 + """Three params."""
198 + return {}
199 +
200 + def test_first_param_must_be_basemodel(self):
201 + with pytest.raises(ValidationError, match="first parameter"):
202 +
203 + @exp.tool()
204 + def swapped(ctx, input: GrepInput):
205 + """Swapped order — ctx first, input second."""
206 + return {}
207 +
208 def test_async_function_rejected(self):
209 with pytest.raises(ValidationError, match="synchronous"):
210
@@ -480,12 +504,20 @@ class TestToolRouterSessionCustomTools:
504 mock_session_deps["client"].tool_router.session.execute.assert_not_called()
505
506 def test_execute_remote(self, mock_session_deps):
507 + mock_response = MagicMock()
508 + mock_response.data = {"sent": True}
509 + mock_response.error = None
510 + mock_response.log_id = "log_123"
511 mock_session_deps[
512 "client"
485 - ].tool_router.session.execute.return_value = MagicMock()
513 + ].tool_router.session.execute.return_value = mock_response
514 s = _session(mock_session_deps)
487 - s.execute("GMAIL_SEND_EMAIL", arguments={"to": "a@b.com"})
515 + result = s.execute("GMAIL_SEND_EMAIL", arguments={"to": "a@b.com"})
516 mock_session_deps["client"].tool_router.session.execute.assert_called_once()
517 + # Remote returns same dict shape as local
518 + assert isinstance(result, dict)
519 + assert result["data"] == {"sent": True}
520 + assert result["log_id"] == "log_123"
521
522 def test_custom_tools_list(self, mock_session_deps):
523 s = _session(mock_session_deps)