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 234 lines 8.41 KB
Raw
1 """Session context implementation injected into custom tool execute functions.
2
3 One instance is created per session and shared across all custom tool invocations,
4 including sibling routing (tool A calling tool B without hitting the network).
5 """
6
7 from __future__ import annotations
8
9 import typing as t
10
11 from composio_client import omit
12 from composio_client.types.tool_router.session_execute_response import (
13 SessionExecuteResponse,
14 )
15 from composio_client.types.tool_router.session_proxy_execute_params import Parameter
16 from composio_client.types.tool_router.session_proxy_execute_response import (
17 SessionProxyExecuteBlockedResponse,
18 )
19
20 from composio.client import HttpClient
21 from composio.core.models.custom_tool_execution import (
22 assert_unambiguous_custom_tool_slug,
23 execute_custom_tool,
24 find_custom_tool,
25 )
26 from composio.core.models.custom_tool_types import (
27 CustomToolsMap,
28 InlineCustomToolsWirePayload,
29 ToolRouterSessionProxyExecuteBlocked,
30 ToolRouterSessionProxyExecuteCompleted,
31 ToolRouterSessionProxyExecuteResponse,
32 )
33 from composio.core.models.tools import (
34 _serialize_arguments,
35 hook_results_of,
36 require_execute_result,
37 require_executed,
38 )
39 from composio.exceptions import ValidationError
40
41 _VALID_METHODS = frozenset({"GET", "POST", "PUT", "DELETE", "PATCH"})
42 _VALID_PARAM_TYPES = frozenset({"header", "query"})
43
44
45 def proxy_execute_impl(
46 client: HttpClient,
47 session_id: str,
48 *,
49 toolkit: str,
50 endpoint: str,
51 method: t.Literal["GET", "POST", "PUT", "DELETE", "PATCH"],
52 body: t.Any = None,
53 parameters: t.Optional[t.List[t.Dict[str, t.Any]]] = None,
54 ) -> ToolRouterSessionProxyExecuteResponse:
55 """Shared proxy execute implementation used by SessionContextImpl and ToolRouterSession.
56
57 Projects the generated client's response model onto the SDK's own shape so
58 the public return type does not move when the client is regenerated.
59 """
60 # Client-side validation (matches TS SessionProxyExecuteParamsSchema)
61 if not toolkit:
62 raise ValidationError("proxy_execute: toolkit is required")
63 if not endpoint:
64 raise ValidationError("proxy_execute: endpoint is required")
65 if method not in _VALID_METHODS:
66 raise ValidationError(
67 f"proxy_execute: method must be one of {sorted(_VALID_METHODS)}, got {method!r}"
68 )
69
70 # Transform and validate parameters
71 api_params: t.List[Parameter] = []
72 if parameters:
73 for i, p in enumerate(parameters):
74 if not isinstance(p, dict) or "name" not in p or "value" not in p:
75 raise ValidationError(
76 f"proxy_execute: parameters[{i}] must be a dict with 'name' and 'value' keys"
77 )
78 param_type = p.get("in", p.get("type", "header"))
79 if param_type not in _VALID_PARAM_TYPES:
80 raise ValidationError(
81 f"proxy_execute: parameters[{i}].type must be 'header' or 'query', "
82 f"got {param_type!r}"
83 )
84 api_params.append(
85 Parameter(
86 name=p["name"],
87 type=param_type, # type: ignore[typeddict-item]
88 value=str(p["value"]),
89 )
90 )
91
92 subject = f"{method} proxy call for toolkit {toolkit}"
93 # Disable retries: a proxied call is a non-idempotent write, and a silent
94 # retry after a read timeout can duplicate the side effect.
95 raw = client.without_retries.tool_router.session.proxy_execute(
96 session_id=session_id,
97 toolkit_slug=toolkit,
98 endpoint=endpoint,
99 method=method,
100 body=body if body is not None else omit,
101 parameters=api_params if api_params else omit,
102 )
103
104 # A blocked request has no HTTP response, so it is read before ``status``.
105 if isinstance(raw, SessionProxyExecuteBlockedResponse):
106 blocked_result: ToolRouterSessionProxyExecuteBlocked = {
107 "result_type": "blocked",
108 "block_reason": {
109 "type": raw.reason.type,
110 "hook_id": raw.reason.hook_id,
111 },
112 "message": raw.message,
113 }
114 blocked_hook_results = hook_results_of(raw.hook_results)
115 if blocked_hook_results is not None:
116 blocked_result["hook_results"] = blocked_hook_results
117 return blocked_result
118 response = require_executed(raw, subject)
119
120 # ``status`` and ``size`` are ``float`` on the generated model and pydantic
121 # coerces, so they arrive as ``200.0``/``123.0``. Narrow them here: an HTTP
122 # status and a byte count are integers, and TypeScript reports them as such.
123 result: ToolRouterSessionProxyExecuteCompleted = {
124 "result_type": "completed",
125 "status": int(response.status),
126 "data": response.data,
127 "headers": response.headers,
128 }
129 hook_results = hook_results_of(response.hook_results)
130 if hook_results is not None:
131 result["hook_results"] = hook_results
132 binary_data = response.binary_data
133 if binary_data is not None:
134 result["binary_data"] = {
135 "content_type": binary_data.content_type,
136 "size": int(binary_data.size),
137 "url": binary_data.url,
138 "expires_at": binary_data.expires_at,
139 }
140 return result
141
142
143 class SessionContextImpl:
144 """Concrete implementation of SessionContext.
145
146 One instance is created per session (singleton) and shared across
147 all custom tool invocations. When ``custom_tools_map`` is provided,
148 ``execute()`` checks local tools first before falling back to the
149 backend API (sibling routing).
150 """
151
152 def __init__(
153 self,
154 client: HttpClient,
155 user_id: str,
156 session_id: str,
157 custom_tools_map: t.Optional[CustomToolsMap] = None,
158 inline_custom_tools_payload: t.Optional[InlineCustomToolsWirePayload] = None,
159 ) -> None:
160 self._client = client
161 self._user_id = user_id
162 self._session_id = session_id
163 self._custom_tools_map = custom_tools_map
164 self._inline_custom_tools_payload = inline_custom_tools_payload
165
166 @property
167 def user_id(self) -> str:
168 """The user ID for the current session."""
169 return self._user_id
170
171 def execute(
172 self,
173 tool_slug: str,
174 arguments: t.Dict[str, t.Any],
175 ) -> SessionExecuteResponse:
176 """Execute any tool from within a custom tool.
177
178 Routes to sibling local tools in-process when available,
179 otherwise delegates to the backend API.
180
181 Returns the same response model as ``session.execute()``.
182 """
183 # Try local tool first (sibling routing)
184 entry = find_custom_tool(self._custom_tools_map, tool_slug)
185 if entry:
186 result = execute_custom_tool(entry, arguments, self)
187 return SessionExecuteResponse(
188 data=result["data"],
189 error=result["error"],
190 log_id="",
191 result_type="completed" if result["successful"] else "failed",
192 )
193
194 assert_unambiguous_custom_tool_slug(self._custom_tools_map, tool_slug)
195
196 # Serialize any Pydantic model instances before sending to remote API
197 serialized = _serialize_arguments(arguments)
198
199 # Disable retries: a session execution is a non-idempotent write, and a
200 # silent retry after a read timeout can duplicate the side effect.
201 return require_execute_result(
202 self._client.without_retries.tool_router.session.execute(
203 session_id=self._session_id,
204 tool_slug=tool_slug,
205 arguments=serialized,
206 experimental=self._inline_custom_tools_payload
207 if self._inline_custom_tools_payload is not None
208 else omit,
209 ),
210 tool_slug,
211 )
212
213 def proxy_execute(
214 self,
215 *,
216 toolkit: str,
217 endpoint: str,
218 method: t.Literal["GET", "POST", "PUT", "DELETE", "PATCH"],
219 body: t.Any = None,
220 parameters: t.Optional[t.List[t.Dict[str, t.Any]]] = None,
221 ) -> ToolRouterSessionProxyExecuteResponse:
222 """Proxy API calls through Composio's auth layer.
223
224 Returns the same response shape as ``session.proxy_execute()``.
225 """
226 return proxy_execute_impl(
227 self._client,
228 self._session_id,
229 toolkit=toolkit,
230 endpoint=endpoint,
231 method=method,
232 body=body,
233 parameters=parameters,
234 )