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 | """ |
| 2 | ToolRouter class for managing tool router sessions. |
| 3 | |
| 4 | This module provides tool routing session management with enhanced functionality |
| 5 | for creating isolated MCP sessions with provider-wrapped tools. |
| 6 | """ |
| 7 | |
| 8 | from __future__ import annotations |
| 9 | |
| 10 | import logging |
| 11 | import typing as t |
| 12 | import warnings |
| 13 | from dataclasses import dataclass |
| 14 | from enum import Enum |
| 15 | from urllib.parse import urlsplit |
| 16 | |
| 17 | import typing_extensions as te |
| 18 | from composio_client import omit |
| 19 | from composio_client.types.tool_router import session_create_params |
| 20 | from composio_client.types.tool_router.session_attach_response import ( |
| 21 | SessionAttachResponse, |
| 22 | ) |
| 23 | from composio_client.types.tool_router.session_retrieve_response import ( |
| 24 | SessionRetrieveResponse, |
| 25 | ) |
| 26 | |
| 27 | from composio.client import HttpClient |
| 28 | from composio.core.models.base import Resource, credential_headers, scope_headers |
| 29 | from composio.core.models.custom_tool import ( |
| 30 | ExperimentalToolkit, |
| 31 | LocalToolkit, |
| 32 | assert_no_custom_tool_slugs_in_preload, |
| 33 | build_custom_tools_map, |
| 34 | build_custom_tools_map_from_response, |
| 35 | get_preloaded_custom_tool_slugs, |
| 36 | serialize_custom_toolkits, |
| 37 | serialize_custom_tools, |
| 38 | ) |
| 39 | from composio.core.models.custom_tool_types import ( |
| 40 | CustomTool, |
| 41 | CustomToolsMap, |
| 42 | InlineCustomToolsWirePayload, |
| 43 | LocalTool, |
| 44 | ) |
| 45 | from composio.core.models.tool_router_constants import ( |
| 46 | PRELOAD_TOOLS_ALL, |
| 47 | SESSION_PRESET_DIRECT_TOOLS, |
| 48 | ) |
| 49 | from composio.core.models.tool_router_session import ( |
| 50 | ToolRouterHook, |
| 51 | ToolRouterInstantConfig, |
| 52 | ToolRouterProxyExecuteConfig, |
| 53 | ToolRouterSession, |
| 54 | ToolRouterSessionConfig, |
| 55 | ToolRouterSessionPreloadConfig, |
| 56 | ToolRouterSessionWithMcp, |
| 57 | ToolRouterUpdateExperimentalConfig, |
| 58 | ToolRouterUpdateManageConnectionsConfig, |
| 59 | ToolRouterUpdateMultiAccountConfig, |
| 60 | ) |
| 61 | from composio.core.models.tool_router_session_delete import ( |
| 62 | ToolRouterSessionDeleteResponse, |
| 63 | delete_tool_router_session, |
| 64 | ) |
| 65 | from composio.core.models.tool_router_session_files import ToolRouterSessionFilesMount |
| 66 | from composio.core.provider import TTool, TToolCollection |
| 67 | from composio.core.provider.base import BaseProvider |
| 68 | from composio.exceptions import ( |
| 69 | ComposioDeprecationWarning, |
| 70 | InvalidParams, |
| 71 | MCPDestinationError, |
| 72 | ) |
| 73 | |
| 74 | logger = logging.getLogger(__name__) |
| 75 | |
| 76 | _DEFAULT_PORTS = {"http": 80, "https": 443} |
| 77 | |
| 78 | # Schemes whose URLs have a tuple origin (``scheme://host[:port]``) under the |
| 79 | # WHATWG URL standard. Every other scheme (``data:``, ``file:``, ``blob:`` |
| 80 | # without a base, ...) has an opaque origin that serializes as ``null``, so two |
| 81 | # such URLs would compare equal; they are rejected before any comparison. |
| 82 | _TUPLE_ORIGIN_SCHEMES = frozenset({"ftp", "http", "https", "ws", "wss"}) |
| 83 | |
| 84 | |
| 85 | def _origin(url: str, role: str) -> str: |
| 86 | """Return the origin of an absolute URL. |
| 87 | |
| 88 | The origin is ``scheme://host[:port]`` in lowercase with the scheme's |
| 89 | default port dropped, matching the WHATWG ``URL.origin`` used by the |
| 90 | TypeScript SDK. ``role`` names the URL in the error; the URL itself is |
| 91 | never echoed, since it may carry a query token. |
| 92 | """ |
| 93 | parts = urlsplit(url) |
| 94 | try: |
| 95 | port = parts.port |
| 96 | except ValueError as exc: |
| 97 | raise MCPDestinationError( |
| 98 | f"The {role} is not a valid absolute URL", mcp_origin="", api_origin="" |
| 99 | ) from exc |
| 100 | if not parts.scheme: |
| 101 | raise MCPDestinationError( |
| 102 | f"The {role} is not a valid absolute URL", mcp_origin="", api_origin="" |
| 103 | ) |
| 104 | if parts.scheme.lower() not in _TUPLE_ORIGIN_SCHEMES: |
| 105 | raise MCPDestinationError( |
| 106 | f"The {role} has an opaque origin", mcp_origin="", api_origin="" |
| 107 | ) |
| 108 | if not parts.hostname: |
| 109 | raise MCPDestinationError( |
| 110 | f"The {role} is not a valid absolute URL", mcp_origin="", api_origin="" |
| 111 | ) |
| 112 | scheme = parts.scheme.lower() |
| 113 | hostname = parts.hostname.lower() |
| 114 | host = f"[{hostname}]" if ":" in hostname else hostname |
| 115 | if port is not None and port != _DEFAULT_PORTS.get(scheme): |
| 116 | host = f"{host}:{port}" |
| 117 | return f"{scheme}://{host}" |
| 118 | |
| 119 | |
| 120 | # Type alias for MCP tag literals |
| 121 | ToolRouterTag = t.Literal[ |
| 122 | "readOnlyHint", |
| 123 | "createHint", |
| 124 | "updateHint", |
| 125 | "destructiveHint", |
| 126 | "idempotentHint", |
| 127 | "openWorldHint", |
| 128 | ] |
| 129 | |
| 130 | # Type alias for sandbox compute tier on the session sandbox |
| 131 | # +----------+------+------+ |
| 132 | # | Tier | vCPU | RAM | |
| 133 | # +----------+------+------+ |
| 134 | # | standard | 1 | 1 GB | |
| 135 | # | medium | 2 | 2 GB | |
| 136 | # | large | 4 | 4 GB | |
| 137 | # | xlarge | 8 | 8 GB | |
| 138 | # +----------+------+------+ |
| 139 | # Defaults to "standard" server-side when omitted. |
| 140 | SandboxSize = t.Literal["standard", "medium", "large", "xlarge"] |
| 141 | SessionPreset = t.Literal["direct_tools"] |
| 142 | |
| 143 | |
| 144 | class ToolRouterToolkitsEnableConfig(te.TypedDict, total=False): |
| 145 | """Configuration for enabling specific toolkits in tool router session. |
| 146 | |
| 147 | Attributes: |
| 148 | enable: List of toolkit slugs to enable in the tool router session. |
| 149 | """ |
| 150 | |
| 151 | enable: t.List[str] |
| 152 | require_approval: t.List[str] |
| 153 | """Experimental. Toolkits whose tools need the user's approval before they |
| 154 | run. A call that needs approval doesn't run: ``session.execute()`` raises |
| 155 | ``ToolInputRequiredError`` with the question to show the user.""" |
| 156 | |
| 157 | |
| 158 | class ToolRouterToolkitsDisableConfig(te.TypedDict, total=False): |
| 159 | """Configuration for disabling specific toolkits in tool router session. |
| 160 | |
| 161 | Attributes: |
| 162 | disable: List of toolkit slugs to disable in the tool router session. |
| 163 | """ |
| 164 | |
| 165 | disable: t.List[str] |
| 166 | require_approval: t.List[str] |
| 167 | """Experimental. Toolkits whose tools need the user's approval before they |
| 168 | run. A call that needs approval doesn't run: ``session.execute()`` raises |
| 169 | ``ToolInputRequiredError`` with the question to show the user.""" |
| 170 | |
| 171 | |
| 172 | class ToolRouterToolkitsRequireApprovalConfig(te.TypedDict): |
| 173 | """Toolkit policy that only sets which toolkits need the user's approval.""" |
| 174 | |
| 175 | require_approval: t.List[str] |
| 176 | """Experimental. Toolkits whose tools need the user's approval before they |
| 177 | run. A call that needs approval doesn't run: ``session.execute()`` raises |
| 178 | ``ToolInputRequiredError`` with the question to show the user.""" |
| 179 | |
| 180 | |
| 181 | class ToolRouterToolsEnableConfig(te.TypedDict, total=False): |
| 182 | """Configuration for enabling specific tools for a toolkit. |
| 183 | |
| 184 | Attributes: |
| 185 | enable: List of tool slugs to enable for this toolkit. |
| 186 | """ |
| 187 | |
| 188 | enable: t.List[str] |
| 189 | require_approval: t.List[str] |
| 190 | """Experimental. Tools of this toolkit that need the user's approval |
| 191 | before they run.""" |
| 192 | |
| 193 | |
| 194 | class ToolRouterToolsDisableConfig(te.TypedDict, total=False): |
| 195 | """Configuration for disabling specific tools for a toolkit. |
| 196 | |
| 197 | Attributes: |
| 198 | disable: List of tool slugs to disable for this toolkit. |
| 199 | """ |
| 200 | |
| 201 | disable: t.List[str] |
| 202 | require_approval: t.List[str] |
| 203 | """Experimental. Tools of this toolkit that need the user's approval |
| 204 | before they run.""" |
| 205 | |
| 206 | |
| 207 | class ToolRouterToolsTagsConfig(te.TypedDict, total=False): |
| 208 | """Configuration for filtering tools by MCP tags. |
| 209 | |
| 210 | Attributes: |
| 211 | tags: Tags configuration - can be a list of tags (shorthand for enable) |
| 212 | or an object with enable/disable keys. |
| 213 | Only tools matching these tags will be available. |
| 214 | """ |
| 215 | |
| 216 | tags: ToolRouterConfigTags |
| 217 | require_approval: t.List[str] |
| 218 | """Experimental. Tools of this toolkit that need the user's approval |
| 219 | before they run.""" |
| 220 | |
| 221 | |
| 222 | class ToolRouterToolsRequireApprovalConfig(te.TypedDict): |
| 223 | """Per-toolkit tool policy that only sets which tools need the user's approval.""" |
| 224 | |
| 225 | require_approval: t.List[str] |
| 226 | """Experimental. Tools of this toolkit that need the user's approval |
| 227 | before they run.""" |
| 228 | |
| 229 | |
| 230 | # Type alias for per-toolkit tool configuration |
| 231 | # Can be: |
| 232 | # - List[str]: List of tool slugs (shorthand for enable) |
| 233 | # - ToolRouterToolsEnableConfig: Dict with 'enable' key (whitelist) |
| 234 | # - ToolRouterToolsDisableConfig: Dict with 'disable' key (blacklist) |
| 235 | # - ToolRouterToolsTagsConfig: Dict with 'tags' key (filter by MCP tags) |
| 236 | # - ToolRouterToolsRequireApprovalConfig: Dict with only 'require_approval' |
| 237 | # Each dict can also carry an experimental 'require_approval' list. |
| 238 | ToolRouterToolsConfig = t.Union[ |
| 239 | t.List[str], |
| 240 | ToolRouterToolsEnableConfig, |
| 241 | ToolRouterToolsDisableConfig, |
| 242 | ToolRouterToolsTagsConfig, |
| 243 | ToolRouterToolsRequireApprovalConfig, |
| 244 | ] |
| 245 | |
| 246 | |
| 247 | class ToolRouterTagsEnableDisableConfig(te.TypedDict, total=False): |
| 248 | """Configuration for tags in tool router session. |
| 249 | |
| 250 | Attributes: |
| 251 | enable: List of tags to enable in the tool router session. |
| 252 | disable: List of tags to disable in the tool router session. |
| 253 | """ |
| 254 | |
| 255 | enable: t.Optional[t.List[ToolRouterTag]] |
| 256 | disable: t.Optional[t.List[ToolRouterTag]] |
| 257 | require_approval: t.Optional[t.List[ToolRouterTag]] |
| 258 | """Experimental. Tools with any of these tags need the user's approval |
| 259 | before they run.""" |
| 260 | |
| 261 | |
| 262 | # Type alias for tags configuration |
| 263 | # Can be: |
| 264 | # - List[ToolRouterTag]: List of tag literals (shorthand for enable) |
| 265 | # - ToolRouterTagsEnableDisableConfig: Dict with 'enable' and/or 'disable' keys |
| 266 | ToolRouterConfigTags = t.Union[ |
| 267 | t.List[ToolRouterTag], |
| 268 | ToolRouterTagsEnableDisableConfig, |
| 269 | ] |
| 270 | |
| 271 | |
| 272 | def _is_tools_tags_config( |
| 273 | config: ToolRouterToolsConfig, |
| 274 | ) -> t.TypeGuard[ToolRouterToolsTagsConfig]: |
| 275 | """Type guard to check if config is ToolRouterToolsTagsConfig.""" |
| 276 | return isinstance(config, dict) and "tags" in config |
| 277 | |
| 278 | |
| 279 | class ToolRouterSandboxConfig(te.TypedDict, total=False): |
| 280 | """Configuration for session sandbox settings. |
| 281 | |
| 282 | Attributes: |
| 283 | enable: Whether to enable the sandbox entirely. Defaults to True. |
| 284 | When set to False, no code execution tools |
| 285 | (COMPOSIO_REMOTE_WORKBENCH, COMPOSIO_REMOTE_BASH_TOOL) are |
| 286 | available in the session, sandbox-related prompt lines are |
| 287 | stripped, and direct sandbox calls are rejected. |
| 288 | enable_proxy_execution: Whether to allow proxy execute calls in the sandbox. |
| 289 | If False, prevents arbitrary HTTP requests. |
| 290 | auto_offload_threshold: Maximum execution payload size to offload to the sandbox. |
| 291 | sandbox_size: Sandbox compute tier. One of ``"standard"`` (1 vCPU / 1 GB), |
| 292 | ``"medium"`` (2 vCPU / 2 GB), ``"large"`` (4 vCPU / 4 GB), or |
| 293 | ``"xlarge"`` (8 vCPU / 8 GB). Defaults to ``"standard"`` |
| 294 | server-side when omitted. Changing this on an existing session |
| 295 | recreates the sandbox on next access; the in-memory FS state |
| 296 | is lost, but the ``/mnt/files/`` mount persists. |
| 297 | """ |
| 298 | |
| 299 | enable: bool |
| 300 | enable_proxy_execution: bool |
| 301 | auto_offload_threshold: int |
| 302 | sandbox_size: SandboxSize |
| 303 | |
| 304 | |
| 305 | class ToolRouterWorkbenchConfig(ToolRouterSandboxConfig, total=False): |
| 306 | """Deprecated alias for :class:`ToolRouterSandboxConfig`. |
| 307 | |
| 308 | ``workbench`` is still accepted for backwards compatibility; prefer |
| 309 | ``sandbox`` in new code. |
| 310 | """ |
| 311 | |
| 312 | |
| 313 | class ToolRouterManageConnectionsConfig(te.TypedDict, total=False): |
| 314 | """Configuration for connection management in tool router session. |
| 315 | |
| 316 | Attributes: |
| 317 | enable: Whether to use tools to manage connections. Defaults to True. |
| 318 | If False, you need to manage connections manually. |
| 319 | callback_url: Optional callback URL to use for OAuth redirects. |
| 320 | wait_for_connections: Whether to wait for users to finish authenticating |
| 321 | connections before proceeding to the next step. Defaults to False. |
| 322 | If set to True, a wait for connections tool call will happen and |
| 323 | finish when the connections are ready. |
| 324 | """ |
| 325 | |
| 326 | enable: bool |
| 327 | callback_url: str |
| 328 | wait_for_connections: bool |
| 329 | |
| 330 | |
| 331 | class ToolRouterMultiAccountConfig(te.TypedDict, total=False): |
| 332 | """Configuration for multi-account mode in tool router session. |
| 333 | |
| 334 | Attributes: |
| 335 | enable: When True, enables multi-account mode. When not set, falls back to |
| 336 | org/project-level configuration. |
| 337 | max_accounts_per_toolkit: Maximum connected accounts allowed per toolkit (2-10). |
| 338 | Defaults to 5 when multi-account is enabled. |
| 339 | require_explicit_selection: When True, require explicit account selection when |
| 340 | multiple accounts are connected. Defaults to False. |
| 341 | """ |
| 342 | |
| 343 | enable: bool |
| 344 | max_accounts_per_toolkit: int |
| 345 | require_explicit_selection: bool |
| 346 | |
| 347 | |
| 348 | class ToolRouterPreloadConfig(te.TypedDict, total=False): |
| 349 | """Configuration for tools preloaded into a tool router session. |
| 350 | |
| 351 | Attributes: |
| 352 | tools: Tool slugs to expose directly in ``session.tools()`` and MCP |
| 353 | tool lists without first calling search. |
| 354 | """ |
| 355 | |
| 356 | tools: t.Union[t.List[str], t.Literal["all"]] |
| 357 | |
| 358 | |
| 359 | class _SessionPreloadLike(te.Protocol): |
| 360 | @property |
| 361 | def tools(self) -> t.Union[t.List[str], str, None]: ... |
| 362 | |
| 363 | |
| 364 | def _session_preload_config( |
| 365 | preload: _SessionPreloadLike, |
| 366 | ) -> ToolRouterSessionPreloadConfig: |
| 367 | tools = preload.tools |
| 368 | if tools == PRELOAD_TOOLS_ALL: |
| 369 | return ToolRouterSessionPreloadConfig(tools=PRELOAD_TOOLS_ALL) |
| 370 | if isinstance(tools, list): |
| 371 | return ToolRouterSessionPreloadConfig(tools=t.cast(t.List[str], tools)) |
| 372 | return ToolRouterSessionPreloadConfig(tools=[]) |
| 373 | |
| 374 | |
| 375 | def _preloads_all_custom_tools( |
| 376 | preload: t.Union[ToolRouterPreloadConfig, _SessionPreloadLike, None], |
| 377 | ) -> bool: |
| 378 | tools: t.Union[t.List[str], str, None] |
| 379 | if preload is None: |
| 380 | tools = None |
| 381 | elif isinstance(preload, dict): |
| 382 | tools = preload.get("tools") |
| 383 | else: |
| 384 | tools = preload.tools |
| 385 | return tools == PRELOAD_TOOLS_ALL |
| 386 | |
| 387 | |
| 388 | def _proxy_execute_payload( |
| 389 | proxy_execute: t.Union[bool, ToolRouterProxyExecuteConfig], |
| 390 | ) -> ToolRouterProxyExecuteConfig: |
| 391 | """Expand the ``proxy_execute`` bool shorthand to the API block.""" |
| 392 | if isinstance(proxy_execute, bool): |
| 393 | return {"enable": proxy_execute} |
| 394 | return proxy_execute |
| 395 | |
| 396 | |
| 397 | def _apply_session_preset_defaults( |
| 398 | session_preset: t.Optional[SessionPreset], |
| 399 | manage_connections: t.Optional[t.Union[bool, ToolRouterManageConnectionsConfig]], |
| 400 | workbench: t.Optional[ToolRouterSandboxConfig], |
| 401 | preload: t.Optional[ToolRouterPreloadConfig], |
| 402 | ) -> t.Tuple[ |
| 403 | t.Optional[t.Union[bool, ToolRouterManageConnectionsConfig]], |
| 404 | t.Optional[ToolRouterSandboxConfig], |
| 405 | t.Optional[ToolRouterPreloadConfig], |
| 406 | ]: |
| 407 | if session_preset != SESSION_PRESET_DIRECT_TOOLS: |
| 408 | return manage_connections, workbench, preload |
| 409 | |
| 410 | return ( |
| 411 | False if manage_connections is None else manage_connections, |
| 412 | {"enable": False} if workbench is None else workbench, |
| 413 | {"tools": PRELOAD_TOOLS_ALL} if preload is None else preload, |
| 414 | ) |
| 415 | |
| 416 | |
| 417 | _LocalOption = t.TypeVar("_LocalOption") |
| 418 | |
| 419 | |
| 420 | def _resolve_local_option( |
| 421 | new_name: str, |
| 422 | new_value: t.Optional[_LocalOption], |
| 423 | old_name: str, |
| 424 | old_value: t.Optional[_LocalOption], |
| 425 | ) -> t.Optional[_LocalOption]: |
| 426 | # `custom_*` options were renamed to `local_*` because "custom toolkits" |
| 427 | # also names the server-side Custom MCP toolkits. |
| 428 | if old_value is None: |
| 429 | return new_value |
| 430 | if new_value is not None: |
| 431 | raise InvalidParams( |
| 432 | f"Pass either `{new_name}` or `{old_name}`, not both. " |
| 433 | f"`{old_name}` is a deprecated alias for `{new_name}`." |
| 434 | ) |
| 435 | warnings.warn( |
| 436 | f"`{old_name}` is deprecated; use `{new_name}`", |
| 437 | ComposioDeprecationWarning, |
| 438 | # Point at the caller of create()/use(), past this helper and the |
| 439 | # Resource tracing wrapper around those methods. |
| 440 | stacklevel=4, |
| 441 | ) |
| 442 | return old_value |
| 443 | |
| 444 | |
| 445 | def _prepare_inline_custom_tools( |
| 446 | *, |
| 447 | custom_tools: t.Optional[t.List[CustomTool]], |
| 448 | custom_toolkits: t.Optional[t.List[ExperimentalToolkit]], |
| 449 | default_preload: bool = False, |
| 450 | preload_tools: t.Optional[t.Union[t.Sequence[str], t.Literal["all"]]] = None, |
| 451 | ) -> t.Optional[InlineCustomToolsWirePayload]: |
| 452 | has_customs = bool(custom_tools or custom_toolkits) |
| 453 | local_custom_tools_map = ( |
| 454 | build_custom_tools_map(custom_tools or [], custom_toolkits) |
| 455 | if has_customs |
| 456 | else None |
| 457 | ) |
| 458 | |
| 459 | # Top-level preload["tools"] is for Composio-managed slugs only. Custom tools |
| 460 | # use their own preload flag, so reject LOCAL/custom slugs there before |
| 461 | # serializing the inline custom definitions. |
| 462 | assert_no_custom_tool_slugs_in_preload(preload_tools, local_custom_tools_map) |
| 463 | |
| 464 | inline_custom_tools_payload: t.Optional[InlineCustomToolsWirePayload] = None |
| 465 | if has_customs: |
| 466 | inline_custom_tools_payload = InlineCustomToolsWirePayload() |
| 467 | if custom_tools: |
| 468 | inline_custom_tools_payload["custom_tools"] = serialize_custom_tools( |
| 469 | custom_tools, |
| 470 | default_preload=default_preload, |
| 471 | ) |
| 472 | if custom_toolkits: |
| 473 | inline_custom_tools_payload["custom_toolkits"] = serialize_custom_toolkits( |
| 474 | custom_toolkits, |
| 475 | default_preload=default_preload, |
| 476 | ) |
| 477 | |
| 478 | return inline_custom_tools_payload |
| 479 | |
| 480 | |
| 481 | class ToolRouterAssistivePromptConfig(te.TypedDict, total=False): |
| 482 | """Configuration for assistive prompt generation. |
| 483 | |
| 484 | Attributes: |
| 485 | user_timezone: IANA timezone identifier (e.g., "America/New_York", "Europe/London") |
| 486 | for timezone-aware assistive prompts. |
| 487 | """ |
| 488 | |
| 489 | user_timezone: str |
| 490 | |
| 491 | |
| 492 | class ToolRouterExperimentalConfig(te.TypedDict, total=False): |
| 493 | """Experimental configuration for tool router session. |
| 494 | |
| 495 | Note: These features are experimental and may be modified or removed in future versions. |
| 496 | |
| 497 | Attributes: |
| 498 | assistive_prompt: Configuration for assistive prompt generation. |
| 499 | local_tools: Local tools to include in the session. |
| 500 | local_toolkits: Local toolkits with grouped tools. |
| 501 | custom_tools: Deprecated alias for ``local_tools``. |
| 502 | custom_toolkits: Deprecated alias for ``local_toolkits``. |
| 503 | """ |
| 504 | |
| 505 | assistive_prompt: ToolRouterAssistivePromptConfig |
| 506 | local_tools: t.List[LocalTool] |
| 507 | local_toolkits: t.List[LocalToolkit] |
| 508 | custom_tools: t.List[CustomTool] |
| 509 | custom_toolkits: t.List[ExperimentalToolkit] |
| 510 | no_elicitation_support_fallback: t.Literal["deny", "allow"] |
| 511 | """What happens to a call that needs the user's approval when the |
| 512 | session's MCP client can't ask the user: ``"deny"`` (the default) or |
| 513 | ``"allow"``.""" |
| 514 | |
| 515 | |
| 516 | @dataclass |
| 517 | class ToolkitConnectionAuthConfig: |
| 518 | """Auth config information for a toolkit connection. |
| 519 | |
| 520 | Attributes: |
| 521 | id: The id of the auth config |
| 522 | mode: The auth scheme used by the auth config |
| 523 | is_composio_managed: Whether the auth config is managed by Composio |
| 524 | """ |
| 525 | |
| 526 | id: str |
| 527 | mode: str |
| 528 | is_composio_managed: bool |
| 529 | |
| 530 | |
| 531 | @dataclass |
| 532 | class ToolkitConnectedAccount: |
| 533 | """Connected account information for a toolkit. |
| 534 | |
| 535 | Attributes: |
| 536 | id: The id of the connected account |
| 537 | status: The status of the connected account |
| 538 | """ |
| 539 | |
| 540 | id: str |
| 541 | status: str |
| 542 | |
| 543 | |
| 544 | @dataclass |
| 545 | class ToolkitConnection: |
| 546 | """Connection information for a toolkit. |
| 547 | |
| 548 | Attributes: |
| 549 | is_active: Whether the connection is active or not |
| 550 | auth_config: The auth config of a toolkit |
| 551 | connected_account: The connected account of a toolkit |
| 552 | """ |
| 553 | |
| 554 | is_active: bool |
| 555 | auth_config: t.Optional[ToolkitConnectionAuthConfig] = None |
| 556 | connected_account: t.Optional[ToolkitConnectedAccount] = None |
| 557 | |
| 558 | |
| 559 | @dataclass |
| 560 | class ToolkitConnectionState: |
| 561 | """The connection state of a toolkit. |
| 562 | |
| 563 | Attributes: |
| 564 | slug: The slug of a toolkit |
| 565 | name: The name of a toolkit |
| 566 | logo: The logo of a toolkit (optional) |
| 567 | is_no_auth: Whether the toolkit is no auth or not |
| 568 | connection: The connection information |
| 569 | """ |
| 570 | |
| 571 | slug: str |
| 572 | name: str |
| 573 | is_no_auth: bool |
| 574 | connection: t.Optional[ToolkitConnection] = None |
| 575 | logo: t.Optional[str] = None |
| 576 | |
| 577 | |
| 578 | @dataclass |
| 579 | class ToolkitConnectionsDetails: |
| 580 | """Details of toolkit connections. |
| 581 | |
| 582 | Attributes: |
| 583 | items: List of toolkit connection states |
| 584 | next_cursor: Optional cursor for pagination |
| 585 | total_pages: Total number of pages |
| 586 | """ |
| 587 | |
| 588 | items: t.List[ToolkitConnectionState] |
| 589 | total_pages: int |
| 590 | next_cursor: t.Optional[str] = None |
| 591 | |
| 592 | |
| 593 | class ToolRouterMCPServerType(str, Enum): |
| 594 | """Enum for MCP server types.""" |
| 595 | |
| 596 | HTTP = "http" |
| 597 | SSE = "sse" |
| 598 | |
| 599 | |
| 600 | @dataclass |
| 601 | class ToolRouterMCPServerConfig: |
| 602 | """Configuration for MCP server. |
| 603 | |
| 604 | Attributes: |
| 605 | type: The type of MCP server (HTTP or SSE) |
| 606 | url: The URL of the MCP server |
| 607 | headers: Optional authentication headers (includes x-api-key) |
| 608 | """ |
| 609 | |
| 610 | type: ToolRouterMCPServerType |
| 611 | url: str |
| 612 | headers: t.Optional[t.Dict[str, t.Optional[str]]] = None |
| 613 | |
| 614 | |
| 615 | @dataclass |
| 616 | class ToolRouterSessionExperimental: |
| 617 | """Experimental features in session response. |
| 618 | |
| 619 | Note: These features are experimental and may be modified or removed in future versions. |
| 620 | |
| 621 | Attributes: |
| 622 | files: File mount for list, upload, download, delete operations. |
| 623 | assistive_prompt: The generated assistive system prompt based on the experimental config. |
| 624 | """ |
| 625 | |
| 626 | files: "ToolRouterSessionFilesMount" |
| 627 | assistive_prompt: t.Optional[str] = None |
| 628 | |
| 629 | |
| 630 | class ToolRouter(Resource, t.Generic[TTool, TToolCollection]): |
| 631 | """ |
| 632 | ToolRouter class for managing tool routing sessions. |
| 633 | |
| 634 | Provides functionality to create isolated tool router sessions with provider-wrapped tools, |
| 635 | authorization helpers, and connection management. |
| 636 | |
| 637 | Example: |
| 638 | ```python |
| 639 | from composio import Composio |
| 640 | |
| 641 | composio = Composio() |
| 642 | |
| 643 | # Create a session for a user |
| 644 | session = composio.tool_router.create( |
| 645 | user_id='user_123', |
| 646 | manage_connections=True |
| 647 | ) |
| 648 | |
| 649 | # Get tools wrapped for the provider |
| 650 | tools = session.tools() |
| 651 | |
| 652 | # Authorize a toolkit |
| 653 | connection_request = session.authorize('github') |
| 654 | print(f"Redirect URL: {connection_request.redirect_url}") |
| 655 | ``` |
| 656 | """ |
| 657 | |
| 658 | def __init__( |
| 659 | self, |
| 660 | client: HttpClient, |
| 661 | provider: t.Optional["BaseProvider[TTool, TToolCollection]"] = None, |
| 662 | dangerously_allow_auto_upload_download_files: bool = False, |
| 663 | sensitive_file_upload_protection: bool = True, |
| 664 | file_upload_path_deny_segments: t.Optional[t.Sequence[str]] = None, |
| 665 | file_upload_dirs: t.Union[t.Sequence[str], t.Literal[False], None] = None, |
| 666 | ): |
| 667 | """ |
| 668 | Initialize ToolRouter instance. |
| 669 | |
| 670 | :param client: HTTP client for API calls |
| 671 | :param provider: Optional provider for tool wrapping |
| 672 | :param dangerously_allow_auto_upload_download_files: Opt-in for automatic file upload/download. Defaults to False. |
| 673 | :param sensitive_file_upload_protection: When True, block local paths on the built-in sensitive-path denylist before upload. |
| 674 | :param file_upload_path_deny_segments: Extra path segment names to merge with the built-in denylist. |
| 675 | :param file_upload_dirs: Allowlist of directories for auto-upload. See ``Composio`` for details. |
| 676 | """ |
| 677 | super().__init__(client) |
| 678 | self._provider = provider |
| 679 | self._sensitive_file_upload_protection = sensitive_file_upload_protection |
| 680 | self._file_upload_path_deny_segments = file_upload_path_deny_segments |
| 681 | self._file_upload_dirs = file_upload_dirs |
| 682 | self._auto_upload_download_files = bool( |
| 683 | dangerously_allow_auto_upload_download_files |
| 684 | ) |
| 685 | |
| 686 | def _mcp_destination_rejection(self, url: str) -> t.Optional[MCPDestinationError]: |
| 687 | """The error describing why ``url`` must not receive the session |
| 688 | credential, or ``None`` when it shares the client's API origin.""" |
| 689 | try: |
| 690 | api_origin = _origin(str(self._client.base_url), "API base URL") |
| 691 | mcp_origin = _origin(url, "MCP URL") |
| 692 | except MCPDestinationError as exc: |
| 693 | return exc |
| 694 | if mcp_origin == api_origin: |
| 695 | return None |
| 696 | return MCPDestinationError( |
| 697 | f"The session MCP endpoint origin {mcp_origin} does not match the " |
| 698 | f"API origin {api_origin}; the session credential was not attached", |
| 699 | mcp_origin=mcp_origin, |
| 700 | api_origin=api_origin, |
| 701 | ) |
| 702 | |
| 703 | def _create_mcp_server_config( |
| 704 | self, |
| 705 | mcp_type: ToolRouterMCPServerType, |
| 706 | url: str, |
| 707 | mcp_requested: bool, |
| 708 | ) -> ToolRouterMCPServerConfig: |
| 709 | """ |
| 710 | Create an MCP server config object with authentication headers. |
| 711 | |
| 712 | The headers mirror the effective auth of the underlying client, read |
| 713 | from the ``auth`` and ``scope`` the SDK built it with: its project key |
| 714 | as ``x-api-key``, otherwise its user key as ``x-user-api-key`` (see |
| 715 | :func:`~composio.core.models.base.credential_headers`), plus |
| 716 | ``x-org-id`` / ``x-project-id`` when the client carries an explicit |
| 717 | ``scope``. No other default header is copied and the environment is |
| 718 | never re-read. |
| 719 | |
| 720 | The headers are only attached when the MCP URL has the same origin as |
| 721 | the client's API base URL, whatever scheme is configured: that origin |
| 722 | already receives them on every SDK request. Any other destination (a |
| 723 | different origin, an opaque origin, or a URL that does not parse) |
| 724 | never receives them. When the caller asked for MCP |
| 725 | (``mcp_requested``), that raises |
| 726 | :class:`~composio.exceptions.MCPDestinationError` naming both origins; |
| 727 | otherwise the config is returned with empty headers and a warning |
| 728 | naming both origins is logged, so callers who only use the native |
| 729 | tools are not blocked by an endpoint they never consume. The SDK |
| 730 | itself never connects to the MCP URL and does not follow redirects for |
| 731 | it; an MCP client consuming this config must not forward these headers |
| 732 | to a different origin. |
| 733 | |
| 734 | :param mcp_type: The type of MCP server (HTTP or SSE) |
| 735 | :param url: The URL of the MCP server |
| 736 | :param mcp_requested: Whether the caller passed ``mcp=True`` |
| 737 | :return: MCP server config with headers |
| 738 | """ |
| 739 | rejection = self._mcp_destination_rejection(url) |
| 740 | if rejection is not None: |
| 741 | if mcp_requested: |
| 742 | raise rejection |
| 743 | logger.warning( |
| 744 | "%s. session.mcp.headers was left empty; pass mcp=True to make " |
| 745 | "this an error", |
| 746 | rejection, |
| 747 | ) |
| 748 | return ToolRouterMCPServerConfig(type=mcp_type, url=url, headers={}) |
| 749 | |
| 750 | headers: t.Dict[str, t.Optional[str]] = { |
| 751 | **credential_headers(self._client), |
| 752 | **scope_headers(self._client), |
| 753 | } |
| 754 | return ToolRouterMCPServerConfig(type=mcp_type, url=url, headers=headers) |
| 755 | |
| 756 | def _transform_tags_params( |
| 757 | self, tags: t.Optional[ToolRouterConfigTags] |
| 758 | ) -> t.Optional[session_create_params.TagsUnionMember1]: |
| 759 | """Transform tags configuration to API format. |
| 760 | |
| 761 | Args: |
| 762 | tags: Tags configuration - can be a list (shorthand for enable) |
| 763 | or an object with enable/disable keys. |
| 764 | |
| 765 | Returns: |
| 766 | Transformed tags payload in API format, or None if tags is None. |
| 767 | """ |
| 768 | if tags is None: |
| 769 | return None |
| 770 | |
| 771 | if isinstance(tags, list): |
| 772 | # List shorthand means enable these tags |
| 773 | # Return value structure matches TagsUnionMember1: {"enable": [...]} |
| 774 | return {"enable": tags} |
| 775 | elif isinstance(tags, dict): |
| 776 | # Object format with enable/disable and an approval list |
| 777 | # Only include keys that are present and not None |
| 778 | # Return value structure matches TagsUnionMember1 |
| 779 | result: session_create_params.TagsUnionMember1 = {} |
| 780 | enable_value = tags.get("enable") |
| 781 | if enable_value is not None: |
| 782 | result["enable"] = enable_value |
| 783 | disable_value = tags.get("disable") |
| 784 | if disable_value is not None: |
| 785 | result["disable"] = disable_value |
| 786 | require_approval_value = tags.get("require_approval") |
| 787 | if require_approval_value is not None: |
| 788 | result["require_approval"] = require_approval_value |
| 789 | return result or None |
| 790 | |
| 791 | # Overloads: pass ``mcp=True`` to surface ``session.mcp`` in the returned |
| 792 | # type (ToolRouterSessionWithMcp). The MCP endpoint exists at runtime on |
| 793 | # every session regardless. See https://docs.composio.dev/docs/sessions-via-mcp |
| 794 | @t.overload |
| 795 | def create( |
| 796 | self, |
| 797 | *, |
| 798 | user_id: str, |
| 799 | toolkits: t.Optional[ |
| 800 | t.Union[ |
| 801 | t.List[str], |
| 802 | ToolRouterToolkitsEnableConfig, |
| 803 | ToolRouterToolkitsDisableConfig, |
| 804 | ToolRouterToolkitsRequireApprovalConfig, |
| 805 | ] |
| 806 | ] = None, |
| 807 | tools: t.Optional[t.Dict[str, ToolRouterToolsConfig]] = None, |
| 808 | tags: t.Optional[ToolRouterConfigTags] = None, |
| 809 | manage_connections: t.Optional[ |
| 810 | t.Union[bool, ToolRouterManageConnectionsConfig] |
| 811 | ] = None, |
| 812 | auth_configs: t.Optional[t.Dict[str, str]] = None, |
| 813 | connected_accounts: t.Optional[t.Dict[str, t.Union[str, t.List[str]]]] = None, |
| 814 | sandbox: t.Optional[ToolRouterSandboxConfig] = None, |
| 815 | workbench: t.Optional[ToolRouterWorkbenchConfig] = None, |
| 816 | multi_account: t.Optional[ToolRouterMultiAccountConfig] = None, |
| 817 | proxy_execute: t.Optional[t.Union[bool, ToolRouterProxyExecuteConfig]] = None, |
| 818 | hooks: t.Optional[t.List[ToolRouterHook]] = None, |
| 819 | preload: t.Optional[ToolRouterPreloadConfig] = None, |
| 820 | session_preset: t.Optional[SessionPreset] = None, |
| 821 | experimental: t.Optional[ToolRouterExperimentalConfig] = None, |
| 822 | instant: t.Optional[t.Union[t.Literal[False], ToolRouterInstantConfig]] = None, |
| 823 | mcp: t.Literal[True], |
| 824 | ) -> ToolRouterSessionWithMcp[TTool, TToolCollection]: ... |
| 825 | |
| 826 | @t.overload |
| 827 | def create( |
| 828 | self, |
| 829 | *, |
| 830 | user_id: str, |
| 831 | toolkits: t.Optional[ |
| 832 | t.Union[ |
| 833 | t.List[str], |
| 834 | ToolRouterToolkitsEnableConfig, |
| 835 | ToolRouterToolkitsDisableConfig, |
| 836 | ToolRouterToolkitsRequireApprovalConfig, |
| 837 | ] |
| 838 | ] = None, |
| 839 | tools: t.Optional[t.Dict[str, ToolRouterToolsConfig]] = None, |
| 840 | tags: t.Optional[ToolRouterConfigTags] = None, |
| 841 | manage_connections: t.Optional[ |
| 842 | t.Union[bool, ToolRouterManageConnectionsConfig] |
| 843 | ] = None, |
| 844 | auth_configs: t.Optional[t.Dict[str, str]] = None, |
| 845 | connected_accounts: t.Optional[t.Dict[str, t.Union[str, t.List[str]]]] = None, |
| 846 | sandbox: t.Optional[ToolRouterSandboxConfig] = None, |
| 847 | workbench: t.Optional[ToolRouterWorkbenchConfig] = None, |
| 848 | multi_account: t.Optional[ToolRouterMultiAccountConfig] = None, |
| 849 | proxy_execute: t.Optional[t.Union[bool, ToolRouterProxyExecuteConfig]] = None, |
| 850 | hooks: t.Optional[t.List[ToolRouterHook]] = None, |
| 851 | preload: t.Optional[ToolRouterPreloadConfig] = None, |
| 852 | session_preset: t.Optional[SessionPreset] = None, |
| 853 | experimental: t.Optional[ToolRouterExperimentalConfig] = None, |
| 854 | instant: t.Optional[t.Union[t.Literal[False], ToolRouterInstantConfig]] = None, |
| 855 | mcp: t.Literal[False] = False, |
| 856 | ) -> ToolRouterSession[TTool, TToolCollection]: ... |
| 857 | |
| 858 | def create( |
| 859 | self, |
| 860 | *, |
| 861 | user_id: str, |
| 862 | toolkits: t.Optional[ |
| 863 | t.Union[ |
| 864 | t.List[str], |
| 865 | ToolRouterToolkitsEnableConfig, |
| 866 | ToolRouterToolkitsDisableConfig, |
| 867 | ToolRouterToolkitsRequireApprovalConfig, |
| 868 | ] |
| 869 | ] = None, |
| 870 | tools: t.Optional[t.Dict[str, ToolRouterToolsConfig]] = None, |
| 871 | tags: t.Optional[ToolRouterConfigTags] = None, |
| 872 | manage_connections: t.Optional[ |
| 873 | t.Union[bool, ToolRouterManageConnectionsConfig] |
| 874 | ] = None, |
| 875 | auth_configs: t.Optional[t.Dict[str, str]] = None, |
| 876 | connected_accounts: t.Optional[t.Dict[str, t.Union[str, t.List[str]]]] = None, |
| 877 | sandbox: t.Optional[ToolRouterSandboxConfig] = None, |
| 878 | workbench: t.Optional[ToolRouterWorkbenchConfig] = None, |
| 879 | multi_account: t.Optional[ToolRouterMultiAccountConfig] = None, |
| 880 | proxy_execute: t.Optional[t.Union[bool, ToolRouterProxyExecuteConfig]] = None, |
| 881 | hooks: t.Optional[t.List[ToolRouterHook]] = None, |
| 882 | preload: t.Optional[ToolRouterPreloadConfig] = None, |
| 883 | session_preset: t.Optional[SessionPreset] = None, |
| 884 | experimental: t.Optional[ToolRouterExperimentalConfig] = None, |
| 885 | instant: t.Optional[t.Union[t.Literal[False], ToolRouterInstantConfig]] = None, |
| 886 | mcp: bool = False, |
| 887 | ) -> ToolRouterSession[TTool, TToolCollection]: |
| 888 | """ |
| 889 | Create a new tool router session for a user. |
| 890 | |
| 891 | :param user_id: The user ID to create the session for. |
| 892 | :param toolkits: Optional toolkit configuration. Can be: |
| 893 | - List[str]: List of toolkit slugs to enable. |
| 894 | Example: ['github', 'slack'] |
| 895 | - ToolRouterToolkitsEnableConfig: Dict with 'enable' key. |
| 896 | Example: {'enable': ['github', 'slack']} |
| 897 | - ToolRouterToolkitsDisableConfig: Dict with 'disable' key. |
| 898 | Example: {'disable': ['linear']} |
| 899 | Experimental: any dict can carry 'require_approval', the |
| 900 | toolkits whose tools need the user's approval, or have |
| 901 | only that key. Example: {'require_approval': ['gmail']} |
| 902 | :param tools: Optional per-toolkit tool configuration. Key is toolkit slug, |
| 903 | value is ToolRouterToolsConfig which can be: |
| 904 | - List[str]: List of tool slugs (shorthand for enable). |
| 905 | Example: ['GMAIL_SEND_EMAIL', 'GMAIL_SEARCH'] |
| 906 | - ToolRouterToolsEnableConfig: Dict with 'enable' key. |
| 907 | Example: {'enable': ['GMAIL_SEND_EMAIL']} |
| 908 | - ToolRouterToolsDisableConfig: Dict with 'disable' key. |
| 909 | Example: {'disable': ['GMAIL_DELETE_EMAIL']} |
| 910 | - ToolRouterToolsTagsConfig: Dict with 'tags' key. |
| 911 | Tags can be a list (shorthand for enable) or object with enable/disable. |
| 912 | Example: {'tags': ['readOnlyHint', 'createHint']} |
| 913 | Example: {'tags': {'enable': ['readOnlyHint'], 'disable': ['destructiveHint']}} |
| 914 | Example: { |
| 915 | 'gmail': ['GMAIL_SEND_EMAIL', 'GMAIL_SEARCH'], |
| 916 | 'github': {'enable': ['GITHUB_CREATE_AN_ISSUE']}, |
| 917 | 'slack': {'disable': ['SLACK_DELETE_MESSAGE']}, |
| 918 | 'linear': {'tags': ['readOnlyHint']} |
| 919 | } |
| 920 | Experimental: any dict can carry 'require_approval', the |
| 921 | tools that need the user's approval, or have only that key. |
| 922 | Example: {'gmail': {'require_approval': ['GMAIL_SEND_EMAIL']}} |
| 923 | :param tags: Optional global MCP tags to filter tools by. |
| 924 | Can be: |
| 925 | - List[str]: List of tag literals (shorthand for enable). |
| 926 | Example: ['readOnlyHint', 'createHint'] |
| 927 | - ToolRouterTagsEnableDisableConfig: Dict with 'enable' and/or 'disable' keys. |
| 928 | Example: {'enable': ['readOnlyHint'], 'disable': ['destructiveHint']} |
| 929 | Tag values: 'readOnlyHint', 'createHint', |
| 930 | 'updateHint', 'destructiveHint'. |
| 931 | Experimental: the dict can also carry 'require_approval', |
| 932 | tags whose tools need the user's approval. |
| 933 | Example: {'require_approval': ['destructiveHint']} |
| 934 | Toolkit-level tags override this global setting. |
| 935 | :param manage_connections: Optional connection management configuration. Can be: |
| 936 | - bool: Simple boolean to enable/disable. |
| 937 | Example: True or False |
| 938 | - ToolRouterManageConnectionsConfig: Dict with: |
| 939 | - 'enable' (bool): Whether to use tools to manage |
| 940 | connections. Defaults to True. |
| 941 | - 'callback_url' (str, optional): Callback URL for |
| 942 | OAuth redirects. |
| 943 | - 'wait_for_connections' (bool, optional): Whether to wait |
| 944 | for users to finish authenticating connections before |
| 945 | proceeding to the next step. Defaults to False. |
| 946 | Example: {'enable': True, 'callback_url': 'https://example.com/callback', 'wait_for_connections': True} |
| 947 | :param auth_configs: Optional mapping of toolkit slug to auth config ID. |
| 948 | Example: {'github': 'ac_xxx', 'slack': 'ac_yyy'} |
| 949 | :param connected_accounts: Optional mapping of toolkit slug to connected account ID(s). |
| 950 | Accepts a single string or a list of strings per toolkit. |
| 951 | Only one account per toolkit is allowed when multi-account |
| 952 | mode is disabled. |
| 953 | Example: {'github': 'ca_xxx', 'slack': ['ca_yyy']} |
| 954 | :param sandbox: Optional sandbox configuration. Dict with: |
| 955 | - 'enable' (bool): Whether to enable the sandbox entirely. |
| 956 | Defaults to True. When set to False, no code execution tools |
| 957 | (COMPOSIO_REMOTE_WORKBENCH, COMPOSIO_REMOTE_BASH_TOOL) are |
| 958 | available in the session. |
| 959 | - 'enable_proxy_execution' (bool): Whether to allow proxy execute |
| 960 | calls in the sandbox. If False, prevents arbitrary HTTP requests. |
| 961 | - 'auto_offload_threshold' (int): Maximum execution payload size to |
| 962 | offload to the sandbox. |
| 963 | - 'sandbox_size' (SandboxSize): Sandbox compute tier. One of |
| 964 | 'standard' (1 vCPU / 1 GB, default), 'medium' (2 vCPU / 2 GB), |
| 965 | 'large' (4 vCPU / 4 GB), or 'xlarge' (8 vCPU / 8 GB). |
| 966 | Example: {'enable': False} |
| 967 | Example: {'enable_proxy_execution': False, 'auto_offload_threshold': 300} |
| 968 | Example: {'sandbox_size': 'large'} |
| 969 | :param workbench: Deprecated alias for sandbox. Accepted for backwards compatibility. |
| 970 | :param multi_account: Optional multi-account configuration (ToolRouterMultiAccountConfig). |
| 971 | Dict with: |
| 972 | - 'enable' (bool): When True, enables multi-account mode. |
| 973 | Falls back to org/project-level config when not set. |
| 974 | - 'max_accounts_per_toolkit' (int): Max connected accounts per |
| 975 | toolkit (2-10). Defaults to 5. |
| 976 | - 'require_explicit_selection' (bool): When True, require explicit |
| 977 | account selection when multiple accounts are connected. |
| 978 | Example: {'enable': True, 'max_accounts_per_toolkit': 3} |
| 979 | :param preload: Optional preload configuration. Dict with: |
| 980 | - 'tools' (List[str] | 'all'): Tool slugs to expose directly in |
| 981 | session.tools() and MCP tool lists. 'all' exposes every app |
| 982 | tool allowed by positive session filters such as toolkits, |
| 983 | tools, or tags; the backend validates and caps the final set. |
| 984 | Example: {'tools': ['GMAIL_FETCH_EMAILS']} |
| 985 | :param session_preset: Optional session preset. Use |
| 986 | SESSION_PRESET_DIRECT_TOOLS when all needed tools are |
| 987 | known upfront and should be exposed directly from |
| 988 | session.tools() and the MCP tool list. It disables |
| 989 | meta/helper tools by default; explicit overrides still win. |
| 990 | Loading many tools can increase model context usage. |
| 991 | :param experimental: Optional experimental configuration (ToolRouterExperimentalConfig). |
| 992 | Note: These features are experimental and may change. |
| 993 | Dict with: |
| 994 | - 'assistive_prompt' (dict): Configuration for assistive prompt generation. |
| 995 | - 'user_timezone' (str): IANA timezone identifier |
| 996 | (e.g., "America/New_York", "Europe/London"). |
| 997 | - 'local_tools' / 'local_toolkits': local tools that |
| 998 | run in-process. 'custom_tools' / 'custom_toolkits' |
| 999 | are deprecated aliases. |
| 1000 | - 'no_elicitation_support_fallback' ('deny' or 'allow'): |
| 1001 | what happens to a call that needs approval when the |
| 1002 | session's MCP client can't ask the user. |
| 1003 | Set preload=True on a local tool or toolkit to expose |
| 1004 | it directly from session.tools(); otherwise local tools |
| 1005 | remain search-only. |
| 1006 | Example: {'assistive_prompt': {'user_timezone': 'America/New_York'}} |
| 1007 | :param proxy_execute: Optional proxy execute configuration: a bool or |
| 1008 | ``ToolRouterProxyExecuteConfig``; ``True`` is shorthand for |
| 1009 | ``{"enable": True}``. ``True`` exposes the |
| 1010 | ``COMPOSIO_PROXY_EXECUTE`` meta tool. ``False`` also turns off |
| 1011 | the sandbox ``proxy_execute()`` helper, and the API rejects it |
| 1012 | together with ``sandbox={"enable_proxy_execution": True}``. |
| 1013 | Leaving it out keeps the meta tool off. |
| 1014 | :param hooks: Optional hooks that run on this session's tool calls. A |
| 1015 | ``before_execute`` hook can block a call before it runs; |
| 1016 | an ``after_execute`` hook can block its result before the |
| 1017 | agent sees it. A blocked call comes back with |
| 1018 | ``result_type="blocked"``. Cannot be combined with |
| 1019 | ``experimental={"session_config_id": ...}``. |
| 1020 | :param instant: Experimental Instant usage policy. The project |
| 1021 | must allow Instant usage. ``False`` disables it for this |
| 1022 | Session; a policy can restrict eligible toolkits and tools. |
| 1023 | ``return_instant_charge`` returns the charge with each |
| 1024 | call, and ``return_prices_in_search`` shows each Instant |
| 1025 | tool's price in ``session.search()`` results. |
| 1026 | :param mcp: When True, the returned session surfaces its hosted MCP |
| 1027 | endpoint (``session.mcp.url`` / ``session.mcp.headers``) in |
| 1028 | the type (returns ToolRouterSessionWithMcp). The endpoint |
| 1029 | exists on every session at runtime regardless of this flag; |
| 1030 | native tools (``session.tools()``) are unaffected. |
| 1031 | The session credential is exported in ``session.mcp.headers`` |
| 1032 | only when the MCP URL shares the origin of the configured |
| 1033 | API base URL. When it does not, ``mcp=True`` raises |
| 1034 | :class:`~composio.exceptions.MCPDestinationError` (naming |
| 1035 | both origins, never a key); otherwise the session is |
| 1036 | returned with empty ``session.mcp.headers`` and a warning |
| 1037 | naming both origins is logged. |
| 1038 | See https://docs.composio.dev/docs/sessions-via-mcp |
| 1039 | :return: Tool router session object |
| 1040 | :raises MCPDestinationError: When ``mcp=True`` and the MCP URL is not |
| 1041 | on the API origin. |
| 1042 | |
| 1043 | Example: |
| 1044 | ```python |
| 1045 | # Create a basic session |
| 1046 | session = tool_router.create(user_id='user_123') |
| 1047 | |
| 1048 | # Create a session with specific toolkits |
| 1049 | session = tool_router.create( |
| 1050 | user_id='user_123', |
| 1051 | toolkits=['github', 'slack'] |
| 1052 | ) |
| 1053 | |
| 1054 | # Create a direct-tools session when all needed tools are known upfront |
| 1055 | session = tool_router.create( |
| 1056 | user_id='user_123', |
| 1057 | session_preset=SESSION_PRESET_DIRECT_TOOLS, |
| 1058 | toolkits=['github'] |
| 1059 | ) |
| 1060 | |
| 1061 | # Create a session with per-toolkit tool configuration |
| 1062 | session = tool_router.create( |
| 1063 | user_id='user_123', |
| 1064 | tools={ |
| 1065 | 'gmail': ['GMAIL_SEND_EMAIL', 'GMAIL_SEARCH'], # List shorthand |
| 1066 | 'github': {'enable': ['GITHUB_CREATE_AN_ISSUE']}, # Explicit enable |
| 1067 | 'slack': {'disable': ['SLACK_DELETE_MESSAGE']}, # Explicit disable |
| 1068 | } |
| 1069 | ) |
| 1070 | |
| 1071 | # Create a session with global tag filtering |
| 1072 | session = tool_router.create( |
| 1073 | user_id='user_123', |
| 1074 | tags=['readOnlyHint', 'createHint'] |
| 1075 | ) |
| 1076 | |
| 1077 | # Create a session with toolkit-specific tag filtering (array format) |
| 1078 | session = tool_router.create( |
| 1079 | user_id='user_123', |
| 1080 | tools={ |
| 1081 | 'gmail': {'tags': ['readOnlyHint']}, |
| 1082 | 'github': {'tags': ['readOnlyHint', 'createHint']} |
| 1083 | } |
| 1084 | ) |
| 1085 | |
| 1086 | # Create a session with toolkit-specific tag filtering (object format) |
| 1087 | session = tool_router.create( |
| 1088 | user_id='user_123', |
| 1089 | tools={ |
| 1090 | 'gmail': {'tags': {'enable': ['readOnlyHint']}}, |
| 1091 | 'github': {'tags': {'enable': ['readOnlyHint'], 'disable': ['destructiveHint']}} |
| 1092 | } |
| 1093 | ) |
| 1094 | |
| 1095 | # Create a session with connection management |
| 1096 | session = tool_router.create( |
| 1097 | user_id='user_123', |
| 1098 | manage_connections={ |
| 1099 | 'enable': True, |
| 1100 | 'callback_url': 'https://example.com/callback', |
| 1101 | 'wait_for_connections': True, |
| 1102 | } |
| 1103 | ) |
| 1104 | |
| 1105 | # Create a session with sandbox disabled |
| 1106 | session = tool_router.create( |
| 1107 | user_id='user_123', |
| 1108 | sandbox={ |
| 1109 | 'enable': False |
| 1110 | } |
| 1111 | ) |
| 1112 | |
| 1113 | # Create a session with sandbox config |
| 1114 | session = tool_router.create( |
| 1115 | user_id='user_123', |
| 1116 | sandbox={ |
| 1117 | 'enable_proxy_execution': False, |
| 1118 | 'auto_offload_threshold': 300 |
| 1119 | } |
| 1120 | ) |
| 1121 | |
| 1122 | # Use the session |
| 1123 | tools = session.tools() |
| 1124 | connection = session.authorize('github') |
| 1125 | toolkit_states = session.toolkits() |
| 1126 | ``` |
| 1127 | """ |
| 1128 | |
| 1129 | if sandbox is not None and workbench is not None: |
| 1130 | raise InvalidParams( |
| 1131 | "Pass either `sandbox` or `workbench`, not both. " |
| 1132 | "`workbench` is a backwards-compatible alias for `sandbox`." |
| 1133 | ) |
| 1134 | |
| 1135 | sandbox_config: t.Optional[ToolRouterSandboxConfig] = ( |
| 1136 | sandbox if sandbox is not None else workbench |
| 1137 | ) |
| 1138 | |
| 1139 | direct_tools_preset = session_preset == SESSION_PRESET_DIRECT_TOOLS |
| 1140 | manage_connections, sandbox_config, preload = _apply_session_preset_defaults( |
| 1141 | session_preset=session_preset, |
| 1142 | manage_connections=manage_connections, |
| 1143 | workbench=sandbox_config, |
| 1144 | preload=preload, |
| 1145 | ) |
| 1146 | default_custom_preload = _preloads_all_custom_tools(preload) |
| 1147 | |
| 1148 | # Parse manage_connections config |
| 1149 | manage_connections = ( |
| 1150 | manage_connections if manage_connections is not None else True |
| 1151 | ) |
| 1152 | auto_manage_connections = ( |
| 1153 | manage_connections |
| 1154 | if isinstance(manage_connections, bool) |
| 1155 | else manage_connections.get("enable", True) |
| 1156 | ) |
| 1157 | |
| 1158 | # Parse toolkits config |
| 1159 | toolkits_payload: t.Optional[t.Dict[str, t.List[str]]] = None |
| 1160 | if toolkits is not None: |
| 1161 | if isinstance(toolkits, list): |
| 1162 | toolkits_payload = {"enable": toolkits} |
| 1163 | else: |
| 1164 | toolkits_payload = t.cast(t.Dict[str, t.List[str]], toolkits) |
| 1165 | |
| 1166 | # Parse tools config - transform to API format |
| 1167 | # Transform tools from Dict[str, Union[List, enable/disable/tags]] to client SDK format |
| 1168 | tools_payload: t.Optional[t.Dict[str, t.Any]] = None |
| 1169 | if tools is not None: |
| 1170 | tools_payload = {} |
| 1171 | for toolkit_slug, config in tools.items(): |
| 1172 | if isinstance(config, list): |
| 1173 | # List shorthand means enable these tools |
| 1174 | tools_payload[toolkit_slug] = {"enable": config} |
| 1175 | elif isinstance(config, dict): |
| 1176 | # Transform config dict - handle 'tags' specially if present |
| 1177 | # Build the transformed config explicitly to maintain proper typing |
| 1178 | transformed_config: t.Dict[ |
| 1179 | str, |
| 1180 | t.Union[ |
| 1181 | t.List[str], |
| 1182 | session_create_params.TagsUnionMember1, |
| 1183 | ], |
| 1184 | ] = {} |
| 1185 | # Copy existing keys (enable, disable) if present |
| 1186 | if "enable" in config: |
| 1187 | # config is ToolRouterToolsEnableConfig when "enable" is present |
| 1188 | enable_config = t.cast(ToolRouterToolsEnableConfig, config) |
| 1189 | transformed_config["enable"] = enable_config["enable"] |
| 1190 | if "disable" in config: |
| 1191 | # config is ToolRouterToolsDisableConfig when "disable" is present |
| 1192 | disable_config = t.cast(ToolRouterToolsDisableConfig, config) |
| 1193 | transformed_config["disable"] = disable_config["disable"] |
| 1194 | if "require_approval" in config: |
| 1195 | approval_config = t.cast( |
| 1196 | ToolRouterToolsRequireApprovalConfig, config |
| 1197 | ) |
| 1198 | transformed_config["require_approval"] = approval_config[ |
| 1199 | "require_approval" |
| 1200 | ] |
| 1201 | # Use type guard to narrow the type when "tags" is present |
| 1202 | if _is_tools_tags_config(config): |
| 1203 | # Type narrowed: config is now ToolRouterToolsTagsConfig |
| 1204 | tags_value = config["tags"] |
| 1205 | transformed_tags = self._transform_tags_params(tags_value) |
| 1206 | if transformed_tags is not None: |
| 1207 | transformed_config["tags"] = transformed_tags |
| 1208 | tools_payload[toolkit_slug] = transformed_config |
| 1209 | |
| 1210 | # Parse callback_url and wait_for_connections from manage_connections config |
| 1211 | callback_url = ( |
| 1212 | manage_connections.get("callback_url") |
| 1213 | if isinstance(manage_connections, dict) |
| 1214 | else omit |
| 1215 | ) |
| 1216 | wait_for_connections = ( |
| 1217 | manage_connections.get("wait_for_connections") |
| 1218 | if isinstance(manage_connections, dict) |
| 1219 | else omit |
| 1220 | ) |
| 1221 | |
| 1222 | # Build the API payload |
| 1223 | create_params: t.Dict[str, t.Any] = { |
| 1224 | "user_id": user_id, |
| 1225 | } |
| 1226 | if instant is not None: |
| 1227 | create_params["instant"] = instant |
| 1228 | if proxy_execute is not None: |
| 1229 | create_params["proxy_execute"] = _proxy_execute_payload(proxy_execute) |
| 1230 | if hooks is not None: |
| 1231 | if ( |
| 1232 | experimental is not None |
| 1233 | and t.cast(t.Dict[str, t.Any], experimental).get("session_config_id") |
| 1234 | is not None |
| 1235 | ): |
| 1236 | raise InvalidParams( |
| 1237 | "`hooks` cannot be combined with " |
| 1238 | "`experimental={'session_config_id': ...}`; create the session " |
| 1239 | "from the saved config and add hooks in a separate update() call" |
| 1240 | ) |
| 1241 | create_params["hooks"] = hooks |
| 1242 | |
| 1243 | # Build connections config |
| 1244 | connections_config: t.Dict[str, t.Any] = { |
| 1245 | "enable": auto_manage_connections, |
| 1246 | } |
| 1247 | if callback_url is not None and callback_url is not omit: |
| 1248 | connections_config["callback_url"] = callback_url |
| 1249 | if wait_for_connections is not None and wait_for_connections is not omit: |
| 1250 | connections_config["enable_wait_for_connections"] = wait_for_connections |
| 1251 | |
| 1252 | create_params["manage_connections"] = connections_config |
| 1253 | |
| 1254 | # Add optional fields |
| 1255 | if auth_configs is not None: |
| 1256 | create_params["auth_configs"] = auth_configs |
| 1257 | |
| 1258 | if connected_accounts is not None: |
| 1259 | create_params["connected_accounts"] = { |
| 1260 | k: [v] if isinstance(v, str) else v |
| 1261 | for k, v in connected_accounts.items() |
| 1262 | } |
| 1263 | |
| 1264 | if toolkits_payload is not None: |
| 1265 | create_params["toolkits"] = toolkits_payload |
| 1266 | |
| 1267 | if tools_payload: |
| 1268 | create_params["tools"] = tools_payload |
| 1269 | |
| 1270 | # Transform tags config |
| 1271 | tags_payload = self._transform_tags_params(tags) |
| 1272 | if tags_payload is not None: |
| 1273 | create_params["tags"] = tags_payload |
| 1274 | |
| 1275 | if sandbox_config is not None: |
| 1276 | execution_payload: t.Dict[str, t.Any] = { |
| 1277 | "enable": sandbox_config.get("enable", True), |
| 1278 | } |
| 1279 | if "enable_proxy_execution" in sandbox_config: |
| 1280 | execution_payload["enable_proxy_execution"] = sandbox_config[ |
| 1281 | "enable_proxy_execution" |
| 1282 | ] |
| 1283 | if "auto_offload_threshold" in sandbox_config: |
| 1284 | execution_payload["auto_offload_threshold"] = int( |
| 1285 | sandbox_config["auto_offload_threshold"] |
| 1286 | ) |
| 1287 | if "sandbox_size" in sandbox_config: |
| 1288 | execution_payload["sandbox_size"] = sandbox_config["sandbox_size"] |
| 1289 | |
| 1290 | if execution_payload: |
| 1291 | create_params["workbench"] = execution_payload |
| 1292 | |
| 1293 | if multi_account is not None: |
| 1294 | ma = dict(multi_account) |
| 1295 | if ma.get("enable") and "require_explicit_selection" not in ma: |
| 1296 | ma["require_explicit_selection"] = True |
| 1297 | create_params["multi_account"] = ma |
| 1298 | |
| 1299 | if preload is not None: |
| 1300 | create_params["preload"] = preload |
| 1301 | |
| 1302 | if direct_tools_preset: |
| 1303 | create_params["search"] = {"enable": False} |
| 1304 | create_params["execute"] = {"enable_multi_execute": False} |
| 1305 | |
| 1306 | # Build experimental config |
| 1307 | # Map SDK's experimental.assistive_prompt.user_timezone to API's |
| 1308 | # experimental.assistive_prompt_config.user_timezone |
| 1309 | custom_tools: t.Optional[t.List[CustomTool]] = None |
| 1310 | custom_toolkits: t.Optional[t.List[ExperimentalToolkit]] = None |
| 1311 | inline_custom_tools_payload: t.Optional[InlineCustomToolsWirePayload] = None |
| 1312 | experimental_payload: t.Dict[str, t.Any] = {} |
| 1313 | |
| 1314 | if experimental is not None: |
| 1315 | assistive_prompt_config = experimental.get("assistive_prompt") |
| 1316 | if assistive_prompt_config is not None: |
| 1317 | user_timezone = assistive_prompt_config.get("user_timezone") |
| 1318 | if user_timezone: |
| 1319 | experimental_payload["assistive_prompt_config"] = { |
| 1320 | "user_timezone": user_timezone, |
| 1321 | } |
| 1322 | |
| 1323 | fallback = experimental.get("no_elicitation_support_fallback") |
| 1324 | if fallback is not None: |
| 1325 | experimental_payload["no_elicitation_support_fallback"] = fallback |
| 1326 | |
| 1327 | # Serialize local tools and toolkits for the backend |
| 1328 | custom_tools = _resolve_local_option( |
| 1329 | "local_tools", |
| 1330 | experimental.get("local_tools"), |
| 1331 | "custom_tools", |
| 1332 | experimental.get("custom_tools"), |
| 1333 | ) |
| 1334 | custom_toolkits = _resolve_local_option( |
| 1335 | "local_toolkits", |
| 1336 | experimental.get("local_toolkits"), |
| 1337 | "custom_toolkits", |
| 1338 | experimental.get("custom_toolkits"), |
| 1339 | ) |
| 1340 | |
| 1341 | inline_custom_tools_payload = _prepare_inline_custom_tools( |
| 1342 | custom_tools=custom_tools, |
| 1343 | custom_toolkits=custom_toolkits, |
| 1344 | default_preload=default_custom_preload, |
| 1345 | preload_tools=preload.get("tools") if preload is not None else None, |
| 1346 | ) |
| 1347 | if inline_custom_tools_payload: |
| 1348 | if "custom_tools" in inline_custom_tools_payload: |
| 1349 | experimental_payload["custom_tools"] = inline_custom_tools_payload[ |
| 1350 | "custom_tools" |
| 1351 | ] |
| 1352 | if "custom_toolkits" in inline_custom_tools_payload: |
| 1353 | experimental_payload["custom_toolkits"] = inline_custom_tools_payload[ |
| 1354 | "custom_toolkits" |
| 1355 | ] |
| 1356 | |
| 1357 | if experimental_payload: |
| 1358 | create_params["experimental"] = experimental_payload |
| 1359 | |
| 1360 | if self._provider is None: |
| 1361 | raise ValueError( |
| 1362 | "Provider is required for tool router. " |
| 1363 | "Please initialize ToolRouter with a provider." |
| 1364 | ) |
| 1365 | |
| 1366 | # Make API call to create session |
| 1367 | session = self._client.tool_router.session.create(**create_params) |
| 1368 | |
| 1369 | # Build custom tools routing map from backend response |
| 1370 | custom_tools_map: t.Optional[CustomToolsMap] = None |
| 1371 | if custom_tools or custom_toolkits: |
| 1372 | custom_tools_map = build_custom_tools_map_from_response( |
| 1373 | tools=custom_tools or [], |
| 1374 | toolkits=custom_toolkits, |
| 1375 | experimental=session.experimental, |
| 1376 | ) |
| 1377 | preloaded_custom_tool_slugs = get_preloaded_custom_tool_slugs( |
| 1378 | custom_tools_map, |
| 1379 | default_preload=default_custom_preload, |
| 1380 | ) |
| 1381 | |
| 1382 | # Transform experimental response: |
| 1383 | # API's assistive_prompt -> SDK's assistive_prompt |
| 1384 | # files mount is always present |
| 1385 | files_mount = ToolRouterSessionFilesMount(self._client, session.session_id) |
| 1386 | experimental_response = ToolRouterSessionExperimental( |
| 1387 | files=files_mount, |
| 1388 | assistive_prompt=( |
| 1389 | session.experimental.assistive_prompt if session.experimental else None |
| 1390 | ), |
| 1391 | ) |
| 1392 | |
| 1393 | # Create and return the session. `mcp=True` returns the subclass that |
| 1394 | # surfaces `session.mcp` in the type; the runtime object is otherwise |
| 1395 | # identical (the base always stores the MCP endpoint). |
| 1396 | session_cls: t.Type[ToolRouterSession[TTool, TToolCollection]] = ( |
| 1397 | ToolRouterSessionWithMcp if mcp else ToolRouterSession |
| 1398 | ) |
| 1399 | return session_cls( |
| 1400 | client=self._client, |
| 1401 | provider=self._provider, |
| 1402 | dangerously_allow_auto_upload_download_files=self._auto_upload_download_files, |
| 1403 | sensitive_file_upload_protection=self._sensitive_file_upload_protection, |
| 1404 | file_upload_path_deny_segments=self._file_upload_path_deny_segments, |
| 1405 | file_upload_dirs=self._file_upload_dirs, |
| 1406 | session_id=session.session_id, |
| 1407 | config=t.cast(ToolRouterSessionConfig, session.config), |
| 1408 | config_version=session.config_version, |
| 1409 | mcp=self._create_mcp_server_config( |
| 1410 | mcp_type=ToolRouterMCPServerType(session.mcp.type.lower()), |
| 1411 | url=session.mcp.url, |
| 1412 | mcp_requested=mcp, |
| 1413 | ), |
| 1414 | experimental=experimental_response, |
| 1415 | custom_tools_map=custom_tools_map, |
| 1416 | user_id=user_id, |
| 1417 | preload=_session_preload_config(session.config.preload), |
| 1418 | preloaded_custom_tool_slugs=preloaded_custom_tool_slugs, |
| 1419 | inline_custom_tools_payload=inline_custom_tools_payload, |
| 1420 | ) |
| 1421 | |
| 1422 | # Overloads mirror create(): pass ``mcp=True`` to surface ``session.mcp`` in |
| 1423 | # the returned type. See https://docs.composio.dev/docs/sessions-via-mcp |
| 1424 | @t.overload |
| 1425 | def use( |
| 1426 | self, |
| 1427 | session_id: str, |
| 1428 | *, |
| 1429 | local_tools: t.Optional[t.List[LocalTool]] = None, |
| 1430 | local_toolkits: t.Optional[t.List[LocalToolkit]] = None, |
| 1431 | custom_tools: t.Optional[t.List[CustomTool]] = None, |
| 1432 | custom_toolkits: t.Optional[t.List[ExperimentalToolkit]] = None, |
| 1433 | mcp: t.Literal[True], |
| 1434 | ) -> ToolRouterSessionWithMcp[TTool, TToolCollection]: ... |
| 1435 | |
| 1436 | @t.overload |
| 1437 | def use( |
| 1438 | self, |
| 1439 | session_id: str, |
| 1440 | *, |
| 1441 | local_tools: t.Optional[t.List[LocalTool]] = None, |
| 1442 | local_toolkits: t.Optional[t.List[LocalToolkit]] = None, |
| 1443 | custom_tools: t.Optional[t.List[CustomTool]] = None, |
| 1444 | custom_toolkits: t.Optional[t.List[ExperimentalToolkit]] = None, |
| 1445 | mcp: t.Literal[False] = False, |
| 1446 | ) -> ToolRouterSession[TTool, TToolCollection]: ... |
| 1447 | |
| 1448 | def use( |
| 1449 | self, |
| 1450 | session_id: str, |
| 1451 | *, |
| 1452 | local_tools: t.Optional[t.List[LocalTool]] = None, |
| 1453 | local_toolkits: t.Optional[t.List[LocalToolkit]] = None, |
| 1454 | custom_tools: t.Optional[t.List[CustomTool]] = None, |
| 1455 | custom_toolkits: t.Optional[t.List[ExperimentalToolkit]] = None, |
| 1456 | mcp: bool = False, |
| 1457 | ) -> ToolRouterSession[TTool, TToolCollection]: |
| 1458 | """ |
| 1459 | Use an existing tool router session. |
| 1460 | |
| 1461 | Provide ``local_tools`` or ``local_toolkits`` to bind local tools |
| 1462 | to the session for search and execution. |
| 1463 | |
| 1464 | If the existing session has ``preload.tools = "all"``, every bound |
| 1465 | local tool is also exposed via ``session.tools()`` and re-injected |
| 1466 | with ``preload=True`` on subsequent search/execute calls. A local tool |
| 1467 | with explicit ``preload=False`` still opts out. |
| 1468 | |
| 1469 | :param session_id: The session ID to use. |
| 1470 | :param local_tools: Optional local tools to bind to the session. |
| 1471 | :param local_toolkits: Optional local toolkits to bind to the session. |
| 1472 | :param custom_tools: Deprecated alias for ``local_tools``. |
| 1473 | :param custom_toolkits: Deprecated alias for ``local_toolkits``. |
| 1474 | :param mcp: When True, the returned session surfaces its hosted MCP |
| 1475 | endpoint in the type (returns ToolRouterSessionWithMcp). |
| 1476 | The session credential is exported in ``session.mcp.headers`` |
| 1477 | only when the MCP URL shares the origin of the configured |
| 1478 | API base URL. When it does not, ``mcp=True`` raises |
| 1479 | :class:`~composio.exceptions.MCPDestinationError` (naming |
| 1480 | both origins, never a key); otherwise the session is |
| 1481 | returned with empty ``session.mcp.headers`` and a warning |
| 1482 | naming both origins is logged. |
| 1483 | See https://docs.composio.dev/docs/sessions-via-mcp |
| 1484 | :return: Tool router session object |
| 1485 | :raises MCPDestinationError: When ``mcp=True`` and the MCP URL is not |
| 1486 | on the API origin. |
| 1487 | |
| 1488 | Example: |
| 1489 | ```python |
| 1490 | from composio import Composio |
| 1491 | |
| 1492 | composio = Composio() |
| 1493 | |
| 1494 | # Use an existing session |
| 1495 | session = composio.use('session_123') |
| 1496 | |
| 1497 | # Use an existing session with local tools |
| 1498 | session = composio.use( |
| 1499 | 'session_123', |
| 1500 | local_tools=[my_tool], |
| 1501 | local_toolkits=[my_toolkit], |
| 1502 | ) |
| 1503 | ``` |
| 1504 | """ |
| 1505 | if self._provider is None: |
| 1506 | raise ValueError( |
| 1507 | "Provider is required for tool router. " |
| 1508 | "Please initialize ToolRouter with a provider." |
| 1509 | ) |
| 1510 | |
| 1511 | custom_tools = _resolve_local_option( |
| 1512 | "local_tools", local_tools, "custom_tools", custom_tools |
| 1513 | ) |
| 1514 | custom_toolkits = _resolve_local_option( |
| 1515 | "local_toolkits", local_toolkits, "custom_toolkits", custom_toolkits |
| 1516 | ) |
| 1517 | has_customs = bool(custom_tools or custom_toolkits) |
| 1518 | attach_inline_custom_tools_payload = _prepare_inline_custom_tools( |
| 1519 | custom_tools=custom_tools, |
| 1520 | custom_toolkits=custom_toolkits, |
| 1521 | ) |
| 1522 | inline_custom_tools_payload = attach_inline_custom_tools_payload |
| 1523 | |
| 1524 | session: t.Union[SessionAttachResponse, SessionRetrieveResponse] |
| 1525 | if has_customs: |
| 1526 | session = self._client.tool_router.session.attach( |
| 1527 | session_id, |
| 1528 | experimental=attach_inline_custom_tools_payload |
| 1529 | if attach_inline_custom_tools_payload is not None |
| 1530 | else omit, |
| 1531 | ) |
| 1532 | else: |
| 1533 | session = self._client.tool_router.session.retrieve(session_id) |
| 1534 | |
| 1535 | default_custom_preload = _preloads_all_custom_tools(session.config.preload) |
| 1536 | if has_customs and default_custom_preload: |
| 1537 | # preload.tools = "all" on the existing session is server-authoritative: |
| 1538 | # the backend exposes every custom tool regardless of per-definition |
| 1539 | # preload flags, so the initial attach above (which used the caller's |
| 1540 | # explicit hints) doesn't need re-sending. We only rebuild the in-memory |
| 1541 | # payload so future search/execute calls re-inject with preload=True and |
| 1542 | # session.tools() locally mirrors what the server returns. |
| 1543 | inline_custom_tools_payload = _prepare_inline_custom_tools( |
| 1544 | custom_tools=custom_tools, |
| 1545 | custom_toolkits=custom_toolkits, |
| 1546 | default_preload=True, |
| 1547 | ) |
| 1548 | |
| 1549 | custom_tools_map: t.Optional[CustomToolsMap] = None |
| 1550 | user_id: t.Optional[str] = None |
| 1551 | if has_customs: |
| 1552 | custom_tools_map = build_custom_tools_map_from_response( |
| 1553 | tools=custom_tools or [], |
| 1554 | toolkits=custom_toolkits, |
| 1555 | experimental=session.experimental, |
| 1556 | ) |
| 1557 | user_id = session.config.user_id |
| 1558 | |
| 1559 | preloaded_custom_tool_slugs = get_preloaded_custom_tool_slugs( |
| 1560 | custom_tools_map, |
| 1561 | default_preload=default_custom_preload, |
| 1562 | ) |
| 1563 | |
| 1564 | files_mount = ToolRouterSessionFilesMount(self._client, session.session_id) |
| 1565 | experimental_response = ToolRouterSessionExperimental( |
| 1566 | files=files_mount, |
| 1567 | assistive_prompt=None, |
| 1568 | ) |
| 1569 | |
| 1570 | session_cls: t.Type[ToolRouterSession[TTool, TToolCollection]] = ( |
| 1571 | ToolRouterSessionWithMcp if mcp else ToolRouterSession |
| 1572 | ) |
| 1573 | return session_cls( |
| 1574 | client=self._client, |
| 1575 | provider=self._provider, |
| 1576 | dangerously_allow_auto_upload_download_files=self._auto_upload_download_files, |
| 1577 | sensitive_file_upload_protection=self._sensitive_file_upload_protection, |
| 1578 | file_upload_path_deny_segments=self._file_upload_path_deny_segments, |
| 1579 | file_upload_dirs=self._file_upload_dirs, |
| 1580 | session_id=session.session_id, |
| 1581 | config=t.cast(ToolRouterSessionConfig, session.config), |
| 1582 | config_version=session.config_version, |
| 1583 | mcp=self._create_mcp_server_config( |
| 1584 | mcp_type=ToolRouterMCPServerType(session.mcp.type.lower()), |
| 1585 | url=session.mcp.url, |
| 1586 | mcp_requested=mcp, |
| 1587 | ), |
| 1588 | experimental=experimental_response, |
| 1589 | custom_tools_map=custom_tools_map, |
| 1590 | user_id=user_id, |
| 1591 | preload=_session_preload_config(session.config.preload), |
| 1592 | preloaded_custom_tool_slugs=preloaded_custom_tool_slugs, |
| 1593 | inline_custom_tools_payload=inline_custom_tools_payload, |
| 1594 | ) |
| 1595 | |
| 1596 | def delete(self, session_id: str) -> ToolRouterSessionDeleteResponse: |
| 1597 | """ |
| 1598 | Delete a tool router session by ID. |
| 1599 | |
| 1600 | Deleted sessions immediately stop being retrievable or executable. A |
| 1601 | missing or already-deleted session surfaces the backend 404. |
| 1602 | """ |
| 1603 | return delete_tool_router_session(self._client, session_id) |
| 1604 | |
| 1605 | |
| 1606 | __all__ = [ |
| 1607 | "ToolRouter", |
| 1608 | "ToolRouterSession", |
| 1609 | "ToolRouterSessionWithMcp", |
| 1610 | "ToolRouterSessionDeleteResponse", |
| 1611 | "ToolRouterSessionExperimental", |
| 1612 | "ToolRouterToolkitsEnableConfig", |
| 1613 | "ToolRouterToolkitsDisableConfig", |
| 1614 | "ToolRouterToolsEnableConfig", |
| 1615 | "ToolRouterToolsDisableConfig", |
| 1616 | "ToolRouterToolsTagsConfig", |
| 1617 | "ToolRouterToolsConfig", |
| 1618 | "ToolRouterTag", |
| 1619 | "ToolRouterTagsEnableDisableConfig", |
| 1620 | "ToolRouterConfigTags", |
| 1621 | "ToolRouterManageConnectionsConfig", |
| 1622 | "ToolRouterUpdateManageConnectionsConfig", |
| 1623 | "ToolRouterUpdateMultiAccountConfig", |
| 1624 | "ToolRouterUpdateExperimentalConfig", |
| 1625 | "ToolRouterSandboxConfig", |
| 1626 | "ToolRouterWorkbenchConfig", |
| 1627 | "SandboxSize", |
| 1628 | "SessionPreset", |
| 1629 | "SESSION_PRESET_DIRECT_TOOLS", |
| 1630 | "ToolRouterMultiAccountConfig", |
| 1631 | "ToolRouterPreloadConfig", |
| 1632 | "ToolRouterExperimentalConfig", |
| 1633 | "ToolRouterAssistivePromptConfig", |
| 1634 | "ToolRouterSessionPreloadConfig", |
| 1635 | "ToolkitConnectionState", |
| 1636 | "ToolkitConnectionsDetails", |
| 1637 | "ToolRouterMCPServerConfig", |
| 1638 | "ToolRouterMCPServerType", |
| 1639 | ] |