Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
TypeScript agentic-aiagentsaiai-agentsaiagentsdeveloper-toolsfunction-callinggpt-4javascriptjsllmllmopsmcppythonremote-mcp-serverssetypescript
fix(python): address PR review comments
Dhawal Upadhyayd21e7e76f40f
diff --git a/python/composio/core/models/custom_tool.py b/python/composio/core/models/custom_tool.pyindex c03a290dd..905474486 100644--- a/python/composio/core/models/custom_tool.py+++ b/python/composio/core/models/custom_tool.py@@ -253,6 +253,14 @@ def _infer_tool_from_function(# (input: BaseModel) — no session context needed# (input: BaseModel, ctx) — with session context# The first param MUST be annotated with a BaseModel subclass.+ # Reject async before wrapping (wrapper would hide it from _create_tool)+ if asyncio.iscoroutinefunction(fn):+ raise ValidationError(+ f'experimental.tool: "{fn.__name__}" is async. '+ f"The Composio Python SDK is synchronous — use a regular "+ f"'def {fn.__name__}(input, ctx)' instead of 'async def'."+ )+sig = inspect.signature(fn)params = list(sig.parameters.values())diff --git a/python/examples/custom_tools_agent_test.py b/python/examples/custom_tools_agent_test.pyindex f3507a52f..b74dea33c 100644--- a/python/examples/custom_tools_agent_test.py+++ b/python/examples/custom_tools_agent_test.py@@ -24,14 +24,17 @@ composio = Composio(provider=OpenAIAgentsProvider())# ── 1. Standalone tool — slug/name/description inferred from function ──+class UserLookupInput(BaseModel):user_id: str = Field(description="User ID (e.g. user-1)")+USERS = {"user-1": {"name": "Alice Johnson", "email": "[email protected]", "role": "admin"},"user-2": {"name": "Bob Smith", "email": "[email protected]", "role": "developer"},}+@composio.experimental.tool()def get_user(input: UserLookupInput, ctx):"""Look up an internal user by ID. Returns name, email, and role."""@@ -39,16 +42,16 @@ def get_user(input: UserLookupInput, ctx):if not user:raise ValueError(f'User "{input.user_id}" not found')return user-# slug = GET_USER (from function name)-# name = Get User (humanized)-# description = "Look up an internal user by ID..." (from docstring)+# ── 2. Standalone tool with overrides ──────────────────────────────────+class GreetInput(BaseModel):name: str = Field(description="Name to greet")style: str = Field(default="friendly", description="Greeting style")+@composio.experimental.tool(slug="GREET_V2",name="Greeting Generator",@@ -62,17 +65,17 @@ def greet(input: GreetInput, ctx):"casual": f"Yo {input.name}, what's up?",}return {"message": greetings.get(input.style, f"Hello {input.name}!")}-# slug = GREET_V2 (overridden, not GREET)-# name = Greeting Generator (overridden, not Greet)-# description = "Generate a personalized..." (overridden, not docstring)+# ── 3. Extension tool — inherits Gmail auth via ctx.proxy_execute() ────+class DraftInput(BaseModel):to: str = Field(description="Recipient email address")subject: str = Field(description="Email subject")body: str = Field(description="Email body (plain text)")+@composio.experimental.tool(extends_toolkit="gmail")def create_draft(input: DraftInput, ctx):"""Create a real Gmail draft. Appears in the user's drafts folder."""@@ -92,6 +95,7 @@ def create_draft(input: DraftInput, ctx):data = res["data"]return {"draft_id": data["id"], "to": input.to, "subject": input.subject}+# ── 4. Custom toolkit — groups related tools under one namespace ───────role_manager = composio.experimental.Toolkit(@@ -100,22 +104,27 @@ role_manager = composio.experimental.Toolkit(description="Manage user roles in the system",)+class SetRoleInput(BaseModel):user_id: str = Field(description="User ID")role: str = Field(description="New role (admin, developer, viewer)")+@role_manager.tool()def set_role(input: SetRoleInput, ctx):"""Set a user's role. Returns confirmation."""return {"user_id": input.user_id, "role": input.role, "updated": True}+@role_manager.tool(name="List All Roles")def list_roles(input: UserLookupInput, ctx):"""List available roles for a user."""return {"roles": ["admin", "developer", "viewer"], "current": "admin"}+# ── Agent ──────────────────────────────────────────────────────────────+async def run_test(prompt, test_name):print(f"\n{'=' * 60}")print(f"TEST: {test_name}")@@ -150,6 +159,7 @@ async def run_test(prompt, test_name):print(f"\nERROR: {e}")return False+async def main():tests = [("Look up user-2", "Standalone (inferred slug/name)"),@@ -157,8 +167,14 @@ async def main():("Set user-1 role to developer", "Toolkit tool"),("Look up user-1 and set their role to viewer", "Mixed local tools"),("What is the weather in Tokyo?", "Remote (weathermap)"),- ('Draft an email to [email protected] with subject "Test" and body "Hello!"', "Gmail proxy"),- ("Look up user-1, draft them an email saying hi, include weather in SF", "Mixed all"),+ (+ 'Draft an email to [email protected] with subject "Test" and body "Hello!"',+ "Gmail proxy",+ ),+ (+ "Look up user-1, draft them an email saying hi, include weather in SF",+ "Mixed all",+ ),]results = []@@ -173,6 +189,7 @@ async def main():print(f" [{'PASS' if ok else 'FAIL'}] {name}")print(f"\n{sum(1 for _, ok in results if ok)}/{len(results)} passed")+if __name__ == "__main__":if not os.environ.get("OPENAI_API_KEY"):print("Error: OPENAI_API_KEY env var required")diff --git a/python/tests/test_custom_tools.py b/python/tests/test_custom_tools.pyindex 4c7c815aa..c800b78d1 100644--- a/python/tests/test_custom_tools.py+++ b/python/tests/test_custom_tools.py@@ -236,13 +236,22 @@ class TestDecoratorTool:return {}def test_async_function_rejected(self):- with pytest.raises(ValidationError, match="synchronous"):+ with pytest.raises(ValidationError, match="async"):@exp.tool()async def async_tool(input: GrepInput, ctx):"""Async tool."""return {}+ def test_async_single_param_rejected(self):+ """Async must be caught even when wrapper hides it (single-param path)."""+ with pytest.raises(ValidationError, match="async"):++ @exp.tool()+ async def async_single(input: GrepInput):+ """Async single param."""+ return {}+def test_root_model_rejected(self):from pydantic import RootModel