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 | from __future__ import annotations |
| 2 | |
| 3 | import functools |
| 4 | import typing as t |
| 5 | from collections.abc import Mapping |
| 6 | from pathlib import Path |
| 7 | |
| 8 | import typing_extensions as te |
| 9 | from composio_client import APIStatusError, omit |
| 10 | from composio_client.types.tool_router.session_execute_meta_response import ( |
| 11 | SessionExecuteMetaBlockedResponse, |
| 12 | SessionExecuteMetaInputRequiredResponse, |
| 13 | SessionExecuteMetaResult, |
| 14 | SessionExecuteMetaResponse, |
| 15 | ) |
| 16 | from composio_client.types.tool_router.session_execute_response import ( |
| 17 | SessionExecuteBlockedResponse, |
| 18 | SessionExecuteInputRequiredResponse, |
| 19 | SessionExecuteResponse, |
| 20 | SessionExecuteResult, |
| 21 | ) |
| 22 | from composio_client.types.tool_router.session_proxy_execute_response import ( |
| 23 | SessionProxyExecuteInputRequiredResponse, |
| 24 | ) |
| 25 | from pydantic import BaseModel as PydanticBaseModel |
| 26 | |
| 27 | from composio.client import HttpClient |
| 28 | from composio.client.types import ( |
| 29 | Tool, |
| 30 | ToolkitMinimal, |
| 31 | tool_execute_params, |
| 32 | tool_proxy_params, |
| 33 | tool_proxy_response, |
| 34 | ) |
| 35 | from composio.core.models._files import FileHelper |
| 36 | from composio.core.models.base import Resource |
| 37 | from composio.core.models.custom_tool_types import ( |
| 38 | InlineCustomToolsWirePayload, |
| 39 | ToolRouterHookResult, |
| 40 | ) |
| 41 | from composio.core.provider import TTool, TToolCollection |
| 42 | from composio.core.provider.agentic import ( |
| 43 | AgenticProvider, |
| 44 | AgenticProviderExecuteFn, |
| 45 | bind_execution_target, |
| 46 | ) |
| 47 | from composio.core.provider.base import BaseProvider, ExecuteToolFn |
| 48 | from composio.core.provider.none_agentic import NonAgenticProvider |
| 49 | from composio.core.types import ToolkitVersionParam |
| 50 | from composio.exceptions import ( |
| 51 | InvalidParams, |
| 52 | ToolInputRequiredError, |
| 53 | ToolNotFoundError, |
| 54 | ToolVersionRequiredError, |
| 55 | ValidationError, |
| 56 | sanitize_error_text, |
| 57 | ) |
| 58 | from composio.utils.pydantic import none_to_omit |
| 59 | from composio.utils.toolkit_version import get_toolkit_version |
| 60 | from composio.utils.upload_dir_allowlist import resolve_effective_upload_allowlist |
| 61 | |
| 62 | from ._modifiers import ( |
| 63 | Modifiers, |
| 64 | ToolExecuteParams, |
| 65 | after_execute, |
| 66 | apply_modifier_by_type, |
| 67 | before_execute, |
| 68 | before_file_upload, |
| 69 | merge_before_file_upload, |
| 70 | schema_modifier, |
| 71 | ) |
| 72 | |
| 73 | TOOL_ROUTER_SESSION_TOOLS_PAGE_LIMIT = 500 |
| 74 | |
| 75 | |
| 76 | def _normalize_tool(tool: PydanticBaseModel | Mapping[str, object]) -> Tool: |
| 77 | """Normalize generated-client responses to the SDK's tool model shape.""" |
| 78 | normalized: PydanticBaseModel |
| 79 | if isinstance(tool, Mapping): |
| 80 | normalized = Tool.model_construct(_fields_set=set(tool), **dict(tool)) |
| 81 | else: |
| 82 | normalized = tool |
| 83 | |
| 84 | toolkit = getattr(normalized, "toolkit", None) |
| 85 | if isinstance(toolkit, Mapping): |
| 86 | normalized_toolkit = ToolkitMinimal.model_construct( |
| 87 | _fields_set=set(toolkit), **dict(toolkit) |
| 88 | ) |
| 89 | normalized = normalized.model_copy(update={"toolkit": normalized_toolkit}) |
| 90 | |
| 91 | return t.cast(Tool, normalized) |
| 92 | |
| 93 | |
| 94 | def _toolkit_slug(tool: Tool, fallback: str) -> str: |
| 95 | """Resolve untrusted toolkit metadata without assuming a generated shape.""" |
| 96 | toolkit = getattr(tool, "toolkit", None) |
| 97 | slug = ( |
| 98 | toolkit.get("slug") |
| 99 | if isinstance(toolkit, Mapping) |
| 100 | else getattr(toolkit, "slug", None) |
| 101 | ) |
| 102 | return slug if isinstance(slug, str) and slug else fallback |
| 103 | |
| 104 | |
| 105 | def _needs_serialization(obj: t.Any) -> bool: |
| 106 | """Check if an object contains any Pydantic model instances.""" |
| 107 | if isinstance(obj, PydanticBaseModel): |
| 108 | return True |
| 109 | if isinstance(obj, dict): |
| 110 | return any(_needs_serialization(v) for v in obj.values()) |
| 111 | if isinstance(obj, list): |
| 112 | return any(_needs_serialization(item) for item in obj) |
| 113 | return False |
| 114 | |
| 115 | |
| 116 | def _serialize_value(obj: t.Any) -> t.Any: |
| 117 | """Recursively convert Pydantic models to JSON-safe primitives.""" |
| 118 | if isinstance(obj, PydanticBaseModel): |
| 119 | return obj.model_dump(mode="json", by_alias=True) |
| 120 | if isinstance(obj, dict): |
| 121 | return {k: _serialize_value(v) for k, v in obj.items()} |
| 122 | if isinstance(obj, list): |
| 123 | return [_serialize_value(item) for item in obj] |
| 124 | return obj |
| 125 | |
| 126 | |
| 127 | def _serialize_arguments(arguments: t.Dict[str, t.Any]) -> t.Dict[str, t.Any]: |
| 128 | """Serialize any Pydantic model instances in tool arguments to JSON-safe dicts. |
| 129 | |
| 130 | Prevents JSON serialization errors when arguments contain complex types |
| 131 | (e.g., RootModel from discriminated union schemas). Returns the original |
| 132 | dict unchanged when no Pydantic models are present. |
| 133 | """ |
| 134 | if not _needs_serialization(arguments): |
| 135 | return arguments |
| 136 | return {k: _serialize_value(v) for k, v in arguments.items()} |
| 137 | |
| 138 | |
| 139 | _ExecutedT = t.TypeVar("_ExecutedT") |
| 140 | |
| 141 | |
| 142 | def require_executed( |
| 143 | response: t.Union[ |
| 144 | _ExecutedT, |
| 145 | SessionExecuteInputRequiredResponse, |
| 146 | SessionExecuteMetaInputRequiredResponse, |
| 147 | SessionProxyExecuteInputRequiredResponse, |
| 148 | ], |
| 149 | subject: str, |
| 150 | ) -> _ExecutedT: |
| 151 | """Narrow an execute-family response to the variants that carry a result. |
| 152 | |
| 153 | ``input_required`` means the call did not run: it is raised as a |
| 154 | :class:`~composio.exceptions.ToolInputRequiredError` instead of being |
| 155 | returned as a result it is not. |
| 156 | """ |
| 157 | if not isinstance( |
| 158 | response, |
| 159 | ( |
| 160 | SessionExecuteInputRequiredResponse, |
| 161 | SessionExecuteMetaInputRequiredResponse, |
| 162 | SessionProxyExecuteInputRequiredResponse, |
| 163 | ), |
| 164 | ): |
| 165 | return response |
| 166 | raise ToolInputRequiredError( |
| 167 | subject, |
| 168 | input_requests={ |
| 169 | request_id: { |
| 170 | "type": request.type, |
| 171 | "mode": request.mode, |
| 172 | "message": request.message, |
| 173 | "requested_schema": request.requested_schema, |
| 174 | } |
| 175 | for request_id, request in response.input_requests.items() |
| 176 | }, |
| 177 | request_state=response.request_state, |
| 178 | ) |
| 179 | |
| 180 | |
| 181 | class ToolRouterSessionExecuteResponse(SessionExecuteResponse): |
| 182 | """Result of a session tool execution. |
| 183 | |
| 184 | The client's model, with ``hook_results`` as the SDK's own |
| 185 | :class:`ToolRouterHookResult` dicts, as they were before the client typed |
| 186 | them. ``instant_charge`` is present only when the Session sets |
| 187 | ``instant.return_instant_charge`` and a charge is available. |
| 188 | """ |
| 189 | |
| 190 | # The SDK normalizes the client's separate blocked variant into this model. |
| 191 | result_type: t.Optional[t.Literal["completed", "failed", "blocked"]] = None # type: ignore[assignment] |
| 192 | hook_results: t.Optional[t.List[ToolRouterHookResult]] = None # type: ignore[assignment] |
| 193 | |
| 194 | |
| 195 | def _session_execute_result( |
| 196 | fields: t.Mapping[str, t.Any], fields_set: t.AbstractSet[str] |
| 197 | ) -> ToolRouterSessionExecuteResponse: |
| 198 | """The SDK's result over fields the client already parsed, without parsing them again.""" |
| 199 | return ToolRouterSessionExecuteResponse.model_construct( |
| 200 | _fields_set=set(fields_set), **fields |
| 201 | ) |
| 202 | |
| 203 | |
| 204 | def hook_results_of( |
| 205 | hook_results: t.Optional[t.Sequence[PydanticBaseModel]], |
| 206 | ) -> t.Optional[t.List[ToolRouterHookResult]]: |
| 207 | """The client's typed ``hook_results`` as the SDK's own plain dicts. |
| 208 | |
| 209 | The SDK returns hook results as :class:`ToolRouterHookResult` dicts, as it |
| 210 | did before the client typed them. |
| 211 | """ |
| 212 | if hook_results is None: |
| 213 | return None |
| 214 | return [ |
| 215 | t.cast(ToolRouterHookResult, hook_result.model_dump()) |
| 216 | for hook_result in hook_results |
| 217 | ] |
| 218 | |
| 219 | |
| 220 | def _blocked_execute_result( |
| 221 | blocked: t.Union[SessionExecuteBlockedResponse, SessionExecuteMetaBlockedResponse], |
| 222 | ) -> ToolRouterSessionExecuteResponse: |
| 223 | """A call a session hook blocked, as the session execute model. |
| 224 | |
| 225 | The agent reads ``error``, so a blocked call reaches it as a failed call |
| 226 | with the hook's message. The fields are carried over as the client parsed |
| 227 | them instead of being validated a second time. |
| 228 | """ |
| 229 | fields: t.Dict[str, t.Any] = { |
| 230 | "data": {}, |
| 231 | "error": blocked.message, |
| 232 | "log_id": blocked.log_id or "", |
| 233 | "result_type": "blocked", |
| 234 | "block_reason": { |
| 235 | "type": blocked.reason.type, |
| 236 | "hook_id": blocked.reason.hook_id, |
| 237 | }, |
| 238 | } |
| 239 | hook_results = hook_results_of(blocked.hook_results) |
| 240 | if hook_results is not None: |
| 241 | fields["hook_results"] = hook_results |
| 242 | if blocked.instant_charge is not None: |
| 243 | # The client's model: the provider execute path reads it as one. |
| 244 | fields["instant_charge"] = blocked.instant_charge |
| 245 | return _session_execute_result(fields, fields.keys()) |
| 246 | |
| 247 | |
| 248 | def require_execute_result( |
| 249 | response: t.Union[SessionExecuteResult, SessionExecuteMetaResult], |
| 250 | slug: str, |
| 251 | ) -> ToolRouterSessionExecuteResponse: |
| 252 | """Normalize a session execute or execute_meta response to the SDK's result. |
| 253 | |
| 254 | Every session execute response carries a ``result_type``. A ``blocked`` |
| 255 | call (a session hook blocked it) is returned as a result with empty |
| 256 | ``data``, the hook's message in ``error``, and ``block_reason``. One |
| 257 | without a ``result_type``, or with a value this SDK does not know, is |
| 258 | neither a success nor a failure, so it is raised instead of being read as |
| 259 | one. The TypeScript SDK applies the same rule. |
| 260 | |
| 261 | :raises ToolInputRequiredError: If the tool asked for user input instead of |
| 262 | running. |
| 263 | :raises ValidationError: If ``result_type`` is missing or unknown. |
| 264 | """ |
| 265 | if isinstance( |
| 266 | response, (SessionExecuteBlockedResponse, SessionExecuteMetaBlockedResponse) |
| 267 | ): |
| 268 | return _blocked_execute_result(response) |
| 269 | # The completed client models share a contract but no common typed base. |
| 270 | executed = t.cast( |
| 271 | t.Union[SessionExecuteResponse, SessionExecuteMetaResponse], |
| 272 | require_executed(response, f"Tool {slug}"), |
| 273 | ) |
| 274 | if executed.result_type not in ("completed", "failed"): |
| 275 | raise ValidationError( |
| 276 | f"Tool {slug} returned an execute response without a known result_type" |
| 277 | ) |
| 278 | return _session_execute_result( |
| 279 | {**dict(executed), "hook_results": hook_results_of(executed.hook_results)}, |
| 280 | executed.model_fields_set, |
| 281 | ) |
| 282 | |
| 283 | |
| 284 | def is_execution_successful(result_type: t.Optional[str]) -> bool: |
| 285 | """Whether a session tool execution succeeded. |
| 286 | |
| 287 | ``result_type`` decides: a ``failed`` execution is not successful even when |
| 288 | its ``error`` is ``None`` or empty. The TypeScript SDK applies the same rule. |
| 289 | """ |
| 290 | return result_type == "completed" |
| 291 | |
| 292 | |
| 293 | class InstantCharge(te.TypedDict): |
| 294 | """Instant usage charge reported for a Session tool execution.""" |
| 295 | |
| 296 | amount: str |
| 297 | """Exact non-negative USD decimal string, e.g. ``"0.01"``.""" |
| 298 | currency: str |
| 299 | charged_by: str |
| 300 | |
| 301 | |
| 302 | class ToolExecutionResponse(te.TypedDict): |
| 303 | """Dictionary returned by direct tools and provider execution adapters. |
| 304 | |
| 305 | Read ``successful``, not ``error`` or the presence of a log ID. Session |
| 306 | adapters derive it from ``result_type == "completed"`` and retain the |
| 307 | session's ``result_type`` and ``log_id``. This is not a provider message; |
| 308 | serialize it with ``json.dumps`` when building message content. |
| 309 | """ |
| 310 | |
| 311 | data: t.Dict |
| 312 | error: t.Optional[str] |
| 313 | successful: bool |
| 314 | log_id: te.NotRequired[str] |
| 315 | result_type: te.NotRequired[str] |
| 316 | instant_charge: te.NotRequired[InstantCharge] |
| 317 | """Present only when the Session sets |
| 318 | ``instant.return_instant_charge`` and a charge is available.""" |
| 319 | |
| 320 | |
| 321 | def tool_execution_response_from_session( |
| 322 | response: ToolRouterSessionExecuteResponse, |
| 323 | ) -> ToolExecutionResponse: |
| 324 | """Adapt a validated session result without losing its outcome or log ID.""" |
| 325 | result: ToolExecutionResponse = { |
| 326 | "data": response.data if hasattr(response, "data") else {}, |
| 327 | "error": response.error if hasattr(response, "error") else None, |
| 328 | "successful": is_execution_successful(response.result_type), |
| 329 | "log_id": response.log_id, |
| 330 | "result_type": t.cast(str, response.result_type), |
| 331 | } |
| 332 | instant_charge = getattr(response, "instant_charge", None) |
| 333 | if isinstance(instant_charge, PydanticBaseModel): |
| 334 | result["instant_charge"] = t.cast(InstantCharge, instant_charge.model_dump()) |
| 335 | return result |
| 336 | |
| 337 | |
| 338 | class Tools(Resource, t.Generic[TTool, TToolCollection]): |
| 339 | """ |
| 340 | Tools class definition |
| 341 | |
| 342 | This class is used to manage tools in the Composio SDK. |
| 343 | It provides methods to list, get, and execute tools. |
| 344 | |
| 345 | Generic Parameters: |
| 346 | TTool: The individual tool type returned by the provider (e.g., ChatCompletionToolParam for OpenAI). |
| 347 | TToolCollection: The collection type returned by get() (e.g., list[ChatCompletionToolParam]). |
| 348 | |
| 349 | The return type of get() is automatically inferred from the provider's generic parameters. |
| 350 | This works for both built-in providers (OpenAI, Anthropic, etc.) and custom providers. |
| 351 | """ |
| 352 | |
| 353 | provider: BaseProvider[TTool, TToolCollection] |
| 354 | |
| 355 | def __init__( |
| 356 | self, |
| 357 | client: HttpClient, |
| 358 | provider: BaseProvider[TTool, TToolCollection], |
| 359 | file_download_dir: t.Optional[str] = None, |
| 360 | toolkit_versions: t.Optional[ToolkitVersionParam] = None, |
| 361 | dangerously_allow_auto_upload_download_files: bool = False, |
| 362 | sensitive_file_upload_protection: bool = True, |
| 363 | file_upload_path_deny_segments: t.Optional[t.Sequence[str]] = None, |
| 364 | file_upload_dirs: t.Union[t.Sequence[str], t.Literal[False], None] = None, |
| 365 | ): |
| 366 | """ |
| 367 | Initialize the tools resource. |
| 368 | |
| 369 | :param client: The client to use for the tools resource. |
| 370 | :param provider: The provider to use for the tools resource. |
| 371 | :param file_download_dir: Output directory for downloadable files |
| 372 | :param toolkit_versions: The versions of the toolkits to use. Defaults to 'latest' if not provided. |
| 373 | :param dangerously_allow_auto_upload_download_files: Opt-in for automatic file upload/download. Defaults to False. |
| 374 | :param sensitive_file_upload_protection: When True, block local paths on the built-in sensitive-path denylist before upload. |
| 375 | :param file_upload_path_deny_segments: Extra path segment names to merge with the built-in denylist. |
| 376 | :param file_upload_dirs: Allowlist of directories from which local files may |
| 377 | be auto-uploaded. Only consulted when |
| 378 | ``dangerously_allow_auto_upload_download_files=True``. See Composio docs |
| 379 | for details. |
| 380 | """ |
| 381 | self._auto_upload_download_files = bool( |
| 382 | dangerously_allow_auto_upload_download_files |
| 383 | ) |
| 384 | # Resolve allowlist once, but only if auto-upload is enabled. When it's |
| 385 | # disabled there's no auto-upload code path, so we pass ``None`` and |
| 386 | # FileHelper won't run the allowlist check either way. Manual APIs (if |
| 387 | # ever added in the future) should also pass ``None``. |
| 388 | resolved_allowlist: t.Optional[t.List[Path]] = ( |
| 389 | resolve_effective_upload_allowlist(file_upload_dirs) |
| 390 | if self._auto_upload_download_files |
| 391 | else None |
| 392 | ) |
| 393 | |
| 394 | self._client = client |
| 395 | self._tool_schemas: t.Dict[str, Tool] = {} |
| 396 | self._file_helper = FileHelper( |
| 397 | client=self._client, |
| 398 | outdir=file_download_dir, |
| 399 | sensitive_file_upload_protection=sensitive_file_upload_protection, |
| 400 | file_upload_path_deny_segments=file_upload_path_deny_segments, |
| 401 | file_upload_allowlist=resolved_allowlist, |
| 402 | ) |
| 403 | self._toolkit_versions = toolkit_versions |
| 404 | |
| 405 | self.provider = provider |
| 406 | |
| 407 | self.provider.set_execute_tool_fn( |
| 408 | t.cast( |
| 409 | ExecuteToolFn, |
| 410 | functools.partial( |
| 411 | self.execute, |
| 412 | # Dangerously skip version check for provider controlled tool execution |
| 413 | dangerously_skip_version_check=True, |
| 414 | ), |
| 415 | ), |
| 416 | ) |
| 417 | |
| 418 | def get_raw_composio_tool_by_slug(self, slug: str) -> Tool: |
| 419 | """ |
| 420 | Returns schema for the given tool slug. |
| 421 | |
| 422 | :raises ToolNotFoundError: when the backend reports the slug as unknown |
| 423 | (404, or 400 for a malformed slug). Any other client error, such as |
| 424 | an invalid API key, is re-raised unchanged. |
| 425 | """ |
| 426 | try: |
| 427 | response = self._client.tools.retrieve( |
| 428 | tool_slug=slug, |
| 429 | toolkit_versions=none_to_omit(self._toolkit_versions), |
| 430 | ) |
| 431 | except APIStatusError as error: |
| 432 | if error.status_code in (400, 404): |
| 433 | message = f"Tool with slug {slug} not found" |
| 434 | if error.details is not None: |
| 435 | message = ( |
| 436 | f"{message}: {sanitize_error_text(error.details['message'])}" |
| 437 | ) |
| 438 | raise ToolNotFoundError(message) from error |
| 439 | raise |
| 440 | return _normalize_tool(response) |
| 441 | |
| 442 | def get_raw_composio_tools( |
| 443 | self, |
| 444 | tools: t.Optional[list[str]] = None, |
| 445 | search: t.Optional[str] = None, |
| 446 | toolkits: t.Optional[list[str]] = None, |
| 447 | scopes: t.Optional[t.List[str]] = None, |
| 448 | limit: t.Optional[int] = None, |
| 449 | ) -> list[Tool]: |
| 450 | """ |
| 451 | Get a list of tool schemas based on the provided filters. |
| 452 | """ |
| 453 | if tools is None and search is None and toolkits is None: |
| 454 | raise InvalidParams( |
| 455 | "Either `tools`, `search`, or `toolkits` must be provided" |
| 456 | ) |
| 457 | |
| 458 | tools_list = [] |
| 459 | if tools is not None: |
| 460 | if len(tools): |
| 461 | tools_list.extend( |
| 462 | self._client.tools.list( |
| 463 | tool_slugs=",".join(tools), |
| 464 | toolkit_versions=none_to_omit(self._toolkit_versions), |
| 465 | ).items |
| 466 | ) |
| 467 | |
| 468 | # Search tools by toolkit slugs and search term |
| 469 | if toolkits is not None or search is not None: |
| 470 | tools_list.extend( |
| 471 | self._client.tools.list( |
| 472 | toolkit_slug=none_to_omit(",".join(toolkits) if toolkits else None), |
| 473 | query=none_to_omit(search), |
| 474 | scopes=scopes, |
| 475 | limit=limit, |
| 476 | toolkit_versions=none_to_omit(self._toolkit_versions), |
| 477 | ).items |
| 478 | ) |
| 479 | return [_normalize_tool(tool) for tool in tools_list] |
| 480 | |
| 481 | def get_raw_tool_router_meta_tools( |
| 482 | self, |
| 483 | session_id: str, |
| 484 | modifiers: t.Optional["Modifiers"] = None, |
| 485 | ) -> list[Tool]: |
| 486 | """ |
| 487 | Fetches the tools exposed by a tool router session. |
| 488 | |
| 489 | This method fetches helper/meta tools and any preloaded app tools from the |
| 490 | Composio API and transforms them to the expected format. It provides access |
| 491 | to the underlying tool data without provider-specific wrapping. |
| 492 | |
| 493 | :param session_id: The session ID to get the meta tools for |
| 494 | :param modifiers: Optional modifiers to apply to the tool schemas |
| 495 | :return: The list of meta tools |
| 496 | |
| 497 | Example: |
| 498 | ```python |
| 499 | from composio import Composio |
| 500 | |
| 501 | composio = Composio() |
| 502 | tools_model = composio.tools |
| 503 | |
| 504 | # Get meta tools for a session |
| 505 | meta_tools = tools_model.get_raw_tool_router_meta_tools("session_123") |
| 506 | print(meta_tools) |
| 507 | |
| 508 | # Get meta tools with schema modifiers |
| 509 | from composio.core.models import schema_modifier |
| 510 | |
| 511 | @schema_modifier |
| 512 | def modify_schema(tool: str, toolkit: str, schema): |
| 513 | # Customize the schema |
| 514 | schema.description = f"Modified: {schema.description}" |
| 515 | return schema |
| 516 | |
| 517 | meta_tools = tools_model.get_raw_tool_router_meta_tools( |
| 518 | "session_123", |
| 519 | modifiers=[modify_schema] |
| 520 | ) |
| 521 | ``` |
| 522 | """ |
| 523 | # Fetch session tools from the API |
| 524 | tools_list: t.List[Tool] = [] |
| 525 | cursor: t.Optional[str] = None |
| 526 | |
| 527 | while True: |
| 528 | tools_response = self._client.tool_router.session.tools( |
| 529 | session_id=session_id, |
| 530 | cursor=none_to_omit(cursor), |
| 531 | limit=TOOL_ROUTER_SESSION_TOOLS_PAGE_LIMIT, |
| 532 | ) |
| 533 | tools_list.extend(_normalize_tool(item) for item in tools_response.items) |
| 534 | |
| 535 | cursor = getattr(tools_response, "next_cursor", None) |
| 536 | if not cursor: |
| 537 | break |
| 538 | |
| 539 | self._tool_schemas.update( |
| 540 | {tool.slug: tool.model_copy(deep=True) for tool in tools_list} |
| 541 | ) |
| 542 | |
| 543 | tools_list = [tool.model_copy(deep=True) for tool in tools_list] |
| 544 | |
| 545 | # Apply schema modifiers if provided |
| 546 | if modifiers is not None: |
| 547 | from composio.core.models._modifiers import apply_modifier_by_type |
| 548 | |
| 549 | tools_list = [ |
| 550 | t.cast( |
| 551 | Tool, |
| 552 | apply_modifier_by_type( |
| 553 | modifiers=modifiers, |
| 554 | toolkit=_toolkit_slug(tool, "unknown"), |
| 555 | tool=tool.slug, |
| 556 | type="schema", |
| 557 | schema=tool, |
| 558 | ), |
| 559 | ) |
| 560 | for tool in tools_list |
| 561 | ] |
| 562 | |
| 563 | return tools_list |
| 564 | |
| 565 | def _get( |
| 566 | self, |
| 567 | user_id: str, |
| 568 | tools: t.Optional[list[str]] = None, |
| 569 | search: t.Optional[str] = None, |
| 570 | toolkits: t.Optional[list[str]] = None, |
| 571 | scopes: t.Optional[t.List[str]] = None, |
| 572 | modifiers: t.Optional[Modifiers] = None, |
| 573 | limit: t.Optional[int] = None, |
| 574 | ) -> TToolCollection: |
| 575 | """Get a list of tools based on the provided filters.""" |
| 576 | raw_tools = self.get_raw_composio_tools( |
| 577 | tools=tools, |
| 578 | search=search, |
| 579 | toolkits=toolkits, |
| 580 | scopes=scopes, |
| 581 | limit=limit, |
| 582 | ) |
| 583 | self._tool_schemas.update( |
| 584 | {tool.slug: tool.model_copy(deep=True) for tool in raw_tools} |
| 585 | ) |
| 586 | |
| 587 | tools_list = [tool.model_copy(deep=True) for tool in raw_tools] |
| 588 | if modifiers is not None: |
| 589 | tools_list = [ |
| 590 | apply_modifier_by_type( |
| 591 | modifiers=modifiers, |
| 592 | toolkit=_toolkit_slug(tool, "unknown"), |
| 593 | tool=tool.slug, |
| 594 | type="schema", |
| 595 | schema=tool, |
| 596 | ) |
| 597 | for tool in tools_list |
| 598 | ] |
| 599 | |
| 600 | # Always enhance schema descriptions (type hints and required notes) |
| 601 | # regardless of dangerously_allow_auto_upload_download_files |
| 602 | for tool in tools_list: |
| 603 | tool.input_parameters = self._file_helper.enhance_schema_descriptions( |
| 604 | schema=tool.input_parameters, |
| 605 | ) |
| 606 | |
| 607 | # Only process file_uploadable schemas when the caller opted in via |
| 608 | # `dangerously_allow_auto_upload_download_files=True`. |
| 609 | if self._auto_upload_download_files: |
| 610 | for tool in tools_list: |
| 611 | tool.input_parameters = ( |
| 612 | self._file_helper.process_file_uploadable_schema( |
| 613 | schema=tool.input_parameters, |
| 614 | ) |
| 615 | ) |
| 616 | |
| 617 | if issubclass(type(self.provider), NonAgenticProvider): |
| 618 | return t.cast( |
| 619 | TToolCollection, |
| 620 | t.cast( |
| 621 | NonAgenticProvider[TTool, TToolCollection], self.provider |
| 622 | ).wrap_tools(tools=tools_list), |
| 623 | ) |
| 624 | |
| 625 | return t.cast( |
| 626 | TToolCollection, |
| 627 | t.cast(AgenticProvider[TTool, TToolCollection], self.provider).wrap_tools( |
| 628 | tools=tools_list, |
| 629 | execute_tool=self._wrap_execute_tool( |
| 630 | user_id=user_id, |
| 631 | modifiers=modifiers, |
| 632 | ), |
| 633 | ), |
| 634 | ) |
| 635 | |
| 636 | def get( |
| 637 | self, |
| 638 | user_id: str, |
| 639 | *, |
| 640 | slug: t.Optional[str] = None, |
| 641 | tools: t.Optional[list[str]] = None, |
| 642 | search: t.Optional[str] = None, |
| 643 | toolkits: t.Optional[list[str]] = None, |
| 644 | scopes: t.Optional[t.List[str]] = None, |
| 645 | modifiers: t.Optional[Modifiers] = None, |
| 646 | limit: t.Optional[int] = None, |
| 647 | ) -> TToolCollection: |
| 648 | """ |
| 649 | Get a tool or list of tools based on the provided arguments. |
| 650 | |
| 651 | The return type is automatically inferred based on the provider's generic parameters. |
| 652 | For example: |
| 653 | - OpenAIProvider -> list[ChatCompletionToolParam] |
| 654 | - AnthropicProvider -> list[ToolParam] |
| 655 | - CustomProvider[MyTool, list[MyTool]] -> list[MyTool] |
| 656 | |
| 657 | :param user_id: The user ID to get tools for. |
| 658 | :param slug: Get a single tool by slug. |
| 659 | :param tools: Get tools by a list of tool slugs. |
| 660 | :param search: Search tools by search term. |
| 661 | :param toolkits: Get tools from specific toolkits. |
| 662 | :param scopes: Filter by scopes. |
| 663 | :param modifiers: Optional modifiers to apply. |
| 664 | :param limit: Limit the number of tools returned. |
| 665 | :return: Provider-specific tool collection (TToolCollection). |
| 666 | """ |
| 667 | if slug is not None: |
| 668 | return self._get( |
| 669 | user_id=user_id, |
| 670 | tools=[slug], |
| 671 | modifiers=modifiers, |
| 672 | ) |
| 673 | return self._get( |
| 674 | user_id=user_id, |
| 675 | tools=tools, |
| 676 | search=search, |
| 677 | toolkits=toolkits, |
| 678 | scopes=scopes, |
| 679 | modifiers=modifiers, |
| 680 | limit=limit, |
| 681 | ) |
| 682 | |
| 683 | def _wrap_execute_tool( |
| 684 | self, |
| 685 | modifiers: t.Optional[Modifiers] = None, |
| 686 | user_id: t.Optional[str] = None, |
| 687 | ) -> AgenticProviderExecuteFn: |
| 688 | """Wrap the execute tool function""" |
| 689 | execute_tool = t.cast( |
| 690 | AgenticProviderExecuteFn, |
| 691 | functools.partial( |
| 692 | self.execute, |
| 693 | modifiers=modifiers, |
| 694 | user_id=user_id, |
| 695 | # Dangerously skip version check for agentic tool execution via providers |
| 696 | # This can be safe because most agentic flows users fetch latest version and then execute the tool |
| 697 | dangerously_skip_version_check=True, |
| 698 | ), |
| 699 | ) |
| 700 | if user_id is None: |
| 701 | return execute_tool |
| 702 | return bind_execution_target(execute_tool, user_id) |
| 703 | |
| 704 | def _wrap_execute_tool_for_tool_router( |
| 705 | self, |
| 706 | session_id: str, |
| 707 | modifiers: t.Optional[Modifiers] = None, |
| 708 | inline_custom_tools_payload: t.Optional[InlineCustomToolsWirePayload] = None, |
| 709 | ) -> AgenticProviderExecuteFn: |
| 710 | """ |
| 711 | Create an execute function for tool router session tools. |
| 712 | |
| 713 | This method creates a function that executes tools within a tool router session context. |
| 714 | It uses the session's execute endpoint which handles authentication and connection |
| 715 | management automatically. |
| 716 | |
| 717 | :param session_id: The session ID |
| 718 | :param modifiers: Optional modifiers to apply before and after execution |
| 719 | :return: Execute function for tool router |
| 720 | """ |
| 721 | |
| 722 | def execute_tool_fn(slug: str, arguments: t.Dict) -> t.Dict: |
| 723 | """ |
| 724 | Execute a tool in the tool router session. |
| 725 | |
| 726 | This function is used by agentic providers to execute tools within |
| 727 | a tool router session context. It uses the session's execute |
| 728 | endpoint which handles authentication and connection management |
| 729 | automatically. |
| 730 | |
| 731 | :param slug: The tool slug to execute |
| 732 | :param arguments: The tool arguments |
| 733 | :return: Tool execution response |
| 734 | """ |
| 735 | tool = self._tool_schemas.get(slug) |
| 736 | |
| 737 | if tool is None: |
| 738 | tool = self.get_raw_composio_tool_by_slug(slug) |
| 739 | self._tool_schemas[slug] = tool |
| 740 | |
| 741 | if self._auto_upload_download_files: |
| 742 | meta_tk = _toolkit_slug(tool, "composio") |
| 743 | bfu = merge_before_file_upload( |
| 744 | modifiers, |
| 745 | tool=slug, |
| 746 | toolkit=meta_tk, |
| 747 | ) |
| 748 | arguments = self._file_helper.substitute_file_uploads( |
| 749 | tool=tool, |
| 750 | request=arguments, |
| 751 | before_file_upload=bfu, |
| 752 | ) |
| 753 | else: |
| 754 | arguments = self._file_helper.drop_empty_file_uploads( |
| 755 | tool=tool, request=arguments |
| 756 | ) |
| 757 | |
| 758 | toolkit_slug = _toolkit_slug(tool, "composio") |
| 759 | |
| 760 | # Apply before_execute modifiers |
| 761 | processed_arguments = arguments |
| 762 | if modifiers is not None: |
| 763 | params: ToolExecuteParams = { |
| 764 | "arguments": arguments, |
| 765 | } |
| 766 | type_before: t.Literal["before_execute"] = "before_execute" |
| 767 | modified_params = apply_modifier_by_type( |
| 768 | modifiers=modifiers, |
| 769 | toolkit=toolkit_slug, |
| 770 | tool=slug, |
| 771 | type=type_before, |
| 772 | request=params, |
| 773 | ) |
| 774 | processed_arguments = modified_params.get("arguments", arguments) |
| 775 | |
| 776 | # Serialize any Pydantic model instances before sending to the API |
| 777 | processed_arguments = _serialize_arguments(processed_arguments) |
| 778 | |
| 779 | # Disable retries: a session execution is a non-idempotent write, and a |
| 780 | # silent retry after a read timeout can duplicate the side effect. |
| 781 | response = require_execute_result( |
| 782 | self._client.without_retries.tool_router.session.execute( |
| 783 | session_id=session_id, |
| 784 | tool_slug=slug, |
| 785 | arguments=processed_arguments, |
| 786 | # Provider-wrapped session tools are agentic calls, so they opt into |
| 787 | # direct tool offload when the backend session workbench allows it. |
| 788 | enable_auto_workbench_offload=True, |
| 789 | experimental=inline_custom_tools_payload |
| 790 | if inline_custom_tools_payload is not None |
| 791 | else omit, |
| 792 | ), |
| 793 | slug, |
| 794 | ) |
| 795 | |
| 796 | result = tool_execution_response_from_session(response) |
| 797 | |
| 798 | # Apply after_execute modifiers |
| 799 | if modifiers is not None: |
| 800 | type_after: t.Literal["after_execute"] = "after_execute" |
| 801 | result = apply_modifier_by_type( |
| 802 | modifiers=modifiers, |
| 803 | toolkit=toolkit_slug, |
| 804 | tool=slug, |
| 805 | type=type_after, |
| 806 | response=result, |
| 807 | ) |
| 808 | |
| 809 | return t.cast(t.Dict, result) |
| 810 | |
| 811 | return t.cast(AgenticProviderExecuteFn, execute_tool_fn) |
| 812 | |
| 813 | def _execute_tool( |
| 814 | self, |
| 815 | slug: str, |
| 816 | arguments: t.Dict, |
| 817 | tool: Tool, |
| 818 | connected_account_id: t.Optional[str] = None, |
| 819 | custom_auth_params: t.Optional[tool_execute_params.CustomAuthParams] = None, |
| 820 | custom_connection_data: t.Optional[ |
| 821 | tool_execute_params.CustomConnectionData |
| 822 | ] = None, |
| 823 | user_id: t.Optional[str] = None, |
| 824 | text: t.Optional[str] = None, |
| 825 | version: t.Optional[str] = None, |
| 826 | dangerously_skip_version_check: t.Optional[bool] = None, |
| 827 | ) -> ToolExecutionResponse: |
| 828 | """Execute a tool""" |
| 829 | # Serialize any Pydantic model instances in arguments to plain dicts |
| 830 | # before sending to the API (fixes PLEN-1514: RootModel not JSON serializable) |
| 831 | arguments = _serialize_arguments(arguments) |
| 832 | |
| 833 | # If version is not explicitly provided, resolve it from instance-level toolkit versions |
| 834 | # This matches the TypeScript behavior - always resolve version when None |
| 835 | if version is None: |
| 836 | toolkit_slug = _toolkit_slug(tool, "unknown") |
| 837 | # Use instance-level toolkit versions configuration |
| 838 | version = get_toolkit_version(toolkit_slug, self._toolkit_versions) |
| 839 | |
| 840 | # Check if the version is 'latest' and dangerously_skip_version_check is not True |
| 841 | # If so, raise an error to prevent unexpected behavior |
| 842 | if version == "latest" and not dangerously_skip_version_check: |
| 843 | raise ToolVersionRequiredError() |
| 844 | |
| 845 | return t.cast( |
| 846 | ToolExecutionResponse, |
| 847 | # Disable retries: tool execution is a non-idempotent write, and a |
| 848 | # silent retry after a read timeout can duplicate the side effect. |
| 849 | self._client.without_retries.tools.execute( |
| 850 | tool_slug=slug, |
| 851 | arguments=arguments, |
| 852 | connected_account_id=none_to_omit(connected_account_id), |
| 853 | custom_auth_params=none_to_omit(custom_auth_params), |
| 854 | custom_connection_data=none_to_omit(custom_connection_data), |
| 855 | user_id=none_to_omit(user_id), |
| 856 | text=none_to_omit(text), |
| 857 | version=none_to_omit(version), |
| 858 | ).model_dump( |
| 859 | exclude={ |
| 860 | "log_id", |
| 861 | "session_info", |
| 862 | } |
| 863 | ), |
| 864 | ) |
| 865 | |
| 866 | def execute( |
| 867 | self, |
| 868 | slug: str, |
| 869 | arguments: t.Dict, |
| 870 | *, |
| 871 | connected_account_id: t.Optional[str] = None, |
| 872 | custom_auth_params: t.Optional[tool_execute_params.CustomAuthParams] = None, |
| 873 | custom_connection_data: t.Optional[ |
| 874 | tool_execute_params.CustomConnectionData |
| 875 | ] = None, |
| 876 | user_id: t.Optional[str] = None, |
| 877 | text: t.Optional[str] = None, |
| 878 | version: t.Optional[str] = None, |
| 879 | dangerously_skip_version_check: t.Optional[bool] = None, |
| 880 | modifiers: t.Optional[Modifiers] = None, |
| 881 | ) -> ToolExecutionResponse: |
| 882 | """ |
| 883 | Execute a tool with the provided parameters. |
| 884 | |
| 885 | This method calls the Composio API to execute the tool and returns the response. |
| 886 | |
| 887 | :param slug: The slug of the tool to execute. |
| 888 | :param arguments: The arguments to pass to the tool. |
| 889 | :param connected_account_id: The connected account ID, or ``instant_account`` |
| 890 | to explicitly use the Composio Instant account. |
| 891 | :param custom_auth_params: The custom auth params to use for the tool. |
| 892 | :param custom_connection_data: The custom connection data to use for the tool, takes priority over custom_auth_params. |
| 893 | :param user_id: The ID of the user to execute the tool for. |
| 894 | :param text: The text to pass to the tool. |
| 895 | :param version: The version of the tool to execute (overrides the SDK-level toolkit versions for this execution). |
| 896 | :param dangerously_skip_version_check: Skip the version check for 'latest' version. This might cause unexpected behavior when new versions are released. |
| 897 | :param modifiers: The modifiers to apply to the tool (include ``@before_file_upload`` for file path hooks). |
| 898 | :return: The response from the tool. |
| 899 | """ |
| 900 | |
| 901 | tool = self._tool_schemas.get(slug) |
| 902 | |
| 903 | if tool is None: |
| 904 | tool = self.get_raw_composio_tool_by_slug(slug) |
| 905 | self._tool_schemas[slug] = tool |
| 906 | |
| 907 | if self._auto_upload_download_files: |
| 908 | tk = _toolkit_slug(tool, "unknown") |
| 909 | bfu = merge_before_file_upload( |
| 910 | modifiers, |
| 911 | tool=slug, |
| 912 | toolkit=tk, |
| 913 | ) |
| 914 | arguments = self._file_helper.substitute_file_uploads( |
| 915 | tool=tool, |
| 916 | request=arguments, |
| 917 | before_file_upload=bfu, |
| 918 | ) |
| 919 | else: |
| 920 | # Auto-upload is opt-in, but "no file" must still be sent as an |
| 921 | # omitted key rather than ``""`` (issue #4233). Explicit ``None`` |
| 922 | # remains valid for nullable file inputs. |
| 923 | arguments = self._file_helper.drop_empty_file_uploads( |
| 924 | tool=tool, request=arguments |
| 925 | ) |
| 926 | |
| 927 | if modifiers is not None: |
| 928 | type_before_exec: t.Literal["before_execute"] = "before_execute" |
| 929 | request_params: ToolExecuteParams = { |
| 930 | "arguments": arguments, |
| 931 | } |
| 932 | if connected_account_id is not None: |
| 933 | request_params["connected_account_id"] = connected_account_id |
| 934 | if custom_auth_params is not None: |
| 935 | request_params["custom_auth_params"] = custom_auth_params |
| 936 | if custom_connection_data is not None: |
| 937 | request_params["custom_connection_data"] = custom_connection_data |
| 938 | if version is not None: |
| 939 | request_params["version"] = version |
| 940 | if text is not None: |
| 941 | request_params["text"] = text |
| 942 | if user_id is not None: |
| 943 | request_params["user_id"] = user_id |
| 944 | if dangerously_skip_version_check is not None: |
| 945 | request_params["dangerously_skip_version_check"] = ( |
| 946 | dangerously_skip_version_check |
| 947 | ) |
| 948 | processed_params = apply_modifier_by_type( |
| 949 | modifiers=modifiers, |
| 950 | toolkit=_toolkit_slug(tool, "unknown"), |
| 951 | tool=slug, |
| 952 | type=type_before_exec, |
| 953 | request=request_params, |
| 954 | ) |
| 955 | connected_account_id = processed_params.get( |
| 956 | "connected_account_id", connected_account_id |
| 957 | ) |
| 958 | custom_auth_params = processed_params.get( |
| 959 | "custom_auth_params", custom_auth_params |
| 960 | ) |
| 961 | custom_connection_data = processed_params.get( |
| 962 | "custom_connection_data", custom_connection_data |
| 963 | ) |
| 964 | text = processed_params.get("text", text) |
| 965 | version = processed_params.get("version", version) |
| 966 | user_id = processed_params.get("user_id", user_id) |
| 967 | arguments = processed_params["arguments"] |
| 968 | dangerously_skip_version_check = processed_params.get( |
| 969 | "dangerously_skip_version_check", dangerously_skip_version_check |
| 970 | ) |
| 971 | response = self._execute_tool( |
| 972 | slug=slug, |
| 973 | arguments=arguments, |
| 974 | tool=tool, |
| 975 | connected_account_id=connected_account_id, |
| 976 | custom_auth_params=custom_auth_params, |
| 977 | custom_connection_data=custom_connection_data, |
| 978 | user_id=user_id, |
| 979 | text=text, |
| 980 | version=version, |
| 981 | dangerously_skip_version_check=dangerously_skip_version_check, |
| 982 | ) |
| 983 | if self._auto_upload_download_files: |
| 984 | response = self._file_helper.substitute_file_downloads( |
| 985 | tool=tool, |
| 986 | response=response, |
| 987 | ) |
| 988 | if modifiers is not None: |
| 989 | response = apply_modifier_by_type( |
| 990 | modifiers=modifiers, |
| 991 | toolkit=_toolkit_slug(tool, "unknown"), |
| 992 | tool=slug, |
| 993 | type="after_execute", |
| 994 | response=response, |
| 995 | ) |
| 996 | return response |
| 997 | |
| 998 | def proxy( |
| 999 | self, |
| 1000 | endpoint: str, |
| 1001 | method: t.Literal["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD"], |
| 1002 | body: t.Optional[object] = None, |
| 1003 | connected_account_id: t.Optional[str] = None, |
| 1004 | parameters: t.Optional[t.List[tool_proxy_params.Parameter]] = None, |
| 1005 | custom_connection_data: t.Optional[ |
| 1006 | tool_proxy_params.CustomConnectionData |
| 1007 | ] = None, |
| 1008 | user_id: t.Optional[str] = None, |
| 1009 | ) -> tool_proxy_response.ToolProxyResponse: |
| 1010 | """Proxy a tool call to the Composio API. |
| 1011 | |
| 1012 | ``user_id`` is the user the connected account belongs to. Projects with |
| 1013 | 2FA enabled check it against the connected account and may require it. |
| 1014 | """ |
| 1015 | # Disable retries: a proxied call is a non-idempotent write, and a silent |
| 1016 | # retry after a read timeout can duplicate the side effect. |
| 1017 | return self._client.without_retries.tools.proxy( |
| 1018 | endpoint=endpoint, |
| 1019 | method=method, |
| 1020 | body=body if body is not None else omit, |
| 1021 | connected_account_id=connected_account_id |
| 1022 | if connected_account_id is not None |
| 1023 | else omit, |
| 1024 | parameters=parameters if parameters is not None else omit, |
| 1025 | custom_connection_data=custom_connection_data |
| 1026 | if custom_connection_data is not None |
| 1027 | else omit, |
| 1028 | user_id=user_id if user_id is not None else omit, |
| 1029 | ) |
| 1030 | |
| 1031 | |
| 1032 | __all__ = [ |
| 1033 | "Tools", |
| 1034 | "InstantCharge", |
| 1035 | "ToolExecuteParams", |
| 1036 | "ToolExecutionResponse", |
| 1037 | "Modifiers", |
| 1038 | "after_execute", |
| 1039 | "before_execute", |
| 1040 | "before_file_upload", |
| 1041 | "schema_modifier", |
| 1042 | ] |