21
ItemToolkit,
22
)
23
from composio_client.types.tool_router import (
24
- session_attach_response,
24
session_create_response,
25
session_link_params,
26
session_patch_params,
28
- session_patch_response,
29
- session_retrieve_response,
27
+ session_search_response,
28
)
29
from composio_client.types.tool_router.session_execute_response import (
30
SessionExecuteResponse,
31
)
34
-from composio_client.types.tool_router.session_search_response import (
35
- SessionSearchResponse,
36
-)
32
+from pydantic import BaseModel
33
34
from composio import exceptions
35
from composio.client import HttpClient
71
delete_tool_router_session,
72
)
73
from composio.core.models.tools import (
78
- PremiumCharge,
74
+ InstantCharge,
75
ToolExecuteParams,
76
ToolExecutionResponse,
77
)
99
tools: t.Union[t.List[str], t.Literal["all"]]
100
101
106
-#: Server-side session configuration as returned by the API: toolkit and tool
107
-#: allowlists, tags, auth configs, connected accounts, ``manage_connections``,
108
-#: preload, sandbox (``workbench``), search and execute settings. The four
109
-#: generated response models carry the same fields.
110
-ToolRouterSessionConfig = t.Union[
111
- session_create_response.Config,
112
- session_retrieve_response.Config,
113
- session_attach_response.Config,
114
- session_patch_response.Config,
115
-]
102
+class ToolRouterInstantResponseEnable(te.TypedDict):
103
+ enabled: t.List[str]
104
+
105
+
106
+class ToolRouterInstantResponseDisable(te.TypedDict):
107
+ disabled: t.List[str]
108
+
109
+
110
+class ToolRouterInstantResponse(te.TypedDict):
111
+ """Stored Instant policy returned in Session config, using API field casing."""
112
+
113
+ toolkits: te.NotRequired[
114
+ t.Union[ToolRouterInstantResponseEnable, ToolRouterInstantResponseDisable]
115
+ ]
116
+ tools: te.NotRequired[
117
+ t.Dict[
118
+ str,
119
+ t.Union[ToolRouterInstantResponseEnable, ToolRouterInstantResponseDisable],
120
+ ]
121
+ ]
122
+ return_instant_charge: bool
123
+
124
+
125
+class ToolRouterSessionConfig(t.Protocol):
126
+ """Server-side Session config. New Instant fields are retained by the client
127
+ as Pydantic extras until its generated response types adopt this contract.
128
+ """
129
+
130
+ user_id: str
131
+ instant: t.Union[t.Literal[False], ToolRouterInstantResponse]
132
+ auth_configs: t.Optional[t.Dict[str, str]]
133
+ connected_accounts: t.Optional[t.Dict[str, t.List[str]]]
134
+ execute: session_create_response.ConfigExecute
135
+ manage_connections: t.Optional[session_create_response.ConfigManageConnections]
136
+ multi_account: t.Optional[session_create_response.ConfigMultiAccount]
137
+ preload: session_create_response.ConfigPreload
138
+ search: session_create_response.ConfigSearch
139
+ tags: t.Optional[session_create_response.ConfigTags]
140
+ toolkits: t.Union[
141
+ session_create_response.ConfigToolkitsEnabled,
142
+ session_create_response.ConfigToolkitsDisabled,
143
+ None,
144
+ ]
145
+ tools: t.Optional[
146
+ t.Dict[
147
+ str,
148
+ t.Union[
149
+ session_create_response.ConfigToolsEnabled,
150
+ session_create_response.ConfigToolsDisabled,
151
+ session_create_response.ConfigToolsTags,
152
+ ],
153
+ ]
154
+ ]
155
+ workbench: t.Optional[session_create_response.ConfigWorkbench]
156
+
157
+ def model_dump(self, **kwargs: t.Any) -> t.Dict[str, t.Any]: ...
158
+
159
+ def model_dump_json(self, **kwargs: t.Any) -> str: ...
160
+
161
+ def model_copy(self, **kwargs: t.Any) -> ToolRouterSessionConfig: ...
162
163
118
-class ToolRouterPremiumUsageEnable(te.TypedDict):
164
+class ToolRouterInstantEnable(te.TypedDict):
165
enable: t.List[str]
166
167
122
-class ToolRouterPremiumUsageDisable(te.TypedDict):
168
+class ToolRouterInstantDisable(te.TypedDict):
169
disable: t.List[str]
170
171
126
-class ToolRouterPremiumUsageConfig(te.TypedDict, total=False):
127
- """Experimental premium usage policy for a Session."""
172
+class ToolRouterInstantConfig(te.TypedDict, total=False):
173
+ """Experimental Instant usage policy for a Session."""
174
129
- toolkits: t.Union[ToolRouterPremiumUsageEnable, ToolRouterPremiumUsageDisable]
130
- tools: t.Dict[
131
- str, t.Union[ToolRouterPremiumUsageEnable, ToolRouterPremiumUsageDisable]
132
- ]
133
- return_premium_charge: bool
175
+ toolkits: t.Union[ToolRouterInstantEnable, ToolRouterInstantDisable]
176
+ tools: t.Dict[str, t.Union[ToolRouterInstantEnable, ToolRouterInstantDisable]]
177
+ return_instant_charge: bool
178
179
180
class ToolRouterSessionExecuteResponse(SessionExecuteResponse):
181
"""Result of :meth:`ToolRouterSession.execute`."""
182
139
- premium_charge: t.Optional[PremiumCharge] = None
183
+ instant_charge: t.Optional[InstantCharge] = None
184
"""Present only when the Session sets
141
- ``premium_usage.return_premium_charge`` and a charge is available."""
185
+ ``instant.return_instant_charge`` and a charge is available."""
186
+
187
+
188
+class ToolRouterInstantAccount(BaseModel):
189
+ """Tools served by the Composio Instant account for a toolkit."""
190
+
191
+ allowed_tool_slugs: t.List[str]
192
+
193
+
194
+class ToolRouterToolkitConnectionStatus(
195
+ session_search_response.ToolkitConnectionStatus
196
+):
197
+ instant_account: t.Optional[ToolRouterInstantAccount] = None
198
+
199
+
200
+class ToolRouterSessionSearchResponse(session_search_response.SessionSearchResponse):
201
+ """Session search result, including typed Instant account coverage."""
202
+
203
+ # Narrows the generated list item type; `list` is invariant for mypy.
204
+ toolkit_connection_statuses: t.List[ToolRouterToolkitConnectionStatus] # type: ignore[assignment]
205
+
206
+
207
+def _with_instant_account(status: t.Any) -> t.Any:
208
+ if not isinstance(status, BaseModel):
209
+ return status
210
+ fields = dict(status)
211
+ account = fields.get("instant_account")
212
+ if isinstance(account, dict):
213
+ fields["instant_account"] = ToolRouterInstantAccount.model_construct(
214
+ _fields_set=set(account), **account
215
+ )
216
+ return ToolRouterToolkitConnectionStatus.model_construct(
217
+ _fields_set=status.model_fields_set, **fields
218
+ )
219
220
221
class ToolRouterUpdateManageConnectionsConfig(te.TypedDict, total=False):
324
self.preload = preload or ToolRouterSessionPreloadConfig(tools=[])
325
# Sessions built from an API response always carry their config; the
326
# fallback only covers direct construction without one (tests).
250
- self.config = config or session_create_response.Config(
251
- user_id=user_id or "",
252
- execute=session_create_response.ConfigExecute(),
253
- search=session_create_response.ConfigSearch(),
254
- preload=session_create_response.ConfigPreload(tools=self.preload.tools),
255
- premium_usage=False,
327
+ self.config = config or t.cast(
328
+ ToolRouterSessionConfig,
329
+ session_create_response.Config.model_construct(
330
+ user_id=user_id or "",
331
+ execute=session_create_response.ConfigExecute(),
332
+ search=session_create_response.ConfigSearch(),
333
+ preload=session_create_response.ConfigPreload(tools=self.preload.tools),
334
+ instant=False,
335
+ ),
336
)
337
# The MCP endpoint exists on every session at runtime (kept for
338
# backwards compatibility), but is only typed via
787
"error": error_message,
788
"successful": not has_any_error,
789
}
710
- if remote_result and remote_result.get("premium_charge") is not None:
711
- merged["premium_charge"] = remote_result["premium_charge"]
790
+ if remote_result and remote_result.get("instant_charge") is not None:
791
+ merged["instant_charge"] = remote_result["instant_charge"]
792
return merged
793
794
def authorize(
923
*,
924
query: str,
925
model: t.Optional[str] = None,
846
- ) -> SessionSearchResponse:
926
+ ) -> ToolRouterSessionSearchResponse:
927
"""
928
Search for tools by semantic use case.
929
930
Returns relevant tools for the given query with schemas and guidance.
931
"""
852
- return self._client.tool_router.session.search(
932
+ response = self._client.tool_router.session.search(
933
session_id=self.session_id,
934
queries=[{"use_case": query}],
935
model=model if model else omit,
937
self._inline_custom_tools_payload
938
),
939
)
940
+ # The client already built the response without enforcing its schema.
941
+ # Construct without revalidating so an unexpected field can't fail a
942
+ # search; only the Instant account coverage gains a typed model.
943
+ fields = dict(response)
944
+ statuses = fields.get("toolkit_connection_statuses")
945
+ if isinstance(statuses, list):
946
+ fields["toolkit_connection_statuses"] = [
947
+ _with_instant_account(status) for status in statuses
948
+ ]
949
+ return ToolRouterSessionSearchResponse.model_construct(
950
+ _fields_set=response.model_fields_set, **fields
951
+ )
952
953
def execute(
954
self,
970
top-level field or define their own account-selection fields.
971
972
Both paths return a ``ToolRouterSessionExecuteResponse`` with ``data``,
881
- ``error``, ``log_id``, and ``premium_charge`` attributes.
973
+ ``error``, ``log_id``, and ``instant_charge`` attributes.
974
"""
975
# Check if this is a local tool (by original or final slug)
976
entry = find_custom_tool(self._custom_tools_map, tool_slug)
994
),
995
)
996
# The client already validated data/error/log_id and kept the
905
- # undeclared premium_charge as an extra. Construct without
997
+ # undeclared instant_charge as an extra. Construct without
998
# revalidating so a malformed charge can't fail an executed call.
999
return ToolRouterSessionExecuteResponse.model_construct(**dict(response))
1000
1107
self,
1108
*,
1109
toolkits: t.Union[t.Optional[session_patch_params.Toolkits], "Omit"] = omit,
1018
- premium_usage: t.Union[
1019
- t.Literal[False], ToolRouterPremiumUsageConfig, "Omit"
1020
- ] = omit,
1110
+ instant: t.Union[t.Literal[False], ToolRouterInstantConfig, "Omit"] = omit,
1111
tools: t.Union[
1112
t.Optional[t.Dict[str, session_patch_params.Tools]], "Omit"
1113
] = omit,
1147
as-is). Supplied ``tools``, ``auth_configs`` and ``connected_accounts``
1148
maps replace the stored map entirely. Inside ``manage_connections``,
1149
``callback_url=None`` removes only the stored callback URL.
1060
- Experimental ``premium_usage`` accepts ``False`` to disable billed
1150
+ Experimental ``instant`` accepts ``False`` to disable billed
1151
access or an object to set its filters; it does not accept ``None``.
1062
- Any object, even one that only sets ``return_premium_charge``,
1063
- re-enables premium usage on a Session set to ``False``.
1152
+ Any object, even one that only sets ``return_instant_charge``,
1153
+ re-enables Instant usage on a Session set to ``False``.
1154
1155
By default the request carries no precondition: the last writer wins.
1156
Pass ``expected_config_version`` (for example this object's
1182
"Pass either `sandbox` or `workbench`, not both. "
1183
"`workbench` is a backwards-compatible alias for `sandbox`."
1184
)
1095
- if premium_usage is None:
1185
+ if instant is None:
1186
raise exceptions.InvalidParams(
1097
- "`premium_usage` does not accept None; pass False to disable "
1098
- "premium usage, or omit it to keep the stored policy"
1187
+ "`instant` does not accept None; pass False to disable "
1188
+ "Instant usage, or omit it to keep the stored policy"
1189
)
1190
1191
precondition: t.Union[int, "Omit"]
1203
1204
# The generated client has no typed parameter for the precondition, so
1205
# it travels as an extra root body field.
1116
- extra_body = (
1206
+ extra_body: t.Optional[t.Dict[str, t.Any]] = (
1207
None
1208
if isinstance(precondition, Omit)
1209
else {"expected_config_version": precondition}
1210
)
1211
+ if not isinstance(instant, Omit):
1212
+ # Send the new wire contract without passing the old generated keyword.
1213
+ extra_body = {**(extra_body or {}), "instant": instant}
1214
1215
# The generated client does not type ``None`` for every policy block
1216
# although the API accepts it (it removes the stored override), nor the
1244
t.Union[t.Optional[session_patch_params.Experimental], "Omit"],
1245
experimental,
1246
),
1154
- premium_usage=t.cast(
1155
- t.Union[
1156
- t.Literal[False],
1157
- session_patch_params.CurrentPremiumUsageVariant1,
1158
- "Omit",
1159
- ],
1160
- premium_usage,
1161
- ),
1247
extra_body=extra_body,
1248
# A stale precondition is a deterministic 409: never retry it.
1249
request_options={"max_retries": 0},
1266
None if isinstance(precondition, Omit) else precondition
1267
),
1268
) from exc
1184
- self.config = response.config
1269
+ self.config = t.cast(ToolRouterSessionConfig, response.config)
1270
self.config_version = response.config_version
1271
self.preload = _session_preload_config(response.config.preload)
1272
return self.config