@devries-cameron20 / composio Mirror · read-only / commits / 7f55651b3
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 round 3 findings + add e2e example

- P1: Preserve SessionExecuteResponse model for remote execute (don't convert to dict — backward compatible for callers using attribute access) - P2: Serialize Pydantic models in SessionContextImpl.execute remote path via _serialize_arguments() before sending to backend - P2: Apply before_execute/after_execute modifiers around intercepted COMPOSIO_MULTI_EXECUTE_TOOL calls in custom tools routing path - P2: Surface backend batch errors in mixed local/remote multi-execute (include remote batch error message instead of just tool failure count) - Reject async execute handlers at factory level (asyncio.iscoroutinefunction) - Add custom_tools_v2.py e2e example (equivalent of TS custom-tools.ts) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

Dhawal Upadhyay committed Mar 20, 2026 at 13:51 UTC 7f55651b37abe0e2b0711c67ef4662fcc788d35c
3 files changed +274 -16
python/composio/core/models/session_context.py
+7 -1
@@ -111,11 +111,17 @@ class SessionContextImpl:
111 if entry:
112 return execute_custom_tool(entry, arguments, self)
113
114 + # Serialize any Pydantic model instances before sending to remote API
115 + # (custom tools receive validated Pydantic inputs that may be forwarded)
116 + from composio.core.models.tools import _serialize_arguments
117 +
118 + serialized = _serialize_arguments(arguments)
119 +
120 # Fall back to remote execution
121 response = self._client.tool_router.session.execute(
122 session_id=self._session_id,
123 tool_slug=tool_slug,
118 - arguments=arguments,
124 + arguments=serialized,
125 )
126 return {
127 "data": response.data if hasattr(response, "data") else {},
python/composio/core/models/tool_router_session.py
+53 -15
@@ -161,13 +161,45 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
161 tools_model: t.Any,
162 modifiers: t.Optional["Modifiers"],
163 ) -> t.Callable[..., t.Any]:
164 - """Create an execute function that routes local/remote tools."""
164 + """Create an execute function that routes local/remote tools.
165 +
166 + Applies before_execute/after_execute modifiers around the overall
167 + COMPOSIO_MULTI_EXECUTE_TOOL call, consistent with the standard path.
168 + """
169
170 def routing_execute(slug: str, arguments: t.Dict) -> t.Dict:
171 if slug == COMPOSIO_MULTI_EXECUTE_TOOL:
168 - return self._route_multi_execute(
169 - arguments, tools_model, modifiers
172 + # Apply before_execute modifiers
173 + processed_arguments = arguments
174 + if modifiers is not None:
175 + from composio.core.models._modifiers import apply_modifier_by_type
176 + from composio.core.models.tools import ToolExecuteParams
177 +
178 + params: ToolExecuteParams = {"arguments": arguments}
179 + modified = apply_modifier_by_type(
180 + modifiers=modifiers,
181 + toolkit="composio",
182 + tool=slug,
183 + type="before_execute",
184 + request=params,
185 + )
186 + processed_arguments = modified.get("arguments", arguments)
187 +
188 + result = self._route_multi_execute(
189 + processed_arguments, tools_model, modifiers
190 )
191 +
192 + # Apply after_execute modifiers
193 + if modifiers is not None:
194 + result = apply_modifier_by_type(
195 + modifiers=modifiers,
196 + toolkit="composio",
197 + tool=slug,
198 + type="after_execute",
199 + response=result,
200 + )
201 +
202 + return result
203 # Non-multi-execute meta tools always go to backend
204 return tools_model._wrap_execute_tool_for_tool_router(
205 session_id=self.session_id,
@@ -325,13 +357,23 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
357 merged_data.update(remote_data)
358 merged_data["results"] = merged
359
360 + # Build error message — include remote batch error if present
361 + remote_batch_error = (
362 + remote_result.get("error") if remote_result else None
363 + )
364 + if has_any_error:
365 + parts = []
366 + if failed_count > 0:
367 + parts.append(f"{failed_count} out of {len(merged)} tools failed")
368 + if remote_batch_error:
369 + parts.append(f"remote batch error: {remote_batch_error}")
370 + error_msg = "; ".join(parts) if parts else "execution failed"
371 + else:
372 + error_msg = None
373 +
374 return {
375 "data": merged_data,
330 - "error": (
331 - f"{failed_count} out of {len(merged)} tools failed"
332 - if has_any_error
333 - else None
334 - ),
376 + "error": error_msg,
377 "successful": not has_any_error,
378 }
379
@@ -485,17 +527,13 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
527 "log_id": "",
528 }
529
488 - # Remote execution — normalize to dict for consistent return type
489 - response = self._client.tool_router.session.execute(
530 + # Remote execution — return the SessionExecuteResponse model as-is
531 + # to preserve backward compatibility for callers using attribute access
532 + return 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 )
494 - return {
495 - "data": response.data if hasattr(response, "data") else {},
496 - "error": response.error if hasattr(response, "error") else None,
497 - "log_id": response.log_id if hasattr(response, "log_id") else "",
498 - }
537
538 def custom_tools(
539 self, *, toolkit: t.Optional[str] = None
python/examples/custom_tools_v2.py new
+214
@@ -0,0 +1,214 @@
1 +"""
2 +Custom Tools v2 — local tools + proxy execute with tool router sessions.
3 +
4 +Shows how to create custom tools that run in-process alongside
5 +remote Composio tools. Equivalent of ts/examples/tool-router/src/custom-tools.ts.
6 +
7 +Usage:
8 + COMPOSIO_API_KEY=... python examples/custom_tools_v2.py
9 +"""
10 +
11 +import base64
12 +import sys
13 +
14 +from pydantic import BaseModel, Field
15 +
16 +from composio import Composio, experimental_create_tool, experimental_create_toolkit
17 +
18 +
19 +# ── Custom tools ────────────────────────────────────────────────
20 +
21 +
22 +class UserLookupInput(BaseModel):
23 + user_id: str = Field(description="User ID (e.g. user-1)")
24 +
25 +
26 +USERS = {
27 + "user-1": {"name": "Alice Johnson", "email": "alice@acme.com", "role": "admin"},
28 + "user-2": {"name": "Bob Smith", "email": "bob@acme.com", "role": "developer"},
29 +}
30 +
31 +
32 +def get_user_fn(input: UserLookupInput, ctx):
33 + """Look up an internal user by ID."""
34 + user = USERS.get(input.user_id)
35 + if not user:
36 + raise ValueError(f'User "{input.user_id}" not found')
37 + return user
38 +
39 +
40 +get_user = experimental_create_tool(
41 + "GET_USER",
42 + name="Get user",
43 + description="Look up an internal user by ID",
44 + input_params=UserLookupInput,
45 + execute=get_user_fn,
46 +)
47 +
48 +
49 +class DraftInput(BaseModel):
50 + to: str = Field(description="Recipient email address")
51 + subject: str = Field(description="Email subject")
52 + body: str = Field(description="Email body (plain text)")
53 +
54 +
55 +def create_draft_fn(input: DraftInput, ctx):
56 + """Create a real Gmail draft via the Gmail API."""
57 + raw_message = (
58 + f"To: {input.to}\r\n"
59 + f"Subject: {input.subject}\r\n"
60 + f"Content-Type: text/plain; charset=UTF-8\r\n"
61 + f"\r\n"
62 + f"{input.body}"
63 + )
64 + raw = (
65 + base64.urlsafe_b64encode(raw_message.encode("utf-8"))
66 + .decode("ascii")
67 + .rstrip("=")
68 + )
69 +
70 + res = ctx.proxy_execute(
71 + toolkit="gmail",
72 + endpoint="https://gmail.googleapis.com/gmail/v1/users/me/drafts",
73 + method="POST",
74 + body={"message": {"raw": raw}},
75 + )
76 +
77 + if res["status"] != 200:
78 + raise RuntimeError(f"Gmail API error {res['status']}: {res.get('data')}")
79 + data = res["data"]
80 + return {
81 + "draft_id": data["id"],
82 + "message_id": data["message"]["id"],
83 + "to": input.to,
84 + "subject": input.subject,
85 + }
86 +
87 +
88 +create_draft = experimental_create_tool(
89 + "CREATE_DRAFT",
90 + name="Create Gmail draft",
91 + description="Create a real Gmail draft via the Gmail API. Appears in the user's drafts folder.",
92 + extends_toolkit="gmail",
93 + input_params=DraftInput,
94 + execute=create_draft_fn,
95 +)
96 +
97 +
98 +class SetRoleInput(BaseModel):
99 + user_id: str = Field(description="User ID")
100 + role: str = Field(description="New role (admin, developer, viewer)")
101 +
102 +
103 +role_manager = experimental_create_toolkit(
104 + "ROLE_MANAGER",
105 + name="Role Manager",
106 + description="Manage user roles",
107 + tools=[
108 + experimental_create_tool(
109 + "SET_ROLE",
110 + name="Set role",
111 + description="Set a user's role",
112 + input_params=SetRoleInput,
113 + execute=lambda input, ctx: {
114 + "user_id": input.user_id,
115 + "role": input.role,
116 + "updated": True,
117 + },
118 + ),
119 + ],
120 +)
121 +
122 +
123 +# ── Session ─────────────────────────────────────────────────────
124 +
125 +
126 +def main():
127 + composio = Composio()
128 +
129 + print("Creating session with custom tools...")
130 + session = composio.create(
131 + user_id="default",
132 + toolkits=["gmail"],
133 + experimental={
134 + "custom_tools": [get_user, create_draft],
135 + "custom_toolkits": [role_manager],
136 + },
137 + )
138 + print(f"Session ID: {session.session_id}")
139 +
140 + # List registered custom tools
141 + print("\n── Registered custom tools ──")
142 + for tool in session.custom_tools():
143 + print(f" {tool.slug} ({tool.toolkit or 'standalone'})")
144 +
145 + print("\n── Registered custom toolkits ──")
146 + for tk in session.custom_toolkits():
147 + print(f" {tk.slug}: {[t.slug for t in tk.tools]}")
148 +
149 + # Test 1: Execute standalone custom tool (local, no network)
150 + print("\n── Test 1: Execute GET_USER (standalone, local) ──")
151 + result = session.execute("GET_USER", arguments={"user_id": "user-1"})
152 + print(f" Result: {result}")
153 + assert result["data"]["name"] == "Alice Johnson", "GET_USER failed!"
154 + assert result["error"] is None
155 + print(" ✓ Passed")
156 +
157 + # Test 2: Execute by final slug
158 + print("\n── Test 2: Execute LOCAL_GET_USER (by final slug) ──")
159 + result = session.execute("LOCAL_GET_USER", arguments={"user_id": "user-2"})
160 + print(f" Result: {result}")
161 + assert result["data"]["name"] == "Bob Smith", "LOCAL_GET_USER failed!"
162 + print(" ✓ Passed")
163 +
164 + # Test 3: Execute toolkit tool
165 + print("\n── Test 3: Execute SET_ROLE (toolkit tool) ──")
166 + result = session.execute(
167 + "SET_ROLE", arguments={"user_id": "user-1", "role": "viewer"}
168 + )
169 + print(f" Result: {result}")
170 + assert result["data"]["updated"] is True, "SET_ROLE failed!"
171 + print(" ✓ Passed")
172 +
173 + # Test 4: Validation error
174 + print("\n── Test 4: Validation error (missing required field) ──")
175 + result = session.execute("GET_USER", arguments={})
176 + print(f" Result: error={result['error'][:80]}...")
177 + assert result["error"] is not None, "Should have validation error!"
178 + print(" ✓ Passed")
179 +
180 + # Test 5: Execute error
181 + print("\n── Test 5: Execute error (user not found) ──")
182 + result = session.execute("GET_USER", arguments={"user_id": "nonexistent"})
183 + print(f" Result: error={result['error']}")
184 + assert result["error"] is not None, "Should have execution error!"
185 + print(" ✓ Passed")
186 +
187 + # Test 6: Pydantic defaults applied
188 + print("\n── Test 6: Get tools (provider-wrapped) ──")
189 + tools = session.tools()
190 + print(f" Got {len(tools)} tools")
191 + print(" ✓ Passed")
192 +
193 + # Test 7: Proxy execute (if Gmail is connected)
194 + if "--with-gmail" in sys.argv:
195 + print("\n── Test 7: CREATE_DRAFT via proxy_execute ──")
196 + result = session.execute(
197 + "CREATE_DRAFT",
198 + arguments={
199 + "to": "test@example.com",
200 + "subject": "Test from Python custom tools",
201 + "body": "Hello from the Python SDK custom tools e2e test!",
202 + },
203 + )
204 + print(f" Result: {result}")
205 + if result["error"]:
206 + print(f" ⚠ Gmail draft failed (may need connection): {result['error']}")
207 + else:
208 + print(f" ✓ Draft created: {result['data']}")
209 +
210 + print("\n══ All tests passed! ══")
211 +
212 +
213 +if __name__ == "__main__":
214 + main()