Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

next
py 1,545 lines 62.1 KB
Raw
1 """
2 ToolRouterSession class for managing a single tool router session.
3
4 Provides methods for tools, authorize, toolkits, search, execute, and files.
5 When local tools are bound to the session, execution is routed: local tools
6 run in-process, remote tools are sent to the backend.
7 """
8
9 from __future__ import annotations
10
11 import typing as t
12 import warnings
13 from concurrent.futures import ThreadPoolExecutor
14 from dataclasses import dataclass
15
16 import typing_extensions as te
17 from composio_client import BadRequestError, ConflictError, Omit, omit
18 from composio_client._types import SequenceNotStr
19 from composio_client.types.tool_list_response import (
20 ItemDeprecated,
21 ItemDeprecatedToolkit,
22 ItemToolkit,
23 )
24 from composio_client.types.tool_router import (
25 session_create_response,
26 session_execute_params,
27 session_link_params,
28 session_patch_params,
29 session_search_response,
30 )
31
32 from composio import exceptions
33 from composio.client import HttpClient
34 from composio.client.types import (
35 Tool,
36 session_config_history_params,
37 session_config_history_response,
38 )
39 from composio.core.models._modifiers import Modifiers, apply_modifier_by_type
40 from composio.core.models.connected_accounts import ConnectionRequest
41 from composio.core.models.custom_tool import (
42 find_custom_tool_map_entry_by_final_slug,
43 find_custom_tool_map_entry_by_toolkit_and_original_slug,
44 )
45 from composio.core.models.custom_tool_execution import (
46 assert_unambiguous_custom_tool_slug,
47 execute_custom_tool,
48 find_custom_tool,
49 )
50 from composio.core.models.custom_tool_types import (
51 CustomToolsMap,
52 CustomToolsMapEntry,
53 InlineCustomToolsWirePayload,
54 RegisteredCustomTool,
55 RegisteredCustomToolkit,
56 RegisteredLocalTool,
57 RegisteredLocalToolkit,
58 ToolRouterSessionProxyExecuteResponse,
59 )
60 from composio.core.models.experimental import ACL_ONLY_FOR_SHARED_ERROR_FRAGMENT
61 from composio.core.models.session_context import (
62 SessionContextImpl,
63 proxy_execute_impl,
64 )
65 from composio.core.models.tool_router_session_delete import (
66 ToolRouterSessionDeleteResponse,
67 delete_tool_router_session,
68 )
69 from composio.core.models.tools import (
70 ToolExecuteParams,
71 ToolExecutionResponse,
72 ToolRouterSessionExecuteResponse,
73 require_execute_result,
74 )
75 from composio.core.provider import TTool, TToolCollection
76 from composio.core.provider.base import BaseProvider
77
78 if t.TYPE_CHECKING:
79 from composio.core.models.tool_router import (
80 ToolkitConnectionsDetails,
81 ToolRouterMCPServerConfig,
82 ToolRouterSessionExperimental,
83 )
84
85 COMPOSIO_MULTI_EXECUTE_TOOL = "COMPOSIO_MULTI_EXECUTE_TOOL"
86 DIRECT_CUSTOM_TOOL_DESCRIPTION_PREFIX = (
87 "[Direct tool - call directly, no search needed beforehand.]"
88 )
89 MAX_PARALLEL_WORKERS = 5
90
91
92 @dataclass
93 class ToolRouterSessionPreloadConfig:
94 """Preloaded tools configured for a tool router session."""
95
96 tools: t.Union[t.List[str], t.Literal["all"]]
97
98
99 class ToolRouterSessionConfig(t.Protocol):
100 """Server-side Session config, as the generated client models it."""
101
102 user_id: str
103 instant: t.Union[
104 t.Literal[False], session_create_response.CurrentConfigInstantVariant1
105 ]
106 auth_configs: t.Optional[t.Dict[str, str]]
107 connected_accounts: t.Optional[t.Dict[str, t.List[str]]]
108 execute: session_create_response.ConfigExecute
109 manage_connections: t.Optional[session_create_response.ConfigManageConnections]
110 multi_account: t.Optional[session_create_response.ConfigMultiAccount]
111 preload: session_create_response.ConfigPreload
112 search: session_create_response.ConfigSearch
113 tags: t.Optional[session_create_response.ConfigTags]
114 toolkits: t.Union[
115 session_create_response.ConfigToolkitsEnabled,
116 session_create_response.ConfigToolkitsDisabled,
117 session_create_response.ConfigToolkitsRequireApproval,
118 None,
119 ]
120 tools: t.Optional[
121 t.Dict[
122 str,
123 t.Union[
124 session_create_response.ConfigToolsEnabled,
125 session_create_response.ConfigToolsDisabled,
126 session_create_response.ConfigToolsTags,
127 session_create_response.ConfigToolsRequireApproval,
128 ],
129 ]
130 ]
131 workbench: t.Optional[session_create_response.ConfigWorkbench]
132 proxy_execute: t.Optional[session_create_response.CurrentConfigProxyExecute]
133
134 def model_dump(self, **kwargs: t.Any) -> t.Dict[str, t.Any]: ...
135
136 def model_dump_json(self, **kwargs: t.Any) -> str: ...
137
138 def model_copy(self, **kwargs: t.Any) -> ToolRouterSessionConfig: ...
139
140
141 class ToolRouterInstantEnable(te.TypedDict):
142 enable: t.List[str]
143
144
145 class ToolRouterInstantDisable(te.TypedDict):
146 disable: t.List[str]
147
148
149 class ToolRouterInstantConfig(te.TypedDict, total=False):
150 """Experimental Instant usage policy for a Session."""
151
152 toolkits: t.Union[ToolRouterInstantEnable, ToolRouterInstantDisable]
153 tools: t.Dict[str, t.Union[ToolRouterInstantEnable, ToolRouterInstantDisable]]
154 return_instant_charge: bool
155 return_prices_in_search: bool
156 """Experimental. Show each Instant tool's price in Session search results,
157 under ``instant_account.prices``. Controls visibility only."""
158
159
160 class ToolRouterProxyExecuteConfig(te.TypedDict):
161 """Proxy execute settings for a Session.
162
163 ``enable=True`` exposes the ``COMPOSIO_PROXY_EXECUTE`` meta tool and
164 ``enable=False`` also turns off the sandbox ``proxy_execute()`` helper.
165 Leaving the block out keeps the meta tool off while
166 ``sandbox.enable_proxy_execution`` controls the helper.
167 """
168
169 enable: bool
170
171
172 class ToolRouterHookToolkitsScope(te.TypedDict):
173 """Runs a hook only on calls to these toolkits, including their proxy calls."""
174
175 toolkits: t.List[str]
176
177
178 ToolRouterHookAppliesTo = t.Union[t.Literal["all"], ToolRouterHookToolkitsScope]
179 """Which tool calls a hook runs on: ``"all"``, or only the listed toolkits."""
180
181
182 class ToolRouterHookConditionCheckHandler(te.TypedDict):
183 """Blocks a call or result when it matches ``condition``.
184
185 ``condition`` is a plain sentence describing what to block, for example
186 ``"Sending email to anyone outside example.org"``.
187 """
188
189 type: t.Literal["condition_check"]
190 condition: str
191 action: t.Literal["block"]
192
193
194 class ToolRouterHookPromptInjectionCheckHandler(te.TypedDict):
195 """A pre-defined check that blocks results with text that tries to give
196 the agent instructions."""
197
198 type: t.Literal["prompt_injection_check"]
199 action: t.Literal["block"]
200
201
202 class ToolRouterBeforeExecuteHook(te.TypedDict):
203 """A hook that can block a tool call before it runs.
204
205 ``id`` is unique within the session and shows up in results and logs.
206 ``name`` is optional; the agent sees it when this hook blocks a call.
207 """
208
209 type: t.Literal["before_execute"]
210 id: str
211 name: te.NotRequired[str]
212 applies_to: ToolRouterHookAppliesTo
213 handler: ToolRouterHookConditionCheckHandler
214
215
216 class ToolRouterAfterExecuteHook(te.TypedDict):
217 """A hook that can block a tool call's result before the agent sees it.
218
219 ``id`` is unique within the session and shows up in results and logs.
220 ``name`` is optional; the agent sees it when this hook blocks a call.
221 """
222
223 type: t.Literal["after_execute"]
224 id: str
225 name: te.NotRequired[str]
226 applies_to: ToolRouterHookAppliesTo
227 handler: t.Union[
228 ToolRouterHookConditionCheckHandler, ToolRouterHookPromptInjectionCheckHandler
229 ]
230
231
232 ToolRouterHook = t.Union[ToolRouterBeforeExecuteHook, ToolRouterAfterExecuteHook]
233 """A hook on a session's tool calls."""
234
235
236 ToolRouterInputResponse = session_execute_params.CurrentInputResponsesValue
237 """Experimental. The user's answer to one question of a
238 ``ToolInputRequiredError``, in the shape of an MCP elicitation result:
239 ``action`` is ``"accept"`` with the form's fields in ``content``, ``"decline"``
240 when they said no, or ``"cancel"`` when they dismissed it. For an approval,
241 ``content`` is ``{"decision": "approve"}``, ``{"decision": "always_approve"}``
242 or ``{"decision": "deny"}``."""
243
244 ToolRouterSessionMetaToolSlug = t.Literal[
245 "COMPOSIO_SEARCH_TOOLS",
246 "COMPOSIO_MULTI_EXECUTE_TOOL",
247 "COMPOSIO_MANAGE_CONNECTIONS",
248 "COMPOSIO_WAIT_FOR_CONNECTIONS",
249 "COMPOSIO_REMOTE_WORKBENCH",
250 "COMPOSIO_REMOTE_BASH_TOOL",
251 "COMPOSIO_GET_TOOL_SCHEMAS",
252 "COMPOSIO_SUBMIT_FEEDBACK",
253 "COMPOSIO_PROXY_EXECUTE",
254 ]
255 """Slug of a Composio meta tool (``COMPOSIO_*``) that
256 :meth:`ToolRouterSession.execute_meta` can run."""
257
258 ToolRouterSessionSearchResponse = session_search_response.SessionSearchResponse
259 """Session search result. A toolkit served by a Composio Instant account
260 lists the covered tools at ``instant_account.allowed_tool_slugs`` on its
261 connection status, and their prices at ``instant_account.prices`` when the
262 Session sets ``instant.return_prices_in_search``."""
263
264
265 class ToolRouterUpdateManageConnectionsConfig(te.TypedDict, total=False):
266 """``manage_connections`` shape accepted by :meth:`ToolRouterSession.update`.
267
268 Only the supplied subfields travel. Unlike the create-time config,
269 ``callback_url=None`` removes the stored callback URL while leaving the
270 sibling connection settings untouched.
271 """
272
273 enable: t.Optional[bool]
274 callback_url: t.Optional[str]
275 enable_connection_removal: t.Optional[bool]
276 enable_wait_for_connections: t.Optional[bool]
277
278
279 class ToolRouterUpdateMultiAccountConfig(te.TypedDict, total=False):
280 """``multi_account`` shape accepted by :meth:`ToolRouterSession.update`.
281
282 ``max_accounts_per_toolkit=None`` removes the stored maximum so the
283 default applies again.
284 """
285
286 enable: bool
287 max_accounts_per_toolkit: t.Optional[int]
288 require_explicit_selection: bool
289
290
291 class ToolRouterUpdateExperimentalConfig(te.TypedDict, total=False):
292 """``experimental`` shape accepted by :meth:`ToolRouterSession.update`.
293
294 Each leaf follows the PATCH contract: omit to keep the stored value,
295 ``None`` to remove it, a value to replace it.
296 """
297
298 permissions: t.Optional[t.Dict[str, t.Any]]
299 link_url_overwrite: t.Optional[str]
300 fast_mode: t.Optional[bool]
301 submit_feedback: t.Optional[t.Dict[str, bool]]
302 session_config_id: str
303 no_elicitation_support_fallback: t.Literal["deny", "allow"]
304 """What happens to a call that needs the user's approval when the
305 session's MCP client can't ask the user: ``"deny"`` or ``"allow"``."""
306
307
308 _CUSTOM_TOOLS_DEPRECATION = (
309 "`session.custom_tools()` is deprecated; use `session.local_tools()`"
310 )
311 _CUSTOM_TOOLKITS_DEPRECATION = (
312 "`session.custom_toolkits()` is deprecated; use `session.local_toolkits()`"
313 )
314
315
316 class ToolRouterSession(t.Generic[TTool, TToolCollection]):
317 """
318 A Composio session — the object returned by ``composio.create(...)`` /
319 ``composio.use(...)``. Use it to fetch session-scoped tools, authorize
320 toolkits, search, and execute tools.
321
322 Generic Parameters:
323 TTool: The individual tool type returned by the provider.
324 TToolCollection: The collection type returned by tools().
325
326 The hosted MCP endpoint (``session.mcp``) exists at runtime on every
327 session, but is only surfaced in the type when you opt in with
328 ``create(..., mcp=True)`` / ``use(..., mcp=True)``, which returns a
329 :class:`ToolRouterSessionWithMcp`. By default agents use native tools via
330 :meth:`tools`. See https://docs.composio.dev/docs/sessions-via-mcp
331
332 Attributes:
333 session_id: Unique session identifier
334 config: Server-side session configuration as returned by the API,
335 refreshed in place by :meth:`update`
336 experimental: Experimental features (files, assistive prompt, etc.)
337 """
338
339 #: Unique session identifier.
340 session_id: str
341 #: Server-side session configuration (toolkit/tool allowlists, tags,
342 #: preload, sandbox, manage_connections) as returned by the API. Refreshed
343 #: in place by :meth:`update`.
344 config: ToolRouterSessionConfig
345 #: Experimental capabilities available on this session.
346 experimental: "ToolRouterSessionExperimental"
347 #: Version of the server-side configuration this object last observed.
348 #: Refreshed in place by :meth:`update`. Pass it as ``expected_config_version``
349 #: to make an update conditional.
350 config_version: t.Optional[int]
351
352 def __init__(
353 self,
354 *,
355 client: HttpClient,
356 provider: t.Optional[BaseProvider[t.Any, t.Any]],
357 dangerously_allow_auto_upload_download_files: bool,
358 sensitive_file_upload_protection: bool = True,
359 file_upload_path_deny_segments: t.Optional[t.Sequence[str]] = None,
360 file_upload_dirs: t.Union[t.Sequence[str], t.Literal[False], None] = None,
361 session_id: str,
362 mcp: t.Any,
363 experimental: "ToolRouterSessionExperimental",
364 config: t.Optional[ToolRouterSessionConfig] = None,
365 config_version: t.Optional[int] = None,
366 custom_tools_map: t.Optional[CustomToolsMap] = None,
367 user_id: t.Optional[str] = None,
368 preload: t.Optional[ToolRouterSessionPreloadConfig] = None,
369 preloaded_custom_tool_slugs: t.Optional[t.List[str]] = None,
370 inline_custom_tools_payload: t.Optional[InlineCustomToolsWirePayload] = None,
371 ) -> None:
372 self._client = client
373 self._provider = provider
374 self._auto_upload_download_files = dangerously_allow_auto_upload_download_files
375 self._sensitive_file_upload_protection = sensitive_file_upload_protection
376 self._file_upload_path_deny_segments = file_upload_path_deny_segments
377 self._file_upload_dirs = file_upload_dirs
378 self.session_id = session_id
379 self.preload = preload or ToolRouterSessionPreloadConfig(tools=[])
380 # Sessions built from an API response always carry their config; the
381 # fallback only covers direct construction without one (tests).
382 self.config = config or t.cast(
383 ToolRouterSessionConfig,
384 session_create_response.Config.model_construct(
385 user_id=user_id or "",
386 execute=session_create_response.ConfigExecute(),
387 search=session_create_response.ConfigSearch(),
388 preload=session_create_response.ConfigPreload(tools=self.preload.tools),
389 instant=False,
390 ),
391 )
392 # The MCP endpoint exists on every session at runtime (kept for
393 # backwards compatibility), but is only typed via
394 # ToolRouterSessionWithMcp. Assign through setattr so type checkers do
395 # not surface `mcp` on the base class — MCP is an explicit opt-in.
396 setattr(self, "mcp", mcp)
397 self.experimental = experimental
398 self.config_version = (
399 config_version if isinstance(config_version, int) else None
400 )
401 self._custom_tools_map = custom_tools_map
402 self._user_id = user_id
403 self._preloaded_custom_tool_slugs = preloaded_custom_tool_slugs or []
404 self._inline_custom_tools_payload = inline_custom_tools_payload
405
406 # Create singleton session context if custom tools are bound
407 self._session_context: t.Optional[SessionContextImpl] = None
408 if custom_tools_map and user_id:
409 self._session_context = SessionContextImpl(
410 client=client,
411 user_id=user_id,
412 session_id=session_id,
413 custom_tools_map=custom_tools_map,
414 inline_custom_tools_payload=inline_custom_tools_payload,
415 )
416
417 def _has_custom_tools(self) -> bool:
418 """Check if this session has any custom tools bound."""
419 if self._custom_tools_map is None:
420 return False
421 return len(self._custom_tools_map.by_final_slug) > 0
422
423 def _tool_router_backend_execute(
424 self,
425 tools_model: t.Any,
426 modifiers: t.Optional["Modifiers"] = None,
427 ) -> t.Callable[..., t.Any]:
428 """Backend execute wrapper with this session's file-upload settings."""
429 return tools_model._wrap_execute_tool_for_tool_router(
430 session_id=self.session_id,
431 modifiers=modifiers,
432 inline_custom_tools_payload=self._inline_custom_tools_payload,
433 )
434
435 def tools(self, modifiers: t.Optional["Modifiers"] = None) -> TToolCollection:
436 """
437 Get provider-wrapped tools for execution with your AI framework.
438
439 Returns tools configured for this session, wrapped in the format expected
440 by your AI provider (OpenAI, Anthropic, LangChain, etc.).
441
442 When custom tools are bound to the session, execution of
443 COMPOSIO_MULTI_EXECUTE_TOOL is intercepted: local tools are executed
444 in-process, remote tools are sent to the backend.
445 """
446 from composio.core.models.tools import Tools as ToolsModel
447 from composio.core.provider import (
448 AgenticProvider,
449 NonAgenticProvider,
450 bind_execution_target,
451 )
452
453 if self._provider is None:
454 raise ValueError(
455 "Provider is required for tool router. "
456 "Please initialize ToolRouter with a provider."
457 )
458
459 tools_model = ToolsModel(
460 client=self._client,
461 provider=self._provider,
462 dangerously_allow_auto_upload_download_files=self._auto_upload_download_files,
463 sensitive_file_upload_protection=self._sensitive_file_upload_protection,
464 file_upload_path_deny_segments=self._file_upload_path_deny_segments,
465 file_upload_dirs=self._file_upload_dirs,
466 )
467
468 router_tools = tools_model.get_raw_tool_router_meta_tools(
469 session_id=self.session_id,
470 modifiers=modifiers,
471 )
472 router_tools = self._add_preloaded_custom_tools(router_tools, modifiers)
473
474 for tool in router_tools:
475 tool.input_parameters = (
476 tools_model._file_helper.enhance_schema_descriptions(
477 schema=tool.input_parameters,
478 )
479 )
480
481 if issubclass(type(self._provider), NonAgenticProvider):
482 return t.cast(
483 TToolCollection,
484 t.cast(
485 NonAgenticProvider[TTool, TToolCollection], self._provider
486 ).wrap_tools(tools=router_tools),
487 )
488
489 # For agentic providers: if custom tools are bound, create a routing
490 # execute function that intercepts COMPOSIO_MULTI_EXECUTE_TOOL
491 if self._has_custom_tools():
492 execute_fn = self._create_routing_execute_fn(tools_model, modifiers)
493 else:
494 execute_fn = self._tool_router_backend_execute(
495 tools_model, modifiers=modifiers
496 )
497
498 return t.cast(
499 TToolCollection,
500 t.cast(AgenticProvider[TTool, TToolCollection], self._provider).wrap_tools(
501 tools=router_tools,
502 execute_tool=bind_execution_target(execute_fn, self),
503 ),
504 )
505
506 def _add_preloaded_custom_tools(
507 self,
508 tools: t.List[Tool],
509 modifiers: t.Optional["Modifiers"],
510 ) -> t.List[Tool]:
511 custom_tools = self._get_preloaded_custom_tool_schemas(modifiers)
512 if not custom_tools:
513 return tools
514
515 existing_slugs = {tool.slug.upper() for tool in tools}
516 appended_tools = [
517 tool for tool in custom_tools if tool.slug.upper() not in existing_slugs
518 ]
519 if not appended_tools:
520 return tools
521
522 return [*tools, *appended_tools]
523
524 def _get_preloaded_custom_tool_schemas(
525 self,
526 modifiers: t.Optional["Modifiers"],
527 ) -> t.List[Tool]:
528 if not self._custom_tools_map or not self._preloaded_custom_tool_slugs:
529 return []
530
531 tools: t.List[Tool] = []
532 for slug in self._preloaded_custom_tool_slugs:
533 entry = find_custom_tool_map_entry_by_final_slug(
534 self._custom_tools_map,
535 slug,
536 )
537 if entry is None:
538 continue
539
540 tool = self._custom_tool_entry_to_tool(entry)
541 if modifiers is not None:
542 tool = t.cast(
543 Tool,
544 apply_modifier_by_type(
545 modifiers=modifiers,
546 toolkit=tool.toolkit.slug,
547 tool=tool.slug,
548 type="schema",
549 schema=tool,
550 ),
551 )
552 tools.append(tool)
553
554 return tools
555
556 def _custom_tool_entry_to_tool(self, entry: CustomToolsMapEntry) -> Tool:
557 toolkit_slug = entry.toolkit or "custom"
558 toolkit_name = (
559 self._custom_toolkit_name(toolkit_slug) or entry.toolkit or "Custom"
560 )
561
562 return Tool(
563 available_versions=[],
564 deprecated=ItemDeprecated(
565 available_versions=[],
566 displayName=entry.handle.name,
567 is_deprecated=False,
568 toolkit=ItemDeprecatedToolkit(logo=""),
569 version="latest",
570 ),
571 description=(
572 f"{DIRECT_CUSTOM_TOOL_DESCRIPTION_PREFIX}\n{entry.handle.description}"
573 ),
574 input_parameters=entry.handle.input_schema,
575 is_deprecated=False,
576 name=entry.handle.name,
577 no_auth=entry.handle.extends_toolkit is None,
578 output_parameters=entry.handle.output_schema or {},
579 scopes=[],
580 slug=entry.final_slug,
581 tags=[],
582 toolkit=ItemToolkit(logo="", name=toolkit_name, slug=toolkit_slug),
583 version="latest",
584 )
585
586 def _custom_toolkit_name(self, toolkit_slug: str) -> t.Optional[str]:
587 if self._custom_tools_map is None:
588 return None
589
590 for toolkit in self._custom_tools_map.toolkits or []:
591 if toolkit.slug.lower() == toolkit_slug.lower():
592 return toolkit.name
593 return None
594
595 def _create_routing_execute_fn(
596 self,
597 tools_model: t.Any,
598 modifiers: t.Optional["Modifiers"],
599 ) -> t.Callable[..., t.Any]:
600 """Create an execute function that routes local/remote tools.
601
602 Applies before_execute/after_execute modifiers around the overall
603 COMPOSIO_MULTI_EXECUTE_TOOL call, consistent with the standard path.
604 """
605 backend_execute = self._tool_router_backend_execute(
606 tools_model, modifiers=modifiers
607 )
608
609 def routing_execute(slug: str, arguments: t.Dict) -> t.Dict:
610 if slug == COMPOSIO_MULTI_EXECUTE_TOOL:
611 # Apply before_execute modifiers
612 processed_arguments = arguments
613 if modifiers is not None:
614 type_before: t.Literal["before_execute"] = "before_execute"
615 params: ToolExecuteParams = {"arguments": arguments}
616 modified = apply_modifier_by_type(
617 modifiers=modifiers,
618 toolkit="composio",
619 tool=slug,
620 type=type_before,
621 request=params,
622 )
623 processed_arguments = modified.get("arguments", arguments)
624
625 result = self._route_multi_execute(processed_arguments, tools_model)
626
627 # Apply after_execute modifiers
628 if modifiers is not None:
629 type_after: t.Literal["after_execute"] = "after_execute"
630 result = t.cast(
631 t.Dict[str, t.Any],
632 apply_modifier_by_type(
633 modifiers=modifiers,
634 toolkit="composio",
635 tool=slug,
636 type=type_after,
637 response=t.cast(ToolExecutionResponse, result),
638 ),
639 )
640
641 return result
642 entry = find_custom_tool(self._custom_tools_map, slug)
643 if entry:
644 return t.cast(
645 t.Dict[str, t.Any],
646 execute_custom_tool(
647 entry,
648 arguments,
649 t.cast(SessionContextImpl, self._session_context),
650 ),
651 )
652 assert_unambiguous_custom_tool_slug(self._custom_tools_map, slug)
653 # Non-multi-execute meta tools always go to backend
654 return backend_execute(slug, arguments)
655
656 return routing_execute
657
658 def _parse_tool_item(self, item: t.Any) -> t.Dict[str, t.Any]:
659 """Parse an individual tool item from COMPOSIO_MULTI_EXECUTE_TOOL's tools array."""
660 if not isinstance(item, dict):
661 return {"tool_slug": "", "arguments": {}}
662 return {
663 "tool_slug": str(item.get("tool_slug", "")),
664 "arguments": item.get("arguments", {}),
665 }
666
667 def _route_multi_execute(
668 self,
669 input_args: t.Dict[str, t.Any],
670 tools_model: t.Any,
671 ) -> t.Dict[str, t.Any]:
672 """Route a COMPOSIO_MULTI_EXECUTE_TOOL call.
673
674 Splits the tools[] array into local and remote, executes each
675 appropriately, and merges results in the original request order.
676
677 Modifiers are NOT applied here — the caller (routing_execute)
678 handles before_execute/after_execute to avoid double application.
679 """
680 tool_items = input_args.get("tools")
681 if not isinstance(tool_items, list) or len(tool_items) == 0:
682 # Fallback: send to backend as-is (no modifiers — caller handles them)
683 return self._tool_router_backend_execute(tools_model)(
684 COMPOSIO_MULTI_EXECUTE_TOOL,
685 input_args,
686 )
687
688 parsed = [self._parse_tool_item(item) for item in tool_items]
689
690 # Partition into local (with resolved entry) and remote
691 local_items: t.List[t.Tuple[int, CustomToolsMapEntry]] = []
692 remote_indices: t.List[int] = []
693 for i, p in enumerate(parsed):
694 entry = find_custom_tool(self._custom_tools_map, p["tool_slug"])
695 if entry:
696 local_items.append((i, entry))
697 else:
698 assert_unambiguous_custom_tool_slug(
699 self._custom_tools_map, p["tool_slug"]
700 )
701 remote_indices.append(i)
702
703 # All remote — just forward entire payload (no modifiers — caller handles them)
704 if not local_items:
705 return self._tool_router_backend_execute(tools_model)(
706 COMPOSIO_MULTI_EXECUTE_TOOL,
707 input_args,
708 )
709
710 ctx = self._session_context
711 assert ctx is not None
712
713 # Determine worker count (capped at MAX_PARALLEL_WORKERS)
714 num_tasks = len(local_items) + (1 if remote_indices else 0)
715 num_workers = min(MAX_PARALLEL_WORKERS, num_tasks)
716
717 with ThreadPoolExecutor(max_workers=num_workers) as pool:
718 # Submit local tool executions
719 local_futures = []
720 for idx, entry in local_items:
721 future = pool.submit(
722 execute_custom_tool,
723 entry,
724 parsed[idx]["arguments"],
725 ctx,
726 )
727 local_futures.append((idx, future))
728
729 # Submit remote batch (single call) if any
730 # No modifiers here — the outer routing_execute handles them
731 remote_future = None
732 if remote_indices:
733 remote_tool_items = [tool_items[i] for i in remote_indices]
734 remote_input = {**input_args, "tools": remote_tool_items}
735 execute_fn = self._tool_router_backend_execute(tools_model)
736 remote_future = pool.submit(
737 execute_fn,
738 COMPOSIO_MULTI_EXECUTE_TOOL,
739 remote_input,
740 )
741
742 # Gather local results
743 local_results: t.List[t.Tuple[int, ToolExecutionResponse]] = []
744 for idx, future in local_futures:
745 local_results.append((idx, future.result()))
746
747 # Gather remote result. A transport failure (exception from the
748 # backend call) must not discard completed local results, so it
749 # is captured here and surfaced as per-tool failures below
750 # (matches TS).
751 remote_result: t.Optional[t.Dict[str, t.Any]] = None
752 remote_error_message: t.Optional[str] = None
753 if remote_future:
754 try:
755 remote_result = remote_future.result()
756 except exceptions.ToolInputRequiredError:
757 # An input request is not a per-tool failure: re-raise it so
758 # the caller gets `input_requests` and `request_state`.
759 # Accepted: local tools in this batch already ran and their results are discarded.
760 raise
761 except Exception as error:
762 remote_error_message = str(error) or "Remote tool execution failed"
763
764 # If only one local tool and no remote, return unwrapped
765 if not remote_indices and len(local_results) == 1:
766 return t.cast(t.Dict[str, t.Any], local_results[0][1])
767
768 # Build local result entries matching backend format
769 local_entries = []
770 for idx, result in local_results:
771 local_entry: t.Dict[str, t.Any] = {
772 "response": {
773 "successful": result["successful"],
774 "data": result["data"],
775 },
776 "tool_slug": parsed[idx]["tool_slug"],
777 "index": idx,
778 }
779 if result.get("error"):
780 local_entry["response"]["error"] = result["error"]
781 local_entry["error"] = result["error"]
782 local_entries.append(local_entry)
783
784 # Restore original request order, then re-index sequentially.
785 remote_data_raw = (remote_result or {}).get("data")
786 remote_data = remote_data_raw if isinstance(remote_data_raw, dict) else {}
787 remote_results_list: t.List[t.Dict[str, t.Any]]
788 if remote_error_message is not None:
789 remote_results_list = [
790 {
791 "response": {
792 "successful": False,
793 "data": {},
794 "error": remote_error_message,
795 },
796 "tool_slug": parsed[index]["tool_slug"],
797 "error": remote_error_message,
798 }
799 for index in remote_indices
800 ]
801 else:
802 remote_results_list = (
803 remote_data.get("results", [])
804 if isinstance(remote_data.get("results"), list)
805 else []
806 )
807 merged_results = [
808 {
809 **entry,
810 "index": remote_indices[position]
811 if position < len(remote_indices)
812 else position,
813 }
814 for position, entry in enumerate(remote_results_list)
815 ]
816 merged_results.extend(local_entries)
817 merged_results.sort(key=lambda entry: int(entry["index"]))
818 all_results = [{**entry, "index": i} for i, entry in enumerate(merged_results)]
819 failed = sum(1 for r in all_results if r.get("error"))
820 merged_data = {**remote_data, "results": all_results}
821 if local_entries and (
822 remote_error_message is not None
823 or any(
824 key in remote_data
825 for key in ("total_count", "success_count", "error_count")
826 )
827 ):
828 merged_data["total_count"] = len(all_results)
829 merged_data["success_count"] = len(all_results) - failed
830 merged_data["error_count"] = failed
831
832 remote_error = remote_error_message
833 if remote_error is None and remote_result:
834 raw_remote_error = remote_result.get("error")
835 remote_error = (
836 str(raw_remote_error) if raw_remote_error is not None else None
837 )
838 # A failed execution can carry no error text, so success is read from
839 # each result's own verdict and not from the absence of an error message.
840 has_any_failure = (
841 any(not r["successful"] for _, r in local_results)
842 or (remote_result is not None and remote_result.get("successful") is False)
843 or bool(remote_error)
844 )
845 error_message = None
846 if has_any_failure:
847 error_message = (
848 f"{failed} out of {len(all_results)} tools failed"
849 if failed > 0
850 else remote_error
851 )
852
853 merged: t.Dict[str, t.Any] = {
854 "data": merged_data,
855 "error": error_message,
856 "successful": not has_any_failure,
857 }
858 if remote_result and remote_result.get("instant_charge") is not None:
859 merged["instant_charge"] = remote_result["instant_charge"]
860 return merged
861
862 def authorize(
863 self,
864 toolkit: str,
865 *,
866 callback_url: t.Optional[str] = None,
867 alias: t.Optional[str] = None,
868 experimental: t.Optional[session_link_params.Experimental] = None,
869 ) -> ConnectionRequest:
870 """
871 Authorize a toolkit for the user and get a connection request.
872
873 Initiates the OAuth flow and returns a ConnectionRequest with redirect URL.
874
875 :param alias: Human-readable alias for the connection. Must be unique
876 per userId and toolkit within the project.
877 :param experimental: Experimental options for this connection. Pass an
878 ``Experimental`` dict with ``account_type`` and/or
879 ``acl_config_for_shared`` to create a SHARED connection with a
880 per-user ACL. Experimental — shape may change in future releases.
881 """
882 try:
883 response = self._client.tool_router.session.link(
884 session_id=self.session_id,
885 toolkit=toolkit,
886 callback_url=callback_url if callback_url else omit,
887 alias=alias if alias is not None else omit,
888 experimental=experimental if experimental is not None else omit,
889 )
890 except BadRequestError as error:
891 # The server rejects ACL on PRIVATE connections — surface that
892 # as a typed error mirroring ``composio.connected_accounts.link()``.
893 message = str(error)
894 if ACL_ONLY_FOR_SHARED_ERROR_FRAGMENT in message:
895 raise exceptions.ComposioAclOnlyForSharedError(message) from error
896 raise
897
898 return ConnectionRequest(
899 id=response.connected_account_id,
900 redirect_url=response.redirect_url,
901 status="INITIATED",
902 client=self._client,
903 )
904
905 def toolkits(
906 self,
907 *,
908 toolkits: t.Optional[t.List[str]] = None,
909 next_cursor: t.Optional[str] = None,
910 limit: t.Optional[int] = None,
911 is_connected: t.Optional[bool] = None,
912 search: t.Optional[str] = None,
913 ) -> ToolkitConnectionsDetails:
914 """
915 Get toolkit connection states for the session.
916 """
917 from composio.core.models.tool_router import (
918 ToolkitConnectedAccount,
919 ToolkitConnection,
920 ToolkitConnectionAuthConfig,
921 ToolkitConnectionsDetails,
922 ToolkitConnectionState,
923 )
924
925 toolkits_params: t.Dict[str, t.Any] = {}
926 if next_cursor is not None:
927 toolkits_params["cursor"] = next_cursor
928 if limit is not None:
929 toolkits_params["limit"] = limit
930 if toolkits is not None:
931 toolkits_params["toolkits"] = toolkits
932 if is_connected is not None:
933 toolkits_params["is_connected"] = is_connected
934 if search is not None:
935 toolkits_params["search"] = search
936
937 result = self._client.tool_router.session.toolkits(
938 session_id=self.session_id,
939 **toolkits_params,
940 )
941
942 toolkit_states: t.List[ToolkitConnectionState] = []
943 for item in result.items:
944 connected_account = item.connected_account
945 auth_config: t.Optional[ToolkitConnectionAuthConfig] = None
946 connected_acc: t.Optional[ToolkitConnectedAccount] = None
947
948 if connected_account:
949 if connected_account.auth_config:
950 auth_config = ToolkitConnectionAuthConfig(
951 id=connected_account.auth_config.id,
952 mode=connected_account.auth_config.auth_scheme,
953 is_composio_managed=connected_account.auth_config.is_composio_managed,
954 )
955 connected_acc = ToolkitConnectedAccount(
956 id=connected_account.id,
957 status=connected_account.status,
958 )
959
960 connection = (
961 None
962 if item.is_no_auth
963 else ToolkitConnection(
964 is_active=(
965 connected_account.status == "ACTIVE"
966 if connected_account
967 else False
968 ),
969 auth_config=auth_config,
970 connected_account=connected_acc,
971 )
972 )
973
974 toolkit_state = ToolkitConnectionState(
975 slug=item.slug,
976 name=item.name,
977 logo=item.meta.logo if item.meta else None,
978 is_no_auth=item.is_no_auth if item.is_no_auth else False,
979 connection=connection,
980 )
981 toolkit_states.append(toolkit_state)
982
983 return ToolkitConnectionsDetails(
984 items=toolkit_states,
985 next_cursor=result.next_cursor,
986 total_pages=int(result.total_pages),
987 )
988
989 def search(
990 self,
991 *,
992 query: str,
993 model: t.Optional[str] = None,
994 ) -> ToolRouterSessionSearchResponse:
995 """
996 Search for tools by semantic use case.
997
998 Returns relevant tools for the given query with schemas and guidance.
999 """
1000 return self._client.tool_router.session.search(
1001 session_id=self.session_id,
1002 queries=[{"use_case": query}],
1003 model=model if model else omit,
1004 experimental=self._inline_custom_tools_payload
1005 if self._inline_custom_tools_payload is not None
1006 else omit,
1007 )
1008
1009 def execute(
1010 self,
1011 tool_slug: str,
1012 *,
1013 arguments: t.Optional[t.Dict[str, t.Any]] = None,
1014 account: t.Optional[str] = None,
1015 input_responses: t.Optional[t.Dict[str, ToolRouterInputResponse]] = None,
1016 request_state: t.Optional[str] = None,
1017 ) -> ToolRouterSessionExecuteResponse:
1018 """
1019 Execute a tool within the session.
1020
1021 Use ``tool_slug=...`` (not the direct Tools API's ``slug=...``) and
1022 ``arguments={...}``. The return value is a Pydantic model: read
1023 ``result.result_type == "completed"`` for execution success,
1024 ``result.model_dump(mode="json")`` for a JSON-compatible dictionary,
1025 or ``result.model_dump_json()`` for a JSON string. Unlike provider
1026 helper results and ``after_execute`` modifier dictionaries, it has
1027 no ``successful`` key. This call has no model tool-call ID; retain
1028 that ID separately when building provider messages.
1029
1030 For custom tools, accepts the full slug (e.g. "LOCAL_GREP") or the
1031 original slug (e.g. "GREP") when that original slug is unique across
1032 the session's custom tools and toolkits. Custom tools are executed
1033 in-process; remote tools are sent to the Composio backend.
1034
1035 :param account: Account ID or alias for direct app tool execution in
1036 multi-account sessions. Helper/meta tools either ignore this
1037 top-level field or define their own account-selection fields.
1038 :param input_responses: Experimental. The user's answers to an earlier
1039 ``ToolInputRequiredError``, keyed by the IDs in its
1040 ``input_requests``. Repeat the same call (same tool and arguments)
1041 with them. An approved call runs; a denied or declined one returns
1042 ``result_type="failed"``.
1043 :param request_state: Experimental. The ``request_state`` of that
1044 error, sent back unchanged.
1045
1046 Both paths return a ``ToolRouterSessionExecuteResponse`` with ``data``,
1047 ``error``, ``log_id``, ``result_type``, and ``instant_charge``
1048 attributes. ``result_type`` is ``"completed"``, ``"failed"`` or
1049 ``"blocked"``; a failed execution can carry a ``None`` or empty
1050 ``error``, so read ``result_type`` to tell them apart. A ``"blocked"``
1051 call (a session hook blocked it) has empty ``data``, the hook's message
1052 in ``error``, and ``block_reason`` (``type`` and ``hook_id``).
1053 ``hook_results`` lists every session hook that applied.
1054 A log ID correlates an execution; it does not prove that a provider
1055 performed a side effect. Inspect the tool-specific ``data`` as well.
1056 Transport and authentication errors raise instead of returning an
1057 execution result. Handle authentication recovery separately from
1058 returned tool failures; retry/idempotency decisions belong to you.
1059
1060 :raises ToolInputRequiredError: If the tool needs input from the user
1061 (for example an approval) before it can run. Nothing was executed.
1062 :raises ValidationError: If the API response carries no ``result_type``,
1063 or one this SDK does not know.
1064 """
1065 # Check if this is a local tool (by original or final slug)
1066 entry = find_custom_tool(self._custom_tools_map, tool_slug)
1067 if entry and self._session_context:
1068 result = execute_custom_tool(entry, arguments or {}, self._session_context)
1069 return ToolRouterSessionExecuteResponse(
1070 data=result["data"],
1071 error=result["error"],
1072 log_id="",
1073 result_type="completed" if result["successful"] else "failed",
1074 )
1075
1076 assert_unambiguous_custom_tool_slug(self._custom_tools_map, tool_slug)
1077
1078 # Disable retries: a session execution is a non-idempotent write, and a
1079 # silent retry after a read timeout can duplicate the side effect.
1080 return require_execute_result(
1081 self._client.without_retries.tool_router.session.execute(
1082 session_id=self.session_id,
1083 tool_slug=tool_slug,
1084 arguments=arguments if arguments is not None else omit,
1085 account=account if account is not None else omit,
1086 input_responses=(
1087 input_responses if input_responses is not None else omit
1088 ),
1089 request_state=request_state if request_state is not None else omit,
1090 experimental=self._inline_custom_tools_payload
1091 if self._inline_custom_tools_payload is not None
1092 else omit,
1093 ),
1094 tool_slug,
1095 )
1096
1097 def execute_meta(
1098 self,
1099 slug: ToolRouterSessionMetaToolSlug,
1100 *,
1101 arguments: t.Optional[t.Dict[str, t.Any]] = None,
1102 input_responses: t.Optional[t.Dict[str, ToolRouterInputResponse]] = None,
1103 request_state: t.Optional[str] = None,
1104 ) -> ToolRouterSessionExecuteResponse:
1105 """
1106 Execute a Composio meta tool (``COMPOSIO_*``) within the session.
1107
1108 :meth:`execute` also runs meta tools. This method only accepts meta
1109 tool slugs, so a typo is a type error instead of a failed request. The
1110 call is sent to the Composio backend as is: custom tools named in a
1111 ``COMPOSIO_MULTI_EXECUTE_TOOL`` call are not run in-process here.
1112
1113 :param slug: The meta tool slug to execute.
1114 :param arguments: Optional meta tool arguments.
1115 :param input_responses: Experimental. The user's answers to an earlier
1116 ``ToolInputRequiredError``, keyed by the IDs in its
1117 ``input_requests``. Repeat the same call with them, as in :meth:`execute`.
1118 :param request_state: Experimental. The ``request_state`` of that
1119 error, sent back unchanged.
1120 :returns: The tool execution result, in the same shape as
1121 :meth:`execute`.
1122 :raises ToolInputRequiredError: If the tool needs input from the user
1123 (for example an approval) before it can run. Nothing was executed.
1124 :raises ValidationError: If the API response carries no ``result_type``,
1125 or one this SDK does not know.
1126
1127 Example:
1128 result = session.execute_meta(
1129 "COMPOSIO_SEARCH_TOOLS",
1130 arguments={"queries": [{"use_case": "send an email"}]},
1131 )
1132 print(result.result_type, result.data)
1133 """
1134 # Disable retries: a session execution is a non-idempotent write, and a
1135 # silent retry after a read timeout can duplicate the side effect.
1136 return require_execute_result(
1137 self._client.without_retries.tool_router.session.execute_meta(
1138 session_id=self.session_id,
1139 slug=slug,
1140 arguments=arguments if arguments is not None else omit,
1141 input_responses=(
1142 input_responses if input_responses is not None else omit
1143 ),
1144 request_state=request_state if request_state is not None else omit,
1145 experimental=self._inline_custom_tools_payload
1146 if self._inline_custom_tools_payload is not None
1147 else omit,
1148 ),
1149 slug,
1150 )
1151
1152 def local_tools(
1153 self, *, toolkit: t.Optional[str] = None
1154 ) -> t.List[RegisteredLocalTool]:
1155 """List all local tools registered in this session.
1156
1157 Returns tools with their final slugs, schemas, and resolved toolkit.
1158
1159 :param toolkit: Filter by toolkit slug (e.g. 'gmail', 'DEV_TOOLS')
1160 :returns: Array of registered local tools
1161 """
1162 if not self._custom_tools_map:
1163 return []
1164
1165 entries = list(self._custom_tools_map.by_final_slug.values())
1166 if toolkit:
1167 entries = [
1168 e for e in entries if e.toolkit and e.toolkit.lower() == toolkit.lower()
1169 ]
1170
1171 return [
1172 RegisteredCustomTool(
1173 slug=entry.final_slug,
1174 name=entry.handle.name,
1175 description=entry.handle.description,
1176 toolkit=entry.toolkit,
1177 input_schema=entry.handle.input_schema,
1178 output_schema=entry.handle.output_schema,
1179 )
1180 for entry in entries
1181 ]
1182
1183 def local_toolkits(self) -> t.List[RegisteredLocalToolkit]:
1184 """List all toolkits of local tools registered in this session.
1185
1186 Returns toolkits with their tools showing final slugs.
1187 """
1188 if not self._custom_tools_map or not self._custom_tools_map.toolkits:
1189 return []
1190
1191 result = []
1192 for tk in self._custom_tools_map.toolkits:
1193 tools = []
1194 for tool in tk.tools:
1195 entry = find_custom_tool_map_entry_by_toolkit_and_original_slug(
1196 self._custom_tools_map, tk.slug, tool.slug
1197 )
1198 if entry is None:
1199 # Only trust a bare alias that belongs to this toolkit.
1200 bare = self._custom_tools_map.by_original_slug.get(
1201 tool.slug.upper()
1202 )
1203 if (
1204 bare is not None
1205 and bare.toolkit is not None
1206 and bare.toolkit.lower() == tk.slug.lower()
1207 ):
1208 entry = bare
1209 tools.append(
1210 RegisteredCustomTool(
1211 slug=entry.final_slug if entry else tool.slug,
1212 name=tool.name,
1213 description=tool.description,
1214 toolkit=tk.slug,
1215 input_schema=tool.input_schema,
1216 output_schema=tool.output_schema,
1217 )
1218 )
1219 result.append(
1220 RegisteredCustomToolkit(
1221 slug=tk.slug,
1222 name=tk.name,
1223 description=tk.description,
1224 tools=tools,
1225 )
1226 )
1227 return result
1228
1229 @te.deprecated(_CUSTOM_TOOLS_DEPRECATION, category=None)
1230 def custom_tools(
1231 self, *, toolkit: t.Optional[str] = None
1232 ) -> t.List[RegisteredCustomTool]:
1233 """Deprecated alias for :meth:`local_tools`."""
1234 warnings.warn(
1235 _CUSTOM_TOOLS_DEPRECATION,
1236 exceptions.ComposioDeprecationWarning,
1237 stacklevel=2,
1238 )
1239 return self.local_tools(toolkit=toolkit)
1240
1241 @te.deprecated(_CUSTOM_TOOLKITS_DEPRECATION, category=None)
1242 def custom_toolkits(self) -> t.List[RegisteredCustomToolkit]:
1243 """Deprecated alias for :meth:`local_toolkits`."""
1244 warnings.warn(
1245 _CUSTOM_TOOLKITS_DEPRECATION,
1246 exceptions.ComposioDeprecationWarning,
1247 stacklevel=2,
1248 )
1249 return self.local_toolkits()
1250
1251 def proxy_execute(
1252 self,
1253 *,
1254 toolkit: str,
1255 endpoint: str,
1256 method: t.Literal["GET", "POST", "PUT", "DELETE", "PATCH"],
1257 body: t.Any = None,
1258 parameters: t.Optional[t.List[t.Dict[str, t.Any]]] = None,
1259 ) -> ToolRouterSessionProxyExecuteResponse:
1260 """Proxy an API call through Composio's auth layer.
1261
1262 :param toolkit: Composio toolkit slug (e.g. 'gmail', 'github')
1263 :param endpoint: API endpoint URL
1264 :param method: HTTP method
1265 :param body: Request body (for POST, PUT, PATCH)
1266 :param parameters: Query/header parameters
1267 :returns: The proxied API response with ``result_type="completed"``,
1268 or ``result_type="blocked"`` with the hook's ``message`` when a
1269 session hook blocked the request (it then has no ``status``)
1270 :raises ToolInputRequiredError: If the call needs input from the user
1271 before it can run. Nothing was executed.
1272 """
1273 return proxy_execute_impl(
1274 self._client,
1275 self.session_id,
1276 toolkit=toolkit,
1277 endpoint=endpoint,
1278 method=method,
1279 body=body,
1280 parameters=parameters,
1281 )
1282
1283 def update(
1284 self,
1285 *,
1286 toolkits: t.Union[t.Optional[session_patch_params.Toolkits], "Omit"] = omit,
1287 instant: t.Union[t.Literal[False], ToolRouterInstantConfig, "Omit"] = omit,
1288 tools: t.Union[
1289 t.Optional[t.Dict[str, session_patch_params.Tools]], "Omit"
1290 ] = omit,
1291 tags: t.Union[t.Optional[session_patch_params.Tags], "Omit"] = omit,
1292 auth_configs: t.Union[t.Optional[t.Dict[str, str]], "Omit"] = omit,
1293 connected_accounts: t.Union[
1294 t.Optional[t.Dict[str, SequenceNotStr[str]]], "Omit"
1295 ] = omit,
1296 manage_connections: t.Union[
1297 t.Optional[session_patch_params.ManageConnections],
1298 t.Optional[ToolRouterUpdateManageConnectionsConfig],
1299 "Omit",
1300 ] = omit,
1301 sandbox: t.Union[t.Optional[session_patch_params.Workbench], "Omit"] = omit,
1302 workbench: t.Union[t.Optional[session_patch_params.Workbench], "Omit"] = omit,
1303 multi_account: t.Union[
1304 t.Optional[session_patch_params.MultiAccount],
1305 t.Optional[ToolRouterUpdateMultiAccountConfig],
1306 "Omit",
1307 ] = omit,
1308 proxy_execute: t.Union[
1309 t.Optional[t.Union[bool, ToolRouterProxyExecuteConfig]], "Omit"
1310 ] = omit,
1311 hooks: t.Union[t.Optional[t.List[ToolRouterHook]], "Omit"] = omit,
1312 preload: t.Union[t.Optional[session_patch_params.Preload], "Omit"] = omit,
1313 search: t.Union[t.Optional[session_patch_params.Search], "Omit"] = omit,
1314 execute: t.Union[t.Optional[session_patch_params.Execute], "Omit"] = omit,
1315 experimental: t.Union[
1316 t.Optional[session_patch_params.Experimental],
1317 t.Optional[ToolRouterUpdateExperimentalConfig],
1318 "Omit",
1319 ] = omit,
1320 expected_config_version: t.Union[int, None, t.Literal[False]] = None,
1321 ) -> ToolRouterSessionConfig:
1322 """Partially update the session configuration.
1323
1324 Only the fields provided are changed; omitted fields are preserved.
1325 For each policy block ``None`` removes the stored override (which can
1326 increase access: ``toolkits=None`` restores the unrestricted default,
1327 while ``toolkits={"enable": []}`` denies every app toolkit and is sent
1328 as-is). Supplied ``tools``, ``auth_configs`` and ``connected_accounts``
1329 maps replace the stored map entirely. Inside ``manage_connections``,
1330 ``callback_url=None`` removes only the stored callback URL.
1331 Experimental ``instant`` accepts ``False`` to disable billed
1332 access or an object to set its filters; it does not accept ``None``.
1333 Any object, even one that only sets ``return_instant_charge`` or
1334 ``return_prices_in_search``, re-enables Instant usage on a Session
1335 set to ``False``.
1336 ``proxy_execute`` takes a bool or ``{"enable": bool}``; ``True``
1337 exposes the ``COMPOSIO_PROXY_EXECUTE`` meta tool, ``False`` also turns
1338 off the sandbox ``proxy_execute()`` helper, and ``None`` removes the
1339 stored block.
1340 ``hooks`` replaces the whole list of hooks, and ``None`` removes every
1341 hook. ``hooks`` cannot be combined with
1342 ``experimental={'session_config_id': ...}`` (``hooks=None`` counts).
1343
1344 By default the request carries no precondition: the last writer wins.
1345 Pass ``expected_config_version`` (for example this object's
1346 ``config_version``) to make the update conditional: the API then
1347 applies it only when the stored version still matches, and a concurrent
1348 change raises :class:`~composio.exceptions.SessionConfigConflictError`
1349 (HTTP 409) instead of being overwritten. The API must support the
1350 ``expected_config_version`` field; otherwise it rejects the request with
1351 a 400. ``expected_config_version=False`` is the same as omitting it.
1352 The PATCH is never retried by the transport, so a 409 is reported
1353 exactly once. On conflict this object stays unchanged: re-fetch the
1354 session with ``composio.sessions.use(session_id)`` and retry against
1355 the fresh ``config_version``.
1356
1357 ``config``, ``config_version`` and ``preload`` are refreshed in place
1358 only after a successful response, and the updated ``config`` is
1359 returned.
1360
1361 ``workbench`` is a backwards-compatible alias for ``sandbox``. Prefer
1362 ``sandbox`` in new code.
1363
1364 All other parameters use the same types as the generated
1365 ``client.tool_router.session.patch()`` method.
1366 """
1367 from composio.core.models.tool_router import _session_preload_config
1368
1369 if sandbox is not omit and workbench is not omit:
1370 raise exceptions.InvalidParams(
1371 "Pass either `sandbox` or `workbench`, not both. "
1372 "`workbench` is a backwards-compatible alias for `sandbox`."
1373 )
1374 if instant is None:
1375 raise exceptions.InvalidParams(
1376 "`instant` does not accept None; pass False to disable "
1377 "Instant usage, or omit it to keep the stored policy"
1378 )
1379 if (
1380 not isinstance(hooks, Omit)
1381 and isinstance(experimental, dict)
1382 and experimental.get("session_config_id") is not None
1383 ):
1384 raise exceptions.InvalidParams(
1385 "`hooks` cannot be combined with `experimental={'session_config_id': ...}`; "
1386 "a saved Session config sets the session's access policy, so apply "
1387 "hooks in a separate update"
1388 )
1389
1390 precondition: t.Union[int, "Omit"]
1391 if expected_config_version is None or expected_config_version is False:
1392 precondition = omit
1393 elif isinstance(expected_config_version, bool) or expected_config_version < 1:
1394 raise exceptions.InvalidParams(
1395 "`expected_config_version` must be a positive integer, or False to "
1396 "send no precondition"
1397 )
1398 else:
1399 precondition = expected_config_version
1400
1401 workbench_payload = sandbox if sandbox is not omit else workbench
1402
1403 # The spec does not declare the ``expected_config_version`` precondition
1404 # until ComposioHQ/platform#13157 lands, so it travels as an extra root
1405 # body field.
1406 extra_body: t.Optional[t.Dict[str, t.Any]] = (
1407 None
1408 if isinstance(precondition, Omit)
1409 else {"expected_config_version": precondition}
1410 )
1411
1412 # Until ComposioHQ/platform#13157 lands, the spec does not mark every
1413 # policy block nullable although the API accepts ``None`` (it removes the
1414 # stored override), nor the subfield removals inside
1415 # ``manage_connections``, ``multi_account`` and ``experimental``; the
1416 # values are serialized as-is.
1417 try:
1418 response = self._client.tool_router.session.patch(
1419 session_id=self.session_id,
1420 toolkits=t.cast(
1421 t.Union[session_patch_params.Toolkits, "Omit"], toolkits
1422 ),
1423 tools=t.cast(
1424 t.Union[t.Dict[str, session_patch_params.Tools], "Omit"], tools
1425 ),
1426 tags=t.cast(t.Union[session_patch_params.Tags, "Omit"], tags),
1427 instant=t.cast(
1428 t.Union[
1429 t.Literal[False],
1430 session_patch_params.CurrentInstantVariant1,
1431 "Omit",
1432 ],
1433 instant,
1434 ),
1435 auth_configs=t.cast(t.Union[t.Dict[str, str], "Omit"], auth_configs),
1436 connected_accounts=connected_accounts,
1437 manage_connections=t.cast(
1438 t.Union[t.Optional[session_patch_params.ManageConnections], "Omit"],
1439 manage_connections,
1440 ),
1441 workbench=workbench_payload,
1442 multi_account=t.cast(
1443 t.Union[t.Optional[session_patch_params.MultiAccount], "Omit"],
1444 multi_account,
1445 ),
1446 proxy_execute=(
1447 {"enable": proxy_execute}
1448 if isinstance(proxy_execute, bool)
1449 else proxy_execute
1450 ),
1451 preload=t.cast(t.Union[session_patch_params.Preload, "Omit"], preload),
1452 search=t.cast(t.Union[session_patch_params.Search, "Omit"], search),
1453 execute=t.cast(t.Union[session_patch_params.Execute, "Omit"], execute),
1454 experimental=t.cast(
1455 t.Union[t.Optional[session_patch_params.Experimental], "Omit"],
1456 experimental,
1457 ),
1458 hooks=t.cast(
1459 t.Union[
1460 t.Optional[
1461 t.Iterable[
1462 t.Union[
1463 session_patch_params.CurrentHookVariant0,
1464 session_patch_params.CurrentHookVariant1,
1465 ]
1466 ]
1467 ],
1468 "Omit",
1469 ],
1470 hooks,
1471 ),
1472 extra_body=extra_body,
1473 # A stale precondition is a deterministic 409: never retry it.
1474 request_options={"max_retries": 0},
1475 )
1476 except ConflictError as exc:
1477 if precondition is omit:
1478 message = (
1479 f"Session {self.session_id} configuration changed while this "
1480 "update was in flight; re-fetch the session and retry the update"
1481 )
1482 else:
1483 message = (
1484 f"Session {self.session_id} configuration is no longer at "
1485 f"version {precondition}; re-fetch the session and retry the update"
1486 )
1487 raise exceptions.SessionConfigConflictError(
1488 message,
1489 session_id=self.session_id,
1490 expected_config_version=(
1491 None if isinstance(precondition, Omit) else precondition
1492 ),
1493 ) from exc
1494 self.config = t.cast(ToolRouterSessionConfig, response.config)
1495 self.config_version = response.config_version
1496 self.preload = _session_preload_config(response.config.preload)
1497 return self.config
1498
1499 def list_config_history(
1500 self,
1501 **query: te.Unpack[session_config_history_params.SessionConfigHistoryParams],
1502 ) -> session_config_history_response.SessionConfigHistoryResponse:
1503 """
1504 List the configuration history of this session, newest first.
1505
1506 Every ``update()`` records a new config version; this returns those
1507 versions with cursor-based pagination.
1508
1509 :param cursor: Pagination cursor from a previous response.
1510 :param limit: Number of items per page (max 100).
1511 :return: The config versions under ``.items`` plus pagination fields.
1512
1513 Example:
1514 history = session.list_config_history(limit=10)
1515 for entry in history.items:
1516 print(entry.version, entry.is_current)
1517 """
1518 return self._client.tool_router.session.config_history(
1519 session_id=self.session_id,
1520 **query,
1521 )
1522
1523 def delete(self) -> ToolRouterSessionDeleteResponse:
1524 """
1525 Delete this session.
1526
1527 Deleted sessions immediately stop being retrievable or executable. An
1528 already-deleted session surfaces the backend 404.
1529 """
1530 return delete_tool_router_session(self._client, self.session_id)
1531
1532
1533 class ToolRouterSessionWithMcp(ToolRouterSession[TTool, TToolCollection]):
1534 """A :class:`ToolRouterSession` whose hosted MCP endpoint is exposed.
1535
1536 Returned by ``create(..., mcp=True)`` / ``use(..., mcp=True)``. The ``mcp``
1537 attribute is populated by the base ``__init__`` at runtime; this subclass
1538 only surfaces it in the type. See
1539 https://docs.composio.dev/docs/sessions-via-mcp
1540 """
1541
1542 #: Hosted MCP server configuration (url + auth headers) for this session.
1543 #: This is the recommended MCP path, gated behind ``mcp=True``.
1544 #: See https://docs.composio.dev/docs/sessions-via-mcp
1545 mcp: "ToolRouterMCPServerConfig"