@devries-cameron20 / composio-1 / commits / d21e7e76f
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.

fix(python): address PR review comments

- Fix async validation bypass for single-param tools: check asyncio.iscoroutinefunction(fn) before wrapping in _infer_tool - Remove inline # slug/name comments from example (jkomyno review) - Add test for async single-param rejection Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

Dhawal Upadhyay committed Mar 24, 2026 at 14:03 UTC d21e7e76f40fc6e4d56b076c7c7f23fe2ab7e6e9
3 files changed +43 -9
python/composio/core/models/custom_tool.py
+8
@@ -253,6 +253,14 @@ def _infer_tool_from_function(
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 + # Reject async before wrapping (wrapper would hide it from _create_tool)
257 + if asyncio.iscoroutinefunction(fn):
258 + raise ValidationError(
259 + f'experimental.tool: "{fn.__name__}" is async. '
260 + f"The Composio Python SDK is synchronous — use a regular "
261 + f"'def {fn.__name__}(input, ctx)' instead of 'async def'."
262 + )
263 +
264 sig = inspect.signature(fn)
265 params = list(sig.parameters.values())
266
python/examples/custom_tools_agent_test.py
+25 -8
@@ -24,14 +24,17 @@ composio = Composio(provider=OpenAIAgentsProvider())
24
25 # ── 1. Standalone tool — slug/name/description inferred from function ──
26
27 +
28 class UserLookupInput(BaseModel):
29 user_id: str = Field(description="User ID (e.g. user-1)")
30
31 +
32 USERS = {
33 "user-1": {"name": "Alice Johnson", "email": "alice@acme.com", "role": "admin"},
34 "user-2": {"name": "Bob Smith", "email": "bob@acme.com", "role": "developer"},
35 }
36
37 +
38 @composio.experimental.tool()
39 def get_user(input: UserLookupInput, ctx):
40 """Look up an internal user by ID. Returns name, email, and role."""
@@ -39,16 +42,16 @@ def get_user(input: UserLookupInput, ctx):
42 if not user:
43 raise ValueError(f'User "{input.user_id}" not found')
44 return user
42 -# slug = GET_USER (from function name)
43 -# name = Get User (humanized)
44 -# description = "Look up an internal user by ID..." (from docstring)
45 +
46
47 # ── 2. Standalone tool with overrides ──────────────────────────────────
48
49 +
50 class GreetInput(BaseModel):
51 name: str = Field(description="Name to greet")
52 style: str = Field(default="friendly", description="Greeting style")
53
54 +
55 @composio.experimental.tool(
56 slug="GREET_V2",
57 name="Greeting Generator",
@@ -62,17 +65,17 @@ def greet(input: GreetInput, ctx):
65 "casual": f"Yo {input.name}, what's up?",
66 }
67 return {"message": greetings.get(input.style, f"Hello {input.name}!")}
65 -# slug = GREET_V2 (overridden, not GREET)
66 -# name = Greeting Generator (overridden, not Greet)
67 -# description = "Generate a personalized..." (overridden, not docstring)
68 +
69
70 # ── 3. Extension tool — inherits Gmail auth via ctx.proxy_execute() ────
71
72 +
73 class DraftInput(BaseModel):
74 to: str = Field(description="Recipient email address")
75 subject: str = Field(description="Email subject")
76 body: str = Field(description="Email body (plain text)")
77
78 +
79 @composio.experimental.tool(extends_toolkit="gmail")
80 def create_draft(input: DraftInput, ctx):
81 """Create a real Gmail draft. Appears in the user's drafts folder."""
@@ -92,6 +95,7 @@ def create_draft(input: DraftInput, ctx):
95 data = res["data"]
96 return {"draft_id": data["id"], "to": input.to, "subject": input.subject}
97
98 +
99 # ── 4. Custom toolkit — groups related tools under one namespace ───────
100
101 role_manager = composio.experimental.Toolkit(
@@ -100,22 +104,27 @@ role_manager = composio.experimental.Toolkit(
104 description="Manage user roles in the system",
105 )
106
107 +
108 class SetRoleInput(BaseModel):
109 user_id: str = Field(description="User ID")
110 role: str = Field(description="New role (admin, developer, viewer)")
111
112 +
113 @role_manager.tool()
114 def set_role(input: SetRoleInput, ctx):
115 """Set a user's role. Returns confirmation."""
116 return {"user_id": input.user_id, "role": input.role, "updated": True}
117
118 +
119 @role_manager.tool(name="List All Roles")
120 def list_roles(input: UserLookupInput, ctx):
121 """List available roles for a user."""
122 return {"roles": ["admin", "developer", "viewer"], "current": "admin"}
123
124 +
125 # ── Agent ──────────────────────────────────────────────────────────────
126
127 +
128 async def run_test(prompt, test_name):
129 print(f"\n{'=' * 60}")
130 print(f"TEST: {test_name}")
@@ -150,6 +159,7 @@ async def run_test(prompt, test_name):
159 print(f"\nERROR: {e}")
160 return False
161
162 +
163 async def main():
164 tests = [
165 ("Look up user-2", "Standalone (inferred slug/name)"),
@@ -157,8 +167,14 @@ async def main():
167 ("Set user-1 role to developer", "Toolkit tool"),
168 ("Look up user-1 and set their role to viewer", "Mixed local tools"),
169 ("What is the weather in Tokyo?", "Remote (weathermap)"),
160 - ('Draft an email to bob@acme.com with subject "Test" and body "Hello!"', "Gmail proxy"),
161 - ("Look up user-1, draft them an email saying hi, include weather in SF", "Mixed all"),
170 + (
171 + 'Draft an email to bob@acme.com with subject "Test" and body "Hello!"',
172 + "Gmail proxy",
173 + ),
174 + (
175 + "Look up user-1, draft them an email saying hi, include weather in SF",
176 + "Mixed all",
177 + ),
178 ]
179
180 results = []
@@ -173,6 +189,7 @@ async def main():
189 print(f" [{'PASS' if ok else 'FAIL'}] {name}")
190 print(f"\n{sum(1 for _, ok in results if ok)}/{len(results)} passed")
191
192 +
193 if __name__ == "__main__":
194 if not os.environ.get("OPENAI_API_KEY"):
195 print("Error: OPENAI_API_KEY env var required")
python/tests/test_custom_tools.py
+10 -1
@@ -236,13 +236,22 @@ class TestDecoratorTool:
236 return {}
237
238 def test_async_function_rejected(self):
239 - with pytest.raises(ValidationError, match="synchronous"):
239 + with pytest.raises(ValidationError, match="async"):
240
241 @exp.tool()
242 async def async_tool(input: GrepInput, ctx):
243 """Async tool."""
244 return {}
245
246 + def test_async_single_param_rejected(self):
247 + """Async must be caught even when wrapper hides it (single-param path)."""
248 + with pytest.raises(ValidationError, match="async"):
249 +
250 + @exp.tool()
251 + async def async_single(input: GrepInput):
252 + """Async single param."""
253 + return {}
254 +
255 def test_root_model_rejected(self):
256 from pydantic import RootModel
257