Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
| 1 | """Standalone functions for custom tool lookup and execution. |
| 2 | |
| 3 | Extracted for reuse in SessionContextImpl (sibling routing). |
| 4 | |
| 5 | Security invariant (CWE-639 / SEC-365): on this code path the trusted |
| 6 | ``user_id`` arrives via ``SessionContext`` — never via ``arguments``. The |
| 7 | ``arguments`` dict is LLM-supplied and is validated through the tool's |
| 8 | Pydantic ``input_params`` model, which discards unknown fields, so an |
| 9 | attempt to smuggle ``user_id`` (or any other identity-bearing key) inside |
| 10 | ``arguments`` cannot reach the tool's execute function or auth lookup. |
| 11 | Keep this property when modifying ``execute_custom_tool``. |
| 12 | """ |
| 13 | |
| 14 | from __future__ import annotations |
| 15 | |
| 16 | import typing as t |
| 17 | |
| 18 | from pydantic import ValidationError as PydanticValidationError |
| 19 | |
| 20 | from composio.exceptions import ToolInputRequiredError, ValidationError |
| 21 | |
| 22 | from .custom_tool_types import ( |
| 23 | CustomToolsMap, |
| 24 | CustomToolsMapEntry, |
| 25 | SessionContext, |
| 26 | ) |
| 27 | from .tools import ToolExecutionResponse |
| 28 | |
| 29 | |
| 30 | def find_custom_tool( |
| 31 | map_: t.Optional[CustomToolsMap], |
| 32 | slug: str, |
| 33 | ) -> t.Optional[CustomToolsMapEntry]: |
| 34 | """Find a custom tool entry by slug. |
| 35 | |
| 36 | Checks both the final slug map (LOCAL_X — agent/LLM path) |
| 37 | and original slug map (X — programmatic path). Case-insensitive. |
| 38 | """ |
| 39 | if map_ is None: |
| 40 | return None |
| 41 | upper = slug.upper() |
| 42 | final_slug_match = map_.by_final_slug.get(upper) |
| 43 | if final_slug_match is not None: |
| 44 | return final_slug_match |
| 45 | if upper in map_.ambiguous_original_slugs: |
| 46 | return None |
| 47 | return map_.by_original_slug.get(upper) |
| 48 | |
| 49 | |
| 50 | def assert_unambiguous_custom_tool_slug( |
| 51 | map_: t.Optional[CustomToolsMap], slug: str |
| 52 | ) -> None: |
| 53 | """Reject ambiguous bare original slugs before remote fallback.""" |
| 54 | if map_ is None: |
| 55 | return |
| 56 | |
| 57 | upper = slug.upper() |
| 58 | if upper not in map_.ambiguous_original_slugs: |
| 59 | return |
| 60 | |
| 61 | final_slugs = sorted( |
| 62 | entry.final_slug |
| 63 | for entry in map_.by_final_slug.values() |
| 64 | if entry.handle.slug.upper() == upper |
| 65 | ) |
| 66 | hint = f" Use one of: {', '.join(final_slugs)}." if final_slugs else "" |
| 67 | raise ValidationError( |
| 68 | f'Ambiguous custom tool slug "{slug}". Multiple custom toolkit tools ' |
| 69 | "share this original slug; manual session.execute() by original slug " |
| 70 | "is only supported when the original slug is unique." |
| 71 | f"{hint}" |
| 72 | ) |
| 73 | |
| 74 | |
| 75 | def execute_custom_tool( |
| 76 | entry: CustomToolsMapEntry, |
| 77 | arguments: t.Dict[str, t.Any], |
| 78 | session_context: SessionContext, |
| 79 | ) -> ToolExecutionResponse: |
| 80 | """Execute a custom tool in-process. |
| 81 | |
| 82 | Validates input via the Pydantic model, calls the user's execute function, |
| 83 | and wraps the result into the standard response format. |
| 84 | |
| 85 | :raises ToolInputRequiredError: If a call the tool made through the session |
| 86 | context needs user input before it can run. |
| 87 | """ |
| 88 | handle = entry.handle |
| 89 | |
| 90 | # Validate and transform input using the Pydantic model. |
| 91 | # This applies defaults, coercions, and validators. |
| 92 | try: |
| 93 | validated = handle.input_params.model_validate(arguments) |
| 94 | except PydanticValidationError as e: |
| 95 | return { |
| 96 | "data": {}, |
| 97 | "error": f"Input validation failed: {e}", |
| 98 | "successful": False, |
| 99 | } |
| 100 | |
| 101 | try: |
| 102 | # User's execute returns data directly — we wrap into {data, error, successful} |
| 103 | data = handle.execute(validated, session_context) |
| 104 | return { |
| 105 | "data": data if data is not None else {}, |
| 106 | "error": None, |
| 107 | "successful": True, |
| 108 | } |
| 109 | except ToolInputRequiredError: |
| 110 | # ``ctx.execute()`` / ``ctx.proxy_execute()`` asked for user input: |
| 111 | # nothing ran. Flattening it into a failed result would drop the |
| 112 | # questions and the request state the caller needs to answer them. |
| 113 | raise |
| 114 | except Exception as e: |
| 115 | return { |
| 116 | "data": {}, |
| 117 | "error": str(e), |
| 118 | "successful": False, |
| 119 | } |